UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

10,386 lines • 1.28 MB
import{$ as e,$t as t,A as n,An as r,At as i,B as a,Bn as o,Bt as s,C as c,Cn as l,Ct as u,D as d,Dn as f,Dt as p,E as m,En as h,Et as g,F as _,Fn as v,Ft as y,G as b,Gn as ee,Gt as x,H as te,Hn as ne,Ht as re,I as ie,In as ae,It as oe,J as se,Jt as ce,K as le,Kn as ue,Kt as S,Ln as de,Lt as fe,M as pe,Mn as C,Mt as me,N as he,Nn as w,Nt as ge,O as _e,On as ve,Ot as ye,P as be,Pn as xe,Pt as Se,Q as Ce,Qt as we,R as T,Rn as Te,Rt as Ee,S as De,Sn as Oe,St as ke,T as Ae,Tn as je,Tt as Me,U as E,Un as Ne,Ut as Pe,V as Fe,Vn as Ie,Vt as Le,W as Re,Wn as ze,Wt as D,X as Be,Xt as Ve,Y as He,Yt as Ue,Z as We,Zt as Ge,_ as Ke,_n as qe,_t as Je,a as Ye,an as Xe,at as Ze,b as Qe,bn as $e,bt as et,cn as O,ct as tt,d as nt,dn as rt,dt as it,en as at,et as ot,f as st,fn as ct,ft as lt,g as ut,gn as k,gt as dt,h as ft,hn as pt,ht as mt,i as ht,in as gt,it as _t,j as vt,jn as A,jt as yt,k as bt,kn as xt,kt as St,ln as Ct,lt as wt,m as Tt,mn as Et,mt as Dt,n as Ot,nn as kt,nt as At,on as jt,ot as Mt,p as Nt,pn as Pt,pt as Ft,q as It,qt as Lt,r as Rt,rn as zt,rt as Bt,s as j,sn as Vt,st as Ht,tn as Ut,tt as Wt,u as Gt,un as Kt,ut as qt,v as Jt,vn as M,vt as Yt,w as Xt,wn as Zt,wt as Qt,x as $t,xn as N,xt as en,y as tn,yn as P,yt as nn,z as rn,zn as F,zt as an}from"./session-transcript-reconcile.worker-openclaw-state-db-cache-BwXc4xzw.mjs";import{$ as on,At as I,B as sn,Bt as cn,C as ln,Ct as un,Dt as L,E as dn,Et as fn,F as pn,Ft as mn,It as R,Lt as hn,Mt as gn,N as _n,Nt as vn,O as yn,Ot as bn,P as xn,Pt as Sn,S as Cn,T as wn,Tt as Tn,Ut as En,Vt as Dn,X as On,_ as kn,_t as An,at as jn,ct as Mn,dt as Nn,ft as Pn,g as Fn,h as In,i as Ln,it as Rn,j as zn,jt as Bn,kt as Vn,l as Hn,m as Un,mt as Wn,n as Gn,nt as Kn,o as qn,ot as Jn,p as Yn,pt as Xn,r as Zn,rt as Qn,st as $n,t as er,tt as tr,u as nr,w as rr,xt as ir,yt as ar}from"./session-transcript-reconcile.worker-subsystem-BUNaGCPF.mjs";import{$ as or,$t as sr,A as cr,An as lr,Ar as ur,Bn as dr,Br as fr,Cn as pr,D as mr,Dn as hr,Dr as gr,E as _r,En as z,Er as vr,F as yr,Ft as br,G as xr,Gn as Sr,Gt as Cr,H as wr,Hn as Tr,Ht as Er,Ir as Dr,It as Or,J as kr,Jn as Ar,Jr as jr,Jt as B,Kn as Mr,Kr as Nr,L as V,Lr as Pr,Lt as Fr,Mn as Ir,Mr as Lr,Mt as Rr,Nn as zr,Nr as Br,Nt as Vr,O as Hr,On as Ur,Or as Wr,Pn as Gr,Q as Kr,Qt as qr,R as Jr,Rr as Yr,Rt as Xr,Sn as Zr,Sr as Qr,T as $r,Tn as ei,Tr as ti,Un as ni,Ut as ri,V as ii,Vn as ai,Vr as oi,Vt as si,W as ci,Wn as li,Wr as ui,Wt as di,X as fi,Xt as pi,Yr as mi,Yt as hi,Z as gi,Zn as _i,_ as vi,_n as yi,_r as bi,a as xi,ar as Si,at as Ci,bt as wi,c as Ti,cn as Ei,cr as Di,d as Oi,dn as ki,en as Ai,er as ji,et as Mi,f as Ni,fn as Pi,fr as Fi,ft as Ii,g as Li,gn as Ri,gr as zi,h as Bi,hn as Vi,i as Hi,in as Ui,it as Wi,j as Gi,jn as Ki,jr as qi,jt as H,k as Ji,kn as Yi,kr as Xi,kt as Zi,l as Qi,ln as $i,lr as ea,lt as ta,m as na,mn as ra,mr as ia,n as aa,nn as oa,nr as sa,nt as ca,o as la,on as ua,or as U,pn as da,q as fa,qn as pa,qr as ma,qt as ha,r as ga,rr as _a,s as va,sn as ya,tn as W,tr as ba,u as xa,un as Sa,ur as Ca,v as wa,vn as Ta,wn as G,wr as Ea,xr as Da,xt as Oa,zn as ka,zr as Aa}from"./session-transcript-reconcile.worker-worker-task-pool-iygKQQAw.mjs";import{$ as ja,$t as Ma,An as Na,B as Pa,Bt as Fa,C as Ia,Cn as La,Dt as K,En as Ra,Et as za,Ft as Ba,G as Va,Gt as Ha,Ht as Ua,It as Wa,J as Ga,Jt as Ka,K as qa,Kt as Ja,Lt as Ya,Mt as Xa,N as Za,Nt as Qa,Ot as $a,P as eo,Pt as to,Qt as no,R as ro,Rt as io,S as ao,Sn as q,St as oo,Tn as so,Tt as co,U as lo,Ut as uo,V as fo,Vt as po,W as mo,Wt as ho,Xt as go,Y as _o,Yt as vo,Z as yo,Zt as bo,_ as xo,_n as So,_t as J,a as Co,an as wo,at as To,bn as Eo,cn as Do,ct as Oo,dt as ko,en as Ao,fn as jo,ft as Mo,gt as No,hn as Po,i as Fo,in as Io,it as Lo,jn as Ro,jt as zo,ln as Bo,lt as Vo,m as Ho,mn as Uo,mt as Wo,n as Go,nn as Ko,nt as qo,o as Jo,on as Yo,ot as Xo,p as Zo,pn as Qo,qt as $o,r as es,rn as ts,rt as ns,s as rs,sn as is,st as as,tn as os,un as ss,ut as cs,vn as ls,vt as us,w as ds,wt as fs,xt as ps,yt as ms,z as hs,zt as gs}from"./session-transcript-reconcile.worker-sqlite-snapshot-staging-owner-By9qNyNO.mjs";import{r as _s,t as vs}from"./session-transcript-reconcile.worker-deferred-BtGQJMOQ.mjs";import{n as ys,r as bs,t as xs}from"./session-transcript-reconcile.worker-src-N0n_HcqU.mjs";import{t as Ss}from"./session-transcript-reconcile.worker-usingCtx-03vOGQ3v.mjs";import{t as Cs}from"./session-transcript-reconcile.worker-errors-7HrY_OUG.mjs";import{c as ws,d as Ts}from"./session-transcript-reconcile.worker-service-child-group-ownership-AVmJ78Uc.mjs";import{a as Es}from"./session-transcript-reconcile.worker-runtime-binary-DoB2Z7UB.mjs";import{i as Ds,n as Os,r as ks,t as As}from"./session-transcript-reconcile.worker-runtime-worker-url-BKeFM3b_.mjs";import{i as js,n as Ms,r as Ns}from"./session-transcript-reconcile.worker-path-existence-BSsZ8dW-.mjs";import{d as Ps}from"./session-transcript-reconcile.worker-gateway-process-argv-BLuCIIZP.mjs";import{a as Fs,i as Is,r as Ls}from"./session-transcript-reconcile.worker-openclaw-root-C8Ptm0sQ.mjs";import{createRequire as Rs}from"node:module";import{MessageChannel as zs,MessagePort as Bs,isMainThread as Vs,isMarkedAsUntransferable as Hs,parentPort as Us,receiveMessageOnPort as Ws,threadId as Gs}from"node:worker_threads";import Y,{existsSync as Ks,mkdirSync as qs,readFile as Js,realpathSync as Ys,statSync as Xs}from"node:fs";import Zs,{realpath as Qs,stat as $s}from"node:fs/promises";import X from"node:path";import"@openclaw/fs-safe/path";import{AsyncLocalStorage as ec}from"node:async_hooks";import tc,{createHash as nc,randomUUID as rc}from"node:crypto";import ic,{hostname as ac}from"node:os";import{fileURLToPath as oc,pathToFileURL as sc}from"node:url";import{isPromise as cc,isProxy as lc}from"node:util/types";import{isDeepStrictEqual as uc,promisify as dc}from"node:util";import fc,{deserialize as pc,getHeapSpaceStatistics as mc,getHeapStatistics as hc,serialize as gc}from"node:v8";import{Session as _c}from"node:inspector/promises";import{performance as vc}from"node:perf_hooks";import{assertDirectoryIdentitySync as yc,createDirectorySync as bc,createFileSync as xc,resolvePathViaExistingAncestorSync as Sc}from"@openclaw/fs-safe/advanced";import{FsSafeError as Cc}from"@openclaw/fs-safe/errors";import{spawn as wc,spawnSync as Tc}from"node:child_process";import{parse as Ec}from"semver";import{EventEmitter as Dc}from"node:events";import"node:buffer";import{setTimeout as Oc}from"node:timers/promises";import kc from"json5";import{inspectDarwinAcl as Ac}from"@openclaw/fs-safe/permissions";import{probeTreeClone as jc}from"@openclaw/fs-safe/copy";import{Value as Mc}from"typebox/value";import{Type as Nc}from"typebox";import Pc from"node:zlib";function postTaskMessage(e,t,n,r=[]){e.postMessage(t,r),n&&(Atomics.add(n,0,1),Atomics.notify(n,0))}function serveOwnedWorkerTasks$1(e,t,n){if(!Us)return;let r=Us,i=r,a=!1,o=!1;n.initialize(i);let s,c=Promise.resolve(),l=Promise.resolve(),u=0,d,f=typeof e==`function`?void 0:e.synchronousStateless,p=typeof e==`function`?e:e.synchronousStateless,reply=(e,r)=>{postTaskMessage(i,{status:`ok`,value:r,taskId:e.taskId,...n.collectTaskDiagnostics?{diagnostics:n.collectTaskDiagnostics()}:{}},e.progressSignal,t.transferList?.(r)??[])},fail=(e,r)=>{t.retireOnError?o=!0:postTaskMessage(i,{status:`failed`,taskId:e.taskId,error:r instanceof Error?r.message:String(r),...n.collectTaskDiagnostics?{diagnostics:n.collectTaskDiagnostics()}:{}},e.progressSignal)},finish=()=>{o?(async()=>{try{await l}finally{try{await n.onRetire?.()}finally{process.exitCode=1;try{i.close()}finally{i!==r&&r.close()}}}})().catch(()=>{process.exitCode=1}):n.onIdle()};i.on(`message`,function receive(e){if(o){e.resourcePort?.close();return}if(!a){a=!0;let t=n.selectStartupPort?.(e);if(t){i.off(`message`,receive),i=t,n.initialize(i),i.on(`message`,receive),n.onReady?.();return}}if(n.onMessage(e.sampleMemory===!0),e.closeResource&&e.resourcePort){let r=e.resourcePort,i=t.closesBesideExecution?.(e.key)?void 0:c;u++,l=l.then(()=>i).then(async()=>{if(o)throw Error(`Worker is retiring after a terminal task failure`);await t.closeResource(e.key),r.postMessage({ok:!0},[])}).catch(e=>{r.postMessage({ok:!1,error:e instanceof Error?e.message:String(e),detail:t.encodeResourceError?.(e)},[])}).finally(()=>{r.close(),u--,!s&&!o&&n.onIdle()});return}if(e.responseId!==void 0){if(e.taskId===d?.taskId&&e.responseId===d.responseId)return;if(!s||e.taskId!==s.taskId||e.responseId!==s.responseId||!s.pending)throw Error(`stale worker task response`);try{s.assertCurrent()}catch(e){s.cancelPending(e);return}let t=s.pending;s.pending=void 0;let n=!1,r=e.taskId,a=e.responseId,o=s.progressSignal;t.resolve({input:e.input,consumed:()=>{n||(n=!0,postTaskMessage(i,{status:`consumed`,taskId:r,id:a},o))}});return}if(s)throw Error(`overlapping worker tasks`);let r=new Int32Array(e.nativeSections),m={taskId:e.taskId,responseId:0,progressSignal:e.progressSignal,assertCurrent:()=>g.throwIfCancelled(),cancelPending:e=>{let t=m.pending;t&&(m.pending=void 0,d={taskId:m.taskId,responseId:m.responseId},t.reject(e))}},h=new AbortController,g=Pr(r,()=>s===m,h.signal);if(s=m,f&&!e.interactive&&u===0){try{g.throwIfCancelled(),n.installTaskContext(e.taskContext);let t=f(e.input);s=void 0,reply(m,t)}catch(e){s=void 0,fail(m,e)}finally{finish()}return}let _=Yr(r,()=>s===m,()=>{let e=/* @__PURE__ */ Error(`worker task cancelled`);h.abort(e),m.cancelPending(e)}),v=e.interactive?{notify:e=>{g.throwIfCancelled(),postTaskMessage(i,{status:`notification`,taskId:m.taskId,value:e},m.progressSignal)},consumeInput:()=>postTaskMessage(i,{status:`consumed`,taskId:m.taskId,id:0},m.progressSignal),request:(e,t)=>{if(g.throwIfCancelled(),s!==m||m.pending)throw Error(`closed or busy worker channel`);let n=Promise.withResolvers();m.pending=n;try{let n=t?[...t]:[];g.throwIfCancelled(),postTaskMessage(i,{status:`request`,taskId:m.taskId,id:++m.responseId,value:e},m.progressSignal,n)}catch(e){m.pending=void 0,n.reject(e)}return n.promise}}:void 0,y=l;c=Promise.resolve().then(async()=>{try{return await y,g.throwIfCancelled(),n.installTaskContext(e.taskContext),await Aa(r,()=>s===m,()=>p(e.input,v,g))}finally{await _?.(),s=void 0}}).then(e=>reply(m,e)).catch(e=>fail(m,e)).finally(finish)}),n.onReady?.()}const Fc=33554432,Ic=typeof Bun==`object`?Bun:void 0;let Lc={heapUsed:0,external:0},Rc,zc,Bc=!1;function hasIdleGarbageGrowth(){let e=process.memoryUsage();return e.heapUsed>Lc.heapUsed+Fc||e.external>Lc.external+Fc}async function collectWorkerIdleGarbage(){if(zc=void 0,!hasIdleGarbageGrowth())return;Bc=!0;let e=process.memoryUsage(),t=Date.now();try{if(Ic)Ic.gc(!0);else{if(!Rc){let e=new _c;e.connect(),Rc=e}await Rc.post(`HeapProfiler.collectGarbage`)}Lc=process.memoryUsage();let n=Date.now()-t;if(n>=1e3){let t={elapsedMs:n,threadId:Gs,heapUsedBeforeBytes:e.heapUsed,heapUsedAfterBytes:Lc.heapUsed,externalBeforeBytes:e.external,externalAfterBytes:Lc.external};import(`./session-transcript-reconcile.worker-worker-idle-gc-report.runtime-DEvHw7Kg.mjs`).then(({reportSlowIdleWorkerGc:e})=>e(t)).catch(e=>{process.emitWarning(e instanceof Error?e:String(e))})}}catch(e){process.emitWarning(e instanceof Error?e:String(e))}finally{Bc=!1}}function scheduleWorkerIdleGc(){Vs||zc||Bc||hasIdleGarbageGrowth()&&(zc=setTimeout(()=>{collectWorkerIdleGarbage()},1e3).unref())}function cancelWorkerIdleGc(){clearTimeout(zc),zc=void 0}function serveWorkerMemorySamples(e,t){let{port1:n,port2:r}=new zs,i=ba(e=>{n.postMessage({sqliteReaderCounter:e})}),a=zr(()=>{n.postMessage({postgresBridgeCounters:Ir()})}),o=process.versions.bun?void 0:hc().heap_size_limit,s,c=!1,flushGc=()=>{s&&=(n.postMessage({gc:s}),void 0)},sample=()=>{let{heapUsed:e,heapTotal:r,external:i,arrayBuffers:a}=process.memoryUsage(),c=process.versions.bun?void 0:mc().map(({space_name:e,space_used_size:t})=>({space_name:e,space_used_size:t}));n.postMessage({heapUsed:e,heapTotal:r,external:i,arrayBuffers:a,heapSizeLimitBytes:o,oldGenerationAfterGcBytes:ee(),heapSpaces:c,retainedData:t?.(),gc:s}),s=void 0},l,setGcEnabled=e=>{e?l??=ue(e=>{(s??=[]).push(...e),(c||s.length>=256)&&flushGc()}):(l?.(),l=void 0,s=void 0)};return n.on(`message`,e=>{if(e&&`flush`in e)ze(),flushGc(),n.postMessage({flushed:!0,heapUsed:hc().used_heap_size});else if(e&&`captureGcProfile`in e){let t=e.captureGcProfile;import(`./session-transcript-reconcile.worker-diagnostic-worker-gc-profile-CYM-XECd.mjs`).then(({captureWorkerGcProfiles:e})=>e()).then(e=>{n.postMessage({gcStorm:e.status===`complete`?{...t,captureStatus:`complete`,profiles:e.result}:{...t,captureStatus:`unavailable`,captureReason:e.reason}})}).catch(()=>{n.postMessage({gcStorm:{...t,captureStatus:`unavailable`,captureReason:`capture-failed`}})})}else e?setGcEnabled(e.gc):sample()}),n.once(`close`,()=>{a(),i(),l?.(),s=void 0}),n.on(`messageerror`,()=>n.close()),n.unref(),sample(),e.postMessage({status:`memory`,port:r,postgresBridgeCounters:Ir()},[r]),{setTaskMetrics(e){c=e,setGcEnabled(e)},collectTask(){return c?!0:void 0},close(){a(),i(),l?.(),l=void 0,flushGc(),n.close()}}}function serveWorkerTasks(e,t={}){serveOwnedWorkerTasks(e,t)}function serveOwnedWorkerTasks(e,t={}){let n,r,i,a,o,s,runWithTaskContext=async e=>{let run=async()=>{let t=i;if(!t)return e();let n=!0;try{return await Da((e,r,i,a)=>{if(!n)throw Error(`SQLite admission facts outlived their worker task`);return Tr(t,e,r,i,a)},e)}finally{n=!1}};return o?Xi(o,run):run()};serveOwnedWorkerTasks$1(typeof e==`function`?(t,n,r)=>Si({deadlineAtMs:a,assertActive:()=>r.throwIfCancelled()},()=>runWithTaskContext(async()=>{let i=await e(t,n,r),a=ti();if(a)throw a;return i})):e,{...t,get retireOnError(){return t.retireOnError||ti()!==void 0},closesBesideExecution:e=>{let t=qi(e);return t?.kind===`revive`||t?.kind===`close`&&t.deleted},closeResource:e=>runWithTaskContext(async()=>{let n=qi(e);if(!n&&!t.closeResource)throw Error(`Worker does not own retained resources`);n&&await ur(n),n&&n.kind!==`close`||await t.closeResource?.(e)})},{selectStartupPort(e){if(I(e)&&e.type===`openclaw.worker-task-port`){if(!(e.port instanceof Bs))throw Error(`Retained worker task port is invalid`);return r=e.port,r}},initialize(e){fn.forceConsoleToStderr=!0,n=e},onReady(){r?.postMessage({status:`ready`},[])},onMessage(e){e&&!s&&(s=serveWorkerMemorySamples(n,t.retainedData)),cancelWorkerIdleGc()},installTaskContext(e){s?.setTaskMetrics(e.collectWorkerMetrics===!0),a=e.databaseAdmissionDeadlineAtMs,o=e.databaseEngineSelection,e.postgresPool&&Ea(e.postgresPool),Lr(e.deletedAgentDatabaseFences),e.databaseAdmissionPort&&dr(e.databaseAdmissionPort),i??=e.databaseAdmissionPort},onIdle(){Dr(),t.idleGc!==!1&&scheduleWorkerIdleGc()},collectTaskDiagnostics:()=>s?.collectTask(),onRetire(){cancelWorkerIdleGc();try{s?.close()}finally{i?.close()}}})}function safeParseJson(e){try{return JSON.parse(e)}catch{return}}function safeParseJsonRecord(e){return/^[\t\n\r ]*\{/.test(e)?Vn(safeParseJson(e)):void 0}const preserveString=e=>e;function stableStringify(e,t=preserveString){return stringifyStableValue(e,/* @__PURE__ */ new WeakSet,t)}function stringifyStableValue(e,t,n,r){if(e==null)return String(e);if(typeof e==`number`&&!Number.isFinite(e))return JSON.stringify(String(e));if(typeof e==`bigint`)return JSON.stringify(e.toString());if(typeof e==`string`)return JSON.stringify(n(e));if(typeof e!=`object`)return JSON.stringify(e)??`null`;if(t.has(e))return JSON.stringify(`[Circular]`);t.add(e);try{if(e instanceof Date)return`Date(${Number.isNaN(e.getTime())?`null`:JSON.stringify(n(e.toISOString()))})`;if(e instanceof RegExp)return`RegExp(${JSON.stringify(n(e.toString()))})`;if(e instanceof Set||e instanceof Map){let r=Array.from(e,e=>stringifyStableValue(e,t,n)).toSorted(compareStableStrings);return`${e instanceof Set?`Set`:`Map`}([${r.join(`,`)}])`}if(e instanceof Error||e instanceof Uint8Array)return stringifyStableValue(e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{type:`Uint8Array`,data:encodeBase64(e)},t,n,r);if(Array.isArray(e)){if(r){r(`[`);let i=``;for(let a of e)r(i),r(stringifyStableValue(a,t,n,r)),i=`,`;return r(`]`),``}return`[${Array.from(e,e=>stringifyStableValue(e,t,n)).join(`,`)}]`}let i=e,a=Object.keys(i),o=n===preserveString?a.sort():a.map(e=>({key:e,normalizedKey:n(e)})).sort((e,t)=>compareStableStrings(e.normalizedKey,t.normalizedKey)||compareStableStrings(e.key,t.key));r?.(`{`);let s=n===preserveString?a:[],c=``,l=0;for(let e of o){let a=typeof e==`string`?e:e.key,o=`${JSON.stringify(typeof e==`string`?e:e.normalizedKey)}:`;r?(r(`${c}${o}`),r(stringifyStableValue(i[a],t,n,r)),c=`,`):s[l++]=`${o}${stringifyStableValue(i[a],t,n)}`}return r?(r(`}`),``):`{${s.join(`,`)}}`}finally{t.delete(e)}}function encodeBase64(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function compareStableStrings(e,t){return e<t?-1:+(e>t)}function preparePostgresQuery(e){let t=``,n=0,r=!0,i,a;for(let o=0;o<e.length;){let s=e.slice(o),c=/^(?:[eE]'(?:\\[\s\S]|''|[^'\\])*'|'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\]|--[^\n]*(?:\n|$))/.exec(s),l=/^\$(?:[A-Za-z_][A-Za-z_0-9]*)?\$/.exec(s)?.[0];if(s.startsWith(`/*`)){let n=o+2,r=1;for(;n<e.length&&r>0;)e.startsWith(`/*`,n)?(r++,n+=2):e.startsWith(`*/`,n)?(r--,n+=2):n++;t+=e.slice(o,n),o=n}else if(l){let n=e.indexOf(l,o+l.length),a=n<0?e.length:n+l.length;t+=e.slice(o,a),o=a,i=void 0,r=!1}else if(c)t+=c[0],o+=c[0].length,c[0].startsWith(`--`)||(i=void 0,r=!1);else{if(r&&/^pragma\b/i.test(s))throw Error(`The PostgreSQL engine does not support PRAGMA statements`);let c=/^(?:\d[\d_]*(?:\.[\d_]*)?|\.[\d_]+)(?:[eE][+-]?[\d_]+)?/.exec(s)?.[0];if(c){t+=c,o+=c.length,i=void 0,r=!1;continue}let l=/^[A-Za-z_][A-Za-z_0-9$]*/.exec(s)?.[0];if(l){let e=l.toUpperCase();i!==`AS`&&i!==`.`&&(e===`INTO`&&i!==`INSERT`&&i!==`MERGE`?a=`unscoped`:a===void 0&&/^(?:INSERT|UPDATE|DELETE|MERGE)$/.test(e)&&(e!==`UPDATE`||i!==`FOR`&&i!==`KEY`)&&(a=`scoped`)),i=e,t+=l,o+=l.length,r=!1;continue}let u=e.charAt(o);/\s/.test(u)||(i=u),u===`?`&&e[o+1]===`?`?(t+=`?`,o+=2):u===`?`?(t+=`$${++n}`,o++):(t+=u,o++),u===`;`?r=!0:/\s/.test(u)||(r=!1)}}return{sql:t,mutation:a}}function validatePostgresBindings(e){for(let t of e)if(t!==null&&typeof t!=`string`&&typeof t!=`number`&&typeof t!=`bigint`&&!ArrayBuffer.isView(t))throw TypeError(`SQL bindings must be null, numbers, bigints, strings, or ArrayBuffer views`)}function decodePostgresRows(e,t){return e.rows.map(n=>Object.fromEntries(e.fields.map(e=>{let r=n[e.name],i;if(r===null)i=null;else if(e.dataTypeID===20){if(typeof r!=`string`)throw TypeError(`PostgreSQL int8 results must be text`);let e=BigInt(r);if(t)i=e;else{let t=Number(e);if(!Number.isSafeInteger(t))throw RangeError(`PostgreSQL int8 ${e} cannot be represented safely as a number`);i=t}}else if(r instanceof Uint8Array)i=new Uint8Array(r);else if(typeof r==`boolean`)i=Number(r);else if(typeof r==`string`||typeof r==`number`||typeof r==`bigint`)i=r;else throw TypeError(`Unsupported PostgreSQL result type for column ${e.name}`);return[e.name,i]})))}function isPostgresConnectionError(e){return!e||e.startsWith(`08`)||/^57P0[123]$/.test(e)}function decodePostgresError(e){let t=Object.assign(Error(e.message),e);if(e.code===`57014`&&(t.name=`PostgresQueryCanceledError`),e.code===`55P03`||e.code===`40P01`||e.code===`40001`)return Object.assign(Error(e.message,{cause:t}),{code:`ERR_SQLITE_ERROR`,errcode:5});let n={23505:[2067,`UNIQUE`],23503:[787,`FOREIGN KEY`],23502:[1299,`NOT NULL`],23514:[275,`CHECK`]}[e.code??``];return n?Object.assign(Error(`${n[1]} constraint failed: ${e.constraint??e.column??`unknown`}`,{cause:t}),{code:`ERR_SQLITE_ERROR`,errcode:n[0]}):t}Object.freeze(/* @__PURE__ */ `activity.ai-agents.appearance.approve.apps.ask.automation.automations.channels.chat.templates.communications.config.cron.custodian.dashboard.dashboards.debug.focus.infrastructure.lobsterdex.logs.mcp.meetings.memory-import.model-providers.model-setup.new.nodes.plugin.plugins.portals.profile.sessions.settings.share.skills.systems.terminal.usage.workboard.worktrees`.split(`.`));let Vc,Hc=0;function startHost(){let e=wc(process.execPath,[...As(cr(`directoryWatchHost`)),String(process.pid)],{stdio:[`pipe`,`pipe`,`ignore`],detached:!0,env:{...process.env,NODE_OPTIONS:void 0}}),t={child:e,watches:/* @__PURE__ */ new Map,retired:0},n=``;e.stdout.setEncoding(`utf8`).on(`data`,e=>{let r=(n+e).split(`
`);n=r.pop()??``;for(let e of r){let n=JSON.parse(e),r=t.watches.get(n.id);r&&(n.event?r.emit(`change`,n.event,n.filename??void 0):(t.watches.delete(n.id),r.emit(`error`,/* @__PURE__ */ Error(`Directory watch host lost the watch`),!0)))}});let lost=()=>{Vc===t&&(Vc=void 0);let e=Array.from(t.watches.values());t.watches.clear();for(let t of e)t.emit(`error`,/* @__PURE__ */ Error(`Directory watch host exited`),!1)};e.on(`error`,lost).on(`exit`,lost),e.stdin.on(`error`,()=>{}),e.unref();for(let t of[e.stdin,e.stdout])t.unref?.();return t}function register(e,t,n){e.watches.set(t,n),e.child.stdin.write(`${JSON.stringify({id:t,path:n.path,recursive:n.recursive})}\n`)}function watchDirectory(e,t,n=!1){let r=Hc++,i=Object.assign(new Dc,{path:e,recursive:n});i.on(`change`,t);try{register(Vc??=startHost(),r,i)}catch(e){Vc?.watches.delete(r),queueMicrotask(()=>i.emit(`error`,e,!1))}return Object.assign(i,{close(){i.removeAllListeners(`change`);let e=Vc;if(e?.watches.delete(r)){if(e.watches.size&&(process.platform!==`darwin`||++e.retired<64))e.child.stdin.write(`${JSON.stringify({id:r})}\n`);else{if(Vc=void 0,e.watches.size){let t=Vc=startHost();for(let[n,r]of e.watches)register(t,n,r);e.watches.clear()}e.child.stdin.end()}}}})}const Uc=/* @__PURE__ */ new Map,Wc=/* @__PURE__ */ new Map;let Gc,Kc=1/0;const qc=3e4;function nextFallback(e=qc){let t=Date.now(),n=(Math.floor(t/e)+1)*e;return{atMs:n,elapsedAtMs:performance.now()+n-t}}function fallbackRemaining(e){return Math.min(e.nextFallback.atMs-Date.now(),e.nextFallback.elapsedAtMs-performance.now())}function retainEarlierFallback(e,t){e.nextFallback.atMs=Math.min(e.nextFallback.atMs,t.atMs),e.nextFallback.elapsedAtMs=Math.min(e.nextFallback.elapsedAtMs,t.elapsedAtMs)}function scheduleFallback(e){if(!Uc.size)return;let t=e?fallbackRemaining(e):Math.min(...Array.from(Uc.values(),fallbackRemaining)),n=performance.now()+Math.max(0,Math.ceil(t));Gc&&Kc<=n||(clearTimeout(Gc),Kc=n,Gc=gn(()=>setTimeout(()=>{reconcile()},Math.max(0,Math.ceil(t))).unref()))}async function reconcile(){Gc=void 0;let e=Array.from(Uc.values()).filter(e=>fallbackRemaining(e)<=0),t=/* @__PURE__ */ new Map;for(let n of e){n.nextFallback=nextFallback(n.reconcileIntervalMs);let e=n.source;if((!e||!await Zs.access(e.path).then(()=>!0,()=>!1)||e.path!==n.path&&await Zs.access(n.path).then(()=>!0,()=>!1))&&n.source===e)for(let r of e?.directories??[n])t.set(r,e)}for(let[e,n]of t)(Uc.get(e.key)!==e||e.source!==n)&&t.delete(e);for(let e of t.keys())detach(e);for(let e of t.keys())attach(e);for(let t of e)Uc.get(t.key)===t&&notify(t);scheduleFallback()}function detach(e){let t=e.source;e.source=void 0,t&&(t.directories=t.directories.filter(t=>t!==e),t.directories.length||(Wc.delete(t.key),t.watcher.close()))}function notify(e,t,n){for(let r of e.listeners)r(t,n)}function attach(e,t=e.watchRoot){let n=e.recursive&&t===e.watchRoot,r=JSON.stringify([t,n]),i=Wc.get(r);if(i){i.directories=[...i.directories,e],e.source=i;return}let a=X.basename(t),o=gn(()=>watchDirectory(t,(e,n)=>{let i=Wc.get(r);if(!i||i.watcher!==o)return;i.admitted=!0;let s=i.directories,c=e===`rename`&&(!n||n===a),l;for(let r of s)(r.path===t||!n||c||hn(r.path,l??=X.resolve(t,n))||hn(l,r.path))&&notify(r,r.path===t?n:void 0,e);if(e===`rename`){let e;for(let r of s)(c||r.watchRoot!==t&&n!==void 0&&hn(l??=X.resolve(t,n),r.watchRoot))&&(e??=[]).push(r);if(!e)return;for(let t of e)detach(t);for(let t of e)Uc.get(t.key)===t&&(attach(t),retainEarlierFallback(t,nextFallback(t.reconcileIntervalMs)),scheduleFallback(t))}},n)),s={key:r,path:t,watcher:o,admitted:!1,directories:[e]};Wc.set(r,s),e.source=s,o.on(`error`,(e,n)=>{for(let e of s.directories){detach(e);let r=X.dirname(t);n&&!s.admitted&&r!==t?attach(e,r):(notify(e),retainEarlierFallback(e,nextFallback()),scheduleFallback(e))}})}function observeOwnedDirectory(e,t,n={}){let r=X.resolve(e),i=n.watchRoot?X.resolve(n.watchRoot):r,a=n.recursive??!1,o=n.reconcileIntervalMs??qc,s=JSON.stringify([r,i,a,o]),c=Uc.get(s);c||(c={key:s,path:r,watchRoot:i,recursive:a,reconcileIntervalMs:o,listeners:[],nextFallback:{atMs:1/0,elapsedAtMs:1/0}},Uc.set(s,c),attach(c));let listener=(e,n)=>t(e,n);return c.listeners=[...c.listeners,listener],retainEarlierFallback(c,nextFallback(o)),scheduleFallback(c),{isWatching:()=>c.listeners.includes(listener)&&c.source!==void 0,close(){c.listeners=c.listeners.filter(e=>e!==listener),!(c.listeners.length||Uc.get(s)!==c)&&(Uc.delete(s),detach(c),Uc.size||(clearTimeout(Gc),Gc=void 0))}}}Sn(Symbol.for(`openclaw.agentDirPreparedPaths`),e=>{for(let t of e.values())t.close();e.clear()},`shared-state`);function normalizeAgentDirRegistryPath(e,t=process.env){return Ns(yn(e,t))}mn(Symbol.for(`openclaw.sessionRowChanges`),`close-and-restart`),mn(Symbol.for(`openclaw.sessionRowFactChanges`),`close-and-restart`),mn(Symbol.for(`openclaw.sessionRowProjectionChanges`),`close-and-restart`),R(Symbol.for(`openclaw.sessionRowInvalidationSources`),()=>/* @__PURE__ */ new WeakMap),R(Symbol.for(`openclaw.sessionRowPrivateFacts`),()=>/* @__PURE__ */ new WeakMap),R(Symbol.for(`openclaw.sessionRowChangeCaptures`),()=>/* @__PURE__ */ new WeakMap),R(Symbol.for(`openclaw.sessionRowChangeRevision`),()=>({value:0}));const Jc=[[`acp_parent_stream_events`,[`idx_agent_acp_parent_stream_run`]],[`agent_tool_usage`,[]],[`auth_profile_state`,[]],[`auth_profile_store`,[]],[`board_tabs`,[]],[`board_widgets`,[`idx_agent_board_widgets_tab_position`]],[`cache_entries`,[`idx_agent_cache_expiry`,`idx_agent_cache_updated`,`idx_agent_voice_session_open_scope`,`idx_agent_voice_session_open_updated`]],[`context_engine_turn_outbox`,[`idx_agent_context_engine_turn_outbox_engine`]],[`conversation_deliveries`,[`idx_agent_conversation_deliveries_reply`,`idx_agent_conversation_deliveries_source_session`,`idx_agent_conversation_deliveries_updated`]],[`conversations`,[`idx_agent_conversations_identity`,`idx_agent_conversations_lookup`,`idx_agent_conversations_updated`]],[`heartbeat_outcomes`,[]],[`memory_embedding_cache`,[`idx_memory_embedding_cache_updated_at`]],[`memory_entry_origins`,[]],[`memory_index_chunk_provenance`,[]],[`memory_index_chunk_recall_metadata`,[]],[`memory_index_chunks`,[`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_meta`,[]],[`memory_index_sources`,[`idx_memory_index_sources_source`]],[`memory_index_state`,[]],[`memory_session_tombstones`,[]],[`message_tool_run_outcomes`,[`idx_agent_message_tool_run_outcomes_occurred`]],[`schema_meta`,[]],[`session_canonical_validation_pending`,[]],[`session_conversations`,[`idx_agent_session_conversations_conversation`,`idx_agent_session_conversations_primary`]],[`session_creation_operations`,[`idx_agent_session_creation_operations_expiry`]],[`session_entry_snapshots`,[]],[`session_goal_operations`,[`idx_agent_session_goal_operations_expiry`]],[`session_input_completions`,[`idx_agent_session_input_completions_session_key`]],[`session_key_contract`,[]],[`session_members`,[`idx_agent_session_members_identity`]],[`session_nodes`,[`idx_agent_session_nodes_active`,`idx_agent_session_nodes_archived_at`,`idx_agent_session_nodes_current_session_id`,`idx_agent_session_nodes_entry_not_valid`,`idx_agent_session_nodes_entry_valid_pending`,`idx_agent_session_nodes_label`,`idx_agent_session_nodes_parent_session_key`,`idx_agent_session_nodes_spawned_by`,`idx_agent_session_nodes_status`,`idx_agent_session_nodes_updated_at`]],[`session_participants`,[]],[`session_pending_inputs`,[`idx_agent_session_pending_inputs_session`]],[`session_progress_cards`,[]],[`session_reactions`,[]],[`session_suggestions`,[`idx_agent_session_suggestions_author_created`,`idx_agent_session_suggestions_session_state_created`]],[`session_transcript_active_event_facts`,[]],[`session_transcript_active_events`,[`idx_agent_transcript_active_event_seq`,`idx_agent_transcript_active_messages`,`idx_agent_transcript_context_pending`]],[`session_transcript_archives`,[`idx_agent_session_transcript_archives_pending`,`idx_agent_session_transcript_archives_retention`]],[`session_transcript_cold_archive_chunks`,[]],[`session_transcript_cold_archives`,[]],[`session_transcript_fts`,[]],[`session_transcript_fts_config`,[]],[`session_transcript_fts_content`,[]],[`session_transcript_fts_data`,[]],[`session_transcript_fts_docsize`,[]],[`session_transcript_fts_idx`,[]],[`session_transcript_fts_rows`,[`idx_session_transcript_fts_rows_session_message`]],[`session_transcript_index_state`,[]],[`session_windows`,[`idx_agent_session_windows_conversation`,`idx_agent_session_windows_created_at`,`idx_agent_session_windows_session_key`,`idx_agent_session_windows_updated_at`]],[`standing_intents`,[`idx_standing_intents_lifecycle`,`idx_standing_intents_scope`]],[`standing_intents_fts`,[]],[`standing_intents_fts_config`,[]],[`standing_intents_fts_data`,[]],[`standing_intents_fts_docsize`,[]],[`standing_intents_fts_idx`,[]],[`trajectory_runtime_events`,[`idx_agent_trajectory_runtime_run`]],[`transcript_event_identities`,[`idx_agent_transcript_event_identity_sequence`,`idx_agent_transcript_event_sequence`,`idx_agent_transcript_message_idempotency`]],[`transcript_events`,[]],[`transcript_rewrite_watermarks`,[]],[`context_engine_turn_outbox`,[`idx_agent_context_engine_turn_outbox_engine`]],[`conversation_deliveries`,[`idx_agent_conversation_deliveries_reply`,`idx_agent_conversation_deliveries_updated`]],[`memory_embedding_cache`,[`idx_memory_embedding_cache_updated_at`]],[`memory_entry_origins`,[]],[`memory_index_chunks`,[`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_sources`,[`idx_memory_index_sources_source`]],[`session_input_completions`,[]],[`session_nodes`,[`idx_agent_session_nodes_active`,`idx_agent_session_nodes_archived_at`,`idx_agent_session_nodes_current_session_id`,`idx_agent_session_nodes_entry_not_valid`,`idx_agent_session_nodes_entry_valid_pending`,`idx_agent_session_nodes_label`,`idx_agent_session_nodes_last_interaction_at`,`idx_agent_session_nodes_parent_session_key`,`idx_agent_session_nodes_spawned_by`,`idx_agent_session_nodes_status`,`idx_agent_session_nodes_updated_at`]],[`session_participants`,[]],[`session_reactions`,[`idx_agent_session_reactions_message`]],[`session_windows`,[`idx_agent_session_windows_conversation`,`idx_agent_session_windows_created_at`,`idx_agent_session_windows_session_key`,`idx_agent_session_windows_updated_at`]],[`trajectory_runtime_events`,[`idx_agent_trajectory_runtime_run`]],[`transcript_event_identities`,[`idx_agent_transcript_event_identity_sequence`,`idx_agent_transcript_event_parent`,`idx_agent_transcript_event_sequence`,`idx_agent_transcript_message_idempotency`]],[`transcript_events`,[]],[`session_key_contract`,[]],[`session_nodes`,[`idx_agent_session_nodes_active`,`idx_agent_session_nodes_archived_at`,`idx_agent_session_nodes_current_session_id`,`idx_agent_session_nodes_entry_not_valid`,`idx_agent_session_nodes_entry_valid_pending`,`idx_agent_session_nodes_label`,`idx_agent_session_nodes_last_interaction_at`,`idx_agent_session_nodes_parent_session_key`,`idx_agent_session_nodes_spawned_by`,`idx_agent_session_nodes_status`,`idx_agent_session_nodes_updated_at`]],[`session_windows`,[`idx_agent_session_windows_conversation`,`idx_agent_session_windows_created_at`,`idx_agent_session_windows_session_key`,`idx_agent_session_windows_updated_at`]],[`session_transcript_fts_rows`,[`idx_agent_transcript_fts_rows_session`]],[`session_transcript_index_state`,[]],[`memory_index_chunks`,[`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`transcript_events`,[]],[`session_nodes`,[`idx_agent_session_nodes_active`,`idx_agent_session_nodes_archived_at`,`idx_agent_session_nodes_current_session_id`,`idx_agent_session_nodes_entry_not_valid`,`idx_agent_session_nodes_entry_valid_pending`,`idx_agent_session_nodes_label`,`idx_agent_session_nodes_last_interaction_at`,`idx_agent_session_nodes_parent_session_key`,`idx_agent_session_nodes_spawned_by`,`idx_agent_session_nodes_status`,`idx_agent_session_nodes_updated_at`]],[`session_nodes`,[`idx_agent_session_nodes_active`,`idx_agent_session_nodes_archived_at`,`idx_agent_session_nodes_current_session_id`,`idx_agent_session_nodes_entry_not_valid`,`idx_agent_session_nodes_entry_valid_pending`,`idx_agent_session_nodes_label`,`idx_agent_session_nodes_last_interaction_at`,`idx_agent_session_nodes_parent_session_key`,`idx_agent_session_nodes_spawned_by`,`idx_agent_session_nodes_status`,`idx_agent_session_nodes_updated_at`]],[`context_engine_turn_outbox`,[`idx_agent_context_engine_turn_outbox_engine`]],[`session_nodes`,[`idx_agent_session_nodes_active`,`idx_agent_session_nodes_archived_at`,`idx_agent_session_nodes_current_session_id`,`idx_agent_session_nodes_entry_not_valid`,`idx_agent_session_nodes_entry_valid_pending`,`idx_agent_session_nodes_label`,`idx_agent_session_nodes_last_interaction_at`,`idx_agent_session_nodes_parent_session_key`,`idx_agent_session_nodes_spawned_by`,`idx_agent_session_nodes_status`,`idx_agent_session_nodes_updated_at`]],[`transcript_events`,[]],[`state_leases`,[]]],Yc={afcfcf93ca60eab84c0b9c33cd6d8d342d42ad526e10371f9f43a3d201a5a28e:[`agent`,`8e70873f6fddd58ffc765c3786c293164dfe8ad7754ae73272875acbae360fc7`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59],[]],"0d8863d033ed867b9e5410fbf5653fff5668cde5bc9933efdc54a948ef28b3a7":[`agent-version-1`,`0ac0c6eca2bd401dba88942343f73a31b0c1fa320b4ef72672a421775667f341`,[0,2,3,4,5,6,60,61,9,10,62,63,13,14,64,16,65,18,19,20,21,23,26,66,28,29,67,68,32,33,69,35,37,38,40,41,42,43,44,45,46,48,70,50,51,52,53,54,55,71,72,73,59],[]],"987c7895f0acfaa27bdd4af5532a6a9d7364cbbefe8fe63fa9775b9520b25f85":[`agent-version-18`,`516c6a0cbc9a63134e84a65c3af806fbc6b526292c614c84109f4a2b2c106afc`,[0,2,3,4,5,6,60,61,9,10,62,63,13,14,64,16,65,18,19,20,21,23,26,66,28,29,67,31,32,33,69,35,37,38,40,41,42,43,44,45,46,48,70,50,51,52,53,54,55,71,72,73,59],[]],"7a92498057481f996a0c0716dd078ea69694645fbdb3a011dadaee411478b7ad":[`agent-version-21`,`fd83bd56e757e27046bc16f16e0dfd056a4bdb4c187672807f9286089fd4c130`,[0,2,3,4,5,6,60,61,9,10,62,63,13,14,64,16,65,18,19,20,21,22,23,26,66,74,29,75,31,32,33,69,35,37,38,40,41,42,43,44,45,46,48,76,50,51,52,53,54,55,71,72,73,59],[]],"789a67b22bc47d0b58acb19a6041b3ba55bd68c7e7271a4043573739edae02d1":[`agent-version-22`,`1571750d60d036d5b09e53c9d062396551d72f79642ee52ae104e9213da8592c`,[0,2,3,4,5,6,60,61,9,10,62,63,13,14,64,16,65,18,19,20,21,22,23,26,66,74,29,75,31,32,33,69,35,37,38,40,41,42,43,44,45,46,77,78,76,50,51,52,53,54,55,71,72,73,59],[]],dd91f9df477a6b80f156003269b951f0d4e55d62e6dec37ad23dc909ed61f71f:[`agent-version-23`,`4cd5cf45ce55fd199d3025021381ad10187c3a5db5340aec56aa108c5a315611`,[0,2,3,4,5,6,60,61,9,10,11,63,13,14,79,16,65,18,19,20,21,22,23,26,66,74,29,75,31,32,33,69,35,37,38,40,41,42,43,44,45,46,47,48,76,50,51,52,53,54,55,71,72,80,59],[]],"9b51fb6f3b7692ed5b1d114c9123184aacb35d5c8450f896b5d289fd46f0ae60":[`agent-version-24`,`7ba969c7ed61eb3596c809150d7c46676bfb3d8310052ca5f07141762b345e9b`,[0,2,3,4,5,6,60,61,9,10,11,63,13,14,79,16,65,18,19,20,21,22,23,25,26,66,74,29,81,31,32,33,69,35,37,38,40,41,42,43,44,45,46,47,48,76,50,51,52,53,54,55,71,72,80,59],[]],"17cbb50319db12e22248e0397cb068ce670687a96328f502ce3577e4798ae299":[`agent-version-25`,`f4118fc6b09e2d36542335eec66c82e9846b7f50e69e56076814dea6e1244aeb`,[0,2,3,4,5,6,60,61,9,10,11,63,13,14,79,16,65,18,19,20,21,22,23,25,26,66,28,29,82,31,32,33,69,35,37,38,40,41,42,43,44,45,46,47,48,70,50,51,52,53,54,55,71,72,80,59],[]],ff21eb3fb5a5836d520af3ea0777944cbcfa61aff52a64d0726a4d6b527823c3:[`agent-version-26`,`86dbc086643d83045d9397da12e5e7a5d197b08a10a8aea4942ee7473f03d9ee`,[0,2,3,4,5,6,83,61,9,10,11,63,13,14,79,16,65,18,19,20,21,22,23,25,26,66,28,29,84,31,32,33,69,35,37,38,40,41,42,43,44,45,46,47,48,70,50,51,52,53,54,55,71,72,85,59],[]],"227fcd299f5dfd3012abd0f110cd028ba6add9155bc74e2e558aadeae2761349":[`agent-version-27`,`40d0b84e2467b65ff57c4e8171af1a6b0cc54e0e1b5602b6abbe53fc8c10e151`,[0,2,3,4,5,6,7,61,9,10,11,63,13,14,79,16,65,18,19,20,21,22,23,25,26,66,28,29,84,31,32,33,69,35,37,38,40,41,42,43,44,45,46,47,48,70,50,51,52,53,54,55,71,72,85,59],[]],b2e17ebad450773253e5dddaeb87e6baef26b1c20a48982ed9df7ffea4210511:[`agent-version-28`,`a48c6c4d7bc63bb0c14eb2010893f31aa216e4a0ee135e40c81598a39c64b61f`,[0,2,3,4,5,6,7,61,9,10,11,12,13,14,79,16,65,18,19,20,21,22,23,25,26,66,28,29,84,31,32,33,69,35,37,38,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,71,57,85,59],[]],abf65b8c18ccb84f0e65b8e4faa6fef6abc23b6bab5e93086339f640d2146082:[`agent-version-29`,`ede47c9558c7c22dfd89ed56f0bc28a9d22e512aa69af0ae3acacc989337dc0e`,[0,2,3,4,5,6,7,61,9,10,11,12,13,14,79,16,65,18,19,20,21,22,23,25,26,66,28,29,30,31,32,33,34,35,37,38,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,71,57,85,59],[]],dbab54723ad6be5e0146085df0789ef92d03b867c53bed915d804fb4c60b3068:[`agent-version-30`,`afa4044fdeabdb3042002c27a39be73d1f2edf8c4135515266cf6613adc7f0ba`,[0,2,3,4,5,6,7,61,9,10,11,12,13,14,79,16,65,18,19,20,21,22,23,25,26,66,28,29,30,31,32,33,34,35,37,38,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,85,59],[]],"57f4523156caf6b8446afbd95e0fede01f1c917771242cd05c61c1b48b7e157e":[`agent-version-31`,`4ac0d88399760668d6021213299ff6897bcfd672d2373d5c47b6f0afa31e04a1`,[0,2,3,4,5,6,7,61,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,25,26,66,28,29,30,31,32,33,34,35,37,38,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,85,59],[]],"9ffa671518cafee606f88dd17bfdfa9792d9deece5f6773e3cae4de2c10fc84b":[`agent-version-37`,`08f828422ad38a4ad92a46abdd793fd45ce6c9e09e72d83177130079588ea41e`,[0,2,3,4,5,6,7,61,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,25,26,66,28,29,30,31,32,33,34,35,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,85,59],[]],a67326c9ddb50583c3b76b9854324d6a42a4d94b87b6aa2285cefb42a9ff1f27:[`agent-version-39`,`4a73468ea8dc4b374449c5a8455df0b5b161d9028d4e8a925763d6805dee8664`,[0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,25,26,27,28,29,30,31,32,33,34,35,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59],[]],"4000b93c887a95d954a139e5d78b74e06586e65f8e9dda9d8ffab73b61ee5568":[`agent-version-40`,`d84ecca0d1e44048fac7058389b356bb26e83c05c99631f5f2cbf5d442cf04f4`,[0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59],[]],"91916d079ab20e9e5fd2380d0ec99561d144fed2d0eeca7324d370f295a7205a":[`agent-version-41`,`6b80dff64cad8216687329ec4a9685348b511986ca622623406f44a8164b118b`,[0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59],[]],"067f95cffb76737d9084b726b640bc79b266b19279e6b1a3d2322d0e298c6ab6":[`agent-v14-core`,`14b30834a4c01ee92da4b3390aebbd49d9a8f4d0fb3a40fb517b8093ffb11c76`,[0,2,3,6,60,61,9,10,62,63,13,14,64,16,65,18,19,20,21,23,26,66,28,67,68,32,37,38,40,41,42,43,44,45,46,48,70,50,51,52,53,54,55,71,72,73,59],[]],aca181a3ea4d5a94d263653e1b75d2327bd449673d631e9d22c6cb9fe25e40ea:[`agent-v14-session-sharing`,`dcd6c30e5c80fa6647cf4b3257fc0c5a6e3440c20333797263b813add4f43fa2`,[29],[]],be5d39d4389597fcfe2942f51a97d5b1f4e0aa1d6b184677e6abcedc162a2cf0:[`agent-v14-additive`,`08e596f53eef1390bb3048a8c3807ea2413fde157899e0feb314aeebeb26e132`,[69,35],[]],"9b07b30dc725415736f5873babff2b98a1e8bf40e0afbf4eb8cf3d3cf700dc0b":[`agent-v14-board`,`535e952ff0024800a42260733be4f1ab5095d5f7578d78555e351c3c336b4f5a`,[4,5],[]],"83673559dc6bba9fdf13d5a9131b030103935b04d7c81620b0a67f43cb49f970":[`agent-progress-card`,`cbda56cf07f5a79268f761f3c0478fd5c3a6ddefde2cb72a933d9eef110a17a1`,[33],[]],fdc21b6dc361c491311c11d91fbda296535a9c34dd20f0ab03b949b8a698ded0:[`agent-retired-state-leases`,`6117e088b6b48fe1007de8ef29868981f820404cc3be99040c2bcd899902b7cc`,[86],[]],c45b82b3c3aa8ecc3b2cc09dcf38bd568edfa8305f54b5bb959c975a55571ece:[`agent-legacy-participants`,`30851780a54c5bd9b7bd3be1f420fc2b3e61839901e1a726e6cb24a10f8d4276`,[68],[]],"6ce6f0ae658b1b77759d335e07e75d9371e27363c998bbf9b0e5fc5a132bc4cb":[`agent-deployed-fts-rows`,`81df0b00eeb5ae756a6acce81b099c432f6127233d47582dd60ca32eed304768`,[77],[]],"0e9e5f47efa71d187ed505aee8d1e423865a5de8df5387a15759194561307e72":[`agent-legacy-transcript-events`,`6e5d060cc60439ef893bf9bcf395552be213733a1021f82d9ea1173e6103ed2e`,[73],[]]};let Xc;function readSqliteAgentFingerprint(e){let t=Yc[e];if(!t)return;let[n,r,i,a]=t;return{id:n,fingerprint:r,viewNames:a,tableNames:i.map(e=>Jc[e][0]),indexNames:i.flatMap(e=>Jc[e][1])}}function readSqliteAgentCatalog(e){if(!Yc[e])return;Xc??=Rs(import.meta.url)(oc(new URL(`../../assets/sqlite-schema/sqlite-agent-catalogs.json`,import.meta.url).href));let t=Xc.catalogs[e];return{tables:t.tables.map(e=>Xc.tables[e]),views:t.views}}const Zc=[[`client_credential_migration`,[]],[`device_auth_tokens`,[`idx_device_auth_tokens_updated`]],[`device_identities`,[`idx_device_identities_device`]],[`gateway_origin_device_tokens`,[]],[`native_exec_socket_credentials`,[]]],Qc={"8e4004e9307fcb7ad18d0b12c076f008afd89a8dcacff53e9d40a3b7881acab9":[`client-credentials-v1`,`a00fccb1a356c0d0f77c40341f320602e4f73396bd88865a238b7f4187edd949`,[0,1,2,3,4],[]]};let $c;function readSqliteClientFingerprint(e){let t=Qc[e];if(!t)return;let[n,r,i,a]=t;return{id:n,fingerprint:r,viewNames:a,tableNames:i.map(e=>Zc[e][0]),indexNames:i.flatMap(e=>Zc[e][1])}}function readSqliteClientCatalog(e){if(!Qc[e])return;$c??=Rs(import.meta.url)(oc(new URL(`../../assets/sqlite-schema/sqlite-client-catalogs.json`,import.meta.url).href));let t=$c.catalogs[e];return{tables:t.tables.map(e=>$c.tables[e]),views:t.views}}const el=[[`daemon_runtime_pin_migration`,[]],[`daemon_runtime_pins`,[]]],tl={"2da8e5914c65eb868e035a1ebbab7a104fceca3c4b4c1e44dccd14c3387c3376":[`daemon-runtime-pins-v1`,`126cb31aa1921bcac9c54618fdbb59cc157d4d86a456508eea2879db32a716e0`,[0,1],[]]};let nl;function readSqliteDaemonFingerprint(e){let t=tl[e];if(!t)return;let[n,r,i,a]=t;return{id:n,fingerprint:r,viewNames:a,tableNames:i.map(e=>el[e][0]),indexNames:i.flatMap(e=>el[e][1])}}function readSqliteDaemonCatalog(e){if(!tl[e])return;nl??=Rs(import.meta.url)(oc(new URL(`../../assets/sqlite-schema/sqlite-daemon-catalogs.json`,import.meta.url).href));let t=nl.catalogs[e];return{tables:t.tables.map(e=>nl.tables[e]),views:t.views}}const rl=[[`memory_index_chunk_provenance`,[]],[`memory_index_chunk_recall_metadata`,[]],[`memory_index_chunks`,[]],[`memory_index_meta`,[]],[`memory_index_sources`,[]],[`memory_index_state`,[]],[`memory_embedding_cache`,[]],[`memory_embedding_cache`,[`idx_memory_embedding_cache_updated_at`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_embedding_cache`,[`idx_memory_embedding_cache_updated_at`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_embedding_cache`,[`idx_memory_embedding_cache_updated_at`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks`,[`idx_memory_index_chunks_path`,`idx_memory_index_chunks_path_source`,`idx_memory_index_chunks_source`]],[`memory_index_chunks_fts`,[]],[`memory_index_chunks_fts_config`,[]],[`memory_index_chunks_fts_content`,[]],[`memory_index_chunks_fts_data`,[]],[`memory_index_chunks_fts_docsize`,[]],[`memory_index_chunks_fts_idx`,[]],[`memory_index_paths_fts`,[]],[`memory_index_paths_fts_config`,[]],[`memory_index_paths_fts_content`,[]],[`memory_index_paths_fts_data`,[]],[`memory_index_paths_fts_docsize`,[]],[`memory_index_paths_fts_idx`,[]],[`memory_index_chunks_fts`,[]],[`memory_index_paths_fts`,[]],[`memory_index_chunks_vec`,[]],[`memory_index_chunks_vec_chunks`,[]],[`memory_index_chunks_vec_info`,[]],[`memory_index_chunks_vec_rowids`,[]],[`memory_index_chunks_vec_vector_chunks00`,[]]],il={"27ef93ea7e9facb77b3eead587fd5cb7647bade7c4a0dbc8b03c8f34ba64386c":[`memory-index-v1-cache-0`,`59289b93110d1d3eaf27f0e6d5bef8bc45987a70842597a67302ace145717ec9`,[0,1,2,3,4,5],[]],"93a3fb3dfbcf93f896dd17b298be4c18d2b6d6ee8ab14e46872ecbeadd557654":[`memory-index-v1-cache-1`,`a2cc43111506fdc355121bec101f93d7035cdd20d870dfc5fc5c75ce36eddee8`,[6,0,1,2,3,4,5],[]],b53e7fcdaab29e825534bce175eef96cff2c705bc465308f369f67627a5b53bb:[`memory-cache-binary-strict-1`,`43fea47c3ea00e8ff457540564e0915cb72e75b8f14b119ece1bd74746425ff8`,[7],[]],ac226e0f177ccc01aa1d3df066f10277676100bd8cd01588b860c5d89e8e2269:[`memory-chunks-binary-strict-1-recall-0`,`0e8704d882f34e24b97613115d6552258400608839065e8da56df4b336cfca51`,[8],[]],"257f0fa39f94ca852ed0887002bd286e34727ff73b4825ac5b53cafcb174f453":[`memory-chunks-binary-strict-1-recall-1`,`ed5c454b17073742bf3343b99baec45c854a0927ccd95ab1131ec6856ef08d60`,[9],[]],de46110eea2bb88cd753b7c0efa7aa1becddcb90b1a4b5c9502d5acc41d50939:[`memory-chunks-binary-strict-1-recall-2`,`7c8785c42572cc6669a29704d2079f13a47479484250495898dc3b82e2b8f169`,[10],[]],cc79633111488622f8cf8d50157280d4f9ce002ddf8b731ea7bfce3c1acbc7e9:[`memory-chunks-binary-strict-1-recall-3`,`37b37df7f7ec34ba7fb38ea652c85d9db954b648b3b8b0f2cee1136ace8c4d52`,[11],[]],b12e9eee6fc308eb0d125008d0f4a8a6a7921f87cb0ad03c0dcbabc0f4c9e30b:[`memory-chunks-binary-strict-1-recall-4`,`ded3749dc75f0b9853570d3a29f52e3296835f164d7c7e1471a368e2d79523d3`,[12],[]],b74546436177f3480bbfd0ca7d6f7558e50671a41041aa3b02a4a1d70d4e0124:[`memory-chunks-binary-strict-1-recall-5`,`596ee273523cdc7922a0718a926cff468a4e740a8c653a3e0bebe601037eee7f`,[13],[]],"7b8739ff03a7dabf85ff3846c7cb172a402613024754e064cfd775441b037d2e":[`memory-chunks-binary-strict-1-recall-6`,`126e55c1ce40d42ccb97cdf3f4e35497cf712948f36d794dca163e6a8e0559c4`,[14],[]],"6055ec94ab523719e18078aee8fa973f92d8ba968ecb104f0d61bee314739152":[`memory-chunks-binary-strict-1-recall-7`,`05b66c0fd58af7228e74cb7e881a9ddfe4bc77445ae6215ebf1c38463155d430`,[15],[]],f8f4dda5eccd6ef9b6e82a2187a7dfad76ae3783a0fcfe9623eadc18eecf44b0:[`memory-cache-text-strict-0`,`ca38a58fc93a8fb71370dae23cb0ef9b9d7376b6d48b0cef0b28a1bd9433e8fe`,[16],[]],b9b96c68cff42faadc99ad35ff55d2df4e432e87adf8d5d512c4f2d8e01477e6:[`memory-chunks-text-strict-0-recall-0`,`f62e05b1dac229e56f6bd08d3115e2ea93aec01aa558b17d94ea5bc47cc76cc4`,[17],[]],"572644cd115904fabec76e50a6d81b73b5a738b11e879a1c07bc7f83b12fac8f":[`memory-chunks-text-strict-0-recall-1`,`557db378be09c17e06988bb635f5c1eeac94a0780251f379ca0636c6f955befd`,[18],[]],dc69ef337a630e1c40398b494826d3ef6d8ca67e8a42d5f5b40142cd00e51012:[`memory-chunks-text-strict-0-recall-2`,`f6dea371a0755a537b45176e3219b0fb5123d9bda94527e1e967a63ff1678cfa`,[19],[]],d3e0bbf0a82ae4ca0ae435e0a9943fa32a48ac8d37421809d9fd36d4c0680b13:[`memory-chunks-text-strict-0-recall-3`,`60c4185a64288b050f8ddc89727ff13a6103baeda976c67c791e3c7f7b3e6c95`,[20],[]],f1dbb03304f512a8a7a0e1606d23e7ff1c97223599d3a889850ad0ed69299af3:[`memory-chunks-text-strict-0-recall-4`,`f0061cf0170bf18527093f950d0496fd4601058bc99e9c29dafd6b305dd87296`,[21],[]],"454eb2147f9c1adc93e9210a7aabc5c1fc6a4f937f9e712d632f1b7c76b28b7c":[`memory-chunks-text-strict-0-recall-5`,`2f9c2c14d4995f96d632ba23438b90a607c6345080b59c06fa6fe18fbc1ef789`,[22],[]],"2b12ceffe3ff69a67629d2e195143f53fe0d7f947108f4ee7ce068fa7b288dcf":[`memory-chunks-text-strict-0-recall-6`,`9e7d3aa7fbfd911601a9c372bca6099062bef2a24e26a5d08c21db34abb3e937`,[23],[]],"39602ef462e71c3c485358a1572c7c3f82cda5fe147dbbca5ecf601f72009238":[`memory-chunks-text-strict-0-recall-7`,`5764f18a476a4e6a6aa6f40f9538ac70e10fe5344309dd245d0db339913fbc5d`,[24],[]],"16de82c2873083fc417acc8e09140fd32cbdfb1a6633a82e8746cfe9650c18db":[`memory-cache-text-strict-1`,`aacfccd3fbb3a171753d866a2dbcac2e6ab0cf26d94fa2fa8bd17f7b555c8857`,[25],[]],"50709191e29c47d2702efd82ba0b62cdd7f1b027d532848c2cb08c77b69fa679":[`memory-chunks-text-strict-1-recall-0`,`3477ae66bf655ea65812a5e2dcedeae255314ba79214740c03c2a7fab99e1daa`,[26],[]],bbc96ed43fce73bc3051d0c510bdc3fbfec16c6dd4fa557bd349ac7b60d325f7:[`memory-chunks-text-strict-1-recall-1`,`c672e90a018dba96b0d27706a9aeacc809781009464fcb767a9c4304ae6494b0`,[27],[]],"14b7b7910dc0afdcc0bdd78b889d487bd4281ba57342ba21fbc17e2ac4ab7a5c":[`memory-chunks-text-strict-1-recall-2`,`6070f3ccf01a8815f7cb924aff58ce3ec1a215cb01782915a93b6dc2c334991d`,[28],[]],"671a11689fc7970d79b4be242cf747d6831e32ae4adf3d0cde360d0c43427e2c":[`memory-chunks-text-strict-1-recall-3`,`455f88a45ca48ac0a6a4233d483731d0b0960d2d3610db7f298c39da1c568ae4`,[29],[]],"11a2dca1aa8a69e4db87d79208841dff4abd20d943a3910afc8cc80d92912e9a":[`memory-chunks-text-strict-1-recall-4`,`abcc7d9bd0fb27f1b592b729a59c6a81fbd352917b0996f472ea42bac6dfeef2`,[30],[]],cb98ad487e0d9599983c000d5bdf096ee1f323b982e4afc44229111e5aef2cd1:[`memory-chunks-text-strict-1-recall-5`,`cb12b76fbe6f986bd1f4e7f727731515068c6a6b83d8fb0def4d041f404830c5`,[31],[]],"4a5393a69f56db40e0ada5dc8577a88c91c44f65900e234d46d487d0b5294781":[`memory-chunks-text-strict-1-recall-6`,`64fbd15911fb40635818b4f3397e0749b0b62b92b87fc6c0d067079125ce8f8a`,[32],[]],"05e8eaf13a81810f99cc62d7d25a202c115743c80ebd80c625a0beab0960b892":[`memory-chunks-text-strict-1-recall-7`,`8422ba9c6185a2156a9345807b90032db6858b2f5a12541268d9f4c7967d32e9`,[33],[]],"0ab7773eb3198fc86adb541fe032581ce24b93cd39b7aa229fdf50c8b3f9fe6c":[`memory-body-fts-v1-unicode61`,`c16bed5072a5a006ca243b73fefb1fc86bce894f87a6c8713e87dced77493eb2`,[34,35,36,37,38,39],[]],"315cb6d0263f5aff152863d03d253f867104d86d5028ad2c51e348d10fba2f1a":[`memory-path-fts-v1-unicode61`,`b18b06cf6a1ea0655eeff9c0451fae13336f2ac280468680e7d91370016cf23b`,[40,41,42,43,44,45],[]],"32a102b66f747e2fb75d4b23b2a83928c69d086604e997a29a713eac7a62ec46":[`memory-body-fts-v1-trigram`,`15c47771111fc5beb3af779b2f20333755c0069b7bb113ac6aac160f6aabef7f`,[46,35,36,37,38,39],[]],"02ae4f88ed6c87a22d6eaeb0e4e0a4ececc8d7dd37017aa04659494fd8481ccd":[`memory-path-fts-v1-trigram`,`e2b47e11cf4fa6228471d8f6be5654a6d35ec80d5e0c9e7fd5d6654f47ac200e`,[47,41,42,43,44,45],[]],"8a70e5b7bb1c8163cf6d4f38a6a69165a01f3f44204bbd910428f371ebc376c7":[`memory-vector-v1`,`ebe6798602214794cd87d21d200eaa88c4864fcb30bf8fc0b902246a7fce5023`,[48,49,50,51,52],[]]};let al;function readSqliteMemoryFingerprint(e){let t=il[e];if(!t)return;let[n,r,i,a]=t;return{id:n,fingerprint:r,viewNames:a,tableNames:i.map(e=>rl[e][0]),indexNames:i.flatMap(e=>rl[e][1])}}function readSqliteMemoryCatalog(e){if(!il[e])return;al??=Rs(import.meta.url)(oc(new URL(`../../assets/sqlite-schema/sqlite-memory-catalogs.json`,import.meta.url).href));let t=al.catalogs[e];return{tables:t.tables.map(e=>al.tables[e]),views:t.views}}const ol=[[`acp_replay_events`,[]],[`acp_replay_sessions`,[`idx_acp_replay_sessions_key_updated`,`idx_acp_replay_sessions_updated`]],[`acp_sessions`,[`idx_acp_sessions_agent_activity`,`idx_acp_sessions_resume_acpx`,`idx_acp_sessions_resume_agent`,`idx_acp_sessions_state_activity`]],[`agent_database_leases`,[]],[`agent_databases`,[]],[`agent_deletion_journal`,[]],[`agent_provenance`,[]],[`apns_registration_tombstones`,[]],[`apns_registrations`,[`idx_apns_registrations_updated`]],[`audit_events`,[`idx_audit_events_agent_sequence`,`idx_audit_events_channel_sequence`,`idx_audit_events_direction_sequence`,`idx_audit_events_kind_sequence`,`idx_audit_events_run_sequence`,`idx_audit_events_session_sequence`,`idx_audit_events_status_sequence`,`idx_audit_events_time`]],[`audit_identity_keys`,[]],[`backup_runs`,[`idx_backup_runs_created`]],[`capture_blobs`,[]],[`capture_events`,[`capture_events_flow_idx`,`capture_events_session_ts_idx`]],[`capture_sessions`,[]],[`channel_ingress_events`,[`idx_channel_ingress_claims`,`idx_channel_ingress_lane`,`idx_channel_ingress_pending`]],[`channel_pairing_allow_entries`,[`idx_channel_pairing_allow_account`]],[`channel_pairing_requests`,[`idx_channel_pairing_requests_code`,`idx_channel_pairing_requests_created`]],[`clawhub_promotion_claims`,[]],[`config_health_entries`,[]],[`config_machine_state`,[]],[`config_revision_keys`,[]],[`cron_job_runtime_authorities`,[]],[`cron_job_scratch`,[`idx_cron_job_scratch_store_updated`]],[`cron_jobs`,[`idx_cron_jobs_store_order`]],[`cron_run_receipts`,[`cron_run_receipts_cursor_id_idx`,`idx_cron_run_receipts_active_job`,`idx_cron_run_receipts_job_history`]],[`cron_run_trigger_state_retirements`,[]],[`current_conversation_bindings`,[`idx_current_conversation_bindings_conversation`,`idx_current_conversation_bindings_expires`,`idx_current_conversation_bindings_target`]],[`delivery_queue_entries`,[`idx_delivery_queue_bounded_retention`,`idx_delivery_queue_failed`,`idx_delivery_queue_pending`,`idx_delivery_queue_session`,`idx_delivery_queue_target`]],[`device_bootstrap_tokens`,[`idx_device_bootstrap_tokens_ts`]],[`device_pair_setup_completions`,[]],[`device_pairing_browser_requests`,[]],[`device_pairing_join_codes`,[]],[`device_pairing_paired`,[`idx_device_pairing_paired_approved`]],[`device_pairing_pending`,[`idx_device_pairing_pending_device`]],[`diagnostic_events`,[`idx_diagnostic_events_scope_sequence`]],[`durable_background_processes`,[]],[`exec_approvals_config`,[]],[`execution_decision_facts`,[`execution_decision_facts_context_occurred_idx`,`execution_decision_facts_cursor_id_idx`,`execution_decision_facts_run_occurred_idx`]],[`execution_identity_contexts`,[`execution_identity_contexts_run_created_idx`]],[`execution_owner_lifecycle_bindings`,[]],[`flow_runs`,[`idx_flow_runs_owner_key`,`idx_flow_runs_status`,`idx_flow_runs_updated_at`]],[`gateway_boot_lifecycle`,[`idx_gateway_boot_lifecycle_started`]],[`gateway_restart_handoff`,[`idx_gateway_restart_handoff_expiry`]],[`gateway_restart_intent`,[]],[`gateway_restart_sentinel`,[`idx_gateway_restart_sentinel_ts`]],[`github_personal_publication_requests`,[`idx_github_personal_publication_owner_session`,`idx_github_personal_publication_pending`]],[`github_publication_requests`,[`idx_github_publication_requests_pending`]],[`github_publication_session_lifecycles`,[]],[`github_repository_publication_requests`,[`idx_github_repository_publication_personal_request`,`idx_github_repository_publication_shared_request`]],[`local_workspace_manifest_nodes`,[]],[`local_workspace_projections`,[]],[`local_workspace_source_path_sets`,[]],[`local_workspace_tree_packs`,[]],[`macos_port_guardian_records`,[`idx_macos_port_guardian_records_port`]],[`managed_outgoing_image_records`,[`idx_managed_outgoing_images_agent_message`,`idx_managed_outgoing_images_agent_session`,`idx_managed_outgoing_images_message`,`idx_managed_outgoing_images_session`]],[`mcp_oauth_pending_authorizations`,[]],[`mcp_oauth_stores`,[]],[`meeting_transcript_sessions`,[`idx_meeting_transcript_sessions_account`,`idx_meeting_transcript_sessions_agent`,`idx_meeting_transcript_sessions_chronology`,`idx_meeting_transcript_sessions_export_key`,`idx_meeting_transcript_sessions_id`,`idx_meeting_transcript_sessions_slug`,`idx_meeting_transcript_sessions_source`,`idx_meeting_transcript_sessions_started`]],[`meeting_transcript_summaries`,[]],[`meeting_transcript_utterances`,[`idx_meeting_transcript_utterances_id`]],[`migration_runs`,[`idx_migration_runs_started`]],[`migration_sources`,[`idx_migration_sources_path`,`idx_migration_sources_run`]],[`native_hook_relay_bridges`,[`idx_native_hook_relay_bridges_expires`]],[`node_worker_launch_boots`,[]],[`node_worker_launch_cleanup`,[]],[`node_worker_launch_containers`,[]],[`node_worker_launch_process_scopes`,[]],[`node_worker_launches`,[`idx_node_worker_launches_terminal_completed`]],[`node_worker_prepared_workspaces`,[]],[`node_worker_turns`,[`idx_node_worker_turns_active_owner`,`idx_node_worker_turns_terminal_completed`]],[`official_external_plugin_catalog_snapshots`,[`idx_official_external_plugin_catalog_snapshots_updated`]],[`operator_approval_execution_identities`,[]],[`operator_approval_standing_grant_generations`,[]],[`operator_approval_standing_grants`,[`idx_operator_approval_standing_grants_binding`]],[`operator_approvals`,[`idx_operator_approvals_cursor_id`,`idx_operator_approvals_resolution_ref`,`idx_operator_approvals_resolved`,`idx_operator_approvals_runtime_pending`,`idx_operator_approvals_source_run_resolved`,`idx_operator_approvals_source_session_created`,`idx_operator_approvals_status_expiry`]],[`outbound_media_provenance`,[]],[`outbound_message_execution_bindings`,[`outbound_message_execution_bindings_execution_event_idx`]],[`outbound_message_progress`,[`outbound_message_progress_occurred_idx`,`outbound_message_progress_run_occurred_idx`]],[`plugin_binding_approvals`,[`idx_plugin_binding_approvals_plugin`]],[`plugin_blob_entries`,[`idx_plugin_blob_expiry`,`idx_plugin_blob_listing`]],[`plugin_state_entries`,[`idx_plugin_state_expiry`,`idx_plugin_state_listing`]],[`projects`,[]],[`sandbox_persistent_execs`,[`idx_sandbox_persistent_execs_container`,`idx_sandbox_persistent_execs_container_name`,`idx_sandbox_persistent_execs_source`]],[`sandbox_registry_entries`,[`idx_sandbox_registry_last_used`,`idx_sandbox_registry_session`,`idx_sandbox_registry_updated`]],[`schema_meta`,[]],[`secret_store_entries`,[`secret_store_entries_live_idx`]],[`session_groups`,[]],[`session_repository_workspaces`,[]],[`session_state_events`,[`idx_session_state_events_session_sequence`,`idx_session_state_events_time`]],[`session_state_heads`,[]],[`session_upstream_links`,[`idx_session_upstream_links_catalog_id`]],[`session_watch_cursors`,[`idx_session_watch_cursors_target`]],[`skill_library_entries`,[]],[`skill_library_events`,[]],[`skill_library_revisions`,[]],[`skill_library_uploads`,[]],[`skill_upload_chunks`,[]],[`skill_uploads`,[`idx_skill_uploads_expiry`,`idx_skill_uploads_idempotency`]],[`skill_usage`,[]],[`skill_workshop_changes`,[`idx_skill_workshop_changes_agent_time`,`skill_workshop_changes_cursor_id_idx`]],[`state_leases`,[`idx_state_leases_expiry`,`idx_state_leases_owner`]],[`subagent_runs`,[`idx_subagent_runs_child_session_key`,`idx_subagent_runs_controller_session_key`,`idx_subagent_runs_requester_session_key`]],[`task_delivery_state`,[]],[`task_runs`,[`idx_task_runs_cron_runtime_order`,`idx_task_runs_cron_source_order`,`idx_task_runs_runtime_run`]],[`template_cron_refs`,[]],[`template_installs`,[]],[`template_mcp_server_refs`,[]],[`template_package_refs`,[]],[`template_workspace_files`,[]],[`update_runs`,[`idx_update_runs_active`,`idx_update_runs_created`]],[`user_background_images`,[]],[`user_preferences`,[]],[`user_profile_identities`,[`idx_user_profile_identities_authorization`,`idx_user_profile_identities_profile_id`]],[`web_push_approval_deliveries`,[`idx_web_push_approval_deliveries_subscription`]],[`web_push_subscriptions`,[`idx_web_push_subscriptions_updated`]],[`worker_environment_credentials`,[]],[`worker_environment_ssh_fallback_ports`,[]],[`worker_environments`,[`idx_worker_environments_provider_lease`,`idx_worker_environments_terminal_changed`]],[`worker_inference_turns`,[`idx_worker_inference_turns_pending_run`]],[`worker_session_placement_moves`,[]],[`worker_session_placements`,[`idx_worker_session_placements_environment`,`idx_worker_session_placements_reconcile`,`idx_worker_session_placements_session_key`]],[`worker_session_tool_operations`,[]],[`worker_transcript_commit_heads`,[]],[`worker_transcript_commits`,[]],[`worker_turn_tool_authorities`,[]],[`worker_workspace_pending_results`,[]],[`worker_workspace_reconciliations`,[]],[`workspace_generated_bootstrap_hashes`,[]],[`workspace_path_aliases`,[`idx_workspace_path_aliases_workspace`]],[`workspace_setup_state`,[`idx_workspace_setup_state_path`]],[`worktree_provisioned_file_chunks`,[]],[`worktree_templates`,[]],[`worktrees`,[`idx_worktrees_removed_at`,`idx_worktrees_repo_fingerprint`]],[`worker_environments`,[`idx_worker_environments_provider_lease`,`idx_worker_environments_terminal_changed`]],[`workspace_setup_state`,[`idx_workspace_setup_state_path`]],[`worker_environments`,[`idx_worker_environments_provider_lease`,`idx_worker_environments_terminal_changed`]],[`session_repository_workspaces`,[]],[`worker_workspace_pending_results`,[]],[`worker_environments`,[`idx_worker_environments_provider_lease`,`idx_worker_environments_terminal_changed`]],[`agent_provenance`,[]],[`claw_cron_refs`,[]],[`claw_installs`,[]],[`claw_mcp_server_refs`,[]],[`claw_package_refs`,[]],[`claw_workspace_files`,[]],[`local_workspace_projections`,[]],[`local_workspace_projections`,[]],[`acp_replay_events`,[`idx_acp_replay_events_session_seq`]],[`skill_usage`,[`idx_skill_usage_key`]],[`state_leases`,[`idx_state_leases_expiry`,`idx_state_leases_owner`]],[`session_state_heads`,[]],[`user_profile_emails`,[`idx_user_profile_emails_profile_id`]],[`user_profiles`,[]],[`user_profile_identities`,[]],[`user_profile_emails`,[]],[`worker_environment_session_attachments`,[`worker_environment_session_attachments_session_key`]],[`sandbox_persistent_execs`,[]],[`update_runs`,[]],[`github_repository_publication_requests`,[]],[`github_personal_publication_requests`,[]],[`execution_identity_contexts`,[]],[`node_worker_launches`,[]],[`node_worker_turns`,[]],[`web_push_approval_deliveries`,[]],[`execution_decision_facts`,[]],[`outbound_message_execution_bindings`,[]],[`outbound_message_progress`,[]],[`cron_run_receipts`,[]],[`secret_store_entries`,[]],[`github_publication_requests`,[]],[`skill_workshop_changes`,[]],[`state_leases`,[]],[`migration_runs`,[]],[`commitments`,[`idx_commitments_agent_due`,`idx_commitments_agent_sent`,`idx_commitments_scope_dedupe`,`idx_commitments_scope_due`,`idx_commitments_status_due`]],[`commitments`,[`idx_commitments_scope_dedupe`,`idx_commitments_scope_due`,`idx_commitments_status_due`]]],sl={fcbb00212b86de19fc5fa0f04654883e4714871ea6417f63645a97c1c9e9457f:[`state`,`685cc87a6a367954ee95acecd4646d346e35f2b1048e55de7b66d4dc700f1e5b`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133],[]],"1afe9a93ab5ff5ecdd8a5ef89f60ed9cf1246b4ffb6dd3b31bd782ca5e44ab9d":[`state-before-v40`,`716519c2f5c5484e7061362cd55dc40f25c44fc55598446763c74152b11e4fc6`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,134,119,120,121,122,123,124,125,126,127,128,129,135,131,132,133],[]],"20652e186439d870636fc9def6e16d67f0bc25efbc56bcbd190ab3711c594f0b":[`state-before-v39`,`5e03dab2bf0ab007cdf397cb1e498ff89deb3dbb1bb0429acbe9a45b6e22e509`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,136,119,120,121,122,123,124,125,126,127,128,129,135,131,132,133],[]],"6d3d5985c28174dffe934265721644dda70fb01ad73d03514d35e2ee70a97adc":[`state-before-v38`,`a06d8d965a4799d247b9237439e304fb41eb841ca4ab48c5f347e242e979daa4`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,137,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,136,119,120,121,122,123,124,125,138,127,128,129,135,131,132,133],[]],fe1706f4d38001b97405908240370830f5acfba944ab99d2aaf3b9f4d919424e:[`state-before-v37`,`02c02530dcbfa94282fc7513c2035c144e1da111c571bd677c3fad2feac6aaf5`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,137,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,139,119,120,121,122,123,124,125,138,127,128,129,135,131,132,133],[]],d0cd137b7efd6db59ab303c883f1f8dac6cb8b1f1acd8d8627ada7e06e394071:[`state-before-v36`,`220f897975cabddbbcb199e7cb86bc899e9edb48336439031012ce40d5766b9f`,[0,1,2,3,4,5,140,7,8,9,10,11,12,13,14,15,16,17,141,142,143,144,145,18,19,20,21,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,137,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,110,111,112,113,114,115,116,117,139,119,120,121,122,123,124,125,138,127,128,129,135,131,132,133],[]],"7ed795835c94f05c1ef977fc923efe5546e8ffdba490daf0830f187f1dfb1d80":[`state-before-v35`,`be6695458a7627c186add059bcf2639b5e9e9ddcd8dc53746b440f1ba77a5780`,[0,1,2,3,4,5,140,7,8,9,10,11,12,13,14,15,16,17,141,142,143,144,145,18,19,20,21,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,146,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,137,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,110,111,112,113,114,115,116,117,139,119,120,121,122,123,124,125,138,127,128,129,135,131,132,133],[]],a6d49bc647cab1d6e70a56501e06debe8568094726782bd2d2b9ab3efecadff6:[`state-before-v31`,`89d5364b8c63458f600bdc0b7b30e85eefbcdc71ba09a388dc475bb5ffd404be`,[0,1,2,3,4,5,140,7,8,9,10,11,12,13,14,15,16,17,141,142,143,144,145,18,19,20,21,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,147,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,137,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,110,111,112,113,114,115,116,117,139,119,120,121,122,123,124,125,138,127,128,129,135,131,132,133],[]],d1d0b50ac838dfa09897431b3e3f0f74bd5de636b7a17c7569422cc4e32d419c:[`state-before-v27`,`4d4752c9096151b2d9ac9f843259470d34109ec410b962b9203c5d5192f0abbe`,[148,1,2,3,4,5,140,7,8,9,10,11,12,13,14,15,16,17,141,142,143,144,145,18,19,20,21,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,147,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,137,89,90,91,92,93,94,95,96,97,98,149,100,150,102,103,104,110,111,112,113,114,115,116,117,139,119,120,121,122,123,124,125,138,127,128,129,135,131,132,133],[]],e31a36c4865b72d72a5f7ff8068639e5284f12abe8e58623cbe4bb6907c09c1d:[`state-before-v26`,`153fc4e2e4248b6fb0b9f0d1a936730da53b1ac5f80bfda2d5d4978382cf87ad`,[148,1,2,3,4,5,140,7,8,9,10,11,12,13,14,15,16,17,141,142,143,144,145,18,19,20,21,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,147,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,137,89,151,91,92,93,94,95,96,97,98,149,100,150,102,103,104,110,111,112,113,114,115,116,117,139,119,120,121,122,123,124,125,138,127,128,129,135,131,132,133],[]],f32dcffad8239a4de64de63074202b82a2a8b8671148ade2a5bf66a296a24c94:[`state-before-provision-source`,`65ab29899ed0d4d821be154749cbf12b3deb5fda9006742dcc8513fc24e8726e`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,134,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133],[]],"5bde97da769150d9e0cc19830a835a11599f82cf51c544e629e9d7f5f205b3d5":[`state-before-bootstrap-deferred`,`70b4fd11db71810de8ee5166356977770b88edce037b477b3795972a1af93209`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,134,119,120,121,122,123,124,125,126,127,128,129,135,131,132,133],[]],"54911300fd4efbb44a652d781badc61c60be05619fba7bd6a64b1d1bc2121a81":[`fragment-local_workspace_projections`,`39ab9e54cafe71df0cfcd6b83585693118657dd954cce42b24093e1c4779b497`,[50,51,52,53],[]],f0e11a6fff0a4b79b69a28a0f2ec4694fa1ee88672cac3b7338bc0a3bb9f8d19:[`state-feature-local_workspace_projections`,`39ab9e54cafe71df0cfcd6b83585693118657dd954cce42b24093e1c4779b497`,[50,51,52,53],[]],e119e5203e18e9fba13d43368408775eca1d809807579a697482ab2b7011e840:[`state-feature-local_workspace_manifest_nodes`,`8db5abfb2c2f4c380c80647305b1e4bb5e6af7ac2fec71205a52a97d86835291`,[50],[]],"3142caa54d9bd7d285b37ed3338ed9f4307ad3b32469bd88deecb8725301861e":[`state-feature-local_workspace_tree_packs`,`a63984593fd118417812466c9ee0c189fd7d819401af1943a6f9c11730c47d87`,[53],[]],e95059f2306c8231ee92ef3d76dfcb434a80885f08cbf39380f88a287f98bade:[`state-feature-local_workspace_source_path_sets`,`ead9623df4d41d649f8e4af2351694db5bc8c4e70edb7d2322ba76c11d0dfddb`,[52],[]],bc86e378ea153c42527b6106b01ba4cb8285cca40378ffa0142656577309723e:[`fragment-user_profiles`,`268e6f3b53eb2048a3edf527da424f8df229a01166befc8137ea94dbb560227e`,[152,113,153],[]],f5b54f0fedd88d94c24add8a1fd987ac8592b05d4615424bab9dbc0d19c9cd4a:[`state-feature-user_profiles`,`2c2611b7d0c64f467494ae3922f763dee7fc023a5ee6b92d5821639b18e825aa`,[152,154,153],[]],"9eaae0feb245733106045a2c6766d2a2a729a9bdb22b98ec4434c09d76663264":[`state-feature-user_profile_emails`,`202fadb0df4fc5da385edddbda27e96126d0d7a2db6a63375fa506221163a4fb`,[155],[]],"45451969c6ea5bebf37bbfba310467e482af74731a7cb0f2affb316059e21528":[`state-feature-user_profile_identities`,`3a24e89bd446dffbef50b7bd4b87288abc6eb470c290eaabcb1761fbe5244c06`,[154],[]],"561e14603e294368a12a2b5f6ecb0cc509d0b8847a93817286bd5a14d076ad0f":[`fragment-skill_library_entries`,`c04324d292a056ed135e3b5fad5ddf61bd7fa1bfc44ec905aa32cc220956bf8d`,[93,94,95,96],[]],"6b07280274e87ca0fa5bbc1887818497375298fa700b24852dc981f3da1da555":[`state-feature-skill_library_entries`,`c04324d292a056ed135e3b5fad5ddf61bd7fa1bfc44ec905aa32cc220956bf8d`,[93,94,95,96],[]],"43645abd05379894c2982bcd88b8dff0cd6c9802e5bf2ab6cc54af87a7e6a37d":[`state-feature-skill_library_revisions`,`533218405c3e483d687da824cf15f9ebcb76ba69675946e95c134702dc199890`,[95],[]],ea1b1fb7d6d8256ec58bc7c28541312c1a543e88bf9ed7e4366791ea243d8ec0:[`state-feature-skill_library_events`,`e5269a0f2846007c0b3eef62963979fa7a2cdd01ced20906ec4ac407ace66c03`,[94],[]],"31318a62bdb75dccad514a02adde07df11d26b756f51d1d50d0e6b19d399b26e":[`state-feature-skill_library_uploads`,`ba066e91b42e768b5f705703783cce87eb90fac71a37cad9dfdf308a19ccceb6`,[96],[]],ed3d9e7b13809b3a9b91d48d63816b26354681d727b96e39496d02c775343e1f:[`fragment-operator_approval_standing_grants`,`9d40e9ae6add075aa675521e2664951448cb3c7f360694614c0e39db256ed7fa`,[73,74],[]],be37db3a4634164c401b2d8e5ac3c2d712cd9eb973e3f2b39daa578adedff0ae:[`state-feature-operator_approval_standing_grants`,`9d40e9ae6add075aa675521e2664951448cb3c7f360694614c0e39db256ed7fa`,[73,74],[]],e23a5880a289da464471db5cfff10b9a6962b4d52c99260a3e366746c023de76:[`state-feature-operator_approval_standing_grant_generations`,`0d525f0400a30f0582698e91e78f63063c08a8c06b3bcfe624dbd2f2fbe7834c`,[73],[]],"7b8bf2fd3ae786c589bf138b32270450c1a2582bcb9a825c1eaf7fb3a7bcea06":[`fragment-worker_environment_session_attachments`,`b95d7054311f0f2d1e0885104c66ff243dfe4f68b84ed2d814ae68e748574417`,[156],[]],"32cc45ee15a4c4dd21d3ebeb9c259fe465085ed35ee781e611f293af5bbda189":[`fragment-durable_background_processes`,`a12b3e39e6d9ed28b9aea95a15a7a60f4c9615ad48d323de7a52560475c62ea4`,[36],[]],"6496f80e29da252472af802873996fc3cd761f245f4dcf6fefb1c7aee38e720b":[`fragment-sandbox_persistent_execs`,`f885f117e199277aa5c23a9095f55e742797249d13e2f4e4df8fbef1daba399d`,[83],[]],"156673e9396f27223073abdbbd2e13269bd7f45f577ed6aff00e017ab232d940":[`state-feature-sandbox_persistent_execs`,`026ac7355b83187c8f7eef5cbd48ab36ba7de1b4fe40413ee1168ebff6c2d67a`,[157],[]],"61e308c5a715e5ee5ff29b65a31d2e7ccd039498494d9afe120129f62f86b764":[`fragment-user_background_images`,`1da03995969350f59b3f8a64d9144b781d467e6ea75f70d5abcd6e18734678e1`,[111],[]],b36f4fc0be0d53e48e207f50a3cba34df76c4028a2d85201f7b262b1c7a4c2ab:[`fragment-update_runs`,`7a03cbf22978be3aa41cb030aadff21440667a0035fd3a9795492c10f89b1a55`,[110],[]],c3db4ffcf4092146e5d923b60516a00a8db41825f8bffb138b848195576b987b:[`state-feature-update_runs`,`4caad814f837565106a1a17b982bf4ff004bbdba00a6ff05a3b9c5ef2e5a5945`,[158],[]],a0323917d8786f2e6cbc3470d86c2a4e123103b84a5dc95d59bbf20759b8ab4c:[`fragment-session_repository_workspaces`,`51ee403217b5a9bff65b4d3b93a571f8fbeb60a7b2935860db7e21e7959e7833`,[88],[]],d62b52a34e2626a7983ae5c48268f04567e93170457e63502b7096486a6ce9f7:[`fragment-github_repository_publication_requests`,`1ae034bde6e00a9b919bcbb987df8aebc5856ab6f4c979743355ecb682418a99`,[49],[]],"6d205ed705fcf89e34e2679f192b2dd50e4cbcb9b06b473c3e81dd48c8811102":[`state-feature-github_repository_publication_requests`,`bc5c46f3cc22c0572b25d10344108465509d7189e1d51b0f6fa335b1d86497cf`,[159],[]],"079ee34fc1ed4ca27e807b01c7456deceacc57fead388917ff1b275b5047ab06":[`fragment-github_publication_session_lifecycles`,`755e9a26722c11b5edd9d4f6bf270bfdc706428593de4216c311f85fad0a8e69`,[48],[]],fc4d434c6c76c4e5c5b1fb9c54ebe7e98a395fea6370ada7ac4767ad755051ac:[`fragment-github_personal_publication_requests`,`eda486fc6d1c12adfe86012cfa6d0f6afb64906b1d4c75e3785bda082281a4e1`,[46],[]],"8a4a42e9e8549a0f2e73b33b4031673e2e939624d95586693bc2ac43742bf30f":[`state-feature-github_personal_publication_requests`,`aeb05b8ff41f64e5bab165feac6f1abcdb6dfefc2a5bfbbe88e34861cc40922e`,[160],[]],"0f3d662483be17f95f492157a8ba28b163afab9c52429ab6ff277ebe8b0a27fd":[`fragment-cron_job_runtime_authorities`,`ebce08da69716c0011c0db38decb38e5eaa0069c6f8360e85afdec8c624a360e`,[22],[]],e16c741ca5371718cf7d95114ee1043ad33db04c470f268ccbe3130f699998d9:[`fragment-cron_run_trigger_state_retirements`,`0e85a9fecddeef5129569f503fb32cc0d94e9c98877286be10e15eb657e682bb`,[26],[]],"632466e72325a428d8b4c4dfa1b7a14be9f57236bee791e9412ea07b24fca254":[`fragment-execution_identity_contexts`,`15be6a7de30d2ecb9b15fed1eb13dd65da858f1eb378e95f737f14241c11b3d9`,[39],[]],"7683ab1fd0bccb8e29499c3b6df0070d9cc7cd6249c8c103d654b015ce309417":[`state-feature-execution_identity_contexts`,`2dc283d04b315fd0199a9e13653edb03c8614d12be2ca6f005c7e110aab62d2a`,[161],[]],b796607c50ccb0e85abdec5d76b88b8076596077afe71e238b7831edd061f9e8:[`fragment-mcp_oauth_pending_authorizations`,`39eae7dacb98a3cc36bd7598c4e416fc3f180c95aa78b7fd5a1f11afecf2d5b9`,[56],[]],"15f660904a6ff5b2e08b57e7e1979ae85d7476426da0e6aa8fc35a013d557501":[`fragment-node_worker_launch_containers`,`bae513184057ef120b3b7ff1f08fc0affa1293461353ac060f1c0148346225f5`,[66],[]],"2703e870e99174d91597e44b5619574373f3da7030c4cd9907a8ac341f00802f":[`fragment-node_worker_launch_boots`,`ce110d8dd52daad838b24137dc43979dafe784dd08348e09482093f47dd5d98b`,[64],[]],"7c1c6d4fbba2f48e6ad4003bbc7d22b3b543034a8c2456fc542d2dac90c46aad":[`fragment-node_worker_launch_cleanup`,`d45196104873c5924d0fddabdce7a4f08b8fab2c68880492de968c978ef031c8`,[65],[]],"16bb8bbf8eb97d4a3895c031f758ca37106c072cd78e18b99e4f68463679c153":[`fragment-node_worker_launch_process_scopes`,`d9ce1d80156505cb99854d410b48f37b0cf82d0259417bd3c64e1ff91d5b05b2`,[67],[]],b6d0283d081e77179a54f4e54847168156095e3ec4a487d17feea8dfe26a1626:[`fragment-node_worker_launches`,`cac88014114f03cee09470505617bc58f893efc072306d0b4c6fb48e259fb17c`,[68],[]],"5dc1cf9bb59834e9497e191514c7bfb850e062f7744047c7a4289516b4b0e214":[`state-feature-node_worker_launches`,`f07514c3996f79e89f46d771b58859826342f72a12f024b29726a82f6481d6f9`,[162],[]],"5e238c5c57f8e1bfc2d5fc91ad2a4ad3ae421ca1f36a84f973a8299f99ee7015":[`fragment-node_worker_prepared_workspaces`,`1ab2c378547ad29580b84dcebbc4ed9c99008c8a242446cdad0553a24bf06eec`,[69],[]],"865397a51b0e47eda5349293c3fc590226718cdad61afe420c578ab3ec786732":[`fragment-node_worker_turns`,`cb3eaac1dc2492905a55c037ba7c09748bbdbc9c6a13cbb92e3cbec80c94f5d6`,[70],[]],"64cf0d044c7dede24d58a370a2f52cf19616efc9523343a698f7127c4d187f1d":[`state-feature-node_worker_turns`,`d1d9be01c96d9dd47e4e23d0099074f561aedb976de062622daffd173443c17d`,[163],[]],eee176fa30fb315a218b50f12be8d9e4e5561441d59250cf7029aac4edd9eb38:[`fragment-operator_approval_execution_identities`,`0f2bc5e4d656eda1ad36b778905e7e55f8685c0b41a68883f6e9fb1b838a874c`,[72],[]],"57562a3e6f834f876e5c03711f50dc514c8bdd432a87f1f54cbac2901642d5d4":[`fragment-web_push_approval_deliveries`,`f11526f4044590884acc313f8a8fb921ce93fb2372e2e64a635989af93d3012e`,[114],[]],"74b05c720f6b4a8ff88824c9843816992d5233b93ccd85bea66c2fbd2a3480c5":[`state-feature-web_push_approval_deliveries`,`92bd2e9265be63167980a22960aa201502864ec59e283821ad3eab6e765744ce`,[164],[]],"0b710f9ea230c2d23182de151edebc06dfb2800ad6207647d27ccb2c900b5d6a":[`fragment-execution_decision_facts`,`251fe6aa9c0c1ef726ab36810df59e644d472757b269b7e6ac36a5b7b1864ccc`,[38],[]],"9cd9f63b1002094a7e0538c52b75f2c8d26664937ff5559f64a004feabe47816":[`state-feature-execution_decision_facts`,`8235ed3d9eb951894768fa49670db7390f7950e96618daded2851a55c2e827ed`,[165],[]],"49e2b7094b1bf25586bc63b3ce3e971873c26584de40bd96654a31b945b3881f":[`fragment-execution_owner_lifecycle_bindings`,`83228457b7900a349a7a60693f5be9fe5ce2b86f8ea3be6bd1b3bcbae9381c73`,[40],[]],c222191b2157eb84fae227b67417210870ff546ce38b799805cd32e63e198bcd:[`fragment-outbound_message_execution_bindings`,`90715ffad8419a713baa7a63aa0d15038b16391bba0c3739bdae7c3196cc5fe5`,[77],[]],f782e56e1dca81426ff88a94a9702580d0c6bdd1a420e8c1741fef3aa7c18b81:[`state-feature-outbound_message_execution_bindings`,`c29af535c3d6cf16bb31a085c7b68d150c132921b51f560495e75dd1f5451f2d`,[166],[]],"733bbcfcce8373ce968a993fc1f4d3f911d0011c8a60833f613f9cdb7de22d9e":[`fragment-outbound_message_progress`,`07938ecb7fa35203a80bf93cb28900b5eb0c35dcf47bfa476b436fd39d881135`,[78],[]],"6e2c6c197a77c179716d6ddead9a7226c49db5e8b69c1775ea8808e5e24cf271":[`state-feature-outbound_message_progress`,`b1fdd16f1d29ceeed6d32e873b0ef54831ad693b4e910c1fe55bc59aa60c4709`,[167],[]],ab3748daca8019e0908cc9906304f50a26cffd9d5e9ea3ba1ea3a759315737cb:[`fragment-agent_provenance`,`da5d017b6840d65ebd1bc234ae3fdf4540bd00256bfc50c599a4195d15066c17`,[6],[]],be11d3e5a672ca34875c1f06cfc6d5d5a1293a7077302a759c12c2c17b2cdcb6:[`fragment-cron_run_receipts`,`593a0b293257e23cf22f14e308c7f75a7032d5f0bdbba0fa3d307f3382e3bd4c`,[25],[]],"41824738e9d17ef8abfa9bda96824ab259ca9e81d3ad647b16b407a6bc4dc28f":[`state-feature-cron_run_receipts`,`1c1c9f4b60d18e51e0db6940a6813c5a7a1a14dffbe38921318e61c295597112`,[168],[]],"8b28fd18dffd5b09fb5a09d8e0d04b2dbf1372081b356131f1df2f4c41895745":[`fragment-config_revision_keys`,`8b416bf248c7702519e58249d29725d42d52a95d8a22084964637f3ed57cae9d`,[21],[]],"443ee39ca023c21d0234f2897e3790e8e9757daf427989b731f97074c5bf28fe":[`fragment-secret_store_entries`,`45f2e66f10baf9470316cb216a91ef6ffa865a2c2f25b181e37f20171348576b`,[86],[]],"10e3ba9552ac35206e3f3d467a44f71602f4b1d3404204836f72106155b5fe6d":[`state-feature-secret_store_entries`,`1eefc2ba0eecf91c8fd96442e750b4e555fb97485569f3bd2bf7205c02466cee`,[169],[]],ecb98cd64bfc2fc0828eaaac59c122a4a9381d752dfdc4166d1fe287e9f1cecb:[`fragment-projects`,`9ac5c2cc1d8a72b975287fe40d1f9cf5929671ee033dd68538315e9770df9f36`,[82],[]],"7b5e9bd4ec7f91f71f2fcea1deaa9058d06f907e460e2d1a2a8fa333bf6942c0":[`fragment-worktree_templates`,`a9481ceaf044b2db824f5df1823d0619c7b9e53310b83a32c4399421cc6a7e18`,[132],[]],"85b0f3fbf9815fa0125a5a823eacebc68306ac4864d89047bb2699611b0044c5":[`fragment-user_preferences`,`24c5cd67b1014eb8ca50a492d93a9b9ec5e5a3b936722c35c7b0768a8b1823e2`,[112],[]],"1f164add8aeb9d28f7c779f88fe40dc7a344e14479fe9a017181151330bca6fd":[`fragment-device_pair_setup_completions`,`3400a6259bccdb3546a778b36215284bd14c9613a1ece543e9deaf3539e3b288`,[30],[]],"54a593978142e9fdd957d9aff2368fd3b9d26702968b4ede856df3a933023139":[`fragment-github_publication_requests`,`81c333517fb89efb345896c6452909c6963d2a049bb8b76a8d8adcb626ad592e`,[47],[]],"4c1eb061476b0ecbfc022fb1bd4c927c7c4b3868f40702507c9911ccd3504b2f":[`state-feature-github_publication_requests`,`0375d1a5a88363e5cd216f3addbf170f8be1098ea8626e0e0f95ebb91768588d`,[170],[]],"1f844843f7e4c042331e07eb663873d85bfb1291db181f98c0834a0d01bbf2e2":[`fragment-device_pairing_join_codes`,`4ada0f17fe210baff80cc7da940a58ef4bd27911312469dd15a3473ef1119ad0`,[32],[]],"5ac69298f3597ee21ed377f802610edbd4e638bc0d0cd5be7b2066f5c9104b1e":[`fragment-device_pairing_browser_requests`,`c65ddfeaf2ea8a7653a6e2d374d86422deb3fccbb4424f456bd8d0901c69b4c7`,[31],[]],ddfc4231357afb56d903eca77fbfebf817ffafa47d491193e6948b5032ccfefe:[`fragment-skill_workshop_changes`,`993cb9d62f11305ca322f0c76e895a37604132572f2f651c635d0d72eb416b85`,[100],[]],d3bf805006eb83550c1d4a662610e8897cd41ce52de6e370424d3f3ed26e3d80:[`state-feature-skill_workshop_changes`,`01b83680a33b4f2e7d46a70f3e122ebe40044b44ff733891a29a340bdcbba3fb`,[171],[]],"59c7fa24ee5aa93144f936173f6efde68e9d2af33d074d5e208f971d500ac5d3":[`fragment-worker_environment_ssh_fallback_ports`,`18ead5da9eec5f58b75326fdaf9ed55a3d0433facc14dad465add6bd80dff080`,[117],[]],"62bf1862f7ce3c0abcaaf4cc070834c5f402e1696b78d22e7ca7bd23b0fec36d":[`fragment-worker_session_placement_moves`,`8188e7a581a51d08faad38cdf6b07041e2b2e760d17bcfa109df49ec0c83c430`,[120],[]],f01d4e41642436ccdf0ba63450989879b094bd74a7a97cd98b2ec0c4accd4ad4:[`state-runtime-0-0`,`cf307d842aa556e9f0bbaae9cf448744d4991310b34333f0fbf8c7e894c1a86a`,[0,1,2,3,4,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23,24,27,28,29,33,34,35,37,41,42,43,44,45,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,84,85,87,89,90,91,92,97,98,99,101,102,103,104,105,106,107,108,109,115,116,118,119,121,122,123,124,125,126,127,128,129,130,131,133],[]],"1e2662ff71a59cc056f70d661bddb4c6c0e86b36c4151490343ffd787b15891a":[`state-runtime-before-provision-source-0-0`,`16da1fa5ae0e4e4c25f75803a1b39c8971b93c0a0a311edf4fbdefd50f33d0a2`,[0,1,2,3,4,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23,24,27,28,29,33,34,35,37,41,42,43,44,45,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,84,85,87,89,90,91,92,97,98,99,101,102,103,104,105,106,107,108,109,115,116,134,119,121,122,123,124,125,126,127,128,129,130,131,133],[]],"0c3068a4622b9151d2321f80af94861f162d8288b6391c38d89822e20f856639":[`state-runtime-before-bootstrap-deferred-0-0`,`0d8a0829977f7e6ec02a3fa9febb23562a521779369ad959613d26c4a96d72fe`,[0,1,2,3,4,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23,24,27,28,29,33,34,35,37,41,42,43,44,45,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,84,85,87,89,90,91,92,97,98,99,101,102,103,104,105,106,107,108,109,115,116,134,119,121,122,123,124,125,126,127,128,129,135,131,133],[]],"40222aeec53b8897045719a8d38a4b0658ffd1d21d4fd0fef11458c48ed5625b":[`state-runtime-before-v40-0-0`,`0d8a0829977f7e6ec02a3fa9febb23562a521779369ad959613d26c4a96d72fe`,[0,1,2,3,4,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23,24,27,28,29,33,34,35,37,41,42,43,44,45,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,84,85,87,89,90,91,92,97,98,99,101,102,103,104,105,106,107,108,109,115,116,134,119,121,122,123,124,125,126,127,128,129,135,131,133],[]],a45a311ca45ef1a2814feada0479c1f948470534ccb4bd6b10cf41f2a4ab6d57:[`state-runtime-0-1`,`c913a89e38b081c27405542ec53903e985f81b91564d3f87c237818c1bca9e34`,[0,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23,24,27,28,29,33,34,35,37,41,42,43,44,45,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,84,85,87,89,90,91,92,97,98,99,101,102,103,104,105,106,107,108,109,115,116,118,119,121,122,123,124,125,126,127,128,129,130,131,133],[]],a65a121da4de231f2d96dcf4503136c5f7cc2f80e54aa9d630fb2e5a9de9a97a:[`state-runtime-before-provision-source-0-1`,`350780aa0d95ca738450fff1e3479414d25bc3dca09cbe9741d6e52fb03879f4`,[0,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23,24,27,28,29,33,34,35,37,41,42,43,44,45,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,84,85,87,89,90,91,92,97,98,99,101,102,103,104,105,106,107,108,109,115,116,134,119,121,122,123,124,125,126,127,128,129,130,131,133],[]],"3075984cf7583cf173b40648a7b27d0cf683b2c9d38d218e6584da4efd0ef951":[`state-runtime-before-bootstrap-deferred-0-1`,`b866dbf70f630e748a46d2ad5a2c48c5d95bd4070784a9f7fcec3dc349d28af1`,[0,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23,24,27,28,29,33,34,35,37,41,42,43,44,45,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,84,85,87,89,90,91,92,97,98,99,101,102,103,104,105,106,107,108,109,115,116,134,119,121,122,123,124,125,126,127,128,129,135,131,133],[]],"5ed7c4627eed8b68ddfcf5b4ffbd98c2085cc17c1ab55a1d69f07aee108f202d":[`state-runtime-before-v40-0-1`,`b866dbf70f630e748a46d2ad5a2c48c5d95bd4070784a9f7fcec3dc349d28af1`,[0,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23,24,27,28,29,33,34,35,37,41,42,43,44,45,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,84,85,87,89,90,91,92,97,98,99,101,102,103,104,105,106,107,108,109,115,116,134,119,121,122,123,124,125,126,127,128,129,135,131,133],[]],"381aa534d8d5eb4bec164b7e73e83221d4d78bd8058c425a554dcb91c0e34c58":[`state-runtime-1-0`,`0c8dde495615c5c2a57ec8598ca9ece53f0ea5e72e963b92f1716a5e961106da`,[0,1,2,3,4,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,27,28,29,30,31,32,33,34,35,37,41,42,43,44,45,47,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,82,84,85,86,87,89,90,91,92,97,98,99,100,101,102,103,104,105,106,107,108,109,112,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133],[]],a99f466c73b07f39b54a6711d7e5df7767e45c7c9b2a45943ed96726ba8f4608:[`state-runtime-before-provision-source-1-0`,`77e32f62ae9edd8ad44e5c9995e71e6c19d5ce8c55f468b0b202379b7e27dc54`,[0,1,2,3,4,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,27,28,29,30,31,32,33,34,35,37,41,42,43,44,45,47,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,82,84,85,86,87,89,90,91,92,97,98,99,100,101,102,103,104,105,106,107,108,109,112,115,116,117,134,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133],[]],"90569dbff4f9ac27a68a4c13ddd2baaeb92962f32e1a58a6790eb5baeeb453fc":[`state-runtime-before-bootstrap-deferred-1-0`,`0fc6212e574b5022f924a9ed41c6ffadb979ca10c37deb9fc7f3ecd8af9c03f8`,[0,1,2,3,4,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,27,28,29,30,31,32,33,34,35,37,41,42,43,44,45,47,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,82,84,85,86,87,89,90,91,92,97,98,99,100,101,102,103,104,105,106,107,108,109,112,115,116,117,134,119,120,121,122,123,124,125,126,127,128,129,135,131,132,133],[]],"41b7ccaf89f2ce0b2e8898c714693b62ccdeba93e7eea48612a2783d77a97f28":[`state-runtime-before-v40-1-0`,`c070d1efc0b3e1f67ac4d5d5cc01bb5d57a7ddbf6f72b67da1888dd8a1cb4144`,[0,1,2,3,4,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,27,28,29,30,32,33,34,35,37,41,42,43,44,45,47,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,82,84,85,86,87,89,90,91,92,97,98,99,100,101,102,103,104,105,106,107,108,109,112,115,116,117,134,119,120,121,122,123,124,125,126,127,128,129,135,131,132,133],[]],cc59fb921d6be3730c729838875b379b1aec8edb9acd5e2ed09ea41f9b9ace33:[`state-runtime-1-1`,`26adf2401aaa91b57cac91157367732c55e904f417428fed0a8f7d01510e55fc`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,27,28,29,30,31,32,33,34,35,37,41,42,43,44,45,47,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,82,84,85,86,87,89,90,91,92,97,98,99,100,101,102,103,104,105,106,107,108,109,112,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133],[]],"269874b20b213faf7f8c8ecb6cc4c759853ffd1d63b5f6a395180667ffb2a9b3":[`state-runtime-before-provision-source-1-1`,`8060a02d609b6c8fe37e25568727275eaa76fb8908a93581083675afbdf3bd80`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,27,28,29,30,31,32,33,34,35,37,41,42,43,44,45,47,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,82,84,85,86,87,89,90,91,92,97,98,99,100,101,102,103,104,105,106,107,108,109,112,115,116,117,134,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133],[]],d99906589af97e0bc4e77af6f5e155e6eb689abfde8ef42d8534862f0c0f4d7d:[`state-runtime-before-bootstrap-deferred-1-1`,`288cbad6e819ed548b3fc769bc808be2a06f2b837db943abf969ff334872d540`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,27,28,29,30,31,32,33,34,35,37,41,42,43,44,45,47,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,82,84,85,86,87,89,90,91,92,97,98,99,100,101,102,103,104,105,106,107,108,109,112,115,116,117,134,119,120,121,122,123,124,125,126,127,128,129,135,131,132,133],[]],"126f5f0137d7c19fb0907ad7f763a83d4b675d38190526623081dff1dad6ab99":[`state-runtime-before-v40-1-1`,`8a47e464e648029da13f34055cf04b4337e35a37bfc83f8ff130959ecfeb29cc`,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25,27,28,29,30,32,33,34,35,37,41,42,43,44,45,47,54,55,57,58,59,60,61,62,63,71,75,76,79,80,81,82,84,85,86,87,89,90,91,92,97,98,99,100,101,102,103,104,105,106,107,108,109,112,115,116,117,134,119,120,121,122,123,124,125,126,127,128,129,135,131,132,133],[]],d285aca718d789bb5f8799fd148a30792ae63c7ce10fa0f0c757391806d83cac:[`state-table-agent_database_leases`,`fed699717b3ff6f0f406750e7ef2e57c0e047f4a8aa9669855cd001f4eecb4b9`,[3],[]],cac005273b1563f1269aa41ff5cc8a4d7b94a4cb7d9f82be2917853a736168de:[`state-table-agent_deletion_journal`,`6c66fbe42d4b3d671ea3212b0024f65af05cbf9ea67dc8ce1763542f2ce245f2`,[5],[]],dc1f04127c4146d414429aba7f0f055680178ac035c1566f8202cb8ba6ba2575:[`state-table-config_machine_state`,`21025ec6d7ee6da8951d3f519c48e44744b0392597ce821984dd3a9e5abb1787`,[20],[]],"246e73f17e8b92383ee8d6dfe4b657ee3dc3040e8c6398ff36c17ee14222eb37":[`state-table-gateway_restart_intent`,`91a30a8d1423b5d855a975ceb40e2ef07bdfa21f284c59bee6d189679ca8dba9`,[44],[]],df93d6687254de2f31ff263b2dafdd67656caa6ac10180f95801bde2dce8f7f0:[`state-table-schema_meta`,`df4efc2e7d50f8bde377f55f5a020ae5ba98cfda938879054cf02d9b4905b793`,[85],[]],cb1f3279e7e3b90290d5ab10856edf532f9c69f278116dd1a8002a4b050f2c1c:[`state-table-state_leases`,`6117e088b6b48fe1007de8ef29868981f820404cc3be99040c2bcd899902b7cc`,[172],[]],a503e610cfb224030ab2473b374631cefa4972377d9d04e07b5d5efb07cee14c:[`state-table-worker_session_tool_operations`,`a146f78ad23ec99bfcb50819c65478b5e94c4a8e4159086ef5073fc76e26cc2d`,[122],[]],"4f45746754bef21a88b4fdfc0932df58b22bf31590a961e4a53957cce7ccd873":[`state-table-worker_turn_tool_authorities`,`fef54ec7cc72bf3869c78b67f31ce96ed842a1ba872f7090e52feff5f547560c`,[125],[]],"8cbef48665eec155650765377478b38fde1c87ef57fadb423438f85f8c91ad66":[`state-indexed-github_publication_requests`,`81c333517fb89efb345896c6452909c6963d2a049bb8b76a8d8adcb626ad592e`,[47],[]],c7c1408a52e8649cf030b636ee3d984e969c5fdb96f6834634e7cb4807e624f2:[`state-indexed-update_runs`,`7a03cbf22978be3aa41cb030aadff21440667a0035fd3a9795492c10f89b1a55`,[110],[]],d40fd26bedb861443248d33289dc8d89a1750f3631730dfde2ae285f2c7988ca:[`state-existing-state_leases`,`4289076cebb114b14ac96672941b2be0679f1033e23fe059eedce8dc2b1eea57`,[85,172],[]],"13150d745ef24ab5e6aafe0b365af15d6c5d471a659e5eb2a1c38e359984a47f":[`state-existing-agent_database_leases`,`9fe50268db674b01265b7e77701aedcfffe36567086fc763de8b89f87f4cb67d`,[3,85,172],[]],cc6464642f0f115776287e4d0966e2fc564b8e62db519c2bfad7a25c9e67de51:[`state-existing-migration_runs`,`c8d7a60b14124212b817fab783e7e9e97253d27ae97c14dd6107ba9f1ad727f1`,[173,85],[]],"789bdcc904f4b35b57f9cb829909f2c9cda541c86179beb6904977146665c0c9":[`state-node-worker-lineage`,`f235501e3f5767c362c7aebce3e678d33cdb45e3b776391980019cdf7cc0f37d`,[65,162],[]],"7c5c2640b3ec45cbac611c07c67f478f0ddc85a4bbfceb9c3576f0d7aa3bd14a":[`state-node-worker-descendants`,`0991532bbc3ca042fc5c1c2026b8aa8d50b24a5bccf26e53675340a4853a665e`,[65,67,162],[]],"72c354791974ce88794c96c16135a89f07b48b9b03542f968beadf05b76aae1e":[`state-retired-commitments`,`19bef9367d336bb367e75740610741cb67deeef86a7f54065758609d67ae8a38`,[174],[]],"2309aff06f4bac77072697764926a0042e6b6069c9504d5bb8c6a0601e9d1314":[`state-retired-commitments-shipped`,`f4d088664f133eea8b1e83fd342d1effaa86d836f8593e02778531468372a303`,[175],[]]};let cl;function readSqliteStateFingerprint(e){let t=sl[e];if(!t)return;let[n,r,i,a]=t;return{id:n,fingerprint:r,viewNames:a,tableNames:i.map(e=>ol[e][0]),indexNames:i.flatMap(e=>ol[e][1])}}function readSqliteStateCatalog(e){if(!sl[e])return;cl??=Rs(import.meta.url)(oc(new URL(`../../assets/sqlite-schema/sqlite-state-catalogs.json`,import.meta.url).href));let t=cl.catalogs[e];return{tables:t.tables.map(e=>cl.tables[e]),views:t.views}}function readGeneratedSqliteFingerprint(e){let t=nc(`sha256`).update(e).digest(`hex`);return readSqliteStateFingerprint(t)??readSqliteAgentFingerprint(t)??readSqliteDaemonFingerprint(t)??readSqliteClientFingerprint(t)??readSqliteMemoryFingerprint(t)}function readGeneratedSqliteCatalog(e){let t=nc(`sha256`).update(e).digest(`hex`);return readSqliteStateCatalog(t)??readSqliteAgentCatalog(t)??readSqliteDaemonCatalog(t)??readSqliteClientCatalog(t)??readSqliteMemoryCatalog(t)}function fingerprintSqliteSchemaCatalog(e,t){let n=t&&new Set(t.tableNames),r=t&&new Set(t.viewNames),i=t&&new Set(t.indexNames),triggers=e=>e.map(({name:e,sql:t})=>({name:e,sql:qr(t)})).toSorted(byName),columns=e=>e.map(({cid:e,name:t,type:n,notnull:r,dflt_value:i,pk:a,hidden:o})=>({cid:e,name:t,type:n,notnull:r,dflt_value:i,pk:a,hidden:o})).toSorted((e,t)=>e.cid-t.cid),a={tables:e.tables.filter(e=>!n||n.has(e.name)).map(e=>({name:e.name,sql:qr(e.sql),strict:e.strict,withoutRowid:e.withoutRowid,columns:columns(e.columns),foreignKeys:e.foreignKeys.map(({id:e,seq:t,table:n,from:r,to:i,on_update:a,on_delete:o,match:s})=>({id:e,seq:t,table:n,from:r,to:i,on_update:a,on_delete:o,match:s})).toSorted((e,t)=>e.id-t.id||e.seq-t.seq),indexes:e.indexes.filter(e=>!i||e.unique===1||i.has(e.name)).map(e=>({name:e.name,origin:e.origin,partial:e.partial,unique:e.unique,sql:qr(e.sql),terms:e.terms.map(({seqno:e,cid:t,name:n,desc:r,coll:i,key:a})=>({seqno:e,cid:t,name:n,desc:r,coll:i,key:a})).toSorted((e,t)=>e.seqno-t.seqno)})).toSorted(byName),triggers:triggers(e.triggers)})).toSorted(byName),views:e.views.filter(e=>!r||r.has(e.name)).map(e=>({name:e.name,sql:qr(e.sql),columns:columns(e.columns),triggers:triggers(e.triggers)})).toSorted(byName)};return xt(JSON.stringify(a))}function byName(e,t){return e.name<t.name?-1:+(e.name>t.name)}function assertSqliteSchemaContains(e,t,n,r={},i){let a=collectSqliteSchemaIssues(e,n,r,i);a.length>0&&je(t,Zt(a))}function collectSqliteSchemaIssues(e,t,n={},r){if(!Wa(e))return Ya(e,()=>collectSqliteSchemaIssues(e,t,n,r));let i=typeof t==`string`?readGeneratedSqliteFingerprint(t):void 0,a=i?.viewNames??getSqliteSchemaContract(t).catalog.views.map(e=>e.name),o=r??Pt(e,a,i?.tableNames??getSqliteSchemaContract(t).catalog.tables.map(e=>e.name));if(hasCanonicalSqliteSchemaFingerprint(t,o,n))return[];let s=getSqliteSchemaContract(t),c=new Set(n.excludedTables??[]),l=new Set(n.excludedIndexes??[]),u=new Set(n.allowedMissingTables??[]),d=new Set(n.allowedMissingIndexes??[]),f=[],add=(e,t,n)=>{f.push(Oe(e,t,n))};for(let[t,r]of s.tables){if(c.has(t))continue;let i=o(t);if(!i){if(u.has(t))continue;add(`missing-table`,t);continue}f.push(...compareTableDefinitions(t,i.definition,r.definition,n,!u.has(t)));for(let e of compareTablePragmaFacts(t,i,r,n))f.some(t=>t.code===e.code&&t.objectName===e.objectName)||f.push(e);let a=new Set(i.indexes.map(e=>JSON.stringify(e))),s=/* @__PURE__ */ new Set;for(let n of r.indexes){if(n.name!==null&&l.has(n.name))continue;let r=JSON.stringify(n);if(s.add(r),!a.has(r)){let r=n.name??t;if(n.name&&d.has(n.name)&&!e.prepare(`SELECT 1 FROM main.sqlite_schema WHERE type = 'index' AND name = ? COLLATE NOCASE LIMIT 1`).get(n.name))continue;add(`missing-or-drifted-index`,r,`missing or drifted index ${n.name??`on ${t}`}`)}}for(let e of i.indexes)e.unique===1&&!s.has(JSON.stringify(e))&&add(`unexpected-unique-index`,e.name??t,`unexpected unique index ${e.name??`on ${t}`}`);let p=collectOptionalCanonicalTriggerGroups(e,n,t),m=p.flatMap(e=>e.triggers),h=p.filter(e=>e.optional).flatMap(e=>e.triggers);for(let e of r.triggers)h.some(t=>t.name===e.name)||containsTrigger(i.triggers,e)||add(`missing-or-drifted-trigger`,e.name);for(let e of p){let t=i.triggers.some(t=>e.triggers.some(e=>t.name===e.name));if(!e.optional||t)for(let t of e.triggers)containsTrigger(i.triggers,t)||add(`missing-or-drifted-trigger`,t.name)}for(let e of i.triggers)!containsTrigger(r.triggers,e)&&!containsTrigger(m,e)&&add(`unexpected-trigger`,e.name);i.virtualTableSql!==r.virtualTableSql&&add(`virtual-table-definition-drift`,t),(i.strict!==r.strict||i.withoutRowid!==r.withoutRowid)&&add(`table-options-drift`,t)}let p=o.readView??Pt(e,a).readView;for(let e of s.catalog.views){let t=p(e.name);if(!t||t.sql!==e.sql||JSON.stringify(normalizeColumns(t.columns))!==JSON.stringify(normalizeColumns(e.columns)))add(`missing-or-drifted-view`,e.name);else{for(let n of e.triggers)containsTrigger(t.triggers,n)||add(`missing-or-drifted-trigger`,n.name);for(let n of t.triggers)containsTrigger(e.triggers,n)||add(`unexpected-trigger`,n.name)}}return f}function assertSqliteSchemaTablesPresent(e,t,n,r={}){let i=new Set(r.allowedMissingTables??[]),a=getCanonicalSqliteTableNames(n).filter(e=>!i.has(e)),o=[];for(let t=0;t<a.length;t+=500){let n=a.slice(t,t+500),r=n.map((e,t)=>`(${t}, ?)`).join(`, `),i=e.prepare(`WITH expected(ordinal, name) AS (VALUES ${r})
         SELECT ordinal FROM expected
         WHERE EXISTS (
           SELECT 1 FROM main.sqlite_schema
           WHERE type = 'table' AND name = expected.name LIMIT 1
         )`).all(...n),s=new Set(i.map(e=>e.ordinal));for(let[e,t]of n.entries())s.has(e)||o.push(`missing table ${t}`)}o.length>0&&je(t,o)}function getCanonicalSqliteNamedIndexContracts(e){let t=getSqliteSchemaContract(e),n=[];for(let[e,r]of t.tables)for(let t of r.indexes)t.name!==null&&t.sql!==null&&t.origin===`c`&&n.push({definition:readCanonicalIndexDefinition(t),fingerprint:t,name:t.name,tableName:e,unique:t.unique===1});return n}function getCanonicalSqliteTableNames(e){if(typeof e==`string`){let t=readGeneratedSqliteFingerprint(e);if(t)return[...t.tableNames]}return[...getSqliteSchemaContract(e).tables.keys()]}function getCanonicalSqliteNamedIndexNames(e){if(typeof e==`string`){let t=readGeneratedSqliteFingerprint(e);if(t)return[...t.indexNames]}return getCanonicalSqliteNamedIndexContracts(e).map(e=>e.name)}function hasCanonicalSqliteSchemaFingerprint(e,t,n={}){let r=typeof e==`string`?readGeneratedSqliteFingerprint(e):void 0;if(!r||!t.readCatalog)return!1;let i=t.readCatalog(r.viewNames,r.tableNames);if(fingerprintSqliteSchemaCatalog(i,r)!==r.fingerprint)return!1;for(let e of n.optionalCanonicalTriggerGroups??[]){if(!r.tableNames.includes(e.tableName)||n.excludedTables?.includes(e.tableName))continue;let t=i.tables.find(t=>t.name===e.tableName).triggers;if((e.optionalWhenTableMissing&&i.tables.some(t=>t.name===e.optionalWhenTableMissing)||t.some(t=>e.triggers.some(e=>e.name===t.name)))&&!e.triggers.every(e=>containsTrigger(t,{name:e.name,sql:normalizeOptionalCanonicalTriggerSql(e.sql)})))return!1}return!n.excludedIndexes?.length||!i.tables.some(e=>r.tableNames.includes(e.name)&&!n.excludedTables?.includes(e.name)&&e.indexes.some(e=>e.origin===`c`&&e.unique===1&&n.excludedIndexes?.includes(e.name)))}function collectSqliteNamedIndexContract(e,t){let n=e.prepare(`
      SELECT tbl_name FROM (
        SELECT name, sql, tbl_name FROM main.sqlite_schema WHERE type = 'index' AND name = ?
      )
    `).get(t);if(!n||typeof n.tbl_name!=`string`)return;let r=e.prepare(`PRAGMA main.index_list(${W(n.tbl_name)})`).all().find(e=>e.name===t);return r?collectSqliteIndexContract(e,r):void 0}function collectOptionalCanonicalTriggerGroups(e,t,n){return(t.optionalCanonicalTriggerGroups??[]).filter(e=>e.tableName===n).map(t=>({optional:!t.optionalWhenTableMissing||!e.prepare(`SELECT 1 FROM main.sqlite_schema WHERE type = 'table' AND name = ? LIMIT 1`).get(t.optionalWhenTableMissing),triggers:t.triggers.map(e=>({name:e.name,sql:normalizeOptionalCanonicalTriggerSql(e.sql)}))}))}function normalizeOptionalCanonicalTriggerSql(e){return qr(e)?.replace(/^(CREATE TRIGGER) main\./iu,`$1 `)??null}const ll=/* @__PURE__ */ new WeakMap,ul=/* @__PURE__ */ new Map;function getSqliteSchemaContract(e){if(typeof e==`string`){let t=ul.get(e);if(t)return t}let t=typeof e==`string`?readGeneratedSqliteCatalog(e):e;if(!t)throw Error(`SQLite schema has no generated catalog; run pnpm db:postgres:gen for its declared schema input.`);let n=ll.get(t);return n||(n={catalog:t,tables:Et(t)},ll.set(t,n)),typeof e==`string`&&ul.set(e,n),n}function readCanonicalIndexDefinition(e){if(e.name===null||e.sql===null)throw Error(`Canonical SQLite named index is missing its schema definition.`);let t=(e.unique===1?/^CREATE\s+UNIQUE\s+INDEX\s+/iu:/^CREATE\s+INDEX\s+/iu).exec(e.sql);if(!t)throw Error(`Canonical SQLite index ${e.name} has an unreadable definition.`);let n=oa(e.sql,t[0].length);if(!n||sr(n.raw)!==e.name.toLowerCase())throw Error(`Canonical SQLite index ${e.name} has an unexpected schema name.`);let r=e.sql.slice(n.end).trim();if(!/^ON\s+/iu.test(r))throw Error(`Canonical SQLite index ${e.name} has an unreadable target.`);return r}function normalizeColumns(e){return e.map(({cid:e,name:t,type:n,dflt_value:r,...i})=>({...i,name:sr(t),type:n.toUpperCase(),dflt_value:r===null?null:Ai(r)})).toSorted((e,t)=>e.name.localeCompare(t.name))}function normalizeForeignKeys(e,t){let n=/* @__PURE__ */ new Map;for(let{id:t,from:r,table:i,to:a,...o}of e){let e=n.get(t)??[];e.push({...o,from:sr(r),table:sr(i),to:a===null?null:sr(a)}),n.set(t,e)}return[...n.values()].filter(e=>!e.some(e=>t.has(e.from))).map(e=>e.toSorted((e,t)=>e.seq-t.seq)).toSorted((e,t)=>JSON.stringify(e).localeCompare(JSON.stringify(t)))}function compareTablePragmaFacts(e,t,n,r){let i=[],a=new Map(normalizeColumns(t.columns).map(e=>[e.name,e])),o=normalizeColumns(n.columns),s=/* @__PURE__ */ new Set;for(let n of o){let o=n.name,c=`${e}.${o}`,l=a.get(o);if(!l){(r.allowedMissingColumns??[]).includes(c)?s.add(o):i.push(Oe(`missing-column`,c));continue}let u=t.definition?.columns.get(o),d=r.allowedColumnDefinitions?.[c]??[];u!==void 0&&d.some(e=>Ai(e)===u)?s.add(o):JSON.stringify(l)!==JSON.stringify(n)&&i.push(Oe(`column-definition-drift`,c))}if(n.definition===null){let t=new Set(o.map(e=>e.name));for(let n of a.values())t.has(n.name)||i.push(Oe(`unexpected-column`,`${e}.${n.name}`))}return JSON.stringify(normalizeForeignKeys(t.foreignKeys,s))!==JSON.stringify(normalizeForeignKeys(n.foreignKeys,s))&&i.push(Oe(`table-constraint-drift`,e)),i}function compareTableDefinitions(e,t,n,r,i){let a=[],add=(e,t)=>{a.push(Oe(e,t))};if(!t||!n)return t!==n&&add(`table-definition-drift`,e),a;let o=new Set(r.allowedMissingColumns??[]);for(let[a,o]of t.columns)if(!n.columns.has(a)){let t=`${e}.${a}`;if((r.allowedColumnDefinitions?.[t]??[]).some(e=>Ai(e)===o)||i&&r.allowCompatibleAdditiveColumns&&isCompatibleAdditiveColumnDefinition(o))continue;add(`unexpected-column`,t)}for(let[i,a]of n.columns){let n=`${e}.${i}`,s=t.columns.get(i);s===void 0?o.has(n)||add(`missing-column`,n):s!==a&&((r.allowedColumnDefinitions?.[n]??[]).some(e=>Ai(e)===s)||add(`column-definition-drift`,n))}return JSON.stringify(t.constraints)!==JSON.stringify(n.constraints)&&add(`table-constraint-drift`,e),a}const dl=/* @__PURE__ */ new Set([`ANY`,`BLOB`,`INT`,`INTEGER`,`REAL`,`TEXT`]);function isCompatibleAdditiveColumnDefinition(e){let t=oa(e,0),n=t?oa(e,t.end):null;return!!(n?.keyword&&dl.has(n.keyword)&&e.slice(n.end).trim().length===0)}function collectSqliteIndexContract(e,t){let n=Ra(e,`SELECT sql FROM main.sqlite_schema WHERE type = 'index' AND name = ?`,[t.name],e=>e.get(t.name)),r=e.prepare(`PRAGMA main.index_xinfo(${W(t.name)})`).all();return Cr(t,typeof n?.sql==`string`?n.sql:null,r)}function containsTrigger(e,t){return e.some(e=>e.name===t.name&&e.sql===t.sql)}function readSqliteSchemaCookie(e){return e.prepare(`PRAGMA schema_version`).get()?.schema_version}function createSqliteSchemaEnsurer(e,t){let present=e=>{let n=K(e);return n!==void 0&&t.tables.every(e=>n.tables.has(e))&&(t.indexes?.every(e=>n.indexes.has(e))??!0)};return(t,n)=>{z(t)&&Fa(`postgres`,`repair`),Xa(t,()=>{if(present(t))return;let install=t=>t.exec(e());n?n(install):t.isTransaction?install(t):O(t,()=>install(t))})}}const fl=[[`workspace_setup_state`,`bootstrap_deferred`,`INTEGER`,!0],[`agent_deletion_journal`,`phase`,`TEXT`,!0],[`agent_database_leases`,`provenance`,`TEXT`,!0],[`user_profile_identities`,`canonical_login`,`TEXT`],[`user_profile_identities`,`authorization_id`,`TEXT`],[`user_profile_identities`,`authorization_basis_json`,`TEXT`],[`user_profile_identities`,`verified_email_json`,`TEXT`,!0],[`template_installs`,`bootstrap_content_digest`,`TEXT`],[`template_installs`,`bootstrap_source_path`,`TEXT`],[`worker_environments`,`desktop_json`,`TEXT`],[`worker_environments`,`bootstrap_install_kind`,`TEXT`],[`worker_environments`,`preparation_purpose`,`TEXT`],[`template_package_refs`,`extension_adapter_identity`,`TEXT`],[`template_package_refs`,`extension_detected_format`,`TEXT`],[`template_package_refs`,`extension_format`,`TEXT`],[`template_package_refs`,`extension_id`,`TEXT`],[`template_package_refs`,`extension_mapped_json`,`TEXT`],[`template_package_refs`,`extension_unavailable_json`,`TEXT`],[`worker_environments`,`shared_host`,`INTEGER`],[`worker_environments`,`node_setup_id`,`TEXT`],[`worker_environments`,`node_device_id`,`TEXT`],[`worker_session_placements`,`terminal_reason`,`TEXT`],[`worker_session_placements`,`terminal_at_ms`,`INTEGER`],[`worker_workspace_pending_results`,`repository_workspace_id`,`TEXT`,!0],[`worker_session_placement_moves`,`abandon_source`,`INTEGER`,!0],[`worker_session_placement_moves`,`target_machine_class`,`TEXT`,!0],[`worker_session_placement_moves`,`target_os`,`TEXT`,!0],[`worktrees`,`run_end_cleanup_json`,`TEXT`],[`worktrees`,`gc_protection_json`,`TEXT`],[`device_bootstrap_tokens`,`setup_id`,`TEXT`,!0],[`session_groups`,`cwd`,`TEXT`,!0],[`session_groups`,`worktree`,`INTEGER`,!0],[`secret_store_entries`,`allowed_hosts`,`TEXT`],[`web_push_subscriptions`,`device_id`,`TEXT`,!0],[`web_push_subscriptions`,`user_profile_id`,`TEXT`,!0],[`web_push_subscriptions`,`preferences_json`,`TEXT`,!0],[`task_runs`,`execution_owner_host`,`TEXT`,!0],[`task_runs`,`execution_owner_pid`,`INTEGER`,!0],[`task_runs`,`execution_owner_start_identity`,`INTEGER`,!0],[`session_watch_cursors`,`watcher_store_path`,`TEXT`,!0],[`subagent_runs`,`requester_store_path`,`TEXT`,!0],[`subagent_runs`,`controller_store_path`,`TEXT`,!0],[`cron_jobs`,`grant_definition_revision`,`TEXT`],[`cron_jobs`,`grant_definition_generation`,`INTEGER`],[`cron_jobs`,`grant_definition_updated_at`,`INTEGER`]];function lazyColumnDefinitions(e){return fl.filter(t=>e===void 0||!!t[3]===e).map(([e,t,n])=>({columnName:t,dataType:n,tableName:e}))}const pl=lazyColumnDefinitions(),ml=lazyColumnDefinitions(!1),hl=lazyColumnDefinitions(!0),Z={packageUpdatedAt:[[`template_package_refs`,`updated_at_ms INTEGER NOT NULL DEFAULT 0`]],packageIntegrity:[[`template_package_refs`,`package_integrity TEXT NOT NULL DEFAULT 'sha256:0000000000000000000000000000000000000000000000000000000000000000'`]],diagnosticSequence:[[`diagnostic_events`,`sequence INTEGER NOT NULL DEFAULT 0`]],cronRunLogs:[[`worktrees`,`provisioned_paths_json TEXT`],[`apns_registrations`,`relay_origin TEXT`],[`device_pairing_pending`,`refreshed_at_ms INTEGER`],[`device_pairing_pending`,`browser_origin TEXT`],[`device_pairing_paired`,`approved_via TEXT`],[`device_pairing_paired`,`browser_origin TEXT`],[`device_pairing_paired`,`operator_label TEXT`],[`device_pairing_paired`,`node_surface_json TEXT`],[`device_pairing_paired`,`pending_node_surface_json TEXT`],[`cron_run_logs`,`status TEXT`],[`cron_run_logs`,`error TEXT`],[`cron_run_logs`,`summary TEXT`],[`cron_run_logs`,`diagnostics_summary TEXT`],[`cron_run_logs`,`delivery_status TEXT`],[`cron_run_logs`,`delivery_error TEXT`],[`cron_run_logs`,`delivered INTEGER`],[`cron_run_logs`,`session_id TEXT`],[`cron_run_logs`,`session_key TEXT`],[`cron_run_logs`,`run_id TEXT`],[`cron_run_logs`,`run_at_ms INTEGER`],[`cron_run_logs`,`duration_ms INTEGER`],[`cron_run_logs`,`next_run_at_ms INTEGER`],[`cron_run_logs`,`model TEXT`],[`cron_run_logs`,`provider TEXT`],[`cron_run_logs`,`total_tokens INTEGER`],[`cron_run_logs`,`entry_json TEXT NOT NULL DEFAULT '{}'`],[`cron_run_logs`,`created_at INTEGER NOT NULL DEFAULT 0`]],acpReplay:[[`acp_replay_events`,`estimated_bytes INTEGER NOT NULL DEFAULT 0`],[`acp_replay_sessions`,`estimated_bytes INTEGER NOT NULL DEFAULT 0`]],cronJobs:[[`cron_jobs`,`description TEXT`],[`cron_jobs`,`declaration_key TEXT`],[`cron_jobs`,`owner_agent_id TEXT`],[`cron_jobs`,`name TEXT NOT NULL DEFAULT ''`],[`cron_jobs`,`enabled INTEGER NOT NULL DEFAULT 1`],[`cron_jobs`,`agent_id TEXT`],[`cron_jobs`,`payload_kind TEXT NOT NULL DEFAULT 'message'`],[`cron_jobs`,`state_json TEXT NOT NULL DEFAULT '{}'`],[`cron_jobs`,`runtime_updated_at_ms INTEGER`],[`cron_jobs`,`schedule_identity TEXT`],[`cron_jobs`,`sort_order INTEGER NOT NULL DEFAULT 0`]],deliveryQueue:[[`sandbox_registry_entries`,`session_key TEXT`],[`sandbox_registry_entries`,`backend_id TEXT`],[`sandbox_registry_entries`,`runtime_label TEXT`],[`sandbox_registry_entries`,`image TEXT`],[`sandbox_registry_entries`,`created_at_ms INTEGER`],[`sandbox_registry_entries`,`last_used_at_ms INTEGER`],[`sandbox_registry_entries`,`config_label_kind TEXT`],[`sandbox_registry_entries`,`config_hash TEXT`],[`sandbox_registry_entries`,`cdp_port INTEGER`],[`sandbox_registry_entries`,`no_vnc_port INTEGER`],[`delivery_queue_entries`,`entry_kind TEXT`],[`delivery_queue_entries`,`session_key TEXT`],[`delivery_queue_entries`,`channel TEXT`],[`delivery_queue_entries`,`target TEXT`],[`delivery_queue_entries`,`account_id TEXT`],[`delivery_queue_entries`,`retry_count INTEGER NOT NULL DEFAULT 0`],[`delivery_queue_entries`,`last_attempt_at INTEGER`],[`delivery_queue_entries`,`last_error TEXT`],[`delivery_queue_entries`,`recovery_state TEXT`],[`delivery_queue_entries`,`platform_send_started_at INTEGER`]],originalMediaRoot:[[`managed_outgoing_image_records`,`original_media_root TEXT NOT NULL DEFAULT ''`]],beforeTaskAttribution:[[`managed_outgoing_image_records`,`agent_id TEXT`],[`managed_outgoing_image_records`,`cleanup_pending INTEGER NOT NULL DEFAULT 0 CHECK (cleanup_pending IN (0, 1))`],[`current_conversation_bindings`,`conversation_kind TEXT NOT NULL DEFAULT 'channel'`],[`device_bootstrap_tokens`,`pending_profile_json TEXT`],[`gateway_restart_handoff`,`restart_trace_started_at INTEGER`],[`gateway_restart_handoff`,`restart_trace_last_at INTEGER`],[`gateway_restart_intent`,`reason TEXT`],[`gateway_restart_sentinel`,`delivery_channel TEXT`],[`gateway_restart_sentinel`,`delivery_to TEXT`],[`gateway_restart_sentinel`,`delivery_account_id TEXT`],[`gateway_restart_sentinel`,`message TEXT`],[`gateway_restart_sentinel`,`continuation_json TEXT`],[`gateway_restart_sentinel`,`doctor_hint TEXT`],[`gateway_restart_sentinel`,`stats_json TEXT`],[`gateway_boot_lifecycle`,`startup_reason TEXT`],[`official_external_plugin_catalog_snapshots`,`trust_mode TEXT`],[`official_external_plugin_catalog_snapshots`,`trust_key_id TEXT`],[`official_external_plugin_catalog_snapshots`,`trust_signature_count INTEGER`],[`official_external_plugin_catalog_snapshots`,`trust_threshold INTEGER`],[`official_external_plugin_catalog_snapshots`,`trust_verified_at TEXT`]],taskRequester:[[`task_runs`,`requester_agent_id TEXT`]],taskRunDetails:[[`task_runs`,`tool_use_count INTEGER`],[`task_runs`,`last_tool_name TEXT`],[`task_runs`,`detail_json TEXT`]],workerEnvironments:[[`worker_environments`,`bootstrap_bundle_hash TEXT`],[`worker_environments`,`bootstrap_openclaw_version TEXT`],[`worker_environments`,`bootstrap_protocol_features_json TEXT`],[`worker_environments`,`bootstrap_install_kind TEXT`],[`worker_environments`,`owner_epoch INTEGER NOT NULL DEFAULT 0 CHECK (owner_epoch >= 0)`],[`worker_environments`,`ssh_host_key TEXT`],[`worker_workspace_pending_results`,`staged_result_ref TEXT`],[`worker_environments`,`teardown_terminal_state TEXT CHECK (teardown_terminal_state IN ('destroyed', 'failed'))`]]};function resolvePathViaExistingAncestorSync$1(e){return gn(()=>Sc(e))}function resolveUpdateSqlitePath(e){try{return Ys.native(e)}catch(t){return Dn(t),resolvePathViaExistingAncestorSync$1(e)}}const gl=new ec;function hasUpdateDoctorMigrationCapture(){return gl.getStore()?.capture!==void 0}function getUpdateDoctorMigrationSource(e){let t=gl.getStore(),n=resolveUpdateSqlitePath(e),r=t?.source?.path===n?t.source:t?.companions?.find(e=>e.path===n);if(!r)return;let{generation:i,assertCurrent:a}=r;return a(),{path:e,generation:i,assertCurrent:a}}function getDoctorMigrationBackup(e,t){let n=gl.getStore();if(n?.capture){if(n.capture.expected(resolveUpdateSqlitePath(t.path))!==void 0)throw Error(`Updater migration requires its captured source generation.`);return n.capture.refuse(`The migration source path is outside the updater's captured paths.`),gl.run({...n,capture:void 0,source:void 0},()=>n.backup?.(e,t))}return n?.backup?.(e,t)}function capturedAttribution(){if(hasUpdateDoctorMigrationCapture())throw Error(`Update migration capture is active without its attribution owner.`)}function runUpdateSqliteMigration(...e){let t=capturedAttribution();return t?t.runSqlite(...e):e[2]()}async function runUpdateSqliteMigrationAsync(...e){let t=capturedAttribution();if(t)return await t.runSqliteAsync(...e);us(Is())?.throwIfAborted();let n=e[2]();if(lr(n))throw Error(`Update migration callbacks must remain synchronous.`);return n}function beginUpdatePostgresMigration(e,t){return capturedAttribution()?.beginPostgres(e,t)}function beginUpdateSqliteCompanion(e,t,n){return capturedAttribution()?.beginSqliteCompanion(e,t,n)}const _l=36e5,vl=/* @__PURE__ */ new Map;function closeBridge(e){e.port.close()}function closeIdleBridges(){let e=[...vl.values()];vl.clear(),unwatch();for(let{bridge:t,timeout:n}of e)clearTimeout(n),closeBridge(t)}function unwatch(){vl.size||(process.off(`beforeExit`,closeIdleBridges),process.off(`exit`,closeIdleBridges))}function removeIdleBridge(e){let t=vl.get(e);return vl.delete(e),t&&clearTimeout(t.timeout),unwatch(),t}function takeIdlePostgresBridge(e){let t=removeIdleBridge(e);if(t){if(Atomics.load(t.bridge.service,1))closeBridge(t.bridge);else return{bridge:t.bridge,validate:Date.now()-t.releasedAt>=1e3}}}function retainIdlePostgresBridge(e,t){let n=removeIdleBridge(e);if(n&&closeBridge(n.bridge),vl.size===2){let e=vl.keys().next().value;closeBridge(removeIdleBridge(e).bridge)}vl.size||(process.once(`beforeExit`,closeIdleBridges),process.once(`exit`,closeIdleBridges));let r=setTimeout(()=>{let t=removeIdleBridge(e);t&&closeBridge(t.bridge)},18e4);r.unref(),vl.set(e,{bridge:t,timeout:r,releasedAt:Date.now()})}function postgresBridgeReuseKey(e){return xt(JSON.stringify([e.url,e.lockTimeoutMs??6e4,e.statementTimeoutMs??9e4,e.readOnly===!0]))}function preparedBridgeKey(e){return JSON.stringify([postgresBridgeReuseKey(e),e.schema,e.storeId])}function createPostgresBridge(e){let{port1:t,port2:n}=new zs,r=new SharedArrayBuffer(8),i=new Int32Array(r),{port:a,signal:o,nextStep:s}=Ji(),c=new Int32Array(o);if(Atomics.load(c,1)){t.close(),n.close();let e=/* @__PURE__ */ Error(`PostgreSQL I/O service is unavailable.${s?` Run ${s}.`:``}`);throw vr(e),e}try{a.postMessage({connection:{port:n,signal:r,url:e.url,schema:e.schema,connectTimeoutMs:6e4,lockTimeoutMs:e.lockTimeoutMs??6e4,statementTimeoutMs:e.statementTimeoutMs??9e4,readOnly:e.readOnly===!0}},[n])}catch(e){throw t.close(),n.close(),e}return t.unref(),{port:t,control:i,service:c,nextStep:s,requestId:0}}const yl=new ec;function findPreparedBridge(e){let t=yl.getStore();for(;t;){if(t.key===e&&t.bridge&&!Atomics.load(t.bridge.service,1))return t;t=t.parent}}function takePreparedPostgresBridge(e){let t=findPreparedBridge(preparedBridgeKey(e)),n=t?.bridge;return t&&n&&(t.bridge=void 0,t.detachAbort()),n}function assertPostgresOperationCurrent(){let e=$r.getStore();if(e&&(!e.active||e.owner.refusal))throw e.owner.refusal??/* @__PURE__ */ Error(`PostgreSQL worker operation is no longer active`)}function runPostgresTransactionSync(e,t,n,r=!1,i=!1){assertPostgresOperationCurrent();let a=hr(e);return ra(a,()=>{let a=e.isTransaction&&!i,o=!1,s;try{r&&!a&&(s=za(e)),a?e.exec(`SAVEPOINT openclaw_tx_nested`):e.isTransaction||e.exec(r?`BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY`:`BEGIN ISOLATION LEVEL READ COMMITTED; SELECT pg_advisory_xact_lock(${e.advisoryLockKey})`);let i=n?.maintenance&&a?String(e.prepare(`SHOW statement_timeout`).get().statement_timeout):void 0;n?.maintenance&&e.exec(`SET LOCAL statement_timeout = '${_l}ms'`);let c=t();if(ei(c),a)i!==void 0&&e.prepare(`SELECT set_config('statement_timeout', ?, true)`).get(i),e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`);else{let commit=()=>{assertPostgresOperationCurrent(),r||Sa(e),e.exec(r?`ROLLBACK`:`COMMIT`),o=!r};n?.withCommit?ei(n.withCommit(commit)):commit()}return c}catch(t){let n=Di(t)||o;if(!n)try{a?(e.exec(`ROLLBACK TO SAVEPOINT openclaw_tx_nested`),e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`)):e.isTransaction&&e.exec(`ROLLBACK`)}catch{n=!0}if(n)try{Ei(e,t,`unknown`)}finally{try{e.close()}catch{}}throw t}finally{s?.()}})}var PostgresSyncConnection=class{constructor(e,t,n,r,i){this.schema=t,this.anchor=n,this.storeId=r,this.isOpen=!0,this.isTransaction=!1,this.mutationRevision=0,this.lastResponseAt=Date.now(),this.outcomeUnknown=!0,this.readOnlyTransaction=!1,this.pendingWrite=!1,this.mainThread=Gs===0,this.maintenance=!1,Ie(),this.admissionReadOnly=i?.readOnly===!0,Object.defineProperty(this,Symbol.for(`openclaw.postgres-sync-connection`),{value:!0}),this.advisoryLockKey=nc(`sha256`).update(r).digest().readBigInt64BE(),this.bridgeParameters={url:e,schema:t,storeId:r,...i},this.reuseKey=i?.reuse?postgresBridgeReuseKey(this.bridgeParameters):void 0,this.connect()}connect(){let e=this.reuseKey?takeIdlePostgresBridge(this.reuseKey):void 0,t=e?.bridge??takePreparedPostgresBridge(this.bridgeParameters)??createPostgresBridge(this.bridgeParameters);if(this.bridge=t,this.idleCheckout=e?e.validate?`validate`:`reconnect`:void 0,t.port.unref(),e)return t;try{this.request({operation:`connect`,schema:this.schema})}catch(e){throw this.isOpen=!1,this.isTransaction=!1,this.bridge=void 0,t.port.close(),e}return t}runTransaction(e,t,...n){let r=this.maintenance;this.maintenance=r||t?.maintenance===!0;try{return runPostgresTransactionSync(this,e,t,this.admissionReadOnly||n[0],n[1])}finally{this.maintenance=r}}readRecoveryGeneration(e=!1){return this.request({operation:`recovery-generation`,schema:this.schema,storeId:this.storeId,lock:e},!1)}loseConnection(){!this.failure&&this.outcomeUnknown&&(this.pendingWrite=!0,Gi(hr(this),!0)),this.finishWrite(),this.failure??=this.outcomeUnknown?new U(`PostgreSQL connection lost; outcome unknown`,`outcome-unknown`):/* @__PURE__ */ Error(`PostgreSQL connection lost; transaction rolled back`);let e=this.bridge;return e?.nextStep&&!this.failure.message.includes(e.nextStep)&&(this.failure.message+=` Run ${e.nextStep}.`),e&&Atomics.load(e.service,1)&&vr(this.failure),this.isOpen=!1,this.isTransaction=!1,e?.port.close(),this.bridge=void 0,this.failure}finishWrite(){this.pendingWrite&&(this.pendingWrite=!1,yr(hr(this)))}assertOpen(){if(this.failure)throw this.failure;if(!this.isOpen)throw Error(`PostgreSQL connection is closed`)}request(e,t=!0){this.mainThread&&e.operation!==`close`&&e.operation!==`release`&&Ie(),this.assertOpen();let n=this.bridge??this.connect();this.outcomeUnknown=t;let r=++n.requestId;if(r>2147483647)throw this.loseConnection();let i=(this.maintenance?_l:this.bridgeParameters.statementTimeoutMs??9e4)+3e4,a=performance.now()+i,o=n.inTransaction===!1,s=(this.idleCheckout!==void 0||o)&&(e.operation===`query`||e.operation===`recovery-generation`),c=s&&(this.idleCheckout===`validate`||o&&Date.now()-this.lastResponseAt>=1e3);n.inTransaction=void 0,this.idleCheckout=void 0,n.port.postMessage({...e,...s?{reconnectIfIdle:s}:{},...c?{validateIfIdle:c}:{},id:r,deadlineMs:i},[]),ni(`sqlite_request`,`to_worker`);for(let e=Atomics.load(n.control,0);e!==r;e=Atomics.load(n.control,0)){if(Atomics.load(n.service,1))throw this.loseConnection();let t=a-performance.now();if(t<=0)throw Atomics.store(n.service,1,1),Atomics.notify(n.service,1),this.loseConnection();Atomics.wait(n.control,0,e,Math.min(t,50))}let l=Ws(n.port)?.message;if(l&&ni(`sqlite_reply`,`from_worker`),!l||l.id!==r)throw this.loseConnection();if(`error`in l)throw e.operation===`connect`?decodePostgresError(l.error):isPostgresConnectionError(l.error.code)?this.loseConnection():(e.operation===`query`&&/^\s*COMMIT\b/i.test(e.sql)&&(this.isTransaction=!1,this.finishWrite()),decodePostgresError(l.error));return this.lastResponseAt=Date.now(),`reusable`in l?(n.inTransaction=!l.reusable,l.reusable):(n.inTransaction=`generation`in l?l.inTransaction:l.result.inTransaction,`generation`in l?l.generation:l.result)}query(e,t=[],n=!1){return ct(`postgres`,`statement`,e,()=>this.execute(preparePostgresQuery(e),t,n))}execute({sql:e,mutation:t},n,r){validatePostgresBindings(n);let i=this.isTransaction;/^\s*BEGIN\b/i.test(e)&&(this.isTransaction=!0);let a=this.request({operation:`query`,schema:this.schema,sql:e,parameters:n},!i||/^\s*COMMIT\b/i.test(e)),o=this.readOnlyTransaction;if(this.isTransaction=a.inTransaction,this.readOnlyTransaction=this.isTransaction&&(o||/^\s*BEGIN\b[^;]*\bREAD\s+ONLY\b/i.test(e)),/^\s*COMMIT\s*;?\s*$/i.test(e)&&a.command!==`COMMIT`)throw this.finishWrite(),Error(`PostgreSQL transaction rolled back instead of committing`);let s=a.mutation===`unscoped`||t===`unscoped`?`unscoped`:a.mutation??t,c=s!==void 0;if(c){if(o||this.readOnlyTransaction)throw Error(`PostgreSQL read snapshot cannot execute a mutation`);this.mutationRevision++,this.pendingWrite=!0,Gi(hr(this),s===`unscoped`)}return!this.isTransaction&&(c||i)&&ra(hr(this),()=>{this.finishWrite()}),this.outcomeUnknown=!this.isTransaction,{rows:decodePostgresRows(a,r),rowCount:a.rowCount,columns:a.fields.map(({name:e})=>({name:e}))}}exec(e){this.query(e)}prepare(e){this.assertOpen();let t=preparePostgresQuery(e),n=!1,r=[],execute=i=>{let a=ct(`postgres`,`statement`,e,()=>this.execute(t,i,n));return r=a.columns,a};return{get:(...e)=>execute(e).rows[0],all:(...e)=>execute(e).rows,iterate:(...e)=>execute(e).rows[Symbol.iterator](),run:(...e)=>({changes:execute(e).rowCount,lastInsertRowid:0}),columns:()=>r,setReadBigInts:e=>{n=e}}}releaseIdleTransport(){let e=this.bridge;if(!this.isOpen||!e||!this.reuseKey||this.isTransaction)return;let t=!1;try{e.inTransaction===!1||this.request({operation:`release`})?(retainIdlePostgresBridge(this.reuseKey,e),t=!0):(this.isOpen=!1,this.finishWrite())}finally{this.bridge=void 0,t||e.port.close()}}close(){if(this.isOpen)try{this.reuseKey&&!this.isTransaction?this.releaseIdleTransport():this.bridge&&this.request({operation:`close`})}finally{this.finishWrite(),this.isOpen=!1,this.isTransaction=!1,this.bridge?.port.close(),this.bridge=void 0}}},AppContainerSpawnUnsupportedError=class extends Error{constructor(e){super(`AppContainer: libuv ${e} cannot create child pipes; 1.53.0+ required. Run OpenClaw outside the AppContainer or use a Node build with libuv >= 1.53.0.`),this.code=`APPCONTAINER_SPAWN_UNSUPPORTED`,this.name=`AppContainerSpawnUnsupportedError`}};let bl=!1,xl;function assertAppContainerSpawnSupported(e){if(process.platform===`win32`&&!(e===`ignore`||e===`inherit`||Array.isArray(e)&&e.length>=3&&e.every(e=>e!=null&&e!==`pipe`&&e!==`overlapped`&&e!==`ipc`&&!(typeof e==`number`&&e<0)))){if(!bl){bl=!0;try{let{readCurrentAppContainerSid:e}=Rs(import.meta.url)(`@openclaw/proc-safe/windows-token`),t=e(),n=process.versions.uv,r=Number(n.split(`.`)[0]),i=Number(n.split(`.`)[1]);t!==null&&(r<1||r===1&&i<53)&&(xl=new AppContainerSpawnUnsupportedError(n))}catch(e){import(`./session-transcript-reconcile.worker-windows-appcontainer-spawn-log.runtime-khlfg3KG.mjs`).then(({logAppContainerTokenProbeFailure:t})=>t(e)).catch(()=>{})}}if(xl)throw xl}}Buffer.from(`
VmRSS:`),Buffer.from(`
VmSwap:`),Buffer.from(`
Pss:`),Buffer.from(`
SwapPss:`);const Sl=de(process.versions.node);!process.versions.bun&&Sl&&(Sl.major===24&&Sl.minor>=19||Sl.major===26&&Sl.minor>=4&&Sl.minor),dc(Js),R(Symbol.for(`openclaw.hostExecMemory`),()=>({watches:/* @__PURE__ */ new Set,sampling:!1,assessmentPending:!1})),new Te;const Cl=`memory_index_sources`,wl=`memory_index_chunks_fts`,Tl=`memory_index_paths_fts`;function buildMemoryFtsTriggers(e,t,n,r,i){let trigger=(n,r,i)=>({name:`${e}_after_${n}`,sql:`
      CREATE TRIGGER IF NOT EXISTS main.${e}_after_${n}
      AFTER ${r} ON ${t}
      BEGIN
${i}
      END;
    `});return[trigger(`insert`,`INSERT`,r),trigger(`update`,`UPDATE OF ${n}`,`${i}
${r}`),trigger(`delete`,`DELETE`,i)]}const El=buildMemoryFtsTriggers(Tl,Cl,`id, path, source`,`        INSERT INTO ${Tl} (rowid, path, source)
        VALUES (NEW.id, NEW.path, NEW.source);`,`        DELETE FROM ${Tl}
        WHERE rowid = OLD.id;`),Dl=buildMemoryFtsTriggers(wl,`memory_index_chunks`,`chunk_rowid, text, id, path, source, model, start_line, end_line`,`        INSERT INTO ${wl} (rowid, text, id, path, source, model, start_line, end_line)
        VALUES (NEW.chunk_rowid, NEW.text, NEW.id, NEW.path, NEW.source, NEW.model, NEW.start_line, NEW.end_line);`,`        DELETE FROM ${wl} WHERE rowid = OLD.chunk_rowid;`),Ol={sqlite:{openConnection:({anchor:e})=>rt(e),schema:{bootstrap:e=>e.openSqlite()}},postgres:{openConnection:e=>{if(!e.input||!e.storeId||!e.namespace)throw Error(`PostgreSQL store is not admitted`);try{return new PostgresSyncConnection(e.input.connection,e.namespace,e.anchor,e.storeId,{reuse:e.reusePostgresConnection,readOnly:e.input.readOnly,lockTimeoutMs:6e4,statementTimeoutMs:9e4})}catch(t){let n=t instanceof Error&&`code`in t&&typeof t.code==`string`?`${t.code}: `:``,r=qn(`${n}${t instanceof Error?t.message:String(t)}`.replaceAll(e.input.connection,`[REDACTED]`),{mode:`tools`});throw Error(`Cannot open PostgreSQL connection: ${r}; verify database.postgres.connection and server availability.`,{cause:t})}},schema:{bootstrap:(e,t)=>{if(!e.schema.postgres)throw Error(`Store has no PostgreSQL schema`);t.exec(ho(e.schema,e.namespace)),t.prepare(`INSERT INTO openclaw_schema_meta (store, version, store_id) VALUES (?, ?, ?)`).run(e.schema.id,e.schema.version,e.storeId)},migrate:(e,t,n)=>{if(t>e.schema.version)throw Error(`PostgreSQL ${e.schema.id} schema ${t} is newer than this build (expected ${e.schema.version}); use a compatible binary, or reverse-port with a compatible binary before downgrading.`);for(let r=t+1;r<=e.schema.version;r++){let t=e.schema.postgresMigrations?.find(e=>e.version===r);if(!t)throw Error(`Missing PostgreSQL ${e.schema.id} migration to version ${r}; use a compatible binary or restore a matching backup.`);let i=Ja(n,e.namespace,e.schema.id),a=vo(e.schema,i);if(Ka(n,e.namespace,{...a,version:r-1,postgres:t.fromSchema.postgres,postgresFragments:t.fromSchema.postgresFragments,postgresWithoutOptionalColumn:t.fromSchema.postgresWithoutOptionalColumn,postgresVectorDecoderVersion:t.fromSchema.postgresVectorDecoderVersion,postgresVectorSearchVersion:t.fromSchema.postgresVectorSearchVersion,postgresTextSearchVersion:t.fromSchema.postgresTextSearchVersion},i),t.schema.postgresVectorSearchVersion===2&&t.fromSchema.postgresVectorSearchVersion!==2)for(let t of[a.search,...Object.values(a.searchExtensions??{})])t&&go(n,t,e.namespace,2);e.beforeMigrate?.(n,r-1,new Set(i.catalog.filter(e=>e.kind===`table`).map(e=>e.table))),n.exec(t.sql),n.prepare(`UPDATE openclaw_schema_meta SET version = ? WHERE store = ?`).run(r,e.schema.id),$o(n,e.namespace,{...a,version:r,postgres:t.schema.postgres,postgresFragments:t.schema.postgresFragments,postgresWithoutOptionalColumn:t.schema.postgresWithoutOptionalColumn,postgresVectorDecoderVersion:t.schema.postgresVectorDecoderVersion,postgresVectorSearchVersion:t.schema.postgresVectorSearchVersion,postgresTextSearchVersion:t.schema.postgresTextSearchVersion})}}}}},kl={name:`database.engine`};function readEngineAnchor(e,t=`identity`,n=!1){try{return t===`schema`?[e.prepare(`SELECT schema FROM openclaw_engine_anchor LIMIT 1`).get()]:e.prepare(`SELECT store_id, engine, schema FROM openclaw_engine_anchor`).all()}catch(e){if(n||!(e instanceof Error)||e.message!==`no such table: openclaw_engine_anchor`)throw e;return}}function familySetting(e){return`database.families.${e.id===`team_reports`?`team-reports`:e.id}.engine`}function refusePostgresAnchor(e,t){let n=readEngineAnchor(e,`schema`);if(n)throw Error(`This store lives in PostgreSQL schema ${String(n[0]?.schema??`unknown`)}; set ${familySetting(t)} to postgres and configure database.postgres.connection.`)}function openEngineStore(e){let{anchor:t}=e,n=e.schema;rt(t);let r=e.input!==void 0&&n.postgres!==void 0,i=V(t,kl);if(!r){if(i?.engine===`postgres`)throw Error(`This store lives in PostgreSQL schema ${i.namespace}; set ${familySetting(n)} to postgres and configure database.postgres.connection.`);return!i&&e.inspectSqlite().hasEngineAnchor&&refusePostgresAnchor(t,n),e.prepareAnchor(),Ol.sqlite.schema.bootstrap({...e,input:e.input},t),fi(t,kl,{engine:`sqlite`}),Ol.sqlite.openConnection({...e,input:e.input})}if(i?.engine===`sqlite`)throw Error(`Existing SQLite ${n.id} data cannot switch engines; stop the Gateway and use openclaw database port for a supported store family before changing ${familySetting(n)}.`);let a=e.input?.readOnly===!0;a||e.prepareAnchor();let readOrCreateAnchor=()=>{let r=e.inspectSqlite();if(r.hasExistingData)throw Error(`Existing SQLite ${n.id} data cannot switch engines; stop the Gateway and use openclaw database port for a supported store family before changing ${familySetting(n)}.`);if(!r.hasEngineAnchor&&(e.existingOnly||a))throw Error(`Missing PostgreSQL anchor; restore the matching PostgreSQL schema and anchor.`);r.hasEngineAnchor||t.exec(`CREATE TABLE IF NOT EXISTS openclaw_engine_anchor (store_id TEXT NOT NULL, engine TEXT NOT NULL CHECK (engine = 'postgres'), schema TEXT NOT NULL)`);let i=readEngineAnchor(t,`identity`,!0)??[];if(i.length>1||r.hasEngineAnchor&&i.length===0)throw Error(`Invalid engine anchor: expected exactly one identity. Restore a matching backup.`);let o=i[0];if(o){if(typeof o.store_id!=`string`||o.engine!==`postgres`||typeof o.schema!=`string`)throw Error(`Invalid PostgreSQL anchor identity. Restore a matching backup.`);return{storeId:o.store_id,namespace:o.schema}}let s=rc(),c=Ha(e.input.schemaPrefix,n.id,s);return t.prepare(`INSERT INTO openclaw_engine_anchor (store_id, engine, schema) VALUES (?, 'postgres', ?)`).run(s,c),e.onFreshAnchor?.(t),{storeId:s,namespace:c}},o=i?.engine===`postgres`?i:e.existingOnly||a?readOrCreateAnchor():O(t,readOrCreateAnchor),s={...e,input:e.input,...o},c=Ol.postgres,l=c.openConnection(s),admit=t=>{io({db:l,namespace:o.namespace,storeId:o.storeId,store:n.id,version:n.version,schema:n,recordSchema:t,preserveSchemaSeal:e.existingVersion,requireSealedSchema:a}),e.admitPostgres?.(l,t)};try{let r=n.search?go(l,n.search,o.namespace,e.existingVersion?1:n.postgresVectorSearchVersion):void 0;if(a)l.runTransaction(()=>admit(!1),void 0,!0);else if(!i||i.engine===`postgres`&&i.version!==n.version){po(l);let t,r;l.runTransaction(()=>{let i=!l.prepare(`SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = ?`).get(o.namespace);i&&!e.existingOnly&&(l.exec(`CREATE SCHEMA IF NOT EXISTS "${o.namespace.replaceAll(`"`,`""`)}"`),l.exec(uo));let a;try{a=l.prepare(`SELECT version, store_id FROM openclaw_schema_meta WHERE store = ?`).get(n.id)}catch(e){throw Error(`Missing PostgreSQL metadata; use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.`,{cause:e})}if(a){if(a.store_id!==o.storeId)throw Error(`PostgreSQL database identity mismatch: expected ${o.storeId}, found ${String(a.store_id)}. Restore the matching anchor and PostgreSQL backup.`);if(a.version!==n.version){if(e.existingVersion){let e=n.postgresMigrations?.find(e=>e.version===Number(a.version)+1)?.fromSchema;if(!e)throw Error(`Missing PostgreSQL source schema for inspection`);n={...n,...e,postgresVectorDecoderVersion:e.postgresVectorDecoderVersion,postgresVectorSearchVersion:e.postgresVectorSearchVersion,postgresTextSearchVersion:e.postgresTextSearchVersion,version:Number(a.version)}}else{r=e.assertMigrationCurrent,r?.(),t=beginUpdatePostgresMigration(l,r),wr(l),da(l,{stage:()=>{},rollback:()=>{},commit:()=>gi(l),invalidate:()=>gi(l)});let migrate=()=>c.schema.migrate(s,Number(a.version),l);t?t.run(migrate):migrate()}}}else{if(e.existingOnly||!i)throw Error(`Missing PostgreSQL metadata; restore the matching PostgreSQL schema and anchor.`);c.schema.bootstrap(s,l)}admit(!a)},{maintenance:!0,withCommit(e){r?.(),t?.beforeCommit(),e()}},!1),t?.committed()}else admit(!1);(!i||i.engine===`postgres`&&i.version!==n.version)&&fi(t,kl,{engine:`postgres`,...o,version:n.version}),r?.();for(let e of Object.values(Ua(l)?.searchExtensions??{}))go(l,e,o.namespace,n.postgresVectorSearchVersion)?.();return l}catch(t){if(e.closeOnFailure)return e.closeOnFailure(l,t);throw l.close(),t}}const Al=/CREATE (?:UNIQUE )?INDEX ("(?:[^"]|"")+") ON ("(?:[^"]|"")+") (?:'(?:[^']|'')*'|"(?:[^"]|"")*"|[^;'"])*;/g,jl=/'(?:[^']|'')*'|"(?:[^"]|"")*"|\) (ASC|DESC)(?=,|\))/g;function withLegacyPostgresIndexOrdering(e,t=`sqlite`,n=e){let r=/* @__PURE__ */ new Map;if(t===`schema-nullability`)for(let[,e,t]of n.matchAll(/CREATE TABLE ("(?:[^"]|"")+") \(\n([\s\S]*?)\n\);/g))r.set(e,new Set([...t.matchAll(/^ {2}("(?:[^"]|"")+") (?:text|bigint|bytea|double precision)([^\n]*)/gm)].filter(e=>!/\bNOT NULL\b/.test(e[2].replace(`GENERATED BY DEFAULT AS IDENTITY`,``).split(/\bDEFAULT\b/)[0])).map(([,e])=>e)));return e.replace(Al,(e,n,i)=>t===`schema-nullability`?e.replace(/'(?:[^']|'')*'|"(?:[^"]|"")*"|\(("(?:[^"]|"")+")\) (ASC|DESC)(?=,|\))/g,(e,t,n)=>t&&r.get(i)?.has(t)?`${e} NULLS ${n===`DESC`?`LAST`:`FIRST`}`:e):e.replace(jl,(e,t)=>t?`${e} NULLS ${t===`DESC`?`LAST`:`FIRST`}`:e))}function postgresIndexOrderingMigration(e,t=`sqlite`){let n=withLegacyPostgresIndexOrdering(e,t),r=new Map([...n.matchAll(Al)].map(([e,t])=>[t,e]));return[...e.matchAll(Al)].filter(([e,t])=>r.get(t)!==e).map(([e,t,n])=>`DO $index_order$
BEGIN
  IF to_regclass('${n.replaceAll(`'`,`''`)}') IS NOT NULL THEN
    DROP INDEX ${t};
    ${e}
  END IF;
END $index_order$;`).join(`
`)}function string(e){return Ue(ge,e)}const Ml=/\\([0-7]{3})/g;function decodeMountInfoPath(e){return e.replace(Ml,(e,t)=>String.fromCharCode(Number.parseInt(t,8)))}function stateEngineInput(){if(Wr())return gr(`state`)}const Nl=[`github_publication_requests`,`github_personal_publication_requests`,`github_repository_publication_requests`];function needsPublicationDraftMigration(e){return Nl.some(t=>M(e,t)&&!P(e,t,`draft`))}const Pl={version:28,tables:Nl,columns:Nl.map(e=>`${e}.draft`),migrate:e=>{let t=!1;for(let n of Nl)t=k(e,n,`draft INTEGER`)||t;return t},applied:`Retained the requested GitHub PR draft choice (v28)`};function withLegacyPublicationDraft(e){return e.replace(/(CREATE TABLE(?: IF NOT EXISTS)? "?github_(?:personal_|repository_)?publication_requests"? \([\s\S]*?)\n {2}(?:"draft" bigint|draft INTEGER),/gu,`$1`)}const Fl=[`local_workspace_tree_packs`,`local_workspace_source_path_sets`],Il=[`tree_root_digest`,`source_paths_digest`,`canonical_fingerprints`,`projection_fingerprints`];function migrateLocalWorkspaceCas(e,t){if(t>=35||!M(e,`local_workspace_projections`))return!1;for(let t of Il)k(e,`local_workspace_projections`,`${t} BLOB`);for(let t of Fl)e.exec(B(H,t));return!0}const Ll={version:35,tables:[`local_workspace_projections`,...Fl],columns:Il.map(e=>`local_workspace_projections.${e}`),migrate:migrateLocalWorkspaceCas,applied:`Prepared shared content-addressed workspace trees and compact scan fingerprints (v35)`};function withLegacyLocalWorkspaceCas(e){return e.replace(/\n {2}(?:tree_root_digest|source_paths_digest|canonical_fingerprints|projection_fingerprints) BLOB,/gu,``).replace(/\n {2}"(?:tree_root_digest|source_paths_digest|canonical_fingerprints|projection_fingerprints)" bytea,/gu,``).replace(/CREATE TABLE(?: IF NOT EXISTS)? "?local_workspace_(?:tree_packs|source_path_sets)"? \([\s\S]*?\n\)(?: STRICT(?:, WITHOUT ROWID)?)?;\n?/gu,``)}const Rl=`local_workspace_projections`,zl=`local_workspace_manifest_nodes`,Bl=`CHECK ((baseline_json IS NULL) = (baseline_ref IS NULL))`,Vl=`CHECK (baseline_json IS NULL OR baseline_ref IS NOT NULL)`;function migrateLocalWorkspaceManifests(e,t){if(t>=31||!M(e,Rl))return!1;k(e,Rl,`checkpoint_json TEXT`);let n=K(e)??Qa(e),r=n.tableSql.get(Rl);if(typeof r!=`string`)throw Error(`Local workspace projection migration schema is missing`);if(r.includes(Bl)){let t=W(`${Rl}_migration_v31`),i=W(Rl),a=[...qe(e,Rl)].map(W).join(`, `),o=r.slice(r.indexOf(`(`)).replace(Bl,Vl);e.exec(`CREATE TABLE ${t} ${o};
      INSERT INTO ${t} (rowid, ${a}) SELECT rowid, ${a} FROM ${i};
      DROP TABLE ${i};
      ALTER TABLE ${t} RENAME TO ${i};`);for(let t of[...n.indexDefinitions.values(),...n.triggers.values()])t.table===Rl&&typeof t.sql==`string`&&e.exec(t.sql)}else if(!r.includes(Vl))throw Error(`Local workspace baseline constraint is not recognized; preserve it for Doctor`);return e.exec(B(H,zl)),!0}const Hl={version:31,tables:[Rl,zl],columns:[`${Rl}.checkpoint_json`],migrate:migrateLocalWorkspaceManifests,applied:`Prepared resumable per-path local workspace baselines and checkpoint deltas (v31)`};function withLegacyLocalWorkspaceManifests(e){return withLegacyLocalWorkspaceCas(e).replace(/\n {2}(?:checkpoint_json TEXT|"checkpoint_json" text COLLATE "C"),/gu,``).replace(/^ {2}CHECK \([^\n]*baseline_json[^\n]*baseline_ref[^\n]*\),$/gmu,e=>e.includes(`"`)?`  CHECK ((("baseline_json" IS NULL) = ("baseline_ref" IS NULL))),`:`  ${Bl},`).replace(/CREATE TABLE(?: IF NOT EXISTS)? "?local_workspace_manifest_nodes"? \([\s\S]*?\n\)(?: STRICT)?;\n?/gu,``).replace(/ALTER TABLE "local_workspace_manifest_nodes" ADD FOREIGN KEY[^;]*;\n?/gu,``)}const Ul=[[`claw_installs`,`template_installs`],[`claw_workspace_files`,`template_workspace_files`],[`claw_package_refs`,`template_package_refs`],[`claw_cron_refs`,`template_cron_refs`],[`claw_mcp_server_refs`,`template_mcp_server_refs`]],Wl=[[`template_installs`,`claw_name`,`template_name`],[`template_installs`,`claw_version`,`template_version`],[`template_package_refs`,`claw_name`,`template_name`]],Gl=new Set(Ul.map(([,e])=>e)),Kl=ml.filter(({tableName:e})=>Gl.has(e)),ql=[...Z.packageUpdatedAt,...Z.packageIntegrity],Jl=[[`template_installs`,[1,2,3].map(e=>[`openclaw.clawInstallRecord.v${e}`,`openclaw.templateInstallRecord.v${e}`])],[`template_workspace_files`,[[`openclaw.clawWorkspaceFileRecord.v1`,`openclaw.templateWorkspaceFileRecord.v1`]]],[`template_package_refs`,[[`openclaw.clawPackageRef.v1`,`openclaw.templatePackageRef.v1`]]],[`template_cron_refs`,[[`openclaw.clawCronRef.v1`,`openclaw.templateCronRef.v1`]]],[`template_mcp_server_refs`,[[`openclaw.clawMcpServerRef.v1`,`openclaw.templateMcpServerRef.v1`]]]],literal=e=>`'${e.replaceAll(`'`,`''`)}'`;function legacyTemplateStateIdentifier(e){for(let[t,n]of[...Ul,...Wl.map(([,e,t])=>[e,t])])if(e===n)return t;return e}function withLegacyTemplateStateSchema(e){return e.replace(/\btemplate_(?:installs|workspace_files|package_refs|cron_refs|mcp_server_refs|name|version)\b/gu,legacyTemplateStateIdentifier).replaceAll(`'template-introduced'`,`'claw-introduced'`).replaceAll(`'template'`,`'claw'`)}function withLegacyTemplateStateCompatibility(e){return{...e,excludedTables:e.excludedTables?.map(withLegacyTemplateStateSchema),allowedMissingTables:e.allowedMissingTables?.map(withLegacyTemplateStateSchema),allowedMissingColumns:e.allowedMissingColumns?.map(withLegacyTemplateStateSchema),allowedColumnDefinitions:e.allowedColumnDefinitions&&Object.fromEntries(Object.entries(e.allowedColumnDefinitions).map(([e,t])=>[withLegacyTemplateStateSchema(e),t.map(withLegacyTemplateStateSchema)]))}}function versionUpdates(e,t){return`UPDATE ${W(e)} SET schema_version = CASE schema_version
    ${t.map(([e,t])=>`WHEN ${literal(e)} THEN ${literal(t)}`).join(`
`)}
    ELSE schema_version END WHERE schema_version IN (${t.map(([e])=>literal(e)).join(`, `)});`}function migrateTemplateStateNames(e,t){if(t>=36)return!1;let n=Qa(e),r=new Set(n.tables),i=/* @__PURE__ */ new Set([...Ul.flat(),`agent_provenance`]),a=new Map([...n.tableSql].flatMap(([e,t])=>t&&i.has(e)?[[e,new Set(ha(t,e).columns.keys())]]:[])),addColumn=(t,n)=>{let r=n.trim().split(/\s+/,1)[0],i=a.get(t);return!r||!i||i.has(r)?!1:(e.exec(`ALTER TABLE ${W(t)} ADD COLUMN ${n};`),i.add(r),!0)},o=!1;for(let[t,n]of Ul)if(r.has(t)){if(r.has(n))throw Error(`Both ${t} and ${n} exist; preserve the store for Doctor inspection.`);e.exec(`ALTER TABLE ${W(t)} RENAME TO ${W(n)};`),r.delete(t),r.add(n);let i=a.get(t);if(!i)throw Error(`Missing predecessor column contract for ${t}`);a.set(n,i),a.delete(t),o=!0}for(let[t,n,r]of Wl)a.get(t)?.has(n)&&(e.exec(`ALTER TABLE ${W(t)} RENAME COLUMN ${W(n)} TO ${W(r)};`),a.get(t)?.delete(n),a.get(t)?.add(r),o=!0);for(let{tableName:e,columnName:t,dataType:n}of Kl)addColumn(e,`${t} ${n}`);let s=w(e);addColumn(...Z.packageUpdatedAt[0])&&A(e,s.updateTable(`template_package_refs`).set(e=>({updated_at_ms:e.ref(`installed_at_ms`)})));for(let[e,t]of Z.packageIntegrity)addColumn(e,t);let c=Qa(e),l={template_package_refs:[`origin`,`claw-introduced`,`template-introduced`],template_mcp_server_refs:[`origin`,`claw-introduced`,`template-introduced`],agent_provenance:[`created_via`,`claw`,`template`]};for(let t of[`template_installs`,...Object.keys(l)]){let n=c.tableSql.get(t);if(!n)continue;let r=n.slice(n.indexOf(`(`)),i=r;for(let[e,,n]of Wl)e===t&&(i=i.replaceAll(W(n),n));let a=l[t];if(a&&(i=i.replaceAll(literal(a[1]),literal(a[2]))),i===r)continue;let s=W(`${t}_migration_v36`),u=[...ha(n,t).columns.keys()],d=/\bWITHOUT\s+ROWID\b/iu.test(n)?[]:[`rowid`],f=[...d,...u].map(W).join(`, `),p=[...d.map(W),...u.map(e=>a&&e===a[0]?`CASE ${W(e)} WHEN ${literal(a[1])} THEN ${literal(a[2])} ELSE ${W(e)} END`:W(e))].join(`, `);e.exec(`CREATE TABLE ${s} ${i};
      INSERT INTO ${s} (${f}) SELECT ${p} FROM ${W(t)};
      DROP TABLE ${W(t)};
      ALTER TABLE ${s} RENAME TO ${W(t)};`);for(let n of[...c.indexDefinitions.values(),...c.triggers.values()])n.table===t&&typeof n.sql==`string`&&e.exec(n.sql);o=!0}for(let[t,n]of Jl)if(r.has(t))for(let[r,i]of n)A(e,s.updateTable(t).set({schema_version:i}).where(`schema_version`,`=`,r));return o}const Yl={version:36,tables:[...Ul.flat(),`agent_provenance`,`sqlite_stat1`,`sqlite_stat4`],columns:[...Kl.map(({tableName:e,columnName:t})=>`${e}.${t}`),...ql.map(([e,t])=>`${e}.${t.split(` `,1)[0]}`)],migrate:migrateTemplateStateNames,applied:`Migrated released starter tables and provenance to canonical Template names (v36)`},Xl=`DO $template_names_v36$
DECLARE item record; column_item record; constraint_name text; next_constraint_name text;
BEGIN
  FOR item IN SELECT * FROM (VALUES
    ${Ul.map(([e,t])=>`(${literal(e)}, ${literal(t)})`).join(`,
`)}
  ) AS names(old_name, new_name) LOOP
    EXECUTE format('ALTER TABLE %I RENAME TO %I', item.old_name, item.new_name);
    FOR column_item IN SELECT * FROM (VALUES
      ${Wl.map(([e,t,n])=>`(${literal(e)}, ${literal(t)}, ${literal(n)})`).join(`,
`)}
    ) AS columns(table_name, old_name, new_name) WHERE table_name = item.new_name LOOP
      EXECUTE format('ALTER TABLE %I RENAME COLUMN %I TO %I', item.new_name, column_item.old_name, column_item.new_name);
    END LOOP;
    FOR constraint_name IN SELECT conname FROM pg_constraint
      WHERE conrelid = to_regclass(item.new_name) LOOP
      next_constraint_name := constraint_name;
      IF left(constraint_name, length(item.old_name) + 1) = item.old_name || '_' THEN
        next_constraint_name := item.new_name || substr(constraint_name, length(item.old_name) + 1);
      END IF;
      next_constraint_name := replace(replace(next_constraint_name, '_claw_name_', '_template_name_'), '_claw_version_', '_template_version_');
      IF next_constraint_name <> constraint_name THEN
        EXECUTE format('ALTER TABLE %I RENAME CONSTRAINT %I TO %I', item.new_name, constraint_name, next_constraint_name);
      END IF;
    END LOOP;
  END LOOP;
  ${[`template_package_refs`,`template_mcp_server_refs`].map(e=>`
    ALTER TABLE ${W(e)} DROP CONSTRAINT ${W(`${e}_origin_check`)};
    UPDATE ${W(e)} SET origin = 'template-introduced' WHERE origin = 'claw-introduced';
    ALTER TABLE ${W(e)} ADD CONSTRAINT ${W(`${e}_origin_check`)}
      CHECK (origin IN ('template-introduced', 'pre-existing'));`).join(`
`)}
  IF to_regclass('agent_provenance') IS NOT NULL THEN
    ALTER TABLE agent_provenance DROP CONSTRAINT agent_provenance_created_via_check;
    UPDATE agent_provenance SET created_via = 'template' WHERE created_via = 'claw';
    ALTER TABLE agent_provenance ADD CONSTRAINT agent_provenance_created_via_check
      CHECK (created_via IN ('operator', 'agent', 'template'));
  END IF;
  ${Jl.map(([e,t])=>versionUpdates(e,t)).join(`
`)}
END $template_names_v36$;`,Zl={version:37,tables:[`worker_environments`],columns:[`worker_environments.resource_receipt_json`],migrate(e,t){return t>=37?!1:k(e,`worker_environments`,`resource_receipt_json TEXT`)},applied:`Retained immutable worker provider resource receipts (v37)`};function withLegacyWorkerResourceReceipts(e){return e.replace(/,\n {2}resource_receipt_json TEXT(?=\n\))|\n {2}"resource_receipt_json" text COLLATE "C",/gu,``)}const Ql=[Zl,{version:38,tables:[`session_repository_workspaces`,`worker_workspace_pending_results`],columns:[`session_repository_workspaces.disk_authority_json`,`worker_workspace_pending_results.repository_disk_authority_json`],migrate(e,t){if(t>=38)return!1;let n=k(e,`session_repository_workspaces`,`disk_authority_json TEXT`),r=k(e,`worker_workspace_pending_results`,`repository_disk_authority_json TEXT`);return n||r},applied:`Retained repository disk authority and original pending-result authority (v38)`}];function withLegacyRepositoryDiskAuthority(e){return e.replace(/\n {2}(?:(?:disk_authority_json|repository_disk_authority_json) TEXT|"(?:disk_authority_json|repository_disk_authority_json)" text COLLATE "C"),/gu,``)}const $l={version:39,tables:[`worker_environments`],columns:[`worker_environments.retention_json`],migrate(e,t){return t>=39?!1:k(e,`worker_environments`,`retention_json TEXT`)},applied:`Retained worker acquisition policy, unfinished operation, and observations (v39)`};function withLegacyWorkerRetention(e){return e.replace(/,\n {2}retention_json TEXT(?=\n\))|\n {2}"retention_json" text COLLATE "C",/gu,``)}function withLegacyWorkspaceBootstrapDeferred(e){return e.replace(`  bootstrap_deferred INTEGER,
`,``).replace(`  "bootstrap_deferred" bigint,
`,``)}function withLegacyStateV40Additions(e){return withLegacyWorkspaceBootstrapDeferred(e).replace(/CREATE TABLE IF NOT EXISTS device_pairing_browser_requests \([\s\S]*?\) STRICT;\n\n/u,``)}const eu={version:40,tables:[`worker_environments`],columns:[`worker_environments.provision_source_json`],migrate(e,t){if(t>=40||!M(e,`worker_environments`))return!1;let n=k(e,`worker_environments`,`provision_source_json TEXT`),r=e.prepare(`UPDATE worker_environments
      SET provision_source_json = '{"kind":"unavailable"}'
      WHERE (state IN ('requested', 'provisioning') AND lease_id IS NULL
        OR state = 'bootstrapping' AND owner_epoch = 0)
        AND provision_source_json IS NULL`).run();return n||Number(r.changes)>0},applied:`Original worker provisioning source retained across recovery (v40)`};function withLegacyWorkerProvisionSource(e){return e.replace(/,\n {2}provision_source_json TEXT(?=\n\))|\n {2}"provision_source_json" text COLLATE "C",/gu,``)}const tu=`state.schema.contentVersion`;var PostgresSchemaAdmissionUnavailableError=class extends Error{};function requireStatePostgresPhysicalFacts(e){let t=gs(e);if(!t)throw new PostgresSchemaAdmissionUnavailableError(`Missing PostgreSQL physical schema admission`);return t}const nu=r(e=>v(e,()=>w(e).selectFrom(`config_machine_state`).select(`value_json`).where(`state_key`,`=`,tu)));function readStateSchemaContentVersion(e,n,r=readStateSchemaContentVersionRow,i){if(z(e)){let r=t(e);if(!r)throw new PostgresSchemaAdmissionUnavailableError(`Missing PostgreSQL state schema admission; use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.`);return Math.max(n??r.userVersion,r.contentVersion)}let a=t(e);if(a)return Math.max(n??a.userVersion,a.contentVersion);let o=i??K(e)?.userVersion??Lo(e),s=parseStateSchemaContentVersion(M(e,`config_machine_state`)?r(e)?.value_json:void 0);return zt(e,{userVersion:o,contentVersion:s}),Math.max(n??o,s)}function readStateSchemaContentVersionRow(e){return nu(e)().rows[0]}function parseStateSchemaContentVersion(e){if(e===void 0)return 0;let t;try{t=e===null?null:JSON.parse(e)}catch(e){throw new N(`Invalid shared state schema content version in ${tu}.`,{cause:e})}if(typeof t!=`number`||!Number.isSafeInteger(t)||t<0)throw new N(`Invalid shared state schema content version in ${tu}.`);return t}function admitStateSchemaFacts(e,t,n=`runtime`){if(z(e))requireStatePostgresPhysicalFacts(e);else try{fs(e,r=>assertSupportedStateSchemaVersion(e,t,{userVersion:r,contentVersion:r},void 0,n))}catch(r){let i;try{i=Lo(e)}catch{throw Jo(r,t)}throw i>40?qo(`OpenClaw state database`,t,i,40,To(e),n):Jo(r,t)}}function assertSupportedStateSchemaVersion(e,n,r,i,a=`runtime`){if(z(e))return readStateSchemaContentVersion(e);try{let o=r?.userVersion??t(e)?.userVersion??K(e)?.userVersion??Lo(e),s=r?.contentVersion??(o>40?o:readStateSchemaContentVersion(e,o,i,o));if(s>40)throw qo(`OpenClaw state database`,n,s,40,To(e),a);return o}catch(e){throw Jo(e,n)}}function withPostgresSchemaAdmissionRetry(e,t,n){try{return t()}catch(r){if(!(r instanceof PostgresSchemaAdmissionUnavailableError)||!z(e)||n?.()===!1||!e.isOpen||e.isTransaction)throw r;let i=Math.min(Date.now()+1e3,_a()??1/0),a=performance.now()+Math.max(0,i-Date.now()),o=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));return Si({deadlineAtMs:i},()=>{for(let s=10;;s=Math.min(s*2,100)){sa();let c=Math.min(a-performance.now(),i-Date.now());if(c<=0||(Atomics.wait(o,0,0,Math.min(s,c)),sa(),performance.now()>=a||Date.now()>=i)||n?.()===!1||!e.isOpen||e.isTransaction)throw r;try{if(!gs(e,{refresh:!0}))continue;return t()}catch(t){if(t instanceof ka&&(performance.now()>=a||Date.now()>=i))throw r;if(!(t instanceof PostgresSchemaAdmissionUnavailableError)||n?.()===!1||!e.isOpen||e.isTransaction)throw t}}})}}const ru=18e5,iu=3e5;function isUnfencedUpdateDriver(e){let t=typeof e==`string`?Ec(e):null;return t!==null&&`${t.major}.${t.minor}.${t.patch}`==`2026.9.2`}function readStateSchemaPublicationBlocker(e,t=Date.now()){if(!M(e,`update_runs`))return;let n=A(e,w(e).selectFrom(`update_runs`).select([`run_id`,`before_json`,`status`,`updated_at_ms`,`finished_at_ms`]).where(e=>e.or([e.and([e(`status`,`=`,`running`),e(`updated_at_ms`,`>=`,t-ru)]),e.and([e(`status`,`!=`,`running`),e.or([e(`finished_at_ms`,`>`,t-iu),e(`finished_at_ms`,`is`,null)])])])).orderBy(`run_id`)).rows,r;for(let e of n){let t=JSON.parse(e.before_json);if(!I(t)||typeof t.version!=`string`||!isUnfencedUpdateDriver(t.version))continue;let n=e.status===`running`?e.updated_at_ms+ru+1:e.finished_at_ms===null?null:e.finished_at_ms+iu;(!r||n===null||r.publishAfterMs!==null&&n>r.publishAfterMs)&&(r={runId:e.run_id,updaterVersion:t.version,publishAfterMs:n})}return r}function resolveStateSchemaVersionToPublish(e){let t=Lo(e);if(t>=40||!readStateSchemaPublicationBlocker(e))return 40;if(!M(e,`config_machine_state`))throw Error(`Shared state schema publication cannot be deferred without config_machine_state.`);return writeStateSchemaContentVersion(e),$a(e),t}function writeStateSchemaContentVersion(e){A(e,w(e).insertInto(`config_machine_state`).values({state_key:tu,value_json:`40`,updated_at_ms:Date.now()}).onConflict(e=>e.column(`state_key`).doUpdateSet({value_json:`40`,updated_at_ms:Date.now()}).where(`config_machine_state.value_json`,`!=`,`40`)))}function advanceStateSchemaContentVersion(e,t){A(e,w(e).updateTable(`config_machine_state`).set({value_json:String(t.toVersion)}).where(`state_key`,`=`,tu).where(`value_json`,`=`,String(t.fromVersion)))}const Q={get eagerSql(){let e=`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "acp_replay_events" (
  "session_id" text COLLATE "C" NOT NULL,
  "seq" bigint NOT NULL,
  "at" bigint NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "run_id" text COLLATE "C",
  "update_json" text COLLATE "C" NOT NULL,
  "estimated_bytes" bigint NOT NULL DEFAULT 0,
  PRIMARY KEY ("session_id", "seq")
);

CREATE TABLE "acp_replay_sessions" (
  "session_id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "cwd" text COLLATE "C" NOT NULL,
  "complete" bigint NOT NULL,
  "created_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  "next_seq" bigint NOT NULL,
  "estimated_bytes" bigint NOT NULL DEFAULT 0,
  PRIMARY KEY ("session_id")
);

CREATE TABLE "acp_sessions" (
  "session_key" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C",
  "backend" text COLLATE "C" NOT NULL,
  "agent" text COLLATE "C" NOT NULL,
  "runtime_session_name" text COLLATE "C" NOT NULL,
  "identity_json" text COLLATE "C",
  "resume_agent_session_id" text COLLATE "C",
  "resume_acpx_session_id" text COLLATE "C",
  "mode" text COLLATE "C" NOT NULL,
  "runtime_options_json" text COLLATE "C",
  "cwd" text COLLATE "C",
  "state" text COLLATE "C" NOT NULL,
  "last_activity_at" bigint NOT NULL,
  "last_error" text COLLATE "C",
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("session_key")
);

CREATE TABLE "agent_database_leases" (
  "lease_id" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "path" text COLLATE "C" NOT NULL,
  "owner_pid" bigint NOT NULL,
  "owner_start_time" bigint,
  "opened_at" bigint NOT NULL,
  "provenance" text COLLATE "C",
  PRIMARY KEY ("lease_id")
);

CREATE TABLE "agent_databases" (
  "agent_id" text COLLATE "C" NOT NULL,
  "path" text COLLATE "C" NOT NULL,
  "schema_version" bigint NOT NULL,
  "last_seen_at" bigint NOT NULL,
  "size_bytes" bigint,
  PRIMARY KEY ("agent_id", "path")
);

CREATE TABLE "apns_registration_tombstones" (
  "node_id" text COLLATE "C" NOT NULL,
  "deleted_at_ms" bigint NOT NULL,
  PRIMARY KEY ("node_id")
);

CREATE TABLE "apns_registrations" (
  "node_id" text COLLATE "C" NOT NULL,
  "transport" text COLLATE "C" NOT NULL,
  "token" text COLLATE "C",
  "relay_handle" text COLLATE "C",
  "send_grant" text COLLATE "C",
  "installation_id" text COLLATE "C",
  "relay_origin" text COLLATE "C",
  "topic" text COLLATE "C" NOT NULL,
  "environment" text COLLATE "C" NOT NULL,
  "distribution" text COLLATE "C",
  "token_debug_suffix" text COLLATE "C",
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("node_id")
);

CREATE TABLE "audit_events" (
  "sequence" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "event_id" text COLLATE "C" NOT NULL,
  "source_id" text COLLATE "C" NOT NULL,
  "schema_version" bigint NOT NULL DEFAULT 1,
  "source_sequence" bigint NOT NULL,
  "occurred_at" bigint NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "action" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "error_code" text COLLATE "C",
  "actor_type" text COLLATE "C" NOT NULL,
  "actor_id" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C",
  "session_key" text COLLATE "C",
  "session_id" text COLLATE "C",
  "run_id" text COLLATE "C",
  "tool_call_id" text COLLATE "C",
  "tool_name" text COLLATE "C",
  "direction" text COLLATE "C",
  "channel" text COLLATE "C",
  "conversation_kind" text COLLATE "C",
  "message_outcome" text COLLATE "C",
  "reason_code" text COLLATE "C",
  "delivery_kind" text COLLATE "C",
  "failure_stage" text COLLATE "C",
  "duration_ms" bigint,
  "result_count" bigint,
  "account_ref" text COLLATE "C",
  "conversation_ref" text COLLATE "C",
  "message_ref" text COLLATE "C",
  "target_ref" text COLLATE "C",
  PRIMARY KEY ("sequence"),
  UNIQUE ("event_id"),
  UNIQUE ("source_id")
);

CREATE TABLE "audit_identity_keys" (
  "id" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "key_id" text COLLATE "C" NOT NULL,
  "key" bytea NOT NULL,
  "created_at" bigint NOT NULL,
  PRIMARY KEY ("id"),
  CHECK (("id" = 1))
);

CREATE TABLE "backup_runs" (
  "id" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  "archive_path" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "manifest_json" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("id")
);

CREATE TABLE "capture_blobs" (
  "blob_id" text COLLATE "C" NOT NULL,
  "content_type" text COLLATE "C",
  "encoding" text COLLATE "C" NOT NULL,
  "size_bytes" bigint NOT NULL,
  "sha256" text COLLATE "C" NOT NULL,
  "data" bytea NOT NULL,
  "created_at" bigint NOT NULL,
  PRIMARY KEY ("blob_id")
);

CREATE TABLE "capture_events" (
  "id" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "ts" bigint NOT NULL,
  "source_scope" text COLLATE "C" NOT NULL,
  "source_process" text COLLATE "C" NOT NULL,
  "protocol" text COLLATE "C" NOT NULL,
  "direction" text COLLATE "C" NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "flow_id" text COLLATE "C" NOT NULL,
  "method" text COLLATE "C",
  "host" text COLLATE "C",
  "path" text COLLATE "C",
  "status" bigint,
  "close_code" bigint,
  "content_type" text COLLATE "C",
  "headers_json" text COLLATE "C",
  "data_text" text COLLATE "C",
  "data_blob_id" text COLLATE "C",
  "data_sha256" text COLLATE "C",
  "error_text" text COLLATE "C",
  "meta_json" text COLLATE "C",
  PRIMARY KEY ("id")
);

CREATE TABLE "capture_sessions" (
  "id" text COLLATE "C" NOT NULL,
  "started_at" bigint NOT NULL,
  "ended_at" bigint,
  "mode" text COLLATE "C" NOT NULL,
  "source_scope" text COLLATE "C" NOT NULL,
  "source_process" text COLLATE "C" NOT NULL,
  "proxy_url" text COLLATE "C",
  PRIMARY KEY ("id")
);

CREATE TABLE "channel_ingress_events" (
  "queue_name" text COLLATE "C" NOT NULL,
  "event_id" text COLLATE "C" NOT NULL,
  "channel_id" text COLLATE "C" NOT NULL,
  "account_id" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "lane_key" text COLLATE "C",
  "payload_json" text COLLATE "C" NOT NULL,
  "metadata_json" text COLLATE "C",
  "received_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  "claim_token" text COLLATE "C",
  "claim_owner" text COLLATE "C",
  "claimed_at" bigint,
  "attempts" bigint NOT NULL DEFAULT 0,
  "last_attempt_at" bigint,
  "last_error" text COLLATE "C",
  "failed_reason" text COLLATE "C",
  "failed_at" bigint,
  "completed_at" bigint,
  "completed_metadata_json" text COLLATE "C",
  PRIMARY KEY ("queue_name", "event_id")
);

CREATE TABLE "channel_pairing_allow_entries" (
  "channel_key" text COLLATE "C" NOT NULL,
  "account_id" text COLLATE "C" NOT NULL,
  "entry" text COLLATE "C" NOT NULL,
  "sort_order" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("channel_key", "account_id", "entry")
);

CREATE TABLE "channel_pairing_requests" (
  "channel_key" text COLLATE "C" NOT NULL,
  "account_id" text COLLATE "C" NOT NULL,
  "request_id" text COLLATE "C" NOT NULL,
  "code" text COLLATE "C" NOT NULL,
  "created_at" text COLLATE "C" NOT NULL,
  "last_seen_at" text COLLATE "C" NOT NULL,
  "meta_json" text COLLATE "C",
  PRIMARY KEY ("channel_key", "account_id", "request_id")
);

CREATE TABLE "clawhub_promotion_claims" (
  "slug" text COLLATE "C" NOT NULL,
  "provider" text COLLATE "C",
  "model_keys_json" text COLLATE "C" NOT NULL,
  "ends_at_ms" bigint NOT NULL,
  "claimed_at_ms" bigint NOT NULL,
  PRIMARY KEY ("slug")
);

CREATE TABLE "config_health_entries" (
  "config_path" text COLLATE "C" NOT NULL,
  "last_known_good_json" text COLLATE "C",
  "last_promoted_good_json" text COLLATE "C",
  "last_observed_suspicious_signature" text COLLATE "C",
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("config_path")
);

CREATE TABLE "config_machine_state" (
  "state_key" text COLLATE "C" NOT NULL,
  "value_json" text COLLATE "C" NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("state_key")
);

CREATE TABLE "cron_job_scratch" (
  "store_key" text COLLATE "C" NOT NULL,
  "job_id" text COLLATE "C" NOT NULL,
  "content" text COLLATE "C",
  "revision" bigint NOT NULL,
  "source_sha256" text COLLATE "C",
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("store_key", "job_id"),
  CHECK (("revision" >= 1)),
  CHECK ("content" IS NULL OR (octet_length(convert_to("content", 'UTF8')) <= 262144))
);

CREATE TABLE "cron_jobs" (
  "store_key" text COLLATE "C" NOT NULL,
  "job_id" text COLLATE "C" NOT NULL,
  "declaration_key" text COLLATE "C",
  "owner_agent_id" text COLLATE "C",
  "name" text COLLATE "C" NOT NULL,
  "description" text COLLATE "C",
  "enabled" bigint NOT NULL,
  "agent_id" text COLLATE "C",
  "payload_kind" text COLLATE "C" NOT NULL,
  "job_json" text COLLATE "C" NOT NULL,
  "grant_definition_revision" text COLLATE "C",
  "grant_definition_generation" bigint,
  "grant_definition_updated_at" bigint,
  "state_json" text COLLATE "C" NOT NULL DEFAULT '{}',
  "runtime_updated_at_ms" bigint,
  "schedule_identity" text COLLATE "C",
  "sort_order" bigint NOT NULL DEFAULT 0,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("store_key", "job_id")
);

CREATE TABLE "current_conversation_bindings" (
  "binding_key" text COLLATE "C" NOT NULL,
  "binding_id" text COLLATE "C" NOT NULL,
  "target_session_key" text COLLATE "C" NOT NULL,
  "channel" text COLLATE "C" NOT NULL,
  "account_id" text COLLATE "C" NOT NULL,
  "conversation_kind" text COLLATE "C" NOT NULL,
  "parent_conversation_id" text COLLATE "C",
  "conversation_id" text COLLATE "C" NOT NULL,
  "target_kind" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "bound_at" bigint NOT NULL,
  "expires_at" bigint,
  "metadata_json" text COLLATE "C",
  "record_json" text COLLATE "C" NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("binding_key")
);

CREATE TABLE "delivery_queue_entries" (
  "queue_name" text COLLATE "C" NOT NULL,
  "id" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "entry_kind" text COLLATE "C",
  "session_key" text COLLATE "C",
  "channel" text COLLATE "C",
  "target" text COLLATE "C",
  "account_id" text COLLATE "C",
  "retry_count" bigint NOT NULL DEFAULT 0,
  "last_attempt_at" bigint,
  "last_error" text COLLATE "C",
  "recovery_state" text COLLATE "C",
  "platform_send_started_at" bigint,
  "entry_json" text COLLATE "C" NOT NULL,
  "retention_id_prefix" text COLLATE "C",
  "retention_max_age_ms" bigint,
  "retention_max_entries" bigint,
  "enqueued_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  "failed_at" bigint,
  PRIMARY KEY ("queue_name", "id")
);

CREATE TABLE "device_bootstrap_tokens" (
  "token_key" text COLLATE "C" NOT NULL,
  "token" text COLLATE "C" NOT NULL,
  "setup_id" text COLLATE "C",
  "ts" bigint NOT NULL,
  "device_id" text COLLATE "C",
  "public_key" text COLLATE "C",
  "profile_json" text COLLATE "C",
  "redeemed_profile_json" text COLLATE "C",
  "pending_profile_json" text COLLATE "C",
  "issued_at_ms" bigint NOT NULL,
  "last_used_at_ms" bigint,
  PRIMARY KEY ("token_key")
);

CREATE TABLE "device_pairing_paired" (
  "device_id" text COLLATE "C" NOT NULL,
  "public_key" text COLLATE "C" NOT NULL,
  "display_name" text COLLATE "C",
  "operator_label" text COLLATE "C",
  "platform" text COLLATE "C",
  "device_family" text COLLATE "C",
  "client_id" text COLLATE "C",
  "client_mode" text COLLATE "C",
  "browser_origin" text COLLATE "C",
  "role" text COLLATE "C",
  "roles_json" text COLLATE "C",
  "scopes_json" text COLLATE "C",
  "approved_scopes_json" text COLLATE "C",
  "remote_ip" text COLLATE "C",
  "tokens_json" text COLLATE "C",
  "approved_via" text COLLATE "C",
  "node_surface_json" text COLLATE "C",
  "pending_node_surface_json" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "approved_at_ms" bigint NOT NULL,
  "last_seen_at_ms" bigint,
  "last_seen_reason" text COLLATE "C",
  PRIMARY KEY ("device_id")
);

CREATE TABLE "device_pairing_pending" (
  "request_id" text COLLATE "C" NOT NULL,
  "device_id" text COLLATE "C" NOT NULL,
  "public_key" text COLLATE "C" NOT NULL,
  "display_name" text COLLATE "C",
  "platform" text COLLATE "C",
  "device_family" text COLLATE "C",
  "client_id" text COLLATE "C",
  "client_mode" text COLLATE "C",
  "browser_origin" text COLLATE "C",
  "role" text COLLATE "C",
  "roles_json" text COLLATE "C",
  "scopes_json" text COLLATE "C",
  "remote_ip" text COLLATE "C",
  "silent" bigint,
  "is_repair" bigint,
  "ts" bigint NOT NULL,
  "refreshed_at_ms" bigint,
  PRIMARY KEY ("request_id")
);

CREATE TABLE "diagnostic_events" (
  "scope" text COLLATE "C" NOT NULL,
  "event_key" text COLLATE "C" NOT NULL,
  "payload_json" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  "sequence" bigint NOT NULL DEFAULT 0,
  PRIMARY KEY ("scope", "event_key")
);

CREATE TABLE "exec_approvals_config" (
  "config_key" text COLLATE "C" NOT NULL,
  "raw_json" text COLLATE "C" NOT NULL,
  "socket_path" text COLLATE "C",
  "has_socket_token" bigint NOT NULL,
  "default_security" text COLLATE "C",
  "default_ask" text COLLATE "C",
  "default_ask_fallback" text COLLATE "C",
  "auto_allow_skills" bigint,
  "agent_count" bigint NOT NULL,
  "allowlist_count" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("config_key")
);

CREATE TABLE "flow_runs" (
  "flow_id" text COLLATE "C" NOT NULL,
  "shape" text COLLATE "C",
  "sync_mode" text COLLATE "C" NOT NULL DEFAULT 'managed',
  "owner_key" text COLLATE "C" NOT NULL,
  "requester_origin_json" text COLLATE "C",
  "controller_id" text COLLATE "C",
  "revision" bigint NOT NULL DEFAULT 0,
  "status" text COLLATE "C" NOT NULL,
  "notify_policy" text COLLATE "C" NOT NULL,
  "goal" text COLLATE "C" NOT NULL,
  "current_step" text COLLATE "C",
  "blocked_task_id" text COLLATE "C",
  "blocked_summary" text COLLATE "C",
  "state_json" text COLLATE "C",
  "wait_json" text COLLATE "C",
  "cancel_requested_at" bigint,
  "created_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  "ended_at" bigint,
  PRIMARY KEY ("flow_id")
);

CREATE TABLE "gateway_boot_lifecycle" (
  "boot_id" text COLLATE "C" NOT NULL,
  "pid" bigint NOT NULL,
  "started_at_ms" bigint NOT NULL,
  "completed_at_ms" bigint,
  "outcome" text COLLATE "C",
  "startup_reason" text COLLATE "C",
  "reason" text COLLATE "C",
  PRIMARY KEY ("boot_id")
);

CREATE TABLE "gateway_restart_handoff" (
  "handoff_key" text COLLATE "C" NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "version" bigint NOT NULL,
  "intent_id" text COLLATE "C" NOT NULL,
  "pid" bigint NOT NULL,
  "process_instance_id" text COLLATE "C",
  "created_at" bigint NOT NULL,
  "expires_at" bigint NOT NULL,
  "reason" text COLLATE "C",
  "restart_trace_started_at" bigint,
  "restart_trace_last_at" bigint,
  "source" text COLLATE "C" NOT NULL,
  "restart_kind" text COLLATE "C" NOT NULL,
  "supervisor_mode" text COLLATE "C" NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("handoff_key")
);

CREATE TABLE "gateway_restart_intent" (
  "intent_key" text COLLATE "C" NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "pid" bigint NOT NULL,
  "created_at" bigint NOT NULL,
  "reason" text COLLATE "C",
  "force" bigint,
  "wait_ms" bigint,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("intent_key")
);

CREATE TABLE "gateway_restart_sentinel" (
  "sentinel_key" text COLLATE "C" NOT NULL,
  "version" bigint NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "ts" bigint NOT NULL,
  "session_key" text COLLATE "C",
  "thread_id" text COLLATE "C",
  "delivery_channel" text COLLATE "C",
  "delivery_to" text COLLATE "C",
  "delivery_account_id" text COLLATE "C",
  "message" text COLLATE "C",
  "continuation_json" text COLLATE "C",
  "doctor_hint" text COLLATE "C",
  "stats_json" text COLLATE "C",
  "payload_json" text COLLATE "C" NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("sentinel_key")
);

CREATE TABLE "macos_port_guardian_records" (
  "pid" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "port" bigint NOT NULL,
  "command" text COLLATE "C" NOT NULL,
  "mode" text COLLATE "C" NOT NULL,
  "timestamp" double precision NOT NULL,
  PRIMARY KEY ("pid")
);

CREATE TABLE "managed_outgoing_image_records" (
  "attachment_id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C",
  "message_id" text COLLATE "C",
  "created_at" text COLLATE "C" NOT NULL,
  "updated_at" text COLLATE "C",
  "retention_class" text COLLATE "C",
  "alt" text COLLATE "C" NOT NULL,
  "original_media_root" text COLLATE "C" NOT NULL,
  "original_media_id" text COLLATE "C" NOT NULL,
  "original_media_subdir" text COLLATE "C" NOT NULL,
  "original_content_type" text COLLATE "C" NOT NULL,
  "original_width" bigint,
  "original_height" bigint,
  "original_size_bytes" bigint,
  "original_filename" text COLLATE "C",
  "record_json" text COLLATE "C" NOT NULL,
  "cleanup_pending" bigint NOT NULL DEFAULT 0,
  PRIMARY KEY ("attachment_id"),
  CHECK (("cleanup_pending" IN (0, 1)))
);

CREATE TABLE "mcp_oauth_stores" (
  "store_key" text COLLATE "C" NOT NULL,
  "format_version" bigint NOT NULL,
  "store_json" text COLLATE "C" NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("store_key"),
  CHECK (("format_version" = 1))
);

CREATE TABLE "meeting_transcript_sessions" (
  "started_at_ms" bigint,
  "session_id" text COLLATE "C" NOT NULL,
  "started_at" text COLLATE "C" NOT NULL,
  "selector" text COLLATE "C" NOT NULL,
  "export_key" text COLLATE "C" NOT NULL,
  "session_slug" text COLLATE "C" NOT NULL,
  "provider_id" text COLLATE "C" NOT NULL,
  "title" text COLLATE "C",
  "source_json" text COLLATE "C" NOT NULL,
  "source_account_id" text COLLATE "C",
  "source_guild_id" text COLLATE "C",
  "source_channel_id" text COLLATE "C",
  "source_meeting_url" text COLLATE "C",
  "source_thread_ts" text COLLATE "C",
  "source_file_id" text COLLATE "C",
  "stopped_at" text COLLATE "C",
  "metadata_json" text COLLATE "C",
  "metadata_agent_id" text COLLATE "C",
  "export_manifest_json" text COLLATE "C" NOT NULL DEFAULT '{}',
  "export_pending_json" text COLLATE "C" NOT NULL DEFAULT '[]',
  "next_utterance_seq" bigint NOT NULL DEFAULT 0,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("session_id", "started_at"),
  CHECK (("next_utterance_seq" >= 0)),
  CHECK (("created_at_ms" >= 0)),
  CHECK (("updated_at_ms" >= 0)),
  UNIQUE ("selector")
);

CREATE TABLE "meeting_transcript_summaries" (
  "session_id" text COLLATE "C" NOT NULL,
  "session_started_at" text COLLATE "C" NOT NULL,
  "generated_at" text COLLATE "C",
  "summary_json" text COLLATE "C",
  "overview" text COLLATE "C",
  "markdown" text COLLATE "C",
  "utterance_count" bigint NOT NULL,
  PRIMARY KEY ("session_id", "session_started_at"),
  CHECK (("utterance_count" >= 0)),
  CHECK ("summary_json" IS NOT NULL OR "markdown" IS NOT NULL)
);

CREATE TABLE "meeting_transcript_utterances" (
  "session_id" text COLLATE "C" NOT NULL,
  "session_started_at" text COLLATE "C" NOT NULL,
  "sequence" bigint NOT NULL,
  "utterance_id" text COLLATE "C",
  "started_at" text COLLATE "C",
  "ended_at" text COLLATE "C",
  "speaker_id" text COLLATE "C",
  "speaker_label" text COLLATE "C",
  "text" text COLLATE "C" NOT NULL,
  "final" bigint,
  "metadata_json" text COLLATE "C",
  PRIMARY KEY ("session_id", "session_started_at", "sequence"),
  CHECK (("sequence" >= 0)),
  CHECK (("final" IN (0, 1)))
);

CREATE TABLE "migration_runs" (
  "id" text COLLATE "C" NOT NULL,
  "started_at" bigint NOT NULL,
  "finished_at" bigint,
  "status" text COLLATE "C" NOT NULL,
  "report_json" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("id")
);

CREATE TABLE "migration_sources" (
  "source_key" text COLLATE "C" NOT NULL,
  "migration_kind" text COLLATE "C" NOT NULL,
  "source_path" text COLLATE "C" NOT NULL,
  "target_table" text COLLATE "C" NOT NULL,
  "source_sha256" text COLLATE "C",
  "source_size_bytes" bigint,
  "source_record_count" bigint,
  "last_run_id" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "imported_at" bigint NOT NULL,
  "removed_source" bigint NOT NULL DEFAULT 0,
  "report_json" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("source_key")
);

CREATE TABLE "native_hook_relay_bridges" (
  "relay_id" text COLLATE "C" NOT NULL,
  "pid" bigint NOT NULL,
  "hostname" text COLLATE "C" NOT NULL,
  "port" bigint NOT NULL,
  "token" text COLLATE "C" NOT NULL,
  "expires_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("relay_id")
);

CREATE TABLE "official_external_plugin_catalog_snapshots" (
  "feed_url" text COLLATE "C" NOT NULL,
  "body" text COLLATE "C" NOT NULL,
  "status" bigint NOT NULL,
  "etag" text COLLATE "C",
  "last_modified" text COLLATE "C",
  "checksum" text COLLATE "C" NOT NULL,
  "saved_at" text COLLATE "C" NOT NULL,
  "trust_mode" text COLLATE "C",
  "trust_key_id" text COLLATE "C",
  "trust_signature_count" bigint,
  "trust_threshold" bigint,
  "trust_verified_at" text COLLATE "C",
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("feed_url")
);

CREATE TABLE "operator_approvals" (
  "cursor_id" bigint NOT NULL,
  "approval_id" text COLLATE "C" NOT NULL,
  "resolution_ref" text COLLATE "C" NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "presentation_json" text COLLATE "C" NOT NULL,
  "requested_by_device_id" text COLLATE "C",
  "requested_by_client_id" text COLLATE "C",
  "requested_by_device_token_auth" bigint NOT NULL DEFAULT 0,
  "reviewer_device_ids_json" text COLLATE "C" NOT NULL,
  "source_agent_id" text COLLATE "C",
  "source_session_key" text COLLATE "C",
  "source_session_id" text COLLATE "C",
  "source_run_id" text COLLATE "C",
  "source_tool_call_id" text COLLATE "C",
  "source_tool_name" text COLLATE "C",
  "audience_session_keys_json" text COLLATE "C" NOT NULL,
  "runtime_epoch" text COLLATE "C" NOT NULL,
  "created_at_ms" bigint NOT NULL,
  "expires_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  "decision" text COLLATE "C",
  "terminal_reason" text COLLATE "C",
  "resolved_at_ms" bigint,
  "resolver_kind" text COLLATE "C",
  "resolver_id" text COLLATE "C",
  "consumed_at_ms" bigint,
  "consumed_by" text COLLATE "C",
  PRIMARY KEY ("approval_id"),
  CHECK ((char_length("approval_id") > 0) AND ("approval_id" NOT IN ('.', '..'))),
  CHECK ((char_length("resolution_ref") = 43) AND ("resolution_ref" COLLATE "C" !~ '\\A.*[^A-Za-z0-9_-].*\\Z')),
  CHECK (("kind" IN ('exec', 'plugin', 'system-agent'))),
  CHECK (("status" IN ('pending', 'allowed', 'denied', 'expired', 'cancelled'))),
  CHECK (("decision" IN ('allow-once', 'allow-always', 'deny'))),
  CHECK (("terminal_reason" IN ('user', 'timeout', 'malformed-verdict', 'no-route', 'run-aborted', 'gateway-restart', 'storage-corrupt'))),
  CHECK (("resolver_kind" IN ('device', 'channel', 'runtime', 'system'))),
  CHECK (("expires_at_ms" >= "created_at_ms")),
  CHECK (("updated_at_ms" >= "created_at_ms")),
  CHECK ("resolved_at_ms" IS NULL OR ("resolved_at_ms" >= "created_at_ms")),
  CHECK ("resolved_at_ms" IS NULL OR ("resolved_at_ms" <= "updated_at_ms")),
  CHECK ("consumed_at_ms" IS NULL OR ("consumed_at_ms" >= "resolved_at_ms")),
  CHECK ("consumed_at_ms" IS NULL OR ("consumed_at_ms" <= "updated_at_ms")),
  CHECK (("requested_by_device_token_auth" IN (0, 1))),
  CHECK ((("status" = 'pending') AND "decision" IS NULL AND "terminal_reason" IS NULL AND "resolved_at_ms" IS NULL AND "resolver_kind" IS NULL AND "resolver_id" IS NULL AND "consumed_at_ms" IS NULL AND "consumed_by" IS NULL) OR (("status" = 'allowed') AND ("decision" IN ('allow-once', 'allow-always')) AND ("terminal_reason" = 'user') AND "resolved_at_ms" IS NOT NULL AND "resolver_kind" IS NOT NULL) OR (("status" = 'denied') AND ("decision" = 'deny') AND ("terminal_reason" IN ('user', 'malformed-verdict', 'no-route', 'storage-corrupt')) AND "resolved_at_ms" IS NOT NULL AND "resolver_kind" IS NOT NULL AND "consumed_at_ms" IS NULL AND "consumed_by" IS NULL) OR (("status" = 'expired') AND ("decision" = 'deny') AND ("terminal_reason" = 'timeout') AND "resolved_at_ms" IS NOT NULL AND "resolver_kind" IS NOT NULL AND "consumed_at_ms" IS NULL AND "consumed_by" IS NULL) OR (("status" = 'cancelled') AND ("decision" = 'deny') AND ("terminal_reason" IN ('run-aborted', 'gateway-restart')) AND "resolved_at_ms" IS NOT NULL AND "resolver_kind" IS NOT NULL AND "consumed_at_ms" IS NULL AND "consumed_by" IS NULL)),
  CHECK (("consumed_at_ms" IS NULL AND "consumed_by" IS NULL) OR (("status" = 'allowed') AND ("decision" = 'allow-once') AND "consumed_at_ms" IS NOT NULL AND "consumed_by" IS NOT NULL))
);

CREATE TABLE "outbound_media_provenance" (
  "realpath" text COLLATE "C" NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "version" bigint NOT NULL,
  "sha256" text COLLATE "C" NOT NULL,
  "size_bytes" bigint NOT NULL,
  "created_at_ms" bigint NOT NULL,
  PRIMARY KEY ("realpath")
);

CREATE TABLE "plugin_binding_approvals" (
  "plugin_root" text COLLATE "C" NOT NULL,
  "channel" text COLLATE "C" NOT NULL,
  "account_id" text COLLATE "C" NOT NULL,
  "plugin_id" text COLLATE "C" NOT NULL,
  "plugin_name" text COLLATE "C",
  "approved_at" bigint NOT NULL,
  PRIMARY KEY ("plugin_root", "channel", "account_id")
);

CREATE TABLE "plugin_blob_entries" (
  "plugin_id" text COLLATE "C" NOT NULL,
  "namespace" text COLLATE "C" NOT NULL,
  "entry_key" text COLLATE "C" NOT NULL,
  "metadata_json" text COLLATE "C" NOT NULL,
  "blob" bytea NOT NULL,
  "created_at" bigint NOT NULL,
  "expires_at" bigint,
  PRIMARY KEY ("plugin_id", "namespace", "entry_key")
);

CREATE TABLE "plugin_state_entries" (
  "plugin_id" text COLLATE "C" NOT NULL,
  "namespace" text COLLATE "C" NOT NULL,
  "entry_key" text COLLATE "C" NOT NULL,
  "value_json" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  "expires_at" bigint,
  PRIMARY KEY ("plugin_id", "namespace", "entry_key")
);

CREATE TABLE "sandbox_registry_entries" (
  "registry_kind" text COLLATE "C" NOT NULL,
  "container_name" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C",
  "backend_id" text COLLATE "C",
  "runtime_label" text COLLATE "C",
  "image" text COLLATE "C",
  "created_at_ms" bigint,
  "last_used_at_ms" bigint,
  "config_label_kind" text COLLATE "C",
  "config_hash" text COLLATE "C",
  "cdp_port" bigint,
  "no_vnc_port" bigint,
  "entry_json" text COLLATE "C" NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("registry_kind", "container_name")
);

CREATE TABLE "schema_meta" (
  "meta_key" text COLLATE "C" NOT NULL,
  "role" text COLLATE "C" NOT NULL,
  "schema_version" bigint NOT NULL,
  "agent_id" text COLLATE "C",
  "app_version" text COLLATE "C",
  "created_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("meta_key")
);

CREATE TABLE "session_groups" (
  "name" text COLLATE "C" NOT NULL,
  "position" bigint NOT NULL,
  "created_at" bigint NOT NULL,
  "cwd" text COLLATE "C",
  "worktree" bigint,
  PRIMARY KEY ("name")
);

CREATE TABLE "session_state_events" (
  "sequence" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "dedupe_key" text COLLATE "C",
  "session_key" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C",
  "agent_id" text COLLATE "C" NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "actor_type" text COLLATE "C" NOT NULL,
  "actor_id" text COLLATE "C",
  "run_id" text COLLATE "C",
  "occurred_at" bigint NOT NULL,
  "summary" text COLLATE "C" NOT NULL,
  "payload_json" text COLLATE "C",
  PRIMARY KEY ("sequence"),
  UNIQUE ("dedupe_key")
);

CREATE TABLE "session_state_heads" (
  "session_key" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "last_sequence" bigint NOT NULL,
  "pruned_max_sequence" bigint NOT NULL DEFAULT 0,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("session_key", "agent_id")
);

CREATE TABLE "session_upstream_links" (
  "session_key" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "catalog_id" text COLLATE "C" NOT NULL,
  "host_id" text COLLATE "C" NOT NULL,
  "thread_id" text COLLATE "C" NOT NULL,
  "upstream_kind" text COLLATE "C" NOT NULL,
  "upstream_ref_json" text COLLATE "C",
  "last_marker_json" text COLLATE "C",
  "last_scanned_at" bigint,
  "created_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("session_key", "agent_id")
);

CREATE TABLE "session_watch_cursors" (
  "watcher_session_key" text COLLATE "C" NOT NULL,
  "watcher_store_path" text COLLATE "C",
  "target_session_key" text COLLATE "C" NOT NULL,
  "last_seen_sequence" bigint NOT NULL DEFAULT 0,
  "notified_sequence" bigint NOT NULL DEFAULT 0,
  "material_sequence" bigint NOT NULL DEFAULT 0,
  "provenance" text COLLATE "C" NOT NULL DEFAULT 'explicit',
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("watcher_session_key", "target_session_key"),
  CHECK (("provenance" IN ('explicit', 'ambient-group')))
);

CREATE TABLE "skill_upload_chunks" (
  "upload_id" text COLLATE "C" NOT NULL,
  "byte_offset" bigint NOT NULL,
  "size_bytes" bigint NOT NULL,
  "chunk_blob" bytea NOT NULL,
  PRIMARY KEY ("upload_id", "byte_offset"),
  CHECK (("byte_offset" >= 0)),
  CHECK (("size_bytes" > 0)),
  CHECK ((octet_length("chunk_blob") = "size_bytes"))
);

CREATE TABLE "skill_uploads" (
  "upload_id" text COLLATE "C" NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "slug" text COLLATE "C" NOT NULL,
  "force" bigint NOT NULL,
  "size_bytes" bigint NOT NULL,
  "sha256" text COLLATE "C",
  "actual_sha256" text COLLATE "C",
  "received_bytes" bigint NOT NULL,
  "archive_blob" bytea NOT NULL,
  "created_at" bigint NOT NULL,
  "expires_at" bigint NOT NULL,
  "committed" bigint NOT NULL,
  "committed_at" bigint,
  "idempotency_key_hash" text COLLATE "C",
  PRIMARY KEY ("upload_id"),
  UNIQUE ("idempotency_key_hash")
);

CREATE TABLE "skill_usage" (
  "skill_file" text COLLATE "C" NOT NULL,
  "skill_key" text COLLATE "C" NOT NULL,
  "skill_name" text COLLATE "C" NOT NULL,
  "skill_source" text COLLATE "C" NOT NULL,
  "first_used_at_ms" bigint NOT NULL,
  "last_used_at_ms" bigint NOT NULL,
  "use_count" bigint NOT NULL,
  "last_agent_id" text COLLATE "C",
  PRIMARY KEY ("skill_file")
);

CREATE TABLE "state_leases" (
  "scope" text COLLATE "C" NOT NULL,
  "lease_key" text COLLATE "C" NOT NULL,
  "owner" text COLLATE "C" NOT NULL,
  "expires_at" bigint,
  "heartbeat_at" bigint,
  "payload_json" text COLLATE "C",
  "created_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("scope", "lease_key")
);

CREATE TABLE "subagent_runs" (
  "run_id" text COLLATE "C" NOT NULL,
  "child_session_key" text COLLATE "C" NOT NULL,
  "controller_session_key" text COLLATE "C",
  "controller_store_path" text COLLATE "C",
  "requester_session_key" text COLLATE "C" NOT NULL,
  "requester_store_path" text COLLATE "C",
  "created_at" bigint NOT NULL,
  "payload_json" text COLLATE "C" NOT NULL DEFAULT '{}',
  PRIMARY KEY ("run_id")
);

CREATE TABLE "task_delivery_state" (
  "task_id" text COLLATE "C" NOT NULL,
  "requester_origin_json" text COLLATE "C",
  "last_notified_event_at" bigint,
  PRIMARY KEY ("task_id")
);

CREATE TABLE "task_runs" (
  "task_id" text COLLATE "C" NOT NULL,
  "runtime" text COLLATE "C" NOT NULL,
  "task_kind" text COLLATE "C",
  "source_id" text COLLATE "C",
  "requester_session_key" text COLLATE "C",
  "owner_key" text COLLATE "C" NOT NULL,
  "scope_kind" text COLLATE "C" NOT NULL,
  "child_session_key" text COLLATE "C",
  "parent_flow_id" text COLLATE "C",
  "parent_task_id" text COLLATE "C",
  "agent_id" text COLLATE "C",
  "requester_agent_id" text COLLATE "C",
  "run_id" text COLLATE "C",
  "execution_owner_host" text COLLATE "C",
  "execution_owner_pid" bigint,
  "execution_owner_start_identity" bigint,
  "label" text COLLATE "C",
  "task" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "delivery_status" text COLLATE "C" NOT NULL,
  "notify_policy" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  "started_at" bigint,
  "ended_at" bigint,
  "last_event_at" bigint,
  "cleanup_after" bigint,
  "tool_use_count" bigint,
  "last_tool_name" text COLLATE "C",
  "error" text COLLATE "C",
  "progress_summary" text COLLATE "C",
  "terminal_summary" text COLLATE "C",
  "terminal_outcome" text COLLATE "C",
  "detail_json" text COLLATE "C",
  PRIMARY KEY ("task_id")
);

CREATE TABLE "template_cron_refs" (
  "agent_id" text COLLATE "C" NOT NULL,
  "manifest_id" text COLLATE "C" NOT NULL,
  "schema_version" text COLLATE "C" NOT NULL,
  "declaration_key" text COLLATE "C" NOT NULL,
  "scheduler_job_id" text COLLATE "C",
  "status" text COLLATE "C" NOT NULL,
  "job_json" text COLLATE "C" NOT NULL,
  "error" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("agent_id", "manifest_id"),
  UNIQUE ("declaration_key"),
  UNIQUE ("scheduler_job_id")
);

CREATE TABLE "template_installs" (
  "agent_id" text COLLATE "C" NOT NULL,
  "schema_version" text COLLATE "C" NOT NULL,
  "source_kind" text COLLATE "C" NOT NULL,
  "template_name" text COLLATE "C" NOT NULL,
  "template_version" text COLLATE "C" NOT NULL,
  "package_root" text COLLATE "C" NOT NULL,
  "manifest_path" text COLLATE "C" NOT NULL,
  "integrity_kind" text COLLATE "C" NOT NULL,
  "integrity" text COLLATE "C" NOT NULL,
  "source_byte_length" bigint NOT NULL,
  "manifest_schema_version" bigint NOT NULL,
  "plan_integrity" text COLLATE "C" NOT NULL,
  "workspace" text COLLATE "C" NOT NULL,
  "agent_config_digest" text COLLATE "C" NOT NULL,
  "agent_owned_paths_json" text COLLATE "C" NOT NULL,
  "bootstrap_source_path" text COLLATE "C",
  "bootstrap_content_digest" text COLLATE "C",
  "status" text COLLATE "C" NOT NULL,
  "added_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("agent_id"),
  CHECK (("status" IN ('pending', 'workspace_ready', 'config_committed', 'complete', 'partial'))),
  UNIQUE ("workspace")
);

CREATE TABLE "template_mcp_server_refs" (
  "agent_id" text COLLATE "C" NOT NULL,
  "name" text COLLATE "C" NOT NULL,
  "schema_version" text COLLATE "C" NOT NULL,
  "config_digest" text COLLATE "C" NOT NULL,
  "relationship" text COLLATE "C" NOT NULL,
  "origin" text COLLATE "C" NOT NULL,
  "independent_owner" bigint NOT NULL DEFAULT 0,
  "status" text COLLATE "C" NOT NULL,
  "error" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("agent_id", "name"),
  CHECK (("relationship" IN ('managed', 'referenced'))),
  CHECK (("origin" IN ('template-introduced', 'pre-existing'))),
  CHECK (("independent_owner" IN (0, 1)))
);

CREATE TABLE "template_package_refs" (
  "agent_id" text COLLATE "C" NOT NULL,
  "package_kind" text COLLATE "C" NOT NULL,
  "package_source" text COLLATE "C" NOT NULL,
  "package_ref" text COLLATE "C" NOT NULL,
  "package_version" text COLLATE "C" NOT NULL,
  "package_integrity" text COLLATE "C" NOT NULL,
  "schema_version" text COLLATE "C" NOT NULL,
  "template_name" text COLLATE "C" NOT NULL,
  "package_status" text COLLATE "C" NOT NULL,
  "relationship" text COLLATE "C" NOT NULL,
  "origin" text COLLATE "C" NOT NULL,
  "independent_owner" bigint NOT NULL,
  "extension_id" text COLLATE "C",
  "extension_format" text COLLATE "C",
  "extension_detected_format" text COLLATE "C",
  "extension_mapped_json" text COLLATE "C",
  "extension_unavailable_json" text COLLATE "C",
  "extension_adapter_identity" text COLLATE "C",
  "installed_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("agent_id", "package_kind", "package_source", "package_ref", "package_version"),
  CHECK (("relationship" IN ('managed', 'referenced'))),
  CHECK (("origin" IN ('template-introduced', 'pre-existing'))),
  CHECK (("independent_owner" IN (0, 1)))
);

CREATE TABLE "template_workspace_files" (
  "agent_id" text COLLATE "C" NOT NULL,
  "target_path" text COLLATE "C" NOT NULL,
  "schema_version" text COLLATE "C" NOT NULL,
  "workspace" text COLLATE "C" NOT NULL,
  "source_path" text COLLATE "C" NOT NULL,
  "content_digest" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("agent_id", "target_path")
);

CREATE TABLE "web_push_subscriptions" (
  "endpoint_hash" text COLLATE "C" NOT NULL,
  "subscription_id" text COLLATE "C" NOT NULL,
  "endpoint" text COLLATE "C" NOT NULL,
  "p256dh" text COLLATE "C" NOT NULL,
  "auth" text COLLATE "C" NOT NULL,
  "device_id" text COLLATE "C",
  "user_profile_id" text COLLATE "C",
  "preferences_json" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("endpoint_hash"),
  UNIQUE ("subscription_id")
);

CREATE TABLE "worker_environment_credentials" (
  "environment_id" text COLLATE "C" NOT NULL,
  "credential_hash" text COLLATE "C" NOT NULL,
  "bundle_hash" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C",
  "rpc_set_version" bigint NOT NULL,
  "owner_epoch" bigint NOT NULL,
  "expires_at_ms" bigint NOT NULL,
  "delivered_at_ms" bigint,
  PRIMARY KEY ("environment_id"),
  CHECK (("rpc_set_version" >= 1)),
  CHECK (("owner_epoch" >= 0)),
  CHECK (("expires_at_ms" >= 0)),
  CHECK (("delivered_at_ms" >= 0)),
  UNIQUE ("credential_hash")
);

CREATE TABLE "worker_environments" (
  "environment_id" text COLLATE "C" NOT NULL,
  "provider_id" text COLLATE "C" NOT NULL,
  "profile_id" text COLLATE "C" NOT NULL,
  "profile_snapshot_json" text COLLATE "C" NOT NULL,
  "last_activated_at_ms" bigint,
  "preparation_key" text COLLATE "C",
  "preparation_purpose" text COLLATE "C",
  "preparation_demand_at_ms" bigint,
  "preparation_expires_at_ms" bigint,
  "preparation_consumed_at_ms" bigint,
  "provision_operation_id" text COLLATE "C" NOT NULL,
  "lease_id" text COLLATE "C",
  "node_setup_id" text COLLATE "C",
  "node_device_id" text COLLATE "C",
  "ssh_host" text COLLATE "C",
  "ssh_port" bigint,
  "ssh_user" text COLLATE "C",
  "ssh_host_key" text COLLATE "C",
  "ssh_key_ref_json" text COLLATE "C",
  "desktop_json" text COLLATE "C",
  "state" text COLLATE "C" NOT NULL,
  "bootstrap_bundle_hash" text COLLATE "C",
  "bootstrap_openclaw_version" text COLLATE "C",
  "bootstrap_protocol_features_json" text COLLATE "C",
  "bootstrap_install_kind" text COLLATE "C",
  "owner_epoch" bigint NOT NULL DEFAULT 0,
  "teardown_terminal_state" text COLLATE "C",
  "attached_session_ids_json" text COLLATE "C" NOT NULL DEFAULT '[]',
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  "state_changed_at_ms" bigint NOT NULL,
  "idle_since_at_ms" bigint,
  "destroy_requested_at_ms" bigint,
  "last_error" text COLLATE "C",
  "shared_host" bigint,
  "resource_receipt_json" text COLLATE "C",
  "retention_json" text COLLATE "C",
  "provision_source_json" text COLLATE "C",
  PRIMARY KEY ("environment_id"),
  CHECK (("preparation_key" IS NULL AND "preparation_demand_at_ms" IS NULL AND "preparation_expires_at_ms" IS NULL AND "preparation_consumed_at_ms" IS NULL) OR ("preparation_key" IS NOT NULL AND (char_length("preparation_key") = 64) AND ("preparation_key" COLLATE "C" !~ '\\A.*[^0-9a-f].*\\Z') AND "preparation_demand_at_ms" IS NOT NULL AND ("preparation_demand_at_ms" BETWEEN 0 AND 9007199254740991) AND "preparation_expires_at_ms" IS NOT NULL AND ("preparation_expires_at_ms" > "preparation_demand_at_ms") AND ("preparation_expires_at_ms" <= 9007199254740991) AND ("preparation_consumed_at_ms" IS NULL OR (("preparation_consumed_at_ms" >= "preparation_demand_at_ms") AND ("preparation_consumed_at_ms" < "preparation_expires_at_ms"))))),
  CHECK ("ssh_port" IS NULL OR (("ssh_port" >= 1) AND ("ssh_port" <= 65535))),
  CHECK (("state" IN ('requested', 'provisioning', 'bootstrapping', 'ready', 'attached', 'idle', 'draining', 'destroying', 'destroyed', 'failed', 'orphaned'))),
  CHECK (("owner_epoch" >= 0)),
  CHECK (("teardown_terminal_state" IN ('destroyed', 'failed'))),
  UNIQUE ("provision_operation_id")
);

CREATE TABLE "worker_inference_turns" (
  "session_id" text COLLATE "C" NOT NULL,
  "run_epoch" bigint NOT NULL,
  "run_id" text COLLATE "C" NOT NULL,
  "turn_id" text COLLATE "C" NOT NULL,
  "environment_id" text COLLATE "C" NOT NULL,
  "request_hash" text COLLATE "C" NOT NULL,
  "state" text COLLATE "C" NOT NULL,
  "terminal_json" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("session_id", "run_epoch", "run_id", "turn_id"),
  CHECK (("run_epoch" >= 0)),
  CHECK (("state" IN ('pending', 'terminal'))),
  CHECK (("created_at_ms" >= 0)),
  CHECK (("updated_at_ms" >= 0)),
  CHECK ((("state" = 'pending') AND "terminal_json" IS NULL) OR (("state" = 'terminal') AND "terminal_json" IS NOT NULL))
);

CREATE TABLE "worker_session_placements" (
  "session_id" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "execution_mode" text COLLATE "C",
  "state" text COLLATE "C" NOT NULL,
  "environment_id" text COLLATE "C",
  "transition_generation" bigint NOT NULL DEFAULT 0,
  "active_owner_epoch" bigint,
  "workspace_base_manifest_ref" text COLLATE "C",
  "remote_workspace_dir" text COLLATE "C",
  "worker_bundle_hash" text COLLATE "C",
  "last_transcript_ack_cursor" bigint,
  "last_live_event_ack_cursor" bigint,
  "recovery_error" text COLLATE "C",
  "turn_claim_owner" text COLLATE "C",
  "turn_claim_id" text COLLATE "C",
  "turn_claim_run_id" text COLLATE "C",
  "turn_claim_generation" bigint,
  "turn_claim_owner_epoch" bigint,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  "state_changed_at_ms" bigint NOT NULL,
  "terminal_reason" text COLLATE "C",
  "terminal_at_ms" bigint,
  PRIMARY KEY ("session_id"),
  CHECK (("execution_mode" IN ('worker-turn', 'remote-exec'))),
  CHECK (("state" IN ('local', 'requested', 'provisioning', 'syncing', 'starting', 'active', 'draining', 'reconciling', 'reclaimed', 'failed'))),
  CHECK (("transition_generation" >= 0)),
  CHECK ("active_owner_epoch" IS NULL OR ("active_owner_epoch" >= 1)),
  CHECK ("last_transcript_ack_cursor" IS NULL OR ("last_transcript_ack_cursor" >= 0)),
  CHECK ("last_live_event_ack_cursor" IS NULL OR ("last_live_event_ack_cursor" >= 0)),
  CHECK (("turn_claim_owner" IN ('local', 'worker'))),
  CHECK ("turn_claim_generation" IS NULL OR ("turn_claim_generation" >= 0)),
  CHECK ("turn_claim_owner_epoch" IS NULL OR ("turn_claim_owner_epoch" >= 1)),
  CHECK ((("state" IN ('local', 'requested')) AND "environment_id" IS NULL AND "active_owner_epoch" IS NULL AND "workspace_base_manifest_ref" IS NULL AND "remote_workspace_dir" IS NULL AND "worker_bundle_hash" IS NULL AND "last_transcript_ack_cursor" IS NULL AND "last_live_event_ack_cursor" IS NULL AND "recovery_error" IS NULL) OR ("state" IS NOT DISTINCT FROM 'provisioning' AND "active_owner_epoch" IS NULL AND "workspace_base_manifest_ref" IS NULL AND "remote_workspace_dir" IS NULL AND "worker_bundle_hash" IS NULL AND "last_transcript_ack_cursor" IS NULL AND "last_live_event_ack_cursor" IS NULL AND "recovery_error" IS NULL) OR ("state" IS NOT DISTINCT FROM 'syncing' AND "environment_id" IS NOT NULL AND "active_owner_epoch" IS NULL AND "workspace_base_manifest_ref" IS NULL AND "remote_workspace_dir" IS NULL AND "worker_bundle_hash" IS NOT NULL AND "last_transcript_ack_cursor" IS NULL AND "last_live_event_ack_cursor" IS NULL AND "recovery_error" IS NULL) OR ("state" IS NOT DISTINCT FROM 'starting' AND "environment_id" IS NOT NULL AND "active_owner_epoch" IS NULL AND "workspace_base_manifest_ref" IS NOT NULL AND "remote_workspace_dir" IS NOT NULL AND "worker_bundle_hash" IS NOT NULL AND "last_transcript_ack_cursor" IS NULL AND "last_live_event_ack_cursor" IS NULL AND "recovery_error" IS NULL) OR (("state" IN ('active', 'draining', 'reconciling')) AND "environment_id" IS NOT NULL AND "active_owner_epoch" IS NOT NULL AND "workspace_base_manifest_ref" IS NOT NULL AND "remote_workspace_dir" IS NOT NULL AND "worker_bundle_hash" IS NOT NULL AND "recovery_error" IS NULL) OR ("state" IS NOT DISTINCT FROM 'reclaimed' AND "environment_id" IS NOT NULL AND "active_owner_epoch" IS NOT NULL AND "workspace_base_manifest_ref" IS NOT NULL AND "remote_workspace_dir" IS NOT NULL AND "worker_bundle_hash" IS NOT NULL AND "recovery_error" IS NULL AND "turn_claim_owner" IS NULL AND "turn_claim_id" IS NULL AND "turn_claim_run_id" IS NULL AND "turn_claim_generation" IS NULL AND "turn_claim_owner_epoch" IS NULL) OR ("state" IS NOT DISTINCT FROM 'failed' AND "recovery_error" IS NOT NULL)),
  CHECK (("turn_claim_owner" IS NULL AND "turn_claim_id" IS NULL AND "turn_claim_run_id" IS NULL AND "turn_claim_generation" IS NULL AND "turn_claim_owner_epoch" IS NULL) OR ("turn_claim_owner" IS NOT DISTINCT FROM 'local' AND "turn_claim_id" IS NOT NULL AND "turn_claim_run_id" IS NOT NULL AND "turn_claim_generation" IS NOT NULL AND "turn_claim_owner_epoch" IS NULL) OR ("turn_claim_owner" IS NOT DISTINCT FROM 'worker' AND "turn_claim_id" IS NOT NULL AND "turn_claim_run_id" IS NOT NULL AND "turn_claim_generation" IS NOT NULL AND "turn_claim_owner_epoch" IS NOT NULL)),
  CHECK ("turn_claim_owner" IS NULL OR ("turn_claim_owner" IS NOT DISTINCT FROM 'local' AND (("state" IN ('local', 'requested', 'failed')) OR (("state" IN ('active', 'draining')) AND "execution_mode" IS NOT DISTINCT FROM 'remote-exec'))) OR ("turn_claim_owner" IS NOT DISTINCT FROM 'worker' AND ("state" IN ('active', 'draining')) AND ("execution_mode" IS NULL OR "execution_mode" IS NOT DISTINCT FROM 'worker-turn') AND "turn_claim_owner_epoch" IS NOT DISTINCT FROM "active_owner_epoch"))
);

CREATE TABLE "worker_session_tool_operations" (
  "source_session_id" text COLLATE "C" NOT NULL,
  "source_claim_id" text COLLATE "C" NOT NULL,
  "tool_call_id" text COLLATE "C" NOT NULL,
  "tool_name" text COLLATE "C" NOT NULL,
  "request_digest" text COLLATE "C" NOT NULL,
  "operation_seed" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "child_session_key" text COLLATE "C",
  "result_json" text COLLATE "C",
  "gateway_instance_id" text COLLATE "C" NOT NULL,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("source_session_id", "source_claim_id", "tool_call_id"),
  CHECK (("tool_name" IN ('sessions_spawn', 'sessions_send'))),
  CHECK (("status" IN ('running', 'succeeded', 'failed', 'unknown')))
);

CREATE TABLE "worker_transcript_commit_heads" (
  "session_id" text COLLATE "C" NOT NULL,
  "run_epoch" bigint NOT NULL,
  "environment_id" text COLLATE "C" NOT NULL,
  "next_seq" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("session_id", "run_epoch"),
  CHECK (("run_epoch" >= 0)),
  CHECK (("next_seq" >= 1)),
  CHECK (("updated_at_ms" >= 0))
);

CREATE TABLE "worker_transcript_commits" (
  "session_id" text COLLATE "C" NOT NULL,
  "run_epoch" bigint NOT NULL,
  "seq" bigint NOT NULL,
  "request_hash" text COLLATE "C" NOT NULL,
  "state" text COLLATE "C" NOT NULL,
  "result_json" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("session_id", "run_epoch", "seq"),
  CHECK (("run_epoch" >= 0)),
  CHECK (("seq" >= 1)),
  CHECK (("state" IN ('pending', 'terminal'))),
  CHECK (("created_at_ms" >= 0)),
  CHECK (("updated_at_ms" >= 0)),
  CHECK ((("state" = 'pending') AND "result_json" IS NULL) OR (("state" = 'terminal') AND "result_json" IS NOT NULL))
);

CREATE TABLE "worker_turn_tool_authorities" (
  "session_id" text COLLATE "C" NOT NULL,
  "environment_id" text COLLATE "C" NOT NULL,
  "owner_epoch" bigint NOT NULL,
  "placement_generation" bigint NOT NULL,
  "claim_id" text COLLATE "C" NOT NULL,
  "run_id" text COLLATE "C" NOT NULL,
  "tool_names_json" text COLLATE "C" NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("session_id"),
  CHECK (("owner_epoch" >= 1)),
  CHECK (("placement_generation" >= 0))
);

CREATE TABLE "worker_workspace_pending_results" (
  "session_id" text COLLATE "C" NOT NULL,
  "environment_id" text COLLATE "C" NOT NULL,
  "owner_epoch" bigint NOT NULL,
  "placement_generation" bigint NOT NULL,
  "claim_id" text COLLATE "C" NOT NULL,
  "run_id" text COLLATE "C" NOT NULL,
  "gateway_instance_id" text COLLATE "C" NOT NULL,
  "recovery_requested_at_ms" bigint,
  "workspace_accepted_at_ms" bigint,
  "staged_result_ref" text COLLATE "C",
  "repository_workspace_id" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "repository_disk_authority_json" text COLLATE "C",
  PRIMARY KEY ("session_id"),
  CHECK (("owner_epoch" >= 1)),
  CHECK (("placement_generation" >= 0))
);

CREATE TABLE "worker_workspace_reconciliations" (
  "session_id" text COLLATE "C" NOT NULL,
  "environment_id" text COLLATE "C" NOT NULL,
  "owner_epoch" bigint NOT NULL,
  "placement_generation" bigint NOT NULL,
  "base_manifest_ref" text COLLATE "C" NOT NULL,
  "current_manifest_ref" text COLLATE "C" NOT NULL,
  "plan_json" text COLLATE "C" NOT NULL,
  "base_pack" bytea NOT NULL,
  "created_at_ms" bigint NOT NULL,
  PRIMARY KEY ("session_id"),
  CHECK (("owner_epoch" >= 1)),
  CHECK (("placement_generation" >= 0)),
  CHECK ((octet_length("base_pack") <= 268435456))
);

CREATE TABLE "workspace_generated_bootstrap_hashes" (
  "workspace_key" text COLLATE "C" NOT NULL,
  "filename" text COLLATE "C" NOT NULL,
  "sha256" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("workspace_key", "filename")
);

CREATE TABLE "workspace_path_aliases" (
  "alias_key" text COLLATE "C" NOT NULL,
  "alias_path" text COLLATE "C" NOT NULL,
  "workspace_key" text COLLATE "C" NOT NULL,
  "workspace_path" text COLLATE "C" NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("alias_key")
);

CREATE TABLE "workspace_setup_state" (
  "workspace_key" text COLLATE "C" NOT NULL,
  "workspace_path" text COLLATE "C",
  "version" bigint,
  "bootstrap_seeded_at" text COLLATE "C",
  "setup_completed_at" text COLLATE "C",
  "updated_at" bigint,
  "attested_at_ms" bigint,
  "attestation_updated_at_ms" bigint,
  "bootstrap_deferred" bigint,
  PRIMARY KEY ("workspace_key"),
  CHECK ("version" IS NULL OR "workspace_path" IS NOT NULL)
);

CREATE TABLE "worktree_provisioned_file_chunks" (
  "worktree_id" text COLLATE "C" NOT NULL,
  "path" text COLLATE "C" NOT NULL,
  "chunk_index" bigint NOT NULL,
  "data" bytea NOT NULL,
  PRIMARY KEY ("worktree_id", "path", "chunk_index"),
  CHECK (("chunk_index" >= 0))
);

CREATE TABLE "worktrees" (
  "id" text COLLATE "C" NOT NULL,
  "repo_fingerprint" text COLLATE "C" NOT NULL,
  "repo_root" text COLLATE "C" NOT NULL,
  "path" text COLLATE "C" NOT NULL,
  "branch" text COLLATE "C" NOT NULL,
  "base_ref" text COLLATE "C" NOT NULL,
  "owner_kind" text COLLATE "C" NOT NULL,
  "owner_id" text COLLATE "C",
  "snapshot_ref" text COLLATE "C",
  "provisioned_paths_json" text COLLATE "C",
  "created_at" bigint NOT NULL,
  "last_active_at" bigint NOT NULL,
  "removed_at" bigint,
  "run_end_cleanup_json" text COLLATE "C",
  "gc_protection_json" text COLLATE "C",
  PRIMARY KEY ("id"),
  CHECK (("owner_kind" IN ('manual', 'workboard', 'session')))
);

CREATE INDEX "idx_acp_replay_sessions_key_updated" ON "acp_replay_sessions" (("session_key") ASC, ("complete") ASC, ("updated_at") DESC, ("session_id") ASC);

CREATE INDEX "idx_acp_replay_sessions_updated" ON "acp_replay_sessions" (("updated_at") DESC, ("session_id") ASC);

CREATE INDEX "idx_acp_sessions_agent_activity" ON "acp_sessions" (("agent") ASC, ("last_activity_at") DESC, ("session_key") ASC);

CREATE INDEX "idx_acp_sessions_resume_acpx" ON "acp_sessions" (("resume_acpx_session_id") ASC NULLS FIRST);

CREATE INDEX "idx_acp_sessions_resume_agent" ON "acp_sessions" (("resume_agent_session_id") ASC NULLS FIRST);

CREATE INDEX "idx_acp_sessions_state_activity" ON "acp_sessions" (("state") ASC, ("last_activity_at") DESC, ("session_key") ASC);

CREATE INDEX "idx_apns_registrations_updated" ON "apns_registrations" (("updated_at_ms") DESC, ("node_id") ASC);

CREATE INDEX "idx_audit_events_agent_sequence" ON "audit_events" (("agent_id") ASC NULLS FIRST, ("sequence") DESC);

CREATE INDEX "idx_audit_events_channel_sequence" ON "audit_events" (("channel") ASC NULLS FIRST, ("sequence") DESC);

CREATE INDEX "idx_audit_events_direction_sequence" ON "audit_events" (("direction") ASC NULLS FIRST, ("sequence") DESC);

CREATE INDEX "idx_audit_events_kind_sequence" ON "audit_events" (("kind") ASC, ("sequence") DESC);

CREATE INDEX "idx_audit_events_run_sequence" ON "audit_events" (("run_id") ASC NULLS FIRST, ("sequence") DESC);

CREATE INDEX "idx_audit_events_session_sequence" ON "audit_events" (("session_key") ASC NULLS FIRST, ("sequence") DESC);

CREATE INDEX "idx_audit_events_status_sequence" ON "audit_events" (("status") ASC, ("sequence") DESC);

CREATE INDEX "idx_audit_events_time" ON "audit_events" (("occurred_at") DESC, ("sequence") DESC);

CREATE INDEX "idx_backup_runs_created" ON "backup_runs" (("created_at") DESC, ("id") ASC);

CREATE INDEX "capture_events_flow_idx" ON "capture_events" (("flow_id") ASC, ("ts") ASC);

CREATE INDEX "capture_events_session_ts_idx" ON "capture_events" (("session_id") ASC, ("ts") ASC);

CREATE INDEX "idx_channel_ingress_claims" ON "channel_ingress_events" (("queue_name") ASC, ("status") ASC, ("claimed_at") ASC NULLS FIRST);

CREATE INDEX "idx_channel_ingress_lane" ON "channel_ingress_events" (("queue_name") ASC, ("status") ASC, ("lane_key") ASC NULLS FIRST);

CREATE INDEX "idx_channel_ingress_pending" ON "channel_ingress_events" (("queue_name") ASC, ("status") ASC, ("received_at") ASC, ("event_id") ASC);

CREATE INDEX "idx_channel_pairing_allow_account" ON "channel_pairing_allow_entries" (("channel_key") ASC, ("account_id") ASC, ("sort_order") ASC, ("entry") ASC);

CREATE INDEX "idx_channel_pairing_requests_code" ON "channel_pairing_requests" (("channel_key") ASC, ("code") ASC);

CREATE INDEX "idx_channel_pairing_requests_created" ON "channel_pairing_requests" (("channel_key") ASC, ("created_at") ASC, ("request_id") ASC);

CREATE INDEX "idx_cron_job_scratch_store_updated" ON "cron_job_scratch" (("store_key") ASC, ("updated_at_ms") DESC, ("job_id") ASC);

CREATE INDEX "idx_cron_jobs_store_order" ON "cron_jobs" (("store_key") ASC, ("sort_order") ASC, ("updated_at") ASC, ("job_id") ASC);

CREATE INDEX "idx_current_conversation_bindings_conversation" ON "current_conversation_bindings" (("channel") ASC, ("account_id") ASC, ("conversation_kind") ASC, ("conversation_id") ASC);

CREATE INDEX "idx_current_conversation_bindings_expires" ON "current_conversation_bindings" (("expires_at") ASC NULLS FIRST, ("binding_key") ASC);

CREATE INDEX "idx_current_conversation_bindings_target" ON "current_conversation_bindings" (("target_session_key") ASC, ("updated_at") DESC, ("binding_key") ASC);

CREATE INDEX "idx_delivery_queue_bounded_retention" ON "delivery_queue_entries" (("queue_name") ASC, ("retention_id_prefix") ASC, ("enqueued_at") DESC, ("id") DESC) WHERE ("status" IN ('completed', 'failed')) AND ("recovery_state" = 'completed_bounded') AND "retention_id_prefix" IS NOT NULL;

CREATE INDEX "idx_delivery_queue_failed" ON "delivery_queue_entries" (("status") ASC, ("queue_name") ASC, ("failed_at") ASC NULLS FIRST, ("id") ASC);

CREATE INDEX "idx_delivery_queue_pending" ON "delivery_queue_entries" (("queue_name") ASC, ("status") ASC, ("enqueued_at") ASC, ("id") ASC);

CREATE INDEX "idx_delivery_queue_session" ON "delivery_queue_entries" (("queue_name") ASC, ("status") ASC, ("session_key") ASC, ("enqueued_at") ASC, ("id") ASC) WHERE "session_key" IS NOT NULL;

CREATE INDEX "idx_delivery_queue_target" ON "delivery_queue_entries" (("queue_name") ASC, ("status") ASC, ("channel") ASC, ("target") ASC, ("enqueued_at") ASC, ("id") ASC) WHERE "channel" IS NOT NULL AND "target" IS NOT NULL;

CREATE INDEX "idx_device_bootstrap_tokens_ts" ON "device_bootstrap_tokens" (("ts") ASC);

CREATE INDEX "idx_device_pairing_paired_approved" ON "device_pairing_paired" (("approved_at_ms") DESC, ("device_id") ASC);

CREATE INDEX "idx_device_pairing_pending_device" ON "device_pairing_pending" (("device_id") ASC, ("ts") DESC);

CREATE INDEX "idx_diagnostic_events_scope_sequence" ON "diagnostic_events" (("scope") ASC, ("sequence") ASC, ("event_key") ASC);

CREATE INDEX "idx_flow_runs_owner_key" ON "flow_runs" (("owner_key") ASC);

CREATE INDEX "idx_flow_runs_status" ON "flow_runs" (("status") ASC);

CREATE INDEX "idx_flow_runs_updated_at" ON "flow_runs" (("updated_at") ASC);

CREATE INDEX "idx_gateway_boot_lifecycle_started" ON "gateway_boot_lifecycle" (("started_at_ms") ASC);

CREATE INDEX "idx_gateway_restart_handoff_expiry" ON "gateway_restart_handoff" (("expires_at") ASC, ("pid") ASC);

CREATE INDEX "idx_gateway_restart_sentinel_ts" ON "gateway_restart_sentinel" (("ts") DESC, ("sentinel_key") ASC);

CREATE INDEX "idx_macos_port_guardian_records_port" ON "macos_port_guardian_records" (("port") ASC, ("timestamp") DESC);

CREATE INDEX "idx_managed_outgoing_images_agent_message" ON "managed_outgoing_image_records" (("session_key") ASC, ("agent_id") ASC NULLS FIRST, ("message_id") ASC, ("attachment_id") ASC) WHERE "message_id" IS NOT NULL;

CREATE INDEX "idx_managed_outgoing_images_agent_session" ON "managed_outgoing_image_records" (("session_key") ASC, ("agent_id") ASC NULLS FIRST, ("created_at") DESC, ("attachment_id") ASC);

CREATE INDEX "idx_managed_outgoing_images_message" ON "managed_outgoing_image_records" (("session_key") ASC, ("message_id") ASC, ("attachment_id") ASC) WHERE "message_id" IS NOT NULL;

CREATE INDEX "idx_managed_outgoing_images_session" ON "managed_outgoing_image_records" (("session_key") ASC, ("created_at") DESC, ("attachment_id") ASC);

CREATE INDEX "idx_meeting_transcript_sessions_account" ON "meeting_transcript_sessions" (("source_account_id") ASC NULLS FIRST);

CREATE INDEX "idx_meeting_transcript_sessions_agent" ON "meeting_transcript_sessions" (("metadata_agent_id") ASC NULLS FIRST);

CREATE INDEX "idx_meeting_transcript_sessions_chronology" ON "meeting_transcript_sessions" (("started_at_ms") DESC NULLS LAST, ("session_id") ASC, ("started_at") ASC);

CREATE INDEX "idx_meeting_transcript_sessions_export_key" ON "meeting_transcript_sessions" (("export_key") ASC);

CREATE INDEX "idx_meeting_transcript_sessions_id" ON "meeting_transcript_sessions" (("session_id") ASC, ("started_at") DESC);

CREATE INDEX "idx_meeting_transcript_sessions_slug" ON "meeting_transcript_sessions" (("session_slug") ASC, ("started_at") DESC);

CREATE INDEX "idx_meeting_transcript_sessions_source" ON "meeting_transcript_sessions" (("provider_id") ASC, ("source_account_id") ASC NULLS FIRST, ("source_guild_id") ASC NULLS FIRST, ("source_channel_id") ASC NULLS FIRST, ("source_meeting_url") ASC NULLS FIRST, ("source_thread_ts") ASC NULLS FIRST, ("source_file_id") ASC NULLS FIRST, ("stopped_at") DESC NULLS LAST, ("started_at") DESC, ("session_id") ASC);

CREATE INDEX "idx_meeting_transcript_sessions_started" ON "meeting_transcript_sessions" (("started_at") DESC, ("session_id") ASC);

CREATE INDEX "idx_meeting_transcript_utterances_id" ON "meeting_transcript_utterances" (("session_id") ASC, ("session_started_at") ASC, ("utterance_id") ASC) WHERE "utterance_id" IS NOT NULL;

CREATE INDEX "idx_migration_runs_started" ON "migration_runs" (("started_at") DESC, ("id") ASC);

CREATE INDEX "idx_migration_sources_path" ON "migration_sources" (("source_path") ASC, ("migration_kind") ASC, ("target_table") ASC);

CREATE INDEX "idx_migration_sources_run" ON "migration_sources" (("last_run_id") ASC, ("source_path") ASC);

CREATE INDEX "idx_native_hook_relay_bridges_expires" ON "native_hook_relay_bridges" (("expires_at_ms") ASC, ("relay_id") ASC);

CREATE INDEX "idx_official_external_plugin_catalog_snapshots_updated" ON "official_external_plugin_catalog_snapshots" (("updated_at_ms") DESC, ("feed_url") ASC);

CREATE UNIQUE INDEX "idx_operator_approvals_cursor_id" ON "operator_approvals" (("cursor_id") ASC);

CREATE UNIQUE INDEX "idx_operator_approvals_resolution_ref" ON "operator_approvals" (("resolution_ref") ASC);

CREATE INDEX "idx_operator_approvals_resolved" ON "operator_approvals" (("resolved_at_ms") ASC, ("approval_id") ASC) WHERE "resolved_at_ms" IS NOT NULL;

CREATE INDEX "idx_operator_approvals_runtime_pending" ON "operator_approvals" (("runtime_epoch") ASC, ("approval_id") ASC) WHERE ("status" = 'pending');

CREATE INDEX "idx_operator_approvals_source_run_resolved" ON "operator_approvals" (("source_run_id") ASC, ("resolved_at_ms") ASC, ("approval_id") ASC) WHERE "source_run_id" IS NOT NULL AND "resolved_at_ms" IS NOT NULL;

CREATE INDEX "idx_operator_approvals_source_session_created" ON "operator_approvals" (("source_session_key") ASC NULLS FIRST, ("created_at_ms") DESC, ("approval_id") ASC);

CREATE INDEX "idx_operator_approvals_status_expiry" ON "operator_approvals" (("status") ASC, ("expires_at_ms") ASC, ("approval_id") ASC);

CREATE INDEX "idx_plugin_binding_approvals_plugin" ON "plugin_binding_approvals" (("plugin_id") ASC, ("approved_at") DESC);

CREATE INDEX "idx_plugin_blob_expiry" ON "plugin_blob_entries" (("expires_at") ASC) WHERE "expires_at" IS NOT NULL;

CREATE INDEX "idx_plugin_blob_listing" ON "plugin_blob_entries" (("plugin_id") ASC, ("namespace") ASC, ("created_at") ASC, ("entry_key") ASC);

CREATE INDEX "idx_plugin_state_expiry" ON "plugin_state_entries" (("expires_at") ASC) WHERE "expires_at" IS NOT NULL;

CREATE INDEX "idx_plugin_state_listing" ON "plugin_state_entries" (("plugin_id") ASC, ("namespace") ASC, ("created_at") ASC, ("entry_key") ASC, ("expires_at") ASC NULLS FIRST);

CREATE INDEX "idx_sandbox_registry_last_used" ON "sandbox_registry_entries" (("registry_kind") ASC, ("last_used_at_ms") DESC, ("container_name") ASC) WHERE "last_used_at_ms" IS NOT NULL;

CREATE INDEX "idx_sandbox_registry_session" ON "sandbox_registry_entries" (("registry_kind") ASC, ("session_key") ASC, ("last_used_at_ms") DESC NULLS LAST, ("container_name") ASC) WHERE "session_key" IS NOT NULL;

CREATE INDEX "idx_sandbox_registry_updated" ON "sandbox_registry_entries" (("registry_kind") ASC, ("updated_at") DESC, ("container_name") ASC);

CREATE INDEX "idx_session_state_events_session_sequence" ON "session_state_events" (("session_key") ASC, ("sequence") DESC);

CREATE INDEX "idx_session_state_events_time" ON "session_state_events" (("occurred_at") DESC, ("sequence") DESC);

CREATE INDEX "idx_session_upstream_links_catalog_id" ON "session_upstream_links" (("catalog_id") ASC);

CREATE INDEX "idx_session_watch_cursors_target" ON "session_watch_cursors" (("target_session_key") ASC);

CREATE INDEX "idx_skill_uploads_expiry" ON "skill_uploads" (("expires_at") ASC);

CREATE INDEX "idx_skill_uploads_idempotency" ON "skill_uploads" (("idempotency_key_hash") ASC) WHERE "idempotency_key_hash" IS NOT NULL;

CREATE INDEX "idx_state_leases_expiry" ON "state_leases" (("expires_at") ASC, ("scope") ASC, ("lease_key") ASC) WHERE "expires_at" IS NOT NULL;

CREATE INDEX "idx_state_leases_owner" ON "state_leases" (("owner") ASC);

CREATE INDEX "idx_subagent_runs_child_session_key" ON "subagent_runs" (("child_session_key") ASC, ("created_at") DESC, ("run_id") ASC);

CREATE INDEX "idx_subagent_runs_controller_session_key" ON "subagent_runs" (("controller_session_key") ASC NULLS FIRST, ("created_at") DESC, ("run_id") ASC);

CREATE INDEX "idx_subagent_runs_requester_session_key" ON "subagent_runs" (("requester_session_key") ASC, ("created_at") DESC, ("run_id") ASC);

CREATE INDEX "idx_task_runs_cron_runtime_order" ON "task_runs" (("runtime") ASC, ("created_at") ASC, ("task_id") ASC) WHERE ("runtime" = 'cron');

CREATE INDEX "idx_task_runs_cron_source_order" ON "task_runs" (("source_id") ASC NULLS FIRST, ("created_at") ASC, ("task_id") ASC) WHERE ("runtime" = 'cron');

CREATE INDEX "idx_task_runs_runtime_run" ON "task_runs" (("runtime") ASC, ("run_id") ASC NULLS FIRST, ("source_id") ASC NULLS FIRST, ("created_at") ASC, ("task_id") ASC);

CREATE INDEX "idx_web_push_subscriptions_updated" ON "web_push_subscriptions" (("updated_at_ms") DESC, ("subscription_id") ASC);

CREATE UNIQUE INDEX "idx_worker_environments_provider_lease" ON "worker_environments" (("provider_id") ASC, ("lease_id") ASC) WHERE "lease_id" IS NOT NULL;

CREATE INDEX "idx_worker_environments_terminal_changed" ON "worker_environments" (("state_changed_at_ms") ASC, ("environment_id") ASC);

CREATE UNIQUE INDEX "idx_worker_inference_turns_pending_run" ON "worker_inference_turns" (("session_id") ASC, ("run_epoch") ASC, ("run_id") ASC) WHERE ("state" = 'pending');

CREATE INDEX "idx_worker_session_placements_environment" ON "worker_session_placements" (("environment_id") ASC) WHERE "environment_id" IS NOT NULL;

CREATE INDEX "idx_worker_session_placements_reconcile" ON "worker_session_placements" (("updated_at_ms") ASC, ("session_id") ASC);

CREATE INDEX "idx_worker_session_placements_session_key" ON "worker_session_placements" (("agent_id") ASC, ("session_key") ASC);

CREATE INDEX "idx_workspace_path_aliases_workspace" ON "workspace_path_aliases" (("workspace_key") ASC);

CREATE INDEX "idx_workspace_setup_state_path" ON "workspace_setup_state" (("workspace_path") ASC NULLS FIRST);

CREATE INDEX "idx_worktrees_removed_at" ON "worktrees" (("removed_at") ASC NULLS FIRST);

CREATE INDEX "idx_worktrees_repo_fingerprint" ON "worktrees" (("repo_fingerprint") ASC);

ALTER TABLE "acp_replay_events" ADD FOREIGN KEY ("session_id") REFERENCES "acp_replay_sessions" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "capture_events" ADD FOREIGN KEY ("data_blob_id") REFERENCES "capture_blobs" ("blob_id") ON UPDATE NO ACTION ON DELETE SET NULL NOT DEFERRABLE;

ALTER TABLE "capture_events" ADD FOREIGN KEY ("session_id") REFERENCES "capture_sessions" ("id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "meeting_transcript_summaries" ADD FOREIGN KEY ("session_id", "session_started_at") REFERENCES "meeting_transcript_sessions" ("session_id", "started_at") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "meeting_transcript_utterances" ADD FOREIGN KEY ("session_id", "session_started_at") REFERENCES "meeting_transcript_sessions" ("session_id", "started_at") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "migration_sources" ADD FOREIGN KEY ("last_run_id") REFERENCES "migration_runs" ("id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "skill_upload_chunks" ADD FOREIGN KEY ("upload_id") REFERENCES "skill_uploads" ("upload_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "task_delivery_state" ADD FOREIGN KEY ("task_id") REFERENCES "task_runs" ("task_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "worker_environment_credentials" ADD FOREIGN KEY ("environment_id") REFERENCES "worker_environments" ("environment_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "worker_inference_turns" ADD FOREIGN KEY ("environment_id") REFERENCES "worker_environments" ("environment_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "worker_session_tool_operations" ADD FOREIGN KEY ("source_session_id") REFERENCES "worker_session_placements" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "worker_transcript_commits" ADD FOREIGN KEY ("session_id", "run_epoch") REFERENCES "worker_transcript_commit_heads" ("session_id", "run_epoch") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "worker_turn_tool_authorities" ADD FOREIGN KEY ("session_id") REFERENCES "worker_session_placements" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "worker_workspace_pending_results" ADD FOREIGN KEY ("session_id") REFERENCES "worker_session_placements" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "worker_workspace_reconciliations" ADD FOREIGN KEY ("session_id") REFERENCES "worker_session_placements" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "workspace_generated_bootstrap_hashes" ADD FOREIGN KEY ("workspace_key") REFERENCES "workspace_setup_state" ("workspace_key") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`;return Object.defineProperty(this,"eagerSql",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get operatorRecoveryV25Sql(){let e=`-- Generated v24-to-v25 metadata-only transition; the engine owner publishes openclaw_schema_meta.
-- Subagent operator recovery requires the new reader; catalog and retained rows are unchanged.
UPDATE schema_meta SET schema_version = 25 WHERE meta_key = 'primary' AND schema_version = 24;
UPDATE config_machine_state SET value_json = '25' WHERE state_key = 'state.schema.contentVersion' AND value_json = '24';
`;return Object.defineProperty(this,"operatorRecoveryV25Sql",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get preWriteIndexesV27Sql(){let e={acp_replay_events:`CREATE INDEX "idx_acp_replay_events_session_seq" ON "acp_replay_events" (("session_id") ASC NULLS FIRST, ("seq") ASC NULLS FIRST);`,skill_usage:`CREATE INDEX "idx_skill_usage_key" ON "skill_usage" (("skill_key") ASC NULLS FIRST, ("skill_file") ASC NULLS FIRST);`,state_leases:`CREATE INDEX "idx_state_leases_owner" ON "state_leases" (("owner") ASC NULLS FIRST, ("updated_at") DESC NULLS LAST);`};return Object.defineProperty(this,"preWriteIndexesV27Sql",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get writeIndexesV27Sql(){let e=`
  DROP INDEX IF EXISTS idx_acp_replay_events_session_seq;
  DROP INDEX IF EXISTS idx_skill_usage_key;
  DROP INDEX IF EXISTS idx_state_leases_owner;

CREATE INDEX "idx_state_leases_owner" ON "state_leases" (("owner") ASC NULLS FIRST);`;return Object.defineProperty(this,"writeIndexesV27Sql",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get clientCredentialV29Sql(){let e=`-- Generated v28-to-v29 publication after the local credential owner has verified and retired source rows.
UPDATE schema_meta SET schema_version = 29 WHERE meta_key = 'primary' AND schema_version = 28;
`;return Object.defineProperty(this,"clientCredentialV29Sql",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get workspaceCasV35Sql(){let e=`-- Generated DDL-only v34-to-v35 transition; reconciliation converts retained rows online.
DO $workspace_cas$ BEGIN
IF to_regclass('local_workspace_projections') IS NOT NULL THEN
ALTER TABLE "local_workspace_projections" ADD COLUMN "tree_root_digest" bytea;
ALTER TABLE "local_workspace_projections" ADD COLUMN "source_paths_digest" bytea;
ALTER TABLE "local_workspace_projections" ADD COLUMN "canonical_fingerprints" bytea;
ALTER TABLE "local_workspace_projections" ADD COLUMN "projection_fingerprints" bytea;
CREATE TABLE "local_workspace_source_path_sets" (
  "path_digest" bytea NOT NULL,
  "paths_zstd" bytea NOT NULL,
  "sweep_epoch" bigint NOT NULL,
  PRIMARY KEY ("path_digest"),
  CHECK ((octet_length("path_digest") = 32))
);
CREATE TABLE "local_workspace_tree_packs" (
  "tree_digest" bytea NOT NULL,
  "records_json" text COLLATE "C" NOT NULL,
  "children_json" text COLLATE "C" NOT NULL,
  "sweep_epoch" bigint NOT NULL,
  PRIMARY KEY ("tree_digest"),
  CHECK ((octet_length("tree_digest") = 32))
);
END IF; END $workspace_cas$;
`;return Object.defineProperty(this,"workspaceCasV35Sql",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get clientCredentialSource(){let e={sql:`CREATE TABLE "device_auth_tokens" (
  "device_id" text COLLATE "C" NOT NULL,
  "role" text COLLATE "C" NOT NULL,
  "token" text COLLATE "C" NOT NULL,
  "scopes_json" text COLLATE "C" NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("device_id", "role")
);

CREATE TABLE "device_identities" (
  "identity_key" text COLLATE "C" NOT NULL,
  "device_id" text COLLATE "C" NOT NULL,
  "public_key_pem" text COLLATE "C" NOT NULL,
  "private_key_pem" text COLLATE "C" NOT NULL,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("identity_key")
);

CREATE TABLE "gateway_origin_device_tokens" (
  "gateway_scope" text COLLATE "C" NOT NULL,
  "device_id" text COLLATE "C" NOT NULL,
  "role" text COLLATE "C" NOT NULL,
  "token" text COLLATE "C" NOT NULL,
  "scopes_json" text COLLATE "C" NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("gateway_scope", "device_id", "role")
);

CREATE INDEX "idx_device_auth_tokens_updated" ON "device_auth_tokens" (("updated_at_ms") DESC NULLS LAST, ("device_id") ASC NULLS FIRST, ("role") ASC NULLS FIRST);

CREATE INDEX "idx_device_identities_device" ON "device_identities" (("device_id") ASC NULLS FIRST, ("updated_at_ms") DESC NULLS LAST);`,preData:[0,926],postData:[926,1225],tables:[{name:`device_auth_tokens`,identities:[]},{name:`device_identities`,identities:[]},{name:`gateway_origin_device_tokens`,identities:[]}],expectedCatalog:[{table:`device_auth_tokens`,kind:`table`,value:null},{table:`device_auth_tokens`,kind:`column`,value:{name:`device_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`device_auth_tokens`,kind:`column`,value:{name:`role`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`device_auth_tokens`,kind:`column`,value:{name:`token`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`device_auth_tokens`,kind:`column`,value:{name:`scopes_json`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`device_auth_tokens`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`device_auth_tokens`,kind:`primaryKey`,value:[`device_id`,`role`]},{table:`device_auth_tokens`,kind:`indexes`,value:2},{table:`device_auth_tokens`,kind:`checks`,value:0},{table:`device_identities`,kind:`table`,value:null},{table:`device_identities`,kind:`column`,value:{name:`identity_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`device_identities`,kind:`column`,value:{name:`device_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`device_identities`,kind:`column`,value:{name:`public_key_pem`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`device_identities`,kind:`column`,value:{name:`private_key_pem`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`device_identities`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`device_identities`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`device_identities`,kind:`primaryKey`,value:[`identity_key`]},{table:`device_identities`,kind:`indexes`,value:2},{table:`device_identities`,kind:`checks`,value:0},{table:`gateway_origin_device_tokens`,kind:`table`,value:null},{table:`gateway_origin_device_tokens`,kind:`column`,value:{name:`gateway_scope`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`gateway_origin_device_tokens`,kind:`column`,value:{name:`device_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`gateway_origin_device_tokens`,kind:`column`,value:{name:`role`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`gateway_origin_device_tokens`,kind:`column`,value:{name:`token`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`gateway_origin_device_tokens`,kind:`column`,value:{name:`scopes_json`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`gateway_origin_device_tokens`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`gateway_origin_device_tokens`,kind:`primaryKey`,value:[`gateway_scope`,`device_id`,`role`]},{table:`gateway_origin_device_tokens`,kind:`indexes`,value:1},{table:`gateway_origin_device_tokens`,kind:`checks`,value:0}]};return Object.defineProperty(this,"clientCredentialSource",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get fragments(){let e=[{id:`local_workspace_projections`,tables:[`local_workspace_projections`,`local_workspace_manifest_nodes`,`local_workspace_tree_packs`,`local_workspace_source_path_sets`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "local_workspace_manifest_nodes" (
  "worktree_id" text COLLATE "C" NOT NULL,
  "path" text COLLATE "C" NOT NULL,
  "node_json" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("worktree_id", "path")
);

CREATE TABLE "local_workspace_projections" (
  "worktree_id" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "lifecycle_revision" text COLLATE "C",
  "projection_path" text COLLATE "C" NOT NULL,
  "base_commit" text COLLATE "C" NOT NULL,
  "source_paths_json" text COLLATE "C" NOT NULL,
  "baseline_json" text COLLATE "C",
  "baseline_ref" text COLLATE "C",
  "pending_ref" text COLLATE "C",
  "pending_target" text COLLATE "C",
  "paused_runtimes_json" text COLLATE "C",
  "journal_json" text COLLATE "C",
  "journal_pack" bytea,
  "revision" bigint NOT NULL DEFAULT 0,
  "created_at_ms" bigint NOT NULL,
  "checkpoint_json" text COLLATE "C",
  "tree_root_digest" bytea,
  "source_paths_digest" bytea,
  "canonical_fingerprints" bytea,
  "projection_fingerprints" bytea,
  PRIMARY KEY ("worktree_id"),
  CHECK (("pending_target" IN ('canonical', 'projection'))),
  CHECK ("journal_pack" IS NULL OR (octet_length("journal_pack") <= 268435456)),
  CHECK (("revision" >= 0)),
  CHECK ("baseline_json" IS NULL OR "baseline_ref" IS NOT NULL),
  CHECK ((("journal_json" IS NULL) = ("journal_pack" IS NULL))),
  UNIQUE ("projection_path")
);

CREATE TABLE "local_workspace_source_path_sets" (
  "path_digest" bytea NOT NULL,
  "paths_zstd" bytea NOT NULL,
  "sweep_epoch" bigint NOT NULL,
  PRIMARY KEY ("path_digest"),
  CHECK ((octet_length("path_digest") = 32))
);

CREATE TABLE "local_workspace_tree_packs" (
  "tree_digest" bytea NOT NULL,
  "records_json" text COLLATE "C" NOT NULL,
  "children_json" text COLLATE "C" NOT NULL,
  "sweep_epoch" bigint NOT NULL,
  PRIMARY KEY ("tree_digest"),
  CHECK ((octet_length("tree_digest") = 32))
);

ALTER TABLE "local_workspace_manifest_nodes" ADD FOREIGN KEY ("worktree_id") REFERENCES "local_workspace_projections" ("worktree_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`user_profiles`,tables:[`user_profiles`,`user_profile_emails`,`user_profile_identities`],indexes:[`idx_user_profile_emails_profile_id`,`idx_user_profile_identities_profile_id`,`idx_user_profile_identities_authorization`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "user_profile_emails" (
  "email" text COLLATE "C" NOT NULL,
  "profile_id" text COLLATE "C" NOT NULL,
  "binding_id" text COLLATE "C",
  "created_at" bigint NOT NULL,
  PRIMARY KEY ("email")
);

CREATE TABLE "user_profile_identities" (
  "provider" text COLLATE "C" NOT NULL,
  "subject" text COLLATE "C" NOT NULL,
  "profile_id" text COLLATE "C" NOT NULL,
  "canonical_login" text COLLATE "C",
  "verified_email_json" text COLLATE "C",
  "created_at" bigint NOT NULL,
  "authorization_id" text COLLATE "C",
  "authorization_basis_json" text COLLATE "C",
  PRIMARY KEY ("provider", "subject")
);

CREATE TABLE "user_profiles" (
  "id" text COLLATE "C" NOT NULL,
  "display_name" text COLLATE "C",
  "primary_github_account_id" bigint,
  "avatar" bytea,
  "avatar_mime" text COLLATE "C",
  "avatar_sha256" text COLLATE "C",
  "merged_into" text COLLATE "C",
  "role" text COLLATE "C",
  "created_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("id")
);

CREATE INDEX "idx_user_profile_emails_profile_id" ON "user_profile_emails" (("profile_id") ASC);

CREATE UNIQUE INDEX "idx_user_profile_identities_authorization" ON "user_profile_identities" (("authorization_id") ASC NULLS FIRST);

CREATE INDEX "idx_user_profile_identities_profile_id" ON "user_profile_identities" (("profile_id") ASC);
`},{id:`skill_library_entries`,tables:[`skill_library_entries`,`skill_library_revisions`,`skill_library_events`,`skill_library_uploads`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "skill_library_entries" (
  "skill_id" text COLLATE "C" NOT NULL,
  "owner_profile_id" text COLLATE "C",
  "author_profile_id" text COLLATE "C" NOT NULL,
  "slug" text COLLATE "C" NOT NULL,
  "current_revision" text COLLATE "C" NOT NULL,
  "shared" bigint NOT NULL,
  "enabled" bigint NOT NULL,
  "removed" bigint NOT NULL,
  "created_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("skill_id")
);

CREATE TABLE "skill_library_events" (
  "event_id" text COLLATE "C" NOT NULL,
  "skill_id" text COLLATE "C" NOT NULL,
  "revision" text COLLATE "C" NOT NULL,
  "action" text COLLATE "C" NOT NULL,
  "actor_profile_id" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  PRIMARY KEY ("event_id")
);

CREATE TABLE "skill_library_revisions" (
  "skill_id" text COLLATE "C" NOT NULL,
  "revision" text COLLATE "C" NOT NULL,
  "description" text COLLATE "C" NOT NULL,
  "files_json" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  PRIMARY KEY ("skill_id", "revision")
);

CREATE TABLE "skill_library_uploads" (
  "upload_id" text COLLATE "C" NOT NULL,
  "owner_profile_id" text COLLATE "C" NOT NULL,
  "slug" text COLLATE "C" NOT NULL,
  "size_bytes" bigint NOT NULL,
  "sha256" text COLLATE "C" NOT NULL,
  "archive_blob" bytea NOT NULL,
  "expires_at" bigint NOT NULL,
  "published_skill_id" text COLLATE "C",
  PRIMARY KEY ("upload_id")
);
`},{id:`operator_approval_standing_grants`,tables:[`operator_approval_standing_grants`,`operator_approval_standing_grant_generations`],indexes:[`idx_operator_approval_standing_grants_binding`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "operator_approval_standing_grant_generations" (
  "grant_id" text COLLATE "C" NOT NULL,
  "job_definition_generation" bigint NOT NULL,
  PRIMARY KEY ("grant_id"),
  CHECK (("job_definition_generation" >= 1))
);

CREATE TABLE "operator_approval_standing_grants" (
  "grant_id" text COLLATE "C" NOT NULL,
  "minted_by_approval_id" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "cron_job_id" text COLLATE "C" NOT NULL,
  "job_config_revision" text COLLATE "C" NOT NULL,
  "operation_binding" text COLLATE "C" NOT NULL,
  "created_at_ms" bigint NOT NULL,
  "expires_at_ms" bigint,
  "revoked_at_ms" bigint,
  "revoked_by" text COLLATE "C",
  "last_used_at_ms" bigint,
  "use_count" bigint NOT NULL DEFAULT 0,
  PRIMARY KEY ("grant_id"),
  CHECK ((char_length("grant_id") > 0)),
  CHECK ((char_length("agent_id") > 0)),
  CHECK ((char_length("cron_job_id") > 0)),
  CHECK ((char_length("job_config_revision") > 0)),
  CHECK ((char_length("operation_binding") > 0)),
  CHECK ("expires_at_ms" IS NULL OR ("expires_at_ms" >= "created_at_ms"))
);

CREATE INDEX "idx_operator_approval_standing_grants_binding" ON "operator_approval_standing_grants" (("agent_id") ASC, ("cron_job_id") ASC, ("operation_binding") ASC, ("created_at_ms") DESC);

ALTER TABLE "operator_approval_standing_grant_generations" ADD FOREIGN KEY ("grant_id") REFERENCES "operator_approval_standing_grants" ("grant_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "operator_approval_standing_grants" ADD FOREIGN KEY ("minted_by_approval_id") REFERENCES "operator_approvals" ("approval_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`worker_environment_session_attachments`,tables:[`worker_environment_session_attachments`],indexes:[`worker_environment_session_attachments_session_key`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "worker_environment_session_attachments" (
  "session_id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "session_lifecycle_revision" text COLLATE "C",
  "environment_id" text COLLATE "C" NOT NULL,
  "generation" bigint NOT NULL,
  "created_at_ms" bigint NOT NULL,
  "last_used_at_ms" bigint NOT NULL,
  "closed_at_ms" bigint,
  PRIMARY KEY ("session_id"),
  CHECK (("generation" >= 1)),
  UNIQUE ("environment_id")
);

CREATE INDEX "worker_environment_session_attachments_session_key" ON "worker_environment_session_attachments" (("agent_id") ASC, ("session_key") ASC);

ALTER TABLE "worker_environment_session_attachments" ADD FOREIGN KEY ("environment_id") REFERENCES "worker_environments" ("environment_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`durable_background_processes`,tables:[`durable_background_processes`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "durable_background_processes" (
  "id" text COLLATE "C" NOT NULL,
  "record_json" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("id")
);
`},{id:`sandbox_persistent_execs`,tables:[`sandbox_persistent_execs`],indexes:[`idx_sandbox_persistent_execs_container`,`idx_sandbox_persistent_execs_container_name`,`idx_sandbox_persistent_execs_source`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "sandbox_persistent_execs" (
  "owner_key" text COLLATE "C" NOT NULL,
  "source_identity" text COLLATE "C" NOT NULL,
  "attempt_id" text COLLATE "C" NOT NULL,
  "owner_json" text COLLATE "C" NOT NULL,
  "backend_id" text COLLATE "C" NOT NULL,
  "backend_target_json" text COLLATE "C" NOT NULL,
  "workspace_binding_json" text COLLATE "C" NOT NULL,
  "container_id" text COLLATE "C" NOT NULL,
  "container_name" text COLLATE "C" NOT NULL,
  "container_started_at" text COLLATE "C" NOT NULL,
  "revision" bigint NOT NULL,
  "phase" text COLLATE "C" NOT NULL,
  "receipt_json" text COLLATE "C",
  "error" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("owner_key"),
  CHECK (("backend_id" = 'docker')),
  CHECK (("revision" > 0)),
  CHECK (("phase" IN ('reserved', 'prepared', 'running', 'stopping', 'uncertain', 'stopped'))),
  CHECK (("phase" NOT IN ('prepared', 'running')) OR "receipt_json" IS NOT NULL),
  UNIQUE ("attempt_id")
);

CREATE INDEX "idx_sandbox_persistent_execs_container" ON "sandbox_persistent_execs" (("container_id") ASC, ("owner_key") ASC);

CREATE INDEX "idx_sandbox_persistent_execs_container_name" ON "sandbox_persistent_execs" (("container_name") ASC, ("owner_key") ASC);

CREATE INDEX "idx_sandbox_persistent_execs_source" ON "sandbox_persistent_execs" (("source_identity") ASC, ("owner_key") ASC);
`},{id:`user_background_images`,tables:[`user_background_images`],indexes:[],dependencies:[`user_profiles`],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "user_background_images" (
  "profile_id" text COLLATE "C" NOT NULL,
  "asset_id" text COLLATE "C" NOT NULL,
  "image" bytea NOT NULL,
  "width" bigint NOT NULL,
  "height" bigint NOT NULL,
  PRIMARY KEY ("profile_id"),
  CHECK ((octet_length("image") BETWEEN 1 AND 2097152)),
  CHECK (("width" BETWEEN 1 AND 2560)),
  CHECK (("height" BETWEEN 1 AND 2560)),
  UNIQUE ("asset_id")
);

ALTER TABLE "user_background_images" ADD FOREIGN KEY ("profile_id") REFERENCES "user_profiles" ("id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`update_runs`,tables:[`update_runs`],indexes:[`idx_update_runs_created`,`idx_update_runs_active`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "update_runs" (
  "run_id" text COLLATE "C" NOT NULL,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  "trigger" text COLLATE "C" NOT NULL,
  "phase" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "reason" text COLLATE "C",
  "origin_json" text COLLATE "C" NOT NULL,
  "target_json" text COLLATE "C" NOT NULL,
  "before_json" text COLLATE "C" NOT NULL,
  "after_json" text COLLATE "C" NOT NULL,
  "steps_json" text COLLATE "C" NOT NULL,
  "verification_json" text COLLATE "C" NOT NULL,
  "repair_json" text COLLATE "C" NOT NULL,
  "confirmed_at_ms" bigint,
  "finished_at_ms" bigint,
  "downtime_ms" bigint,
  PRIMARY KEY ("run_id"),
  CHECK (("trigger" IN ('chat', 'control-ui', 'cli', 'campaign', 'mac-app', 'api'))),
  CHECK (("phase" IN ('requested', 'staging', 'validating', 'repairing', 'activating', 'restarting', 'verifying', 'finished'))),
  CHECK (("status" IN ('running', 'succeeded', 'failed', 'rolled-back', 'skipped'))),
  CHECK ((octet_length(convert_to("origin_json", 'UTF8')) <= 16384)),
  CHECK ((octet_length(convert_to("target_json", 'UTF8')) <= 16384)),
  CHECK ((octet_length(convert_to("before_json", 'UTF8')) <= 16384)),
  CHECK ((octet_length(convert_to("after_json", 'UTF8')) <= 16384)),
  CHECK ((octet_length(convert_to("steps_json", 'UTF8')) <= 16384)),
  CHECK ((octet_length(convert_to("verification_json", 'UTF8')) <= 16384)),
  CHECK ((octet_length(convert_to("repair_json", 'UTF8')) <= 16384)),
  CHECK ((("status" = 'running') AND ("phase" != 'finished') AND "finished_at_ms" IS NULL) OR (("status" != 'running') AND ("phase" = 'finished') AND "finished_at_ms" IS NOT NULL))
);

CREATE INDEX "idx_update_runs_active" ON "update_runs" (("status") ASC, ("created_at_ms") DESC, ("run_id") ASC);

CREATE INDEX "idx_update_runs_created" ON "update_runs" (("created_at_ms") DESC, ("run_id") ASC);
`},{id:`session_repository_workspaces`,tables:[`session_repository_workspaces`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "session_repository_workspaces" (
  "workspace_id" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "url" text COLLATE "C" NOT NULL,
  "requested_ref" text COLLATE "C",
  "run_setup_script" bigint NOT NULL DEFAULT 0,
  "base_commit" text COLLATE "C",
  "base_manifest_hash" text COLLATE "C",
  "branch" text COLLATE "C" NOT NULL,
  "checkpoint_ref" text COLLATE "C",
  "manifest_hash" text COLLATE "C",
  "revision" bigint NOT NULL,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  "disk_authority_json" text COLLATE "C",
  PRIMARY KEY ("workspace_id"),
  CHECK ((char_length("workspace_id") = 36)),
  CHECK ((char_length("agent_id") BETWEEN 1 AND 128)),
  CHECK ((char_length("session_key") BETWEEN 1 AND 1024)),
  CHECK ((char_length("url") BETWEEN 1 AND 4096)),
  CHECK ("requested_ref" IS NULL OR (char_length("requested_ref") BETWEEN 1 AND 1024)),
  CHECK (("run_setup_script" IN (0, 1))),
  CHECK ("base_commit" IS NULL OR (char_length("base_commit") IN (40, 64))),
  CHECK ((char_length("branch") BETWEEN 1 AND 256)),
  CHECK (("revision" >= 0)),
  CHECK ("base_manifest_hash" IS NULL OR "base_commit" IS NOT NULL),
  CHECK (("checkpoint_ref" IS NULL AND "manifest_hash" IS NULL) OR ("checkpoint_ref" IS NOT NULL AND "manifest_hash" IS NOT NULL AND "base_manifest_hash" IS NOT NULL)),
  UNIQUE ("agent_id", "session_key")
);
`},{id:`github_repository_publication_requests`,tables:[`github_repository_publication_requests`],indexes:[`idx_github_repository_publication_shared_request`,`idx_github_repository_publication_personal_request`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "github_repository_publication_requests" (
  "request_id" text COLLATE "C" NOT NULL,
  "owner_profile_id" text COLLATE "C",
  "connection_generation" text COLLATE "C",
  "idempotency_key" text COLLATE "C" NOT NULL,
  "request_digest" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "session_lifecycle_revision" text COLLATE "C",
  "requester_authority_json" text COLLATE "C",
  "session_key" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "workspace_id" text COLLATE "C" NOT NULL,
  "checkpoint_ref" text COLLATE "C",
  "checkpoint_digest" text COLLATE "C",
  "claim_id" text COLLATE "C",
  "run_id" text COLLATE "C",
  "environment_id" text COLLATE "C",
  "owner_epoch" bigint,
  "placement_generation" bigint,
  "identity_source" text COLLATE "C" NOT NULL,
  "identity_profile_id" text COLLATE "C",
  "identity_account_id" bigint NOT NULL,
  "identity_login" text COLLATE "C" NOT NULL,
  "title" text COLLATE "C",
  "body" text COLLATE "C",
  "status" text COLLATE "C" NOT NULL,
  "gateway_instance_id" text COLLATE "C",
  "execution_id" text COLLATE "C",
  "last_effect" text COLLATE "C",
  "effect_state" text COLLATE "C",
  "push_repository" text COLLATE "C",
  "repository" text COLLATE "C",
  "branch" text COLLATE "C" NOT NULL,
  "base_branch" text COLLATE "C",
  "source_head_commit" text COLLATE "C",
  "source_index_tree" text COLLATE "C",
  "workspace_tree" text COLLATE "C",
  "previous_head_commit" text COLLATE "C",
  "pushed_head_commit" text COLLATE "C",
  "head_commit" text COLLATE "C",
  "pull_request_url" text COLLATE "C",
  "error_code" text COLLATE "C",
  "next_action" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  "reported_at_ms" bigint,
  "draft" bigint,
  PRIMARY KEY ("request_id"),
  CHECK (("identity_source" IN ('system-detected', 'system-configured', 'agent-override', 'personal'))),
  CHECK (("status" IN ('requested', 'publishing', 'needs_confirmation', 'published', 'failed'))),
  CHECK (("last_effect" IN ('push', 'pull_request'))),
  CHECK (("effect_state" IN ('dispatched', 'observed'))),
  CHECK ((("identity_source" = 'personal') AND "owner_profile_id" IS NOT NULL AND "connection_generation" IS NOT NULL) OR (("identity_source" <> 'personal') AND "owner_profile_id" IS NULL AND "connection_generation" IS NULL)),
  CHECK (("checkpoint_ref" IS NULL AND "checkpoint_digest" IS NULL) OR ("checkpoint_ref" IS NOT NULL AND "checkpoint_digest" IS NOT NULL)),
  CHECK (("last_effect" IS NULL AND "effect_state" IS NULL) OR ("last_effect" IS NOT NULL AND "effect_state" IS NOT NULL))
);

CREATE UNIQUE INDEX "idx_github_repository_publication_personal_request" ON "github_repository_publication_requests" (("owner_profile_id") ASC, ("session_id") ASC, ("idempotency_key") ASC) WHERE "owner_profile_id" IS NOT NULL;

CREATE UNIQUE INDEX "idx_github_repository_publication_shared_request" ON "github_repository_publication_requests" (("session_id") ASC, ("idempotency_key") ASC) WHERE "owner_profile_id" IS NULL;
`},{id:`github_publication_session_lifecycles`,tables:[`github_publication_session_lifecycles`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "github_publication_session_lifecycles" (
  "publication_kind" text COLLATE "C" NOT NULL,
  "request_id" text COLLATE "C" NOT NULL,
  "lifecycle_revision" text COLLATE "C",
  "requester_authority_json" text COLLATE "C",
  PRIMARY KEY ("publication_kind", "request_id"),
  CHECK (("publication_kind" IN ('shared', 'personal')))
);
`},{id:`github_personal_publication_requests`,tables:[`github_personal_publication_requests`],indexes:[`idx_github_personal_publication_owner_session`,`idx_github_personal_publication_pending`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "github_personal_publication_requests" (
  "request_id" text COLLATE "C" NOT NULL,
  "owner_profile_id" text COLLATE "C" NOT NULL,
  "connection_generation" text COLLATE "C" NOT NULL,
  "idempotency_key" text COLLATE "C" NOT NULL,
  "request_digest" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "worktree_id" text COLLATE "C" NOT NULL,
  "repository_fingerprint" text COLLATE "C" NOT NULL,
  "identity_source" text COLLATE "C" NOT NULL,
  "identity_profile_id" text COLLATE "C" NOT NULL,
  "identity_account_id" bigint NOT NULL,
  "identity_login" text COLLATE "C" NOT NULL,
  "title" text COLLATE "C",
  "body" text COLLATE "C",
  "status" text COLLATE "C" NOT NULL,
  "gateway_instance_id" text COLLATE "C",
  "execution_id" text COLLATE "C",
  "last_effect" text COLLATE "C",
  "effect_state" text COLLATE "C",
  "push_repository" text COLLATE "C" NOT NULL,
  "repository" text COLLATE "C" NOT NULL,
  "branch" text COLLATE "C" NOT NULL,
  "base_branch" text COLLATE "C" NOT NULL,
  "source_head_commit" text COLLATE "C" NOT NULL,
  "source_index_tree" text COLLATE "C" NOT NULL,
  "workspace_tree" text COLLATE "C" NOT NULL,
  "head_commit" text COLLATE "C",
  "pull_request_url" text COLLATE "C",
  "error_code" text COLLATE "C",
  "next_action" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  "reported_at_ms" bigint,
  "draft" bigint,
  PRIMARY KEY ("request_id"),
  CHECK ((char_length("request_id") = 36)),
  CHECK ((char_length("owner_profile_id") BETWEEN 1 AND 128)),
  CHECK ((char_length("connection_generation") = 36)),
  CHECK ((char_length("idempotency_key") BETWEEN 1 AND 128)),
  CHECK ((char_length("request_digest") = 64)),
  CHECK ((char_length("session_id") BETWEEN 1 AND 128)),
  CHECK ((char_length("session_key") BETWEEN 1 AND 1024)),
  CHECK ((char_length("agent_id") BETWEEN 1 AND 128)),
  CHECK ((char_length("worktree_id") BETWEEN 1 AND 128)),
  CHECK ((char_length("repository_fingerprint") BETWEEN 1 AND 256)),
  CHECK (("identity_source" = 'personal')),
  CHECK ((char_length("identity_profile_id") = 36)),
  CHECK (("identity_account_id" >= 1)),
  CHECK ((char_length("identity_login") BETWEEN 1 AND 39)),
  CHECK ("title" IS NULL OR (char_length("title") BETWEEN 1 AND 256)),
  CHECK ("body" IS NULL OR (char_length("body") BETWEEN 1 AND 8192)),
  CHECK (("status" IN ('requested', 'publishing', 'needs_confirmation', 'published', 'failed'))),
  CHECK ("gateway_instance_id" IS NULL OR (char_length("gateway_instance_id") BETWEEN 1 AND 128)),
  CHECK ("execution_id" IS NULL OR (char_length("execution_id") = 36)),
  CHECK ("last_effect" IS NULL OR ("last_effect" IN ('push', 'pull_request'))),
  CHECK ("effect_state" IS NULL OR ("effect_state" IN ('dispatched', 'observed'))),
  CHECK ((char_length("push_repository") BETWEEN 3 AND 256)),
  CHECK ((char_length("repository") BETWEEN 3 AND 256)),
  CHECK ((char_length("branch") BETWEEN 1 AND 256)),
  CHECK ((char_length("base_branch") BETWEEN 1 AND 256)),
  CHECK ((char_length("source_head_commit") IN (40, 64))),
  CHECK ((char_length("source_index_tree") IN (40, 64))),
  CHECK ((char_length("workspace_tree") IN (40, 64))),
  CHECK ("head_commit" IS NULL OR (char_length("head_commit") IN (40, 64))),
  CHECK ("pull_request_url" IS NULL OR (char_length("pull_request_url") BETWEEN 1 AND 2048)),
  CHECK ("error_code" IS NULL OR (char_length("error_code") BETWEEN 1 AND 64)),
  CHECK ("next_action" IS NULL OR (char_length("next_action") BETWEEN 1 AND 1024)),
  CHECK (("created_at_ms" >= 0)),
  CHECK (("updated_at_ms" >= "created_at_ms")),
  CHECK ((("status" = 'publishing') AND "gateway_instance_id" IS NOT NULL AND "execution_id" IS NOT NULL) OR ("status" <> 'publishing')),
  CHECK (("last_effect" IS NULL AND "effect_state" IS NULL) OR ("last_effect" IS NOT NULL AND "effect_state" IS NOT NULL)),
  CHECK ((("status" = 'published') AND "pull_request_url" IS NOT NULL AND "head_commit" IS NOT NULL AND "error_code" IS NULL AND "next_action" IS NULL) OR (("status" = 'failed') AND "error_code" IS NOT NULL AND "next_action" IS NOT NULL) OR (("status" IN ('requested', 'publishing', 'needs_confirmation')) AND "error_code" IS NULL AND "next_action" IS NULL)),
  UNIQUE ("owner_profile_id", "session_id", "idempotency_key")
);

CREATE INDEX "idx_github_personal_publication_owner_session" ON "github_personal_publication_requests" (("owner_profile_id") ASC, ("session_id") ASC, ("created_at_ms") ASC);

CREATE INDEX "idx_github_personal_publication_pending" ON "github_personal_publication_requests" (("status") ASC, ("updated_at_ms") ASC, ("request_id") ASC);
`},{id:`cron_job_runtime_authorities`,tables:[`cron_job_runtime_authorities`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "cron_job_runtime_authorities" (
  "store_key" text COLLATE "C" NOT NULL,
  "job_id" text COLLATE "C" NOT NULL,
  "authority_json" text COLLATE "C",
  "authority_input_fingerprint" text COLLATE "C",
  "recovery_required" bigint NOT NULL,
  PRIMARY KEY ("store_key", "job_id"),
  CHECK (("recovery_required" IN (0, 1))),
  CHECK ((("recovery_required" = 0) AND "authority_json" IS NOT NULL AND "authority_input_fingerprint" IS NOT NULL) OR (("recovery_required" = 1) AND "authority_json" IS NULL AND "authority_input_fingerprint" IS NULL))
);

ALTER TABLE "cron_job_runtime_authorities" ADD FOREIGN KEY ("store_key", "job_id") REFERENCES "cron_jobs" ("store_key", "job_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`cron_run_trigger_state_retirements`,tables:[`cron_run_trigger_state_retirements`],indexes:[],dependencies:[`cron_run_receipts`],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "cron_run_trigger_state_retirements" (
  "receipt_id" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("receipt_id")
);

ALTER TABLE "cron_run_trigger_state_retirements" ADD FOREIGN KEY ("receipt_id") REFERENCES "cron_run_receipts" ("receipt_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`execution_identity_contexts`,tables:[`execution_identity_contexts`],indexes:[`execution_identity_contexts_run_created_idx`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "execution_identity_contexts" (
  "context_id" text COLLATE "C" NOT NULL,
  "execution_id" text COLLATE "C" NOT NULL,
  "run_id" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  "coverage_state" text COLLATE "C" NOT NULL,
  "context_bytes" bigint NOT NULL,
  "context_json" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("context_id"),
  CHECK ((char_length("context_id") BETWEEN 1 AND 256)),
  CHECK ((char_length("execution_id") BETWEEN 1 AND 256)),
  CHECK ((char_length("run_id") BETWEEN 1 AND 256)),
  CHECK (("created_at" >= 0)),
  CHECK (("coverage_state" IN ('attribution-only', 'unattributed', 'unknown', 'unsupported'))),
  CHECK (("context_bytes" BETWEEN 1 AND 16384)),
  CHECK ((char_length("context_json") > 0)),
  UNIQUE ("execution_id"),
  UNIQUE ("created_at", "context_id")
);

CREATE INDEX "execution_identity_contexts_run_created_idx" ON "execution_identity_contexts" (("run_id") ASC, ("created_at") ASC, ("execution_id") ASC);
`},{id:`mcp_oauth_pending_authorizations`,tables:[`mcp_oauth_pending_authorizations`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "mcp_oauth_pending_authorizations" (
  "state" text COLLATE "C" NOT NULL,
  "store_key" text COLLATE "C" NOT NULL,
  "create_time" bigint NOT NULL,
  PRIMARY KEY ("state")
);
`},{id:`node_worker_launch_containers`,tables:[`node_worker_launch_containers`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "node_worker_launch_containers" (
  "launch_id" text COLLATE "C" NOT NULL,
  "container_json" text COLLATE "C",
  PRIMARY KEY ("launch_id")
);
`},{id:`node_worker_launch_boots`,tables:[`node_worker_launch_boots`],indexes:[],dependencies:[`node_worker_launches`],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "node_worker_launch_boots" (
  "launch_id" text COLLATE "C" NOT NULL,
  "boot_id" text COLLATE "C",
  PRIMARY KEY ("launch_id"),
  CHECK ("boot_id" IS NULL OR (char_length("boot_id") BETWEEN 1 AND 128))
);

ALTER TABLE "node_worker_launch_boots" ADD FOREIGN KEY ("launch_id") REFERENCES "node_worker_launches" ("launch_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`node_worker_launch_cleanup`,tables:[`node_worker_launch_cleanup`],indexes:[],dependencies:[`node_worker_launches`],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "node_worker_launch_cleanup" (
  "launch_id" text COLLATE "C" NOT NULL,
  "cleanup_mode" text COLLATE "C" NOT NULL,
  "lineage_settled" bigint,
  PRIMARY KEY ("launch_id"),
  CHECK (("cleanup_mode" IN ('process-group', 'owned-anchor'))),
  CHECK ("lineage_settled" IS NULL OR ("lineage_settled" = 1))
);

ALTER TABLE "node_worker_launch_cleanup" ADD FOREIGN KEY ("launch_id") REFERENCES "node_worker_launches" ("launch_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`node_worker_launch_process_scopes`,tables:[`node_worker_launch_process_scopes`],indexes:[],dependencies:[`node_worker_launches`],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "node_worker_launch_process_scopes" (
  "launch_id" text COLLATE "C" NOT NULL,
  "scope_kind" text COLLATE "C" NOT NULL,
  "descendants_reaped" bigint,
  PRIMARY KEY ("launch_id"),
  CHECK (("scope_kind" = 'linux-subreaper')),
  CHECK ("descendants_reaped" IS NULL OR ("descendants_reaped" = 1))
);

ALTER TABLE "node_worker_launch_process_scopes" ADD FOREIGN KEY ("launch_id") REFERENCES "node_worker_launches" ("launch_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`node_worker_launches`,tables:[`node_worker_launches`],indexes:[`idx_node_worker_launches_terminal_completed`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "node_worker_launches" (
  "launch_id" text COLLATE "C" NOT NULL,
  "plan_hash" text COLLATE "C" NOT NULL,
  "gateway_namespace" text COLLATE "C" NOT NULL,
  "environment_id" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "owner_epoch" bigint NOT NULL,
  "placement_generation" bigint NOT NULL,
  "run_id" text COLLATE "C" NOT NULL,
  "state" text COLLATE "C" NOT NULL,
  "supervisor_pid" bigint NOT NULL,
  "supervisor_start_time" bigint NOT NULL,
  "worker_pid" bigint,
  "worker_start_time" bigint,
  "result_json" text COLLATE "C",
  "error_text" text COLLATE "C",
  "completed_at_ms" bigint,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("launch_id"),
  CHECK ((char_length("launch_id") BETWEEN 1 AND 256) AND ("launch_id" IS NOT NULL OR NULL)),
  CHECK ((char_length("plan_hash") = 64) AND ("plan_hash" COLLATE "C" !~ '\\A.*[^0-9a-f].*\\Z')),
  CHECK ((char_length("gateway_namespace") BETWEEN 1 AND 128) AND ("gateway_namespace" COLLATE "C" !~ '\\A.*[^A-Za-z0-9._-].*\\Z') AND ("gateway_namespace" COLLATE "C" ~ '\\A[A-Za-z0-9].*\\Z')),
  CHECK ((char_length("environment_id") BETWEEN 1 AND 256) AND ("environment_id" IS NOT NULL OR NULL)),
  CHECK ((char_length("session_id") BETWEEN 1 AND 256) AND ("session_id" IS NOT NULL OR NULL)),
  CHECK (("owner_epoch" BETWEEN 1 AND 9007199254740991)),
  CHECK (("placement_generation" BETWEEN 0 AND 9007199254740991)),
  CHECK ((char_length("run_id") BETWEEN 1 AND 256) AND ("run_id" IS NOT NULL OR NULL)),
  CHECK (("state" IN ('pending', 'running', 'completed', 'failed', 'interrupted', 'cancelled'))),
  CHECK (("supervisor_pid" BETWEEN 1 AND 2147483647)),
  CHECK (("supervisor_start_time" BETWEEN 0 AND 9007199254740991)),
  CHECK ("worker_pid" IS NULL OR ("worker_pid" BETWEEN 1 AND 2147483647)),
  CHECK ("worker_start_time" IS NULL OR ("worker_start_time" BETWEEN 0 AND 9007199254740991)),
  CHECK ("result_json" IS NULL OR ((octet_length(convert_to("result_json", 'UTF8')) BETWEEN 1 AND 65536) AND ("result_json" IS NOT NULL OR NULL) AND ("result_json" IS JSON))),
  CHECK ("error_text" IS NULL OR ((octet_length(convert_to("error_text", 'UTF8')) BETWEEN 1 AND 4096) AND ("error_text" IS NOT NULL OR NULL) AND (strpos("error_text", '
') = 0) AND (strpos("error_text", '\r') = 0))),
  CHECK ("completed_at_ms" IS NULL OR ("completed_at_ms" BETWEEN 0 AND 9007199254740991)),
  CHECK (("created_at_ms" BETWEEN 0 AND 9007199254740991)),
  CHECK (("updated_at_ms" BETWEEN "created_at_ms" AND 9007199254740991)),
  CHECK ((("worker_pid" IS NULL) = ("worker_start_time" IS NULL))),
  CHECK ((("state" = 'pending') AND "worker_pid" IS NULL AND "result_json" IS NULL AND "error_text" IS NULL AND "completed_at_ms" IS NULL) OR (("state" = 'running') AND "worker_pid" IS NOT NULL AND "result_json" IS NULL AND "error_text" IS NULL AND "completed_at_ms" IS NULL) OR (("state" = 'completed') AND "result_json" IS NOT NULL AND "error_text" IS NULL AND ("completed_at_ms" BETWEEN "created_at_ms" AND "updated_at_ms")) OR (("state" IN ('failed', 'interrupted', 'cancelled')) AND "result_json" IS NULL AND "error_text" IS NOT NULL AND ("completed_at_ms" BETWEEN "created_at_ms" AND "updated_at_ms")))
);

CREATE INDEX "idx_node_worker_launches_terminal_completed" ON "node_worker_launches" (("completed_at_ms") ASC, ("launch_id") ASC) WHERE "completed_at_ms" IS NOT NULL;
`},{id:`node_worker_prepared_workspaces`,tables:[`node_worker_prepared_workspaces`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "node_worker_prepared_workspaces" (
  "preparation_key" text COLLATE "C" NOT NULL,
  "cache_key" text COLLATE "C" NOT NULL,
  "gateway_namespace" text COLLATE "C" NOT NULL,
  "workspace_dir" text COLLATE "C" NOT NULL,
  "home_dir" text COLLATE "C" NOT NULL,
  "source_manifest_ref" text COLLATE "C" NOT NULL,
  "prepared_manifest_ref" text COLLATE "C" NOT NULL,
  "state" text COLLATE "C" NOT NULL,
  "environment_id" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C",
  "session_key" text COLLATE "C",
  "owner_epoch" bigint,
  "created_at_ms" bigint NOT NULL,
  "bound_at_ms" bigint,
  "retired_at_ms" bigint,
  PRIMARY KEY ("preparation_key"),
  CHECK ((char_length("preparation_key") = 64) AND ("preparation_key" COLLATE "C" !~ '\\A.*[^0-9a-f].*\\Z')),
  CHECK ((char_length("cache_key") = 64) AND ("cache_key" COLLATE "C" !~ '\\A.*[^0-9a-f].*\\Z')),
  CHECK ((char_length("gateway_namespace") > 0)),
  CHECK ((char_length("workspace_dir") > 0)),
  CHECK ((char_length("home_dir") > 0)),
  CHECK ((char_length("source_manifest_ref") = 71) AND (substr("source_manifest_ref", 1, 7) = 'sha256:') AND (substr("source_manifest_ref", 8) COLLATE "C" !~ '\\A.*[^0-9a-f].*\\Z')),
  CHECK ((char_length("prepared_manifest_ref") = 71) AND (substr("prepared_manifest_ref", 1, 7) = 'sha256:') AND (substr("prepared_manifest_ref", 8) COLLATE "C" !~ '\\A.*[^0-9a-f].*\\Z')),
  CHECK (("state" IN ('available', 'bound', 'retiring', 'retired'))),
  CHECK ((char_length("environment_id") > 0)),
  CHECK (("owner_epoch" BETWEEN 1 AND 9007199254740991)),
  CHECK (("created_at_ms" BETWEEN 0 AND 9007199254740991)),
  CHECK (("bound_at_ms" BETWEEN "created_at_ms" AND 9007199254740991)),
  CHECK (("retired_at_ms" BETWEEN coalesce("bound_at_ms", "created_at_ms") AND 9007199254740991)),
  CHECK (("session_id" IS NULL AND "session_key" IS NULL AND "owner_epoch" IS NULL AND "bound_at_ms" IS NULL) OR ("session_id" IS NOT NULL AND (char_length("session_id") > 0) AND "session_key" IS NOT NULL AND (char_length("session_key") > 0) AND "owner_epoch" IS NOT NULL AND "bound_at_ms" IS NOT NULL)),
  CHECK ((("state" = 'available') AND "bound_at_ms" IS NULL AND "retired_at_ms" IS NULL) OR (("state" = 'bound') AND "bound_at_ms" IS NOT NULL AND "retired_at_ms" IS NULL) OR (("state" = 'retiring') AND "retired_at_ms" IS NULL) OR (("state" = 'retired') AND "retired_at_ms" IS NOT NULL)),
  UNIQUE ("workspace_dir")
);
`},{id:`node_worker_turns`,tables:[`node_worker_turns`],indexes:[`idx_node_worker_turns_terminal_completed`,`idx_node_worker_turns_active_owner`],dependencies:[`node_worker_launches`],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "node_worker_turns" (
  "turn_id" text COLLATE "C" NOT NULL,
  "owner_launch_id" text COLLATE "C" NOT NULL,
  "plan_hash" text COLLATE "C" NOT NULL,
  "run_id" text COLLATE "C" NOT NULL,
  "state" text COLLATE "C" NOT NULL,
  "result_json" text COLLATE "C",
  "error_text" text COLLATE "C",
  "completed_at_ms" bigint,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("turn_id"),
  CHECK ((char_length("turn_id") BETWEEN 1 AND 256) AND ("turn_id" IS NOT NULL OR NULL)),
  CHECK ((char_length("plan_hash") = 64) AND ("plan_hash" COLLATE "C" !~ '\\A.*[^0-9a-f].*\\Z')),
  CHECK ((char_length("run_id") BETWEEN 1 AND 256) AND ("run_id" IS NOT NULL OR NULL)),
  CHECK (("state" IN ('running', 'completed', 'failed', 'interrupted', 'cancelled'))),
  CHECK ("result_json" IS NULL OR ((octet_length(convert_to("result_json", 'UTF8')) BETWEEN 1 AND 65536) AND ("result_json" IS NOT NULL OR NULL) AND ("result_json" IS JSON))),
  CHECK ("error_text" IS NULL OR ((octet_length(convert_to("error_text", 'UTF8')) BETWEEN 1 AND 4096) AND ("error_text" IS NOT NULL OR NULL) AND (strpos("error_text", '
') = 0) AND (strpos("error_text", '\r') = 0))),
  CHECK ("completed_at_ms" IS NULL OR ("completed_at_ms" BETWEEN 0 AND 9007199254740991)),
  CHECK (("created_at_ms" BETWEEN 0 AND 9007199254740991)),
  CHECK (("updated_at_ms" BETWEEN "created_at_ms" AND 9007199254740991)),
  CHECK ((("state" = 'running') AND "result_json" IS NULL AND "error_text" IS NULL AND "completed_at_ms" IS NULL) OR (("state" = 'completed') AND "result_json" IS NOT NULL AND "error_text" IS NULL AND ("completed_at_ms" BETWEEN "created_at_ms" AND "updated_at_ms")) OR (("state" IN ('failed', 'interrupted', 'cancelled')) AND "result_json" IS NULL AND "error_text" IS NOT NULL AND ("completed_at_ms" BETWEEN "created_at_ms" AND "updated_at_ms")))
);

CREATE UNIQUE INDEX "idx_node_worker_turns_active_owner" ON "node_worker_turns" (("owner_launch_id") ASC) WHERE ("state" = 'running');

CREATE INDEX "idx_node_worker_turns_terminal_completed" ON "node_worker_turns" (("completed_at_ms") ASC, ("turn_id") ASC) WHERE "completed_at_ms" IS NOT NULL;

ALTER TABLE "node_worker_turns" ADD FOREIGN KEY ("owner_launch_id") REFERENCES "node_worker_launches" ("launch_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`operator_approval_execution_identities`,tables:[`operator_approval_execution_identities`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "operator_approval_execution_identities" (
  "approval_id" text COLLATE "C" NOT NULL,
  "source_context_id" text COLLATE "C" NOT NULL,
  "source_execution_id" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("approval_id"),
  CHECK ((char_length("source_context_id") BETWEEN 1 AND 256) AND ("source_context_id" = btrim("source_context_id"))),
  CHECK ((char_length("source_execution_id") BETWEEN 1 AND 256) AND ("source_execution_id" = btrim("source_execution_id")))
);

ALTER TABLE "operator_approval_execution_identities" ADD FOREIGN KEY ("approval_id") REFERENCES "operator_approvals" ("approval_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`web_push_approval_deliveries`,tables:[`web_push_approval_deliveries`],indexes:[`idx_web_push_approval_deliveries_subscription`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "web_push_approval_deliveries" (
  "approval_id" text COLLATE "C" NOT NULL,
  "subscription_id" text COLLATE "C" NOT NULL,
  "device_id" text COLLATE "C" NOT NULL,
  "user_profile_id" text COLLATE "C",
  "prepared_at_ms" bigint NOT NULL,
  PRIMARY KEY ("approval_id", "subscription_id")
);

CREATE INDEX "idx_web_push_approval_deliveries_subscription" ON "web_push_approval_deliveries" (("subscription_id") ASC, ("approval_id") ASC);

ALTER TABLE "web_push_approval_deliveries" ADD FOREIGN KEY ("subscription_id") REFERENCES "web_push_subscriptions" ("subscription_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "web_push_approval_deliveries" ADD FOREIGN KEY ("approval_id") REFERENCES "operator_approvals" ("approval_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`execution_decision_facts`,tables:[`execution_decision_facts`],indexes:[`execution_decision_facts_cursor_id_idx`,`execution_decision_facts_context_occurred_idx`,`execution_decision_facts_run_occurred_idx`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "execution_decision_facts" (
  "cursor_id" bigint NOT NULL,
  "receipt_id" text COLLATE "C" NOT NULL,
  "context_id" text COLLATE "C" NOT NULL,
  "execution_id" text COLLATE "C" NOT NULL,
  "run_id" text COLLATE "C" NOT NULL,
  "action_id" text COLLATE "C",
  "action_family" text COLLATE "C" NOT NULL,
  "decision_outcome" text COLLATE "C" NOT NULL,
  "coverage_state" text COLLATE "C" NOT NULL,
  "reason_code" text COLLATE "C" NOT NULL,
  "owner" text COLLATE "C" NOT NULL,
  "source_ref" text COLLATE "C" NOT NULL,
  "occurred_at" bigint NOT NULL,
  "receipt_bytes" bigint NOT NULL,
  "receipt_json" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("receipt_id"),
  CHECK ((char_length("receipt_id") BETWEEN 1 AND 256)),
  CHECK ((char_length("context_id") BETWEEN 1 AND 256)),
  CHECK ((char_length("execution_id") BETWEEN 1 AND 256)),
  CHECK ((char_length("run_id") BETWEEN 1 AND 256)),
  CHECK ("action_id" IS NULL OR (char_length("action_id") BETWEEN 1 AND 256)),
  CHECK ((char_length("action_family") BETWEEN 1 AND 256)),
  CHECK (("decision_outcome" IN ('allowed', 'denied', 'not-applicable', 'unknown'))),
  CHECK (("coverage_state" IN ('enforced', 'attribution-only', 'unattributed', 'unknown', 'unsupported'))),
  CHECK ((char_length("reason_code") BETWEEN 1 AND 256)),
  CHECK ((char_length("owner") BETWEEN 1 AND 256)),
  CHECK ((char_length("source_ref") BETWEEN 1 AND 256)),
  CHECK (("occurred_at" >= 0)),
  CHECK (("receipt_bytes" BETWEEN 1 AND 16384)),
  CHECK ((char_length("receipt_json") > 0)),
  UNIQUE ("occurred_at", "receipt_id")
);

CREATE INDEX "execution_decision_facts_context_occurred_idx" ON "execution_decision_facts" (("context_id") ASC, ("occurred_at") ASC, ("receipt_id") ASC);

CREATE UNIQUE INDEX "execution_decision_facts_cursor_id_idx" ON "execution_decision_facts" (("cursor_id") ASC);

CREATE INDEX "execution_decision_facts_run_occurred_idx" ON "execution_decision_facts" (("run_id") ASC, ("occurred_at") ASC, ("receipt_id") ASC);
`},{id:`execution_owner_lifecycle_bindings`,tables:[`execution_owner_lifecycle_bindings`],indexes:[],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "execution_owner_lifecycle_bindings" (
  "owner_kind" text COLLATE "C" NOT NULL,
  "owner_id" text COLLATE "C" NOT NULL,
  "context_id" text COLLATE "C" NOT NULL,
  "execution_id" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("owner_kind", "owner_id")
);
`},{id:`outbound_message_execution_bindings`,tables:[`outbound_message_execution_bindings`],indexes:[`outbound_message_execution_bindings_execution_event_idx`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "outbound_message_execution_bindings" (
  "event_id" text COLLATE "C" NOT NULL,
  "context_id" text COLLATE "C" NOT NULL,
  "execution_id" text COLLATE "C" NOT NULL,
  "run_id" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("event_id"),
  CHECK ((char_length("context_id") BETWEEN 1 AND 256)),
  CHECK ((char_length("execution_id") BETWEEN 1 AND 256)),
  CHECK ((char_length("run_id") BETWEEN 1 AND 256))
);

CREATE INDEX "outbound_message_execution_bindings_execution_event_idx" ON "outbound_message_execution_bindings" (("context_id") ASC, ("execution_id") ASC, ("run_id") ASC, ("event_id") ASC);

ALTER TABLE "outbound_message_execution_bindings" ADD FOREIGN KEY ("event_id") REFERENCES "audit_events" ("event_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`outbound_message_progress`,tables:[`outbound_message_progress`],indexes:[`outbound_message_progress_occurred_idx`,`outbound_message_progress_run_occurred_idx`],dependencies:[],activation:`first-use`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "outbound_message_progress" (
  "sequence" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "progress_id" text COLLATE "C" NOT NULL,
  "source_id" text COLLATE "C" NOT NULL,
  "source_sequence" bigint NOT NULL,
  "schema_version" bigint NOT NULL,
  "occurred_at" bigint NOT NULL,
  "action" text COLLATE "C" NOT NULL,
  "outcome" text COLLATE "C" NOT NULL,
  "actor_type" text COLLATE "C" NOT NULL,
  "actor_id" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C",
  "run_id" text COLLATE "C",
  "context_id" text COLLATE "C",
  "execution_id" text COLLATE "C",
  "channel" text COLLATE "C" NOT NULL,
  "conversation_kind" text COLLATE "C" NOT NULL,
  "duration_ms" bigint,
  "account_ref" text COLLATE "C",
  "conversation_ref" text COLLATE "C",
  "target_ref" text COLLATE "C",
  PRIMARY KEY ("sequence"),
  CHECK ((char_length("progress_id") BETWEEN 1 AND 256)),
  CHECK ((char_length("source_id") BETWEEN 1 AND 512)),
  CHECK (("source_sequence" >= 1)),
  CHECK (("schema_version" = 1)),
  CHECK (("occurred_at" >= 0)),
  CHECK (("action" IN ('message.outbound.queued', 'message.outbound.platform-started'))),
  CHECK (("outcome" IN ('queued', 'platform_started'))),
  CHECK (("actor_type" IN ('agent', 'system'))),
  CHECK ((char_length("actor_id") BETWEEN 1 AND 256)),
  CHECK ("agent_id" IS NULL OR (char_length("agent_id") BETWEEN 1 AND 256)),
  CHECK ("run_id" IS NULL OR (char_length("run_id") BETWEEN 1 AND 256)),
  CHECK ((char_length("channel") BETWEEN 1 AND 256)),
  CHECK (("conversation_kind" IN ('direct', 'group', 'channel', 'unknown'))),
  CHECK ("duration_ms" IS NULL OR ("duration_ms" >= 0)),
  UNIQUE ("progress_id"),
  UNIQUE ("source_id"),
  UNIQUE ("occurred_at", "progress_id")
);

CREATE INDEX "outbound_message_progress_occurred_idx" ON "outbound_message_progress" (("occurred_at") ASC, ("sequence") ASC);

CREATE INDEX "outbound_message_progress_run_occurred_idx" ON "outbound_message_progress" (("run_id") ASC NULLS FIRST, ("occurred_at") ASC, ("sequence") ASC);
`},{id:`agent_provenance`,tables:[`agent_provenance`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "agent_provenance" (
  "agent_id" text COLLATE "C" NOT NULL,
  "created_via" text COLLATE "C" NOT NULL,
  "creator_agent_id" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  PRIMARY KEY ("agent_id"),
  CHECK (("created_via" IN ('operator', 'agent', 'template')))
);
`},{id:`cron_run_receipts`,tables:[`cron_run_receipts`],indexes:[`cron_run_receipts_cursor_id_idx`,`idx_cron_run_receipts_active_job`,`idx_cron_run_receipts_job_history`],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "cron_run_receipts" (
  "cursor_id" bigint NOT NULL,
  "receipt_id" text COLLATE "C" NOT NULL,
  "store_key" text COLLATE "C" NOT NULL,
  "job_id" text COLLATE "C" NOT NULL,
  "config_revision" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "request_run_id" text COLLATE "C",
  "delivery_attempt_state" text COLLATE "C" NOT NULL DEFAULT 'unknown',
  "status" text COLLATE "C" NOT NULL,
  "owner_pid" bigint NOT NULL,
  "owner_start_time" bigint,
  "started_at_ms" bigint NOT NULL,
  "finished_at_ms" bigint,
  "error_text" text COLLATE "C",
  PRIMARY KEY ("receipt_id"),
  CHECK (("delivery_attempt_state" IN ('unknown', 'not-started', 'started'))),
  CHECK (("status" IN ('running', 'ok', 'error', 'skipped', 'interrupted', 'superseded'))),
  CHECK ((("status" = 'running') AND "finished_at_ms" IS NULL) OR (("status" != 'running') AND "finished_at_ms" IS NOT NULL))
);

CREATE UNIQUE INDEX "cron_run_receipts_cursor_id_idx" ON "cron_run_receipts" (("cursor_id") ASC);

CREATE UNIQUE INDEX "idx_cron_run_receipts_active_job" ON "cron_run_receipts" (("store_key") ASC, ("job_id") ASC) WHERE ("status" = 'running');

CREATE INDEX "idx_cron_run_receipts_job_history" ON "cron_run_receipts" (("store_key") ASC, ("job_id") ASC, ("started_at_ms") DESC, ("receipt_id") DESC);
`},{id:`config_revision_keys`,tables:[`config_revision_keys`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "config_revision_keys" (
  "id" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "hmac_key" bytea NOT NULL,
  PRIMARY KEY ("id"),
  CHECK (("id" = 1)),
  CHECK ((octet_length("hmac_key") = 32))
);
`},{id:`secret_store_entries`,tables:[`secret_store_entries`],indexes:[`secret_store_entries_live_idx`],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "secret_store_entries" (
  "scope_kind" text COLLATE "C" NOT NULL,
  "scope_id" text COLLATE "C" NOT NULL,
  "name" text COLLATE "C" NOT NULL,
  "value" text COLLATE "C" NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  "updated_by" text COLLATE "C",
  "deleted_at_ms" bigint,
  "allowed_hosts" text COLLATE "C",
  PRIMARY KEY ("scope_kind", "scope_id", "name"),
  CHECK (("scope_kind" IN ('team', 'identity'))),
  CHECK (("kind" IN ('secret', 'env'))),
  CHECK (("created_at_ms" >= 0)),
  CHECK (("updated_at_ms" >= 0)),
  CHECK ((("scope_kind" = 'team') AND ("scope_id" = '')) OR (("scope_kind" = 'identity') AND (char_length("scope_id") > 0)))
);

CREATE INDEX "secret_store_entries_live_idx" ON "secret_store_entries" (("scope_kind") ASC, ("scope_id") ASC, ("name") ASC) WHERE "deleted_at_ms" IS NULL;
`},{id:`projects`,tables:[`projects`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "projects" (
  "id" text COLLATE "C" NOT NULL,
  "display_name" text COLLATE "C" NOT NULL,
  "repo_root" text COLLATE "C" NOT NULL,
  "origin_url" text COLLATE "C",
  "source" text COLLATE "C" NOT NULL,
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("id"),
  CHECK (("source" IN ('registered', 'cloned')))
);
`},{id:`worktree_templates`,tables:[`worktree_templates`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "worktree_templates" (
  "cache_key" text COLLATE "C" NOT NULL,
  "id" text COLLATE "C" NOT NULL,
  "repo_root" text COLLATE "C" NOT NULL,
  "common_dir" text COLLATE "C" NOT NULL,
  "worktree_root" text COLLATE "C" NOT NULL,
  "path" text COLLATE "C" NOT NULL,
  "backend" text COLLATE "C" NOT NULL,
  "source_commit" text COLLATE "C" NOT NULL,
  "content_key" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  "last_used_at" bigint NOT NULL,
  PRIMARY KEY ("cache_key"),
  CHECK (("status" IN ('preparing', 'ready'))),
  UNIQUE ("id")
);
`},{id:`user_preferences`,tables:[`user_preferences`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "user_preferences" (
  "profile_id" text COLLATE "C" NOT NULL,
  "pref_key" text COLLATE "C" NOT NULL,
  "value_json" text COLLATE "C" NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("profile_id", "pref_key")
);
`},{id:`device_pair_setup_completions`,tables:[`device_pair_setup_completions`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "device_pair_setup_completions" (
  "setup_id" text COLLATE "C" NOT NULL,
  "device_id" text COLLATE "C" NOT NULL,
  "device_name" text COLLATE "C",
  "access" text COLLATE "C" NOT NULL,
  "completed_at_ms" bigint NOT NULL,
  "delivery_state" text COLLATE "C" NOT NULL,
  "retain_until_ms" bigint NOT NULL,
  PRIMARY KEY ("setup_id"),
  CHECK (("delivery_state" IN ('uncertain', 'confirmed')))
);
`},{id:`github_publication_requests`,tables:[`github_publication_requests`],indexes:[`idx_github_publication_requests_pending`],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "github_publication_requests" (
  "request_id" text COLLATE "C" NOT NULL,
  "idempotency_key" text COLLATE "C" NOT NULL,
  "request_digest" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "worktree_id" text COLLATE "C" NOT NULL,
  "repository_fingerprint" text COLLATE "C" NOT NULL,
  "claim_id" text COLLATE "C",
  "run_id" text COLLATE "C",
  "environment_id" text COLLATE "C",
  "owner_epoch" bigint,
  "placement_generation" bigint,
  "identity_source" text COLLATE "C" NOT NULL,
  "identity_profile_id" text COLLATE "C",
  "identity_account_id" bigint NOT NULL,
  "identity_login" text COLLATE "C" NOT NULL,
  "title" text COLLATE "C",
  "body" text COLLATE "C",
  "status" text COLLATE "C" NOT NULL,
  "gateway_instance_id" text COLLATE "C",
  "repository" text COLLATE "C",
  "branch" text COLLATE "C" NOT NULL,
  "base_branch" text COLLATE "C",
  "source_head_commit" text COLLATE "C",
  "source_index_tree" text COLLATE "C",
  "workspace_tree" text COLLATE "C",
  "head_commit" text COLLATE "C",
  "pull_request_url" text COLLATE "C",
  "error_code" text COLLATE "C",
  "next_action" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  "reported_at_ms" bigint,
  "draft" bigint,
  PRIMARY KEY ("request_id"),
  CHECK ("owner_epoch" IS NULL OR ("owner_epoch" >= 1)),
  CHECK ("placement_generation" IS NULL OR ("placement_generation" >= 0)),
  CHECK (("identity_source" IN ('system-detected', 'system-configured', 'agent-override'))),
  CHECK (("identity_account_id" >= 1)),
  CHECK (("status" IN ('requested', 'publishing', 'published', 'failed'))),
  CHECK (("claim_id" IS NULL AND "run_id" IS NULL AND "environment_id" IS NULL AND "owner_epoch" IS NULL AND "placement_generation" IS NULL) OR ("claim_id" IS NOT NULL AND "run_id" IS NOT NULL AND "placement_generation" IS NOT NULL AND (("environment_id" IS NULL AND "owner_epoch" IS NULL) OR ("environment_id" IS NOT NULL AND "owner_epoch" IS NOT NULL)))),
  CHECK (("identity_source" IS NOT DISTINCT FROM 'system-detected' AND "identity_profile_id" IS NULL) OR (("identity_source" IN ('system-configured', 'agent-override')) AND "identity_profile_id" IS NOT NULL)),
  CHECK (("source_head_commit" IS NULL AND "source_index_tree" IS NULL AND "workspace_tree" IS NULL) OR ("source_head_commit" IS NOT NULL AND "workspace_tree" IS NOT NULL)),
  CHECK (("status" IS NOT DISTINCT FROM 'published' AND "pull_request_url" IS NOT NULL AND "error_code" IS NULL AND "next_action" IS NULL) OR ("status" IS NOT DISTINCT FROM 'failed' AND "pull_request_url" IS NULL AND "error_code" IS NOT NULL AND "next_action" IS NOT NULL) OR (("status" IN ('requested', 'publishing')) AND "pull_request_url" IS NULL AND "error_code" IS NULL AND "next_action" IS NULL)),
  UNIQUE ("session_id", "idempotency_key")
);

CREATE INDEX "idx_github_publication_requests_pending" ON "github_publication_requests" (("status") ASC, ("updated_at_ms") ASC, ("request_id") ASC);
`},{id:`device_pairing_join_codes`,tables:[`device_pairing_join_codes`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "device_pairing_join_codes" (
  "shortcode" text COLLATE "C",
  "payload_json" text COLLATE "C",
  "created_at_ms" bigint,
  "expires_at_ms" bigint
);
`},{id:`device_pairing_browser_requests`,tables:[`device_pairing_browser_requests`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "device_pairing_browser_requests" (
  "request_id" text COLLATE "C" NOT NULL,
  "code" text COLLATE "C" NOT NULL,
  "device_id" text COLLATE "C" NOT NULL,
  "public_key" text COLLATE "C" NOT NULL,
  "remote_ip" text COLLATE "C",
  "user_agent" text COLLATE "C",
  "origin" text COLLATE "C",
  "status" text COLLATE "C" NOT NULL,
  "approved_token_sha256" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "expires_at_ms" bigint NOT NULL,
  PRIMARY KEY ("request_id"),
  CHECK (("status" IN ('pending', 'approved', 'rejected'))),
  UNIQUE ("code"),
  UNIQUE ("device_id")
);
`},{id:`skill_workshop_changes`,tables:[`skill_workshop_changes`],indexes:[`skill_workshop_changes_cursor_id_idx`,`idx_skill_workshop_changes_agent_time`],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "skill_workshop_changes" (
  "cursor_id" bigint NOT NULL,
  "change_id" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "skill_name" text COLLATE "C" NOT NULL,
  "action" text COLLATE "C" NOT NULL,
  "actor" text COLLATE "C" NOT NULL,
  "summary" text COLLATE "C" NOT NULL,
  "version_id" text COLLATE "C",
  "session_key" text COLLATE "C",
  "run_id" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  PRIMARY KEY ("change_id"),
  CHECK (("action" IN ('create', 'patch', 'write_file', 'remove_file', 'archive', 'restore'))),
  CHECK (("actor" IN ('agent', 'review', 'curator', 'user')))
);

CREATE INDEX "idx_skill_workshop_changes_agent_time" ON "skill_workshop_changes" (("agent_id") ASC, ("created_at_ms") ASC);

CREATE UNIQUE INDEX "skill_workshop_changes_cursor_id_idx" ON "skill_workshop_changes" (("cursor_id") ASC);
`},{id:`worker_environment_ssh_fallback_ports`,tables:[`worker_environment_ssh_fallback_ports`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "worker_environment_ssh_fallback_ports" (
  "environment_id" text COLLATE "C" NOT NULL,
  "position" bigint NOT NULL,
  "port" bigint NOT NULL,
  PRIMARY KEY ("environment_id", "position"),
  CHECK (("position" >= 0) AND ("position" <= 9)),
  CHECK (("port" >= 1) AND ("port" <= 65535)),
  UNIQUE ("environment_id", "port")
);

ALTER TABLE "worker_environment_ssh_fallback_ports" ADD FOREIGN KEY ("environment_id") REFERENCES "worker_environments" ("environment_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`worker_session_placement_moves`,tables:[`worker_session_placement_moves`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "worker_session_placement_moves" (
  "operation_id" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "source_generation" bigint NOT NULL,
  "source_environment_id" text COLLATE "C" NOT NULL,
  "source_owner_epoch" bigint NOT NULL,
  "target_kind" text COLLATE "C" NOT NULL,
  "target_id" text COLLATE "C",
  "target_machine_class" text COLLATE "C",
  "target_os" text COLLATE "C",
  "abandon_source" bigint,
  "last_error" text COLLATE "C",
  "created_at_ms" bigint NOT NULL,
  "updated_at_ms" bigint NOT NULL,
  PRIMARY KEY ("operation_id"),
  CHECK (("source_generation" >= 0)),
  CHECK ((char_length("source_environment_id") BETWEEN 1 AND 256) AND ("source_environment_id" = btrim("source_environment_id"))),
  CHECK (("source_owner_epoch" >= 1)),
  CHECK (("target_kind" IN ('gateway', 'profile', 'device'))),
  CHECK (("target_kind" IS NOT DISTINCT FROM 'gateway' AND "target_id" IS NULL) OR (("target_kind" IN ('profile', 'device')) AND "target_id" IS NOT NULL AND (char_length("target_id") BETWEEN 1 AND 256) AND ("target_id" = btrim("target_id")))),
  UNIQUE ("session_id")
);

ALTER TABLE "worker_session_placement_moves" ADD FOREIGN KEY ("session_id") REFERENCES "worker_session_placements" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;
`},{id:`agent_deletion_journal`,tables:[`agent_deletion_journal`],indexes:[],dependencies:[],activation:`version-additive`,sql:`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE TABLE "agent_deletion_journal" (
  "agent_id" text COLLATE "C" NOT NULL,
  "operation_id" text COLLATE "C" NOT NULL DEFAULT '',
  "phase" text COLLATE "C",
  "agent_dir" text COLLATE "C" NOT NULL,
  "workspace_dir" text COLLATE "C" NOT NULL,
  "sessions_dir" text COLLATE "C" NOT NULL,
  "database_paths_json" text COLLATE "C" NOT NULL DEFAULT '[]',
  "cleanup_paths_json" text COLLATE "C" NOT NULL DEFAULT '[]',
  "created_at" bigint NOT NULL,
  "cleanup_completed" bigint NOT NULL DEFAULT 0,
  "delete_files" bigint NOT NULL DEFAULT 1,
  PRIMARY KEY ("agent_id")
);
`}];return Object.defineProperty(this,"fragments",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get expectedCatalog(){let e=[{table:`acp_replay_events`,kind:`table`,value:null},{table:`acp_replay_events`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`acp_replay_events`,kind:`column`,value:{name:`seq`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`acp_replay_events`,kind:`column`,value:{name:`at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`acp_replay_events`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`acp_replay_events`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`acp_replay_events`,kind:`column`,value:{name:`update_json`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`acp_replay_events`,kind:`column`,value:{name:`estimated_bytes`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:7}},{table:`acp_replay_events`,kind:`primaryKey`,value:[`session_id`,`seq`]},{table:`acp_replay_events`,kind:`foreignKey`,value:{columns:[`session_id`],target:`acp_replay_sessions`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`acp_replay_events`,kind:`indexes`,value:1},{table:`acp_replay_events`,kind:`checks`,value:0},{table:`acp_replay_sessions`,kind:`table`,value:null},{table:`acp_replay_sessions`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`acp_replay_sessions`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`acp_replay_sessions`,kind:`column`,value:{name:`cwd`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`acp_replay_sessions`,kind:`column`,value:{name:`complete`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`acp_replay_sessions`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`acp_replay_sessions`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`acp_replay_sessions`,kind:`column`,value:{name:`next_seq`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`acp_replay_sessions`,kind:`column`,value:{name:`estimated_bytes`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:8}},{table:`acp_replay_sessions`,kind:`primaryKey`,value:[`session_id`]},{table:`acp_replay_sessions`,kind:`indexes`,value:3},{table:`acp_replay_sessions`,kind:`checks`,value:0},{table:`acp_sessions`,kind:`table`,value:null},{table:`acp_sessions`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`acp_sessions`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`acp_sessions`,kind:`column`,value:{name:`backend`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`acp_sessions`,kind:`column`,value:{name:`agent`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`acp_sessions`,kind:`column`,value:{name:`runtime_session_name`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`acp_sessions`,kind:`column`,value:{name:`identity_json`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`acp_sessions`,kind:`column`,value:{name:`resume_agent_session_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`acp_sessions`,kind:`column`,value:{name:`resume_acpx_session_id`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`acp_sessions`,kind:`column`,value:{name:`mode`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`acp_sessions`,kind:`column`,value:{name:`runtime_options_json`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`acp_sessions`,kind:`column`,value:{name:`cwd`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`acp_sessions`,kind:`column`,value:{name:`state`,type:`text`,nullable:!1,identity:!1,default:null,position:12}},{table:`acp_sessions`,kind:`column`,value:{name:`last_activity_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:13}},{table:`acp_sessions`,kind:`column`,value:{name:`last_error`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`acp_sessions`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:15}},{table:`acp_sessions`,kind:`primaryKey`,value:[`session_key`]},{table:`acp_sessions`,kind:`indexes`,value:5},{table:`acp_sessions`,kind:`checks`,value:0},{table:`agent_database_leases`,kind:`table`,value:null},{table:`agent_database_leases`,kind:`column`,value:{name:`lease_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`agent_database_leases`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`agent_database_leases`,kind:`column`,value:{name:`path`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`agent_database_leases`,kind:`column`,value:{name:`owner_pid`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`agent_database_leases`,kind:`column`,value:{name:`owner_start_time`,type:`bigint`,nullable:!0,identity:!1,default:null,position:5}},{table:`agent_database_leases`,kind:`column`,value:{name:`opened_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`agent_database_leases`,kind:`column`,value:{name:`provenance`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`agent_database_leases`,kind:`primaryKey`,value:[`lease_id`]},{table:`agent_database_leases`,kind:`indexes`,value:1},{table:`agent_database_leases`,kind:`checks`,value:0},{table:`agent_databases`,kind:`table`,value:null},{table:`agent_databases`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`agent_databases`,kind:`column`,value:{name:`path`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`agent_databases`,kind:`column`,value:{name:`schema_version`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`agent_databases`,kind:`column`,value:{name:`last_seen_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`agent_databases`,kind:`column`,value:{name:`size_bytes`,type:`bigint`,nullable:!0,identity:!1,default:null,position:5}},{table:`agent_databases`,kind:`primaryKey`,value:[`agent_id`,`path`]},{table:`agent_databases`,kind:`indexes`,value:1},{table:`agent_databases`,kind:`checks`,value:0},{table:`agent_deletion_journal`,kind:`table`,value:null},{table:`agent_deletion_journal`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`agent_deletion_journal`,kind:`column`,value:{name:`operation_id`,type:`text`,nullable:!1,identity:!1,default:`''`,position:2}},{table:`agent_deletion_journal`,kind:`column`,value:{name:`phase`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`agent_deletion_journal`,kind:`column`,value:{name:`agent_dir`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`agent_deletion_journal`,kind:`column`,value:{name:`workspace_dir`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`agent_deletion_journal`,kind:`column`,value:{name:`sessions_dir`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`agent_deletion_journal`,kind:`column`,value:{name:`database_paths_json`,type:`text`,nullable:!1,identity:!1,default:`'[]'`,position:7}},{table:`agent_deletion_journal`,kind:`column`,value:{name:`cleanup_paths_json`,type:`text`,nullable:!1,identity:!1,default:`'[]'`,position:8}},{table:`agent_deletion_journal`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`agent_deletion_journal`,kind:`column`,value:{name:`cleanup_completed`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:10}},{table:`agent_deletion_journal`,kind:`column`,value:{name:`delete_files`,type:`bigint`,nullable:!1,identity:!1,default:`1`,position:11}},{table:`agent_deletion_journal`,kind:`primaryKey`,value:[`agent_id`]},{table:`agent_deletion_journal`,kind:`indexes`,value:1},{table:`agent_deletion_journal`,kind:`checks`,value:0},{table:`agent_provenance`,kind:`table`,value:null},{table:`agent_provenance`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`agent_provenance`,kind:`column`,value:{name:`created_via`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`agent_provenance`,kind:`column`,value:{name:`creator_agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`agent_provenance`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`agent_provenance`,kind:`primaryKey`,value:[`agent_id`]},{table:`agent_provenance`,kind:`indexes`,value:1},{table:`agent_provenance`,kind:`checks`,value:1},{table:`apns_registration_tombstones`,kind:`table`,value:null},{table:`apns_registration_tombstones`,kind:`column`,value:{name:`node_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`apns_registration_tombstones`,kind:`column`,value:{name:`deleted_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`apns_registration_tombstones`,kind:`primaryKey`,value:[`node_id`]},{table:`apns_registration_tombstones`,kind:`indexes`,value:1},{table:`apns_registration_tombstones`,kind:`checks`,value:0},{table:`apns_registrations`,kind:`table`,value:null},{table:`apns_registrations`,kind:`column`,value:{name:`node_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`apns_registrations`,kind:`column`,value:{name:`transport`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`apns_registrations`,kind:`column`,value:{name:`token`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`apns_registrations`,kind:`column`,value:{name:`relay_handle`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`apns_registrations`,kind:`column`,value:{name:`send_grant`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`apns_registrations`,kind:`column`,value:{name:`installation_id`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`apns_registrations`,kind:`column`,value:{name:`relay_origin`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`apns_registrations`,kind:`column`,value:{name:`topic`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`apns_registrations`,kind:`column`,value:{name:`environment`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`apns_registrations`,kind:`column`,value:{name:`distribution`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`apns_registrations`,kind:`column`,value:{name:`token_debug_suffix`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`apns_registrations`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`apns_registrations`,kind:`primaryKey`,value:[`node_id`]},{table:`apns_registrations`,kind:`indexes`,value:2},{table:`apns_registrations`,kind:`checks`,value:0},{table:`audit_events`,kind:`table`,value:null},{table:`audit_events`,kind:`column`,value:{name:`sequence`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`audit_events`,kind:`column`,value:{name:`event_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`audit_events`,kind:`column`,value:{name:`source_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`audit_events`,kind:`column`,value:{name:`schema_version`,type:`bigint`,nullable:!1,identity:!1,default:`1`,position:4}},{table:`audit_events`,kind:`column`,value:{name:`source_sequence`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`audit_events`,kind:`column`,value:{name:`occurred_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`audit_events`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`audit_events`,kind:`column`,value:{name:`action`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`audit_events`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`audit_events`,kind:`column`,value:{name:`error_code`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`audit_events`,kind:`column`,value:{name:`actor_type`,type:`text`,nullable:!1,identity:!1,default:null,position:11}},{table:`audit_events`,kind:`column`,value:{name:`actor_id`,type:`text`,nullable:!1,identity:!1,default:null,position:12}},{table:`audit_events`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`audit_events`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`audit_events`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`audit_events`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`audit_events`,kind:`column`,value:{name:`tool_call_id`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`audit_events`,kind:`column`,value:{name:`tool_name`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`audit_events`,kind:`column`,value:{name:`direction`,type:`text`,nullable:!0,identity:!1,default:null,position:19}},{table:`audit_events`,kind:`column`,value:{name:`channel`,type:`text`,nullable:!0,identity:!1,default:null,position:20}},{table:`audit_events`,kind:`column`,value:{name:`conversation_kind`,type:`text`,nullable:!0,identity:!1,default:null,position:21}},{table:`audit_events`,kind:`column`,value:{name:`message_outcome`,type:`text`,nullable:!0,identity:!1,default:null,position:22}},{table:`audit_events`,kind:`column`,value:{name:`reason_code`,type:`text`,nullable:!0,identity:!1,default:null,position:23}},{table:`audit_events`,kind:`column`,value:{name:`delivery_kind`,type:`text`,nullable:!0,identity:!1,default:null,position:24}},{table:`audit_events`,kind:`column`,value:{name:`failure_stage`,type:`text`,nullable:!0,identity:!1,default:null,position:25}},{table:`audit_events`,kind:`column`,value:{name:`duration_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:26}},{table:`audit_events`,kind:`column`,value:{name:`result_count`,type:`bigint`,nullable:!0,identity:!1,default:null,position:27}},{table:`audit_events`,kind:`column`,value:{name:`account_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:28}},{table:`audit_events`,kind:`column`,value:{name:`conversation_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:29}},{table:`audit_events`,kind:`column`,value:{name:`message_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:30}},{table:`audit_events`,kind:`column`,value:{name:`target_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:31}},{table:`audit_events`,kind:`primaryKey`,value:[`sequence`]},{table:`audit_events`,kind:`unique`,value:[`event_id`]},{table:`audit_events`,kind:`unique`,value:[`source_id`]},{table:`audit_events`,kind:`indexes`,value:11},{table:`audit_events`,kind:`checks`,value:0},{table:`audit_identity_keys`,kind:`table`,value:null},{table:`audit_identity_keys`,kind:`column`,value:{name:`id`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`audit_identity_keys`,kind:`column`,value:{name:`key_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`audit_identity_keys`,kind:`column`,value:{name:`key`,type:`bytea`,nullable:!1,identity:!1,default:null,position:3}},{table:`audit_identity_keys`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`audit_identity_keys`,kind:`primaryKey`,value:[`id`]},{table:`audit_identity_keys`,kind:`indexes`,value:1},{table:`audit_identity_keys`,kind:`checks`,value:1},{table:`backup_runs`,kind:`table`,value:null},{table:`backup_runs`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`backup_runs`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`backup_runs`,kind:`column`,value:{name:`archive_path`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`backup_runs`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`backup_runs`,kind:`column`,value:{name:`manifest_json`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`backup_runs`,kind:`primaryKey`,value:[`id`]},{table:`backup_runs`,kind:`indexes`,value:2},{table:`backup_runs`,kind:`checks`,value:0},{table:`capture_blobs`,kind:`table`,value:null},{table:`capture_blobs`,kind:`column`,value:{name:`blob_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`capture_blobs`,kind:`column`,value:{name:`content_type`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`capture_blobs`,kind:`column`,value:{name:`encoding`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`capture_blobs`,kind:`column`,value:{name:`size_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`capture_blobs`,kind:`column`,value:{name:`sha256`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`capture_blobs`,kind:`column`,value:{name:`data`,type:`bytea`,nullable:!1,identity:!1,default:null,position:6}},{table:`capture_blobs`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`capture_blobs`,kind:`primaryKey`,value:[`blob_id`]},{table:`capture_blobs`,kind:`indexes`,value:1},{table:`capture_blobs`,kind:`checks`,value:0},{table:`capture_events`,kind:`table`,value:null},{table:`capture_events`,kind:`column`,value:{name:`id`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`capture_events`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`capture_events`,kind:`column`,value:{name:`ts`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`capture_events`,kind:`column`,value:{name:`source_scope`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`capture_events`,kind:`column`,value:{name:`source_process`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`capture_events`,kind:`column`,value:{name:`protocol`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`capture_events`,kind:`column`,value:{name:`direction`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`capture_events`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`capture_events`,kind:`column`,value:{name:`flow_id`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`capture_events`,kind:`column`,value:{name:`method`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`capture_events`,kind:`column`,value:{name:`host`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`capture_events`,kind:`column`,value:{name:`path`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`capture_events`,kind:`column`,value:{name:`status`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`capture_events`,kind:`column`,value:{name:`close_code`,type:`bigint`,nullable:!0,identity:!1,default:null,position:14}},{table:`capture_events`,kind:`column`,value:{name:`content_type`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`capture_events`,kind:`column`,value:{name:`headers_json`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`capture_events`,kind:`column`,value:{name:`data_text`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`capture_events`,kind:`column`,value:{name:`data_blob_id`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`capture_events`,kind:`column`,value:{name:`data_sha256`,type:`text`,nullable:!0,identity:!1,default:null,position:19}},{table:`capture_events`,kind:`column`,value:{name:`error_text`,type:`text`,nullable:!0,identity:!1,default:null,position:20}},{table:`capture_events`,kind:`column`,value:{name:`meta_json`,type:`text`,nullable:!0,identity:!1,default:null,position:21}},{table:`capture_events`,kind:`primaryKey`,value:[`id`]},{table:`capture_events`,kind:`foreignKey`,value:{columns:[`data_blob_id`],target:`capture_blobs`,targetColumns:[`blob_id`],onUpdate:`NO ACTION`,onDelete:`SET NULL`,deferrable:!1,deferred:!1}},{table:`capture_events`,kind:`foreignKey`,value:{columns:[`session_id`],target:`capture_sessions`,targetColumns:[`id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`capture_events`,kind:`indexes`,value:3},{table:`capture_events`,kind:`checks`,value:0},{table:`capture_sessions`,kind:`table`,value:null},{table:`capture_sessions`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`capture_sessions`,kind:`column`,value:{name:`started_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`capture_sessions`,kind:`column`,value:{name:`ended_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:3}},{table:`capture_sessions`,kind:`column`,value:{name:`mode`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`capture_sessions`,kind:`column`,value:{name:`source_scope`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`capture_sessions`,kind:`column`,value:{name:`source_process`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`capture_sessions`,kind:`column`,value:{name:`proxy_url`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`capture_sessions`,kind:`primaryKey`,value:[`id`]},{table:`capture_sessions`,kind:`indexes`,value:1},{table:`capture_sessions`,kind:`checks`,value:0},{table:`channel_ingress_events`,kind:`table`,value:null},{table:`channel_ingress_events`,kind:`column`,value:{name:`queue_name`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`channel_ingress_events`,kind:`column`,value:{name:`event_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`channel_ingress_events`,kind:`column`,value:{name:`channel_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`channel_ingress_events`,kind:`column`,value:{name:`account_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`channel_ingress_events`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`channel_ingress_events`,kind:`column`,value:{name:`lane_key`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`channel_ingress_events`,kind:`column`,value:{name:`payload_json`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`channel_ingress_events`,kind:`column`,value:{name:`metadata_json`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`channel_ingress_events`,kind:`column`,value:{name:`received_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`channel_ingress_events`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`channel_ingress_events`,kind:`column`,value:{name:`claim_token`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`channel_ingress_events`,kind:`column`,value:{name:`claim_owner`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`channel_ingress_events`,kind:`column`,value:{name:`claimed_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`channel_ingress_events`,kind:`column`,value:{name:`attempts`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:14}},{table:`channel_ingress_events`,kind:`column`,value:{name:`last_attempt_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:15}},{table:`channel_ingress_events`,kind:`column`,value:{name:`last_error`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`channel_ingress_events`,kind:`column`,value:{name:`failed_reason`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`channel_ingress_events`,kind:`column`,value:{name:`failed_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:18}},{table:`channel_ingress_events`,kind:`column`,value:{name:`completed_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:19}},{table:`channel_ingress_events`,kind:`column`,value:{name:`completed_metadata_json`,type:`text`,nullable:!0,identity:!1,default:null,position:20}},{table:`channel_ingress_events`,kind:`primaryKey`,value:[`queue_name`,`event_id`]},{table:`channel_ingress_events`,kind:`indexes`,value:4},{table:`channel_ingress_events`,kind:`checks`,value:0},{table:`channel_pairing_allow_entries`,kind:`table`,value:null},{table:`channel_pairing_allow_entries`,kind:`column`,value:{name:`channel_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`channel_pairing_allow_entries`,kind:`column`,value:{name:`account_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`channel_pairing_allow_entries`,kind:`column`,value:{name:`entry`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`channel_pairing_allow_entries`,kind:`column`,value:{name:`sort_order`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`channel_pairing_allow_entries`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`channel_pairing_allow_entries`,kind:`primaryKey`,value:[`channel_key`,`account_id`,`entry`]},{table:`channel_pairing_allow_entries`,kind:`indexes`,value:2},{table:`channel_pairing_allow_entries`,kind:`checks`,value:0},{table:`channel_pairing_requests`,kind:`table`,value:null},{table:`channel_pairing_requests`,kind:`column`,value:{name:`channel_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`channel_pairing_requests`,kind:`column`,value:{name:`account_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`channel_pairing_requests`,kind:`column`,value:{name:`request_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`channel_pairing_requests`,kind:`column`,value:{name:`code`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`channel_pairing_requests`,kind:`column`,value:{name:`created_at`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`channel_pairing_requests`,kind:`column`,value:{name:`last_seen_at`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`channel_pairing_requests`,kind:`column`,value:{name:`meta_json`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`channel_pairing_requests`,kind:`primaryKey`,value:[`channel_key`,`account_id`,`request_id`]},{table:`channel_pairing_requests`,kind:`indexes`,value:3},{table:`channel_pairing_requests`,kind:`checks`,value:0},{table:`clawhub_promotion_claims`,kind:`table`,value:null},{table:`clawhub_promotion_claims`,kind:`column`,value:{name:`slug`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`clawhub_promotion_claims`,kind:`column`,value:{name:`provider`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`clawhub_promotion_claims`,kind:`column`,value:{name:`model_keys_json`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`clawhub_promotion_claims`,kind:`column`,value:{name:`ends_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`clawhub_promotion_claims`,kind:`column`,value:{name:`claimed_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`clawhub_promotion_claims`,kind:`primaryKey`,value:[`slug`]},{table:`clawhub_promotion_claims`,kind:`indexes`,value:1},{table:`clawhub_promotion_claims`,kind:`checks`,value:0},{table:`config_health_entries`,kind:`table`,value:null},{table:`config_health_entries`,kind:`column`,value:{name:`config_path`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`config_health_entries`,kind:`column`,value:{name:`last_known_good_json`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`config_health_entries`,kind:`column`,value:{name:`last_promoted_good_json`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`config_health_entries`,kind:`column`,value:{name:`last_observed_suspicious_signature`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`config_health_entries`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`config_health_entries`,kind:`primaryKey`,value:[`config_path`]},{table:`config_health_entries`,kind:`indexes`,value:1},{table:`config_health_entries`,kind:`checks`,value:0},{table:`config_machine_state`,kind:`table`,value:null},{table:`config_machine_state`,kind:`column`,value:{name:`state_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`config_machine_state`,kind:`column`,value:{name:`value_json`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`config_machine_state`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`config_machine_state`,kind:`primaryKey`,value:[`state_key`]},{table:`config_machine_state`,kind:`indexes`,value:1},{table:`config_machine_state`,kind:`checks`,value:0},{table:`config_revision_keys`,kind:`table`,value:null},{table:`config_revision_keys`,kind:`column`,value:{name:`id`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`config_revision_keys`,kind:`column`,value:{name:`hmac_key`,type:`bytea`,nullable:!1,identity:!1,default:null,position:2}},{table:`config_revision_keys`,kind:`primaryKey`,value:[`id`]},{table:`config_revision_keys`,kind:`indexes`,value:1},{table:`config_revision_keys`,kind:`checks`,value:2},{table:`cron_job_runtime_authorities`,kind:`table`,value:null},{table:`cron_job_runtime_authorities`,kind:`column`,value:{name:`store_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`cron_job_runtime_authorities`,kind:`column`,value:{name:`job_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`cron_job_runtime_authorities`,kind:`column`,value:{name:`authority_json`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`cron_job_runtime_authorities`,kind:`column`,value:{name:`authority_input_fingerprint`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`cron_job_runtime_authorities`,kind:`column`,value:{name:`recovery_required`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`cron_job_runtime_authorities`,kind:`primaryKey`,value:[`store_key`,`job_id`]},{table:`cron_job_runtime_authorities`,kind:`foreignKey`,value:{columns:[`store_key`,`job_id`],target:`cron_jobs`,targetColumns:[`store_key`,`job_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`cron_job_runtime_authorities`,kind:`indexes`,value:1},{table:`cron_job_runtime_authorities`,kind:`checks`,value:2},{table:`cron_job_scratch`,kind:`table`,value:null},{table:`cron_job_scratch`,kind:`column`,value:{name:`store_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`cron_job_scratch`,kind:`column`,value:{name:`job_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`cron_job_scratch`,kind:`column`,value:{name:`content`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`cron_job_scratch`,kind:`column`,value:{name:`revision`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`cron_job_scratch`,kind:`column`,value:{name:`source_sha256`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`cron_job_scratch`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`cron_job_scratch`,kind:`primaryKey`,value:[`store_key`,`job_id`]},{table:`cron_job_scratch`,kind:`indexes`,value:2},{table:`cron_job_scratch`,kind:`checks`,value:2},{table:`cron_jobs`,kind:`table`,value:null},{table:`cron_jobs`,kind:`column`,value:{name:`store_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`cron_jobs`,kind:`column`,value:{name:`job_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`cron_jobs`,kind:`column`,value:{name:`declaration_key`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`cron_jobs`,kind:`column`,value:{name:`owner_agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`cron_jobs`,kind:`column`,value:{name:`name`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`cron_jobs`,kind:`column`,value:{name:`description`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`cron_jobs`,kind:`column`,value:{name:`enabled`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`cron_jobs`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`cron_jobs`,kind:`column`,value:{name:`payload_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`cron_jobs`,kind:`column`,value:{name:`job_json`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`cron_jobs`,kind:`column`,value:{name:`grant_definition_revision`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`cron_jobs`,kind:`column`,value:{name:`grant_definition_generation`,type:`bigint`,nullable:!0,identity:!1,default:null,position:12}},{table:`cron_jobs`,kind:`column`,value:{name:`grant_definition_updated_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`cron_jobs`,kind:`column`,value:{name:`state_json`,type:`text`,nullable:!1,identity:!1,default:`'{}'`,position:14}},{table:`cron_jobs`,kind:`column`,value:{name:`runtime_updated_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:15}},{table:`cron_jobs`,kind:`column`,value:{name:`schedule_identity`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`cron_jobs`,kind:`column`,value:{name:`sort_order`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:17}},{table:`cron_jobs`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:18}},{table:`cron_jobs`,kind:`primaryKey`,value:[`store_key`,`job_id`]},{table:`cron_jobs`,kind:`indexes`,value:2},{table:`cron_jobs`,kind:`checks`,value:0},{table:`cron_run_receipts`,kind:`table`,value:null},{table:`cron_run_receipts`,kind:`column`,value:{name:`cursor_id`,type:`bigint`,nullable:!1,identity:!1,default:null,position:1}},{table:`cron_run_receipts`,kind:`column`,value:{name:`receipt_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`cron_run_receipts`,kind:`column`,value:{name:`store_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`cron_run_receipts`,kind:`column`,value:{name:`job_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`cron_run_receipts`,kind:`column`,value:{name:`config_revision`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`cron_run_receipts`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`cron_run_receipts`,kind:`column`,value:{name:`request_run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`cron_run_receipts`,kind:`column`,value:{name:`delivery_attempt_state`,type:`text`,nullable:!1,identity:!1,default:`'unknown'`,position:8}},{table:`cron_run_receipts`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`cron_run_receipts`,kind:`column`,value:{name:`owner_pid`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`cron_run_receipts`,kind:`column`,value:{name:`owner_start_time`,type:`bigint`,nullable:!0,identity:!1,default:null,position:11}},{table:`cron_run_receipts`,kind:`column`,value:{name:`started_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`cron_run_receipts`,kind:`column`,value:{name:`finished_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`cron_run_receipts`,kind:`column`,value:{name:`error_text`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`cron_run_receipts`,kind:`primaryKey`,value:[`receipt_id`]},{table:`cron_run_receipts`,kind:`indexes`,value:4},{table:`cron_run_receipts`,kind:`checks`,value:3},{table:`cron_run_trigger_state_retirements`,kind:`table`,value:null},{table:`cron_run_trigger_state_retirements`,kind:`column`,value:{name:`receipt_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`cron_run_trigger_state_retirements`,kind:`primaryKey`,value:[`receipt_id`]},{table:`cron_run_trigger_state_retirements`,kind:`foreignKey`,value:{columns:[`receipt_id`],target:`cron_run_receipts`,targetColumns:[`receipt_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`cron_run_trigger_state_retirements`,kind:`indexes`,value:1},{table:`cron_run_trigger_state_retirements`,kind:`checks`,value:0},{table:`current_conversation_bindings`,kind:`table`,value:null},{table:`current_conversation_bindings`,kind:`column`,value:{name:`binding_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`binding_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`target_session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`channel`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`account_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`conversation_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`parent_conversation_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`conversation_id`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`target_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`bound_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`expires_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:12}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`metadata_json`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`record_json`,type:`text`,nullable:!1,identity:!1,default:null,position:14}},{table:`current_conversation_bindings`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:15}},{table:`current_conversation_bindings`,kind:`primaryKey`,value:[`binding_key`]},{table:`current_conversation_bindings`,kind:`indexes`,value:4},{table:`current_conversation_bindings`,kind:`checks`,value:0},{table:`delivery_queue_entries`,kind:`table`,value:null},{table:`delivery_queue_entries`,kind:`column`,value:{name:`queue_name`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`entry_kind`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`channel`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`target`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`account_id`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`retry_count`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:9}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`last_attempt_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:10}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`last_error`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`recovery_state`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`platform_send_started_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`entry_json`,type:`text`,nullable:!1,identity:!1,default:null,position:14}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`retention_id_prefix`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`retention_max_age_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:16}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`retention_max_entries`,type:`bigint`,nullable:!0,identity:!1,default:null,position:17}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`enqueued_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:18}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:19}},{table:`delivery_queue_entries`,kind:`column`,value:{name:`failed_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:20}},{table:`delivery_queue_entries`,kind:`primaryKey`,value:[`queue_name`,`id`]},{table:`delivery_queue_entries`,kind:`indexes`,value:6},{table:`delivery_queue_entries`,kind:`checks`,value:0},{table:`device_bootstrap_tokens`,kind:`table`,value:null},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`token_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`token`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`setup_id`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`ts`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`device_id`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`public_key`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`profile_json`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`redeemed_profile_json`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`pending_profile_json`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`issued_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`device_bootstrap_tokens`,kind:`column`,value:{name:`last_used_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:11}},{table:`device_bootstrap_tokens`,kind:`primaryKey`,value:[`token_key`]},{table:`device_bootstrap_tokens`,kind:`indexes`,value:2},{table:`device_bootstrap_tokens`,kind:`checks`,value:0},{table:`device_pair_setup_completions`,kind:`table`,value:null},{table:`device_pair_setup_completions`,kind:`column`,value:{name:`setup_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`device_pair_setup_completions`,kind:`column`,value:{name:`device_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`device_pair_setup_completions`,kind:`column`,value:{name:`device_name`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`device_pair_setup_completions`,kind:`column`,value:{name:`access`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`device_pair_setup_completions`,kind:`column`,value:{name:`completed_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`device_pair_setup_completions`,kind:`column`,value:{name:`delivery_state`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`device_pair_setup_completions`,kind:`column`,value:{name:`retain_until_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`device_pair_setup_completions`,kind:`primaryKey`,value:[`setup_id`]},{table:`device_pair_setup_completions`,kind:`indexes`,value:1},{table:`device_pair_setup_completions`,kind:`checks`,value:1},{table:`device_pairing_browser_requests`,kind:`table`,value:null},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`request_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`code`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`device_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`public_key`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`remote_ip`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`user_agent`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`origin`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`approved_token_sha256`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`device_pairing_browser_requests`,kind:`column`,value:{name:`expires_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`device_pairing_browser_requests`,kind:`primaryKey`,value:[`request_id`]},{table:`device_pairing_browser_requests`,kind:`unique`,value:[`code`]},{table:`device_pairing_browser_requests`,kind:`unique`,value:[`device_id`]},{table:`device_pairing_browser_requests`,kind:`indexes`,value:3},{table:`device_pairing_browser_requests`,kind:`checks`,value:1},{table:`device_pairing_join_codes`,kind:`table`,value:null},{table:`device_pairing_join_codes`,kind:`column`,value:{name:`shortcode`,type:`text`,nullable:!0,identity:!1,default:null,position:1}},{table:`device_pairing_join_codes`,kind:`column`,value:{name:`payload_json`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`device_pairing_join_codes`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:3}},{table:`device_pairing_join_codes`,kind:`column`,value:{name:`expires_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:4}},{table:`device_pairing_join_codes`,kind:`indexes`,value:0},{table:`device_pairing_join_codes`,kind:`checks`,value:0},{table:`device_pairing_paired`,kind:`table`,value:null},{table:`device_pairing_paired`,kind:`column`,value:{name:`device_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`device_pairing_paired`,kind:`column`,value:{name:`public_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`device_pairing_paired`,kind:`column`,value:{name:`display_name`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`device_pairing_paired`,kind:`column`,value:{name:`operator_label`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`device_pairing_paired`,kind:`column`,value:{name:`platform`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`device_pairing_paired`,kind:`column`,value:{name:`device_family`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`device_pairing_paired`,kind:`column`,value:{name:`client_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`device_pairing_paired`,kind:`column`,value:{name:`client_mode`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`device_pairing_paired`,kind:`column`,value:{name:`browser_origin`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`device_pairing_paired`,kind:`column`,value:{name:`role`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`device_pairing_paired`,kind:`column`,value:{name:`roles_json`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`device_pairing_paired`,kind:`column`,value:{name:`scopes_json`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`device_pairing_paired`,kind:`column`,value:{name:`approved_scopes_json`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`device_pairing_paired`,kind:`column`,value:{name:`remote_ip`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`device_pairing_paired`,kind:`column`,value:{name:`tokens_json`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`device_pairing_paired`,kind:`column`,value:{name:`approved_via`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`device_pairing_paired`,kind:`column`,value:{name:`node_surface_json`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`device_pairing_paired`,kind:`column`,value:{name:`pending_node_surface_json`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`device_pairing_paired`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:19}},{table:`device_pairing_paired`,kind:`column`,value:{name:`approved_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:20}},{table:`device_pairing_paired`,kind:`column`,value:{name:`last_seen_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:21}},{table:`device_pairing_paired`,kind:`column`,value:{name:`last_seen_reason`,type:`text`,nullable:!0,identity:!1,default:null,position:22}},{table:`device_pairing_paired`,kind:`primaryKey`,value:[`device_id`]},{table:`device_pairing_paired`,kind:`indexes`,value:2},{table:`device_pairing_paired`,kind:`checks`,value:0},{table:`device_pairing_pending`,kind:`table`,value:null},{table:`device_pairing_pending`,kind:`column`,value:{name:`request_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`device_pairing_pending`,kind:`column`,value:{name:`device_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`device_pairing_pending`,kind:`column`,value:{name:`public_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`device_pairing_pending`,kind:`column`,value:{name:`display_name`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`device_pairing_pending`,kind:`column`,value:{name:`platform`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`device_pairing_pending`,kind:`column`,value:{name:`device_family`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`device_pairing_pending`,kind:`column`,value:{name:`client_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`device_pairing_pending`,kind:`column`,value:{name:`client_mode`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`device_pairing_pending`,kind:`column`,value:{name:`browser_origin`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`device_pairing_pending`,kind:`column`,value:{name:`role`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`device_pairing_pending`,kind:`column`,value:{name:`roles_json`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`device_pairing_pending`,kind:`column`,value:{name:`scopes_json`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`device_pairing_pending`,kind:`column`,value:{name:`remote_ip`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`device_pairing_pending`,kind:`column`,value:{name:`silent`,type:`bigint`,nullable:!0,identity:!1,default:null,position:14}},{table:`device_pairing_pending`,kind:`column`,value:{name:`is_repair`,type:`bigint`,nullable:!0,identity:!1,default:null,position:15}},{table:`device_pairing_pending`,kind:`column`,value:{name:`ts`,type:`bigint`,nullable:!1,identity:!1,default:null,position:16}},{table:`device_pairing_pending`,kind:`column`,value:{name:`refreshed_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:17}},{table:`device_pairing_pending`,kind:`primaryKey`,value:[`request_id`]},{table:`device_pairing_pending`,kind:`indexes`,value:2},{table:`device_pairing_pending`,kind:`checks`,value:0},{table:`diagnostic_events`,kind:`table`,value:null},{table:`diagnostic_events`,kind:`column`,value:{name:`scope`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`diagnostic_events`,kind:`column`,value:{name:`event_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`diagnostic_events`,kind:`column`,value:{name:`payload_json`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`diagnostic_events`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`diagnostic_events`,kind:`column`,value:{name:`sequence`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:5}},{table:`diagnostic_events`,kind:`primaryKey`,value:[`scope`,`event_key`]},{table:`diagnostic_events`,kind:`indexes`,value:2},{table:`diagnostic_events`,kind:`checks`,value:0},{table:`durable_background_processes`,kind:`table`,value:null},{table:`durable_background_processes`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`durable_background_processes`,kind:`column`,value:{name:`record_json`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`durable_background_processes`,kind:`primaryKey`,value:[`id`]},{table:`durable_background_processes`,kind:`indexes`,value:1},{table:`durable_background_processes`,kind:`checks`,value:0},{table:`exec_approvals_config`,kind:`table`,value:null},{table:`exec_approvals_config`,kind:`column`,value:{name:`config_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`exec_approvals_config`,kind:`column`,value:{name:`raw_json`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`exec_approvals_config`,kind:`column`,value:{name:`socket_path`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`exec_approvals_config`,kind:`column`,value:{name:`has_socket_token`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`exec_approvals_config`,kind:`column`,value:{name:`default_security`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`exec_approvals_config`,kind:`column`,value:{name:`default_ask`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`exec_approvals_config`,kind:`column`,value:{name:`default_ask_fallback`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`exec_approvals_config`,kind:`column`,value:{name:`auto_allow_skills`,type:`bigint`,nullable:!0,identity:!1,default:null,position:8}},{table:`exec_approvals_config`,kind:`column`,value:{name:`agent_count`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`exec_approvals_config`,kind:`column`,value:{name:`allowlist_count`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`exec_approvals_config`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`exec_approvals_config`,kind:`primaryKey`,value:[`config_key`]},{table:`exec_approvals_config`,kind:`indexes`,value:1},{table:`exec_approvals_config`,kind:`checks`,value:0},{table:`execution_decision_facts`,kind:`table`,value:null},{table:`execution_decision_facts`,kind:`column`,value:{name:`cursor_id`,type:`bigint`,nullable:!1,identity:!1,default:null,position:1}},{table:`execution_decision_facts`,kind:`column`,value:{name:`receipt_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`execution_decision_facts`,kind:`column`,value:{name:`context_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`execution_decision_facts`,kind:`column`,value:{name:`execution_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`execution_decision_facts`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`execution_decision_facts`,kind:`column`,value:{name:`action_id`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`execution_decision_facts`,kind:`column`,value:{name:`action_family`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`execution_decision_facts`,kind:`column`,value:{name:`decision_outcome`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`execution_decision_facts`,kind:`column`,value:{name:`coverage_state`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`execution_decision_facts`,kind:`column`,value:{name:`reason_code`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`execution_decision_facts`,kind:`column`,value:{name:`owner`,type:`text`,nullable:!1,identity:!1,default:null,position:11}},{table:`execution_decision_facts`,kind:`column`,value:{name:`source_ref`,type:`text`,nullable:!1,identity:!1,default:null,position:12}},{table:`execution_decision_facts`,kind:`column`,value:{name:`occurred_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:13}},{table:`execution_decision_facts`,kind:`column`,value:{name:`receipt_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:14}},{table:`execution_decision_facts`,kind:`column`,value:{name:`receipt_json`,type:`text`,nullable:!1,identity:!1,default:null,position:15}},{table:`execution_decision_facts`,kind:`primaryKey`,value:[`receipt_id`]},{table:`execution_decision_facts`,kind:`unique`,value:[`occurred_at`,`receipt_id`]},{table:`execution_decision_facts`,kind:`indexes`,value:5},{table:`execution_decision_facts`,kind:`checks`,value:14},{table:`execution_identity_contexts`,kind:`table`,value:null},{table:`execution_identity_contexts`,kind:`column`,value:{name:`context_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`execution_identity_contexts`,kind:`column`,value:{name:`execution_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`execution_identity_contexts`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`execution_identity_contexts`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`execution_identity_contexts`,kind:`column`,value:{name:`coverage_state`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`execution_identity_contexts`,kind:`column`,value:{name:`context_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`execution_identity_contexts`,kind:`column`,value:{name:`context_json`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`execution_identity_contexts`,kind:`primaryKey`,value:[`context_id`]},{table:`execution_identity_contexts`,kind:`unique`,value:[`execution_id`]},{table:`execution_identity_contexts`,kind:`unique`,value:[`created_at`,`context_id`]},{table:`execution_identity_contexts`,kind:`indexes`,value:4},{table:`execution_identity_contexts`,kind:`checks`,value:7},{table:`execution_owner_lifecycle_bindings`,kind:`table`,value:null},{table:`execution_owner_lifecycle_bindings`,kind:`column`,value:{name:`owner_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`execution_owner_lifecycle_bindings`,kind:`column`,value:{name:`owner_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`execution_owner_lifecycle_bindings`,kind:`column`,value:{name:`context_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`execution_owner_lifecycle_bindings`,kind:`column`,value:{name:`execution_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`execution_owner_lifecycle_bindings`,kind:`primaryKey`,value:[`owner_kind`,`owner_id`]},{table:`execution_owner_lifecycle_bindings`,kind:`indexes`,value:1},{table:`execution_owner_lifecycle_bindings`,kind:`checks`,value:0},{table:`flow_runs`,kind:`table`,value:null},{table:`flow_runs`,kind:`column`,value:{name:`flow_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`flow_runs`,kind:`column`,value:{name:`shape`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`flow_runs`,kind:`column`,value:{name:`sync_mode`,type:`text`,nullable:!1,identity:!1,default:`'managed'`,position:3}},{table:`flow_runs`,kind:`column`,value:{name:`owner_key`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`flow_runs`,kind:`column`,value:{name:`requester_origin_json`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`flow_runs`,kind:`column`,value:{name:`controller_id`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`flow_runs`,kind:`column`,value:{name:`revision`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:7}},{table:`flow_runs`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`flow_runs`,kind:`column`,value:{name:`notify_policy`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`flow_runs`,kind:`column`,value:{name:`goal`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`flow_runs`,kind:`column`,value:{name:`current_step`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`flow_runs`,kind:`column`,value:{name:`blocked_task_id`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`flow_runs`,kind:`column`,value:{name:`blocked_summary`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`flow_runs`,kind:`column`,value:{name:`state_json`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`flow_runs`,kind:`column`,value:{name:`wait_json`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`flow_runs`,kind:`column`,value:{name:`cancel_requested_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:16}},{table:`flow_runs`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:17}},{table:`flow_runs`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:18}},{table:`flow_runs`,kind:`column`,value:{name:`ended_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:19}},{table:`flow_runs`,kind:`primaryKey`,value:[`flow_id`]},{table:`flow_runs`,kind:`indexes`,value:4},{table:`flow_runs`,kind:`checks`,value:0},{table:`gateway_boot_lifecycle`,kind:`table`,value:null},{table:`gateway_boot_lifecycle`,kind:`column`,value:{name:`boot_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`gateway_boot_lifecycle`,kind:`column`,value:{name:`pid`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`gateway_boot_lifecycle`,kind:`column`,value:{name:`started_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`gateway_boot_lifecycle`,kind:`column`,value:{name:`completed_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:4}},{table:`gateway_boot_lifecycle`,kind:`column`,value:{name:`outcome`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`gateway_boot_lifecycle`,kind:`column`,value:{name:`startup_reason`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`gateway_boot_lifecycle`,kind:`column`,value:{name:`reason`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`gateway_boot_lifecycle`,kind:`primaryKey`,value:[`boot_id`]},{table:`gateway_boot_lifecycle`,kind:`indexes`,value:2},{table:`gateway_boot_lifecycle`,kind:`checks`,value:0},{table:`gateway_restart_handoff`,kind:`table`,value:null},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`handoff_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`version`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`intent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`pid`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`process_instance_id`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`expires_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`reason`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`restart_trace_started_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:10}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`restart_trace_last_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:11}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`source`,type:`text`,nullable:!1,identity:!1,default:null,position:12}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`restart_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:13}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`supervisor_mode`,type:`text`,nullable:!1,identity:!1,default:null,position:14}},{table:`gateway_restart_handoff`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:15}},{table:`gateway_restart_handoff`,kind:`primaryKey`,value:[`handoff_key`]},{table:`gateway_restart_handoff`,kind:`indexes`,value:2},{table:`gateway_restart_handoff`,kind:`checks`,value:0},{table:`gateway_restart_intent`,kind:`table`,value:null},{table:`gateway_restart_intent`,kind:`column`,value:{name:`intent_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`gateway_restart_intent`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`gateway_restart_intent`,kind:`column`,value:{name:`pid`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`gateway_restart_intent`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`gateway_restart_intent`,kind:`column`,value:{name:`reason`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`gateway_restart_intent`,kind:`column`,value:{name:`force`,type:`bigint`,nullable:!0,identity:!1,default:null,position:6}},{table:`gateway_restart_intent`,kind:`column`,value:{name:`wait_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:7}},{table:`gateway_restart_intent`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`gateway_restart_intent`,kind:`primaryKey`,value:[`intent_key`]},{table:`gateway_restart_intent`,kind:`indexes`,value:1},{table:`gateway_restart_intent`,kind:`checks`,value:0},{table:`gateway_restart_sentinel`,kind:`table`,value:null},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`sentinel_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`version`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`ts`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`thread_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`delivery_channel`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`delivery_to`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`delivery_account_id`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`message`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`continuation_json`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`doctor_hint`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`stats_json`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`payload_json`,type:`text`,nullable:!1,identity:!1,default:null,position:15}},{table:`gateway_restart_sentinel`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:16}},{table:`gateway_restart_sentinel`,kind:`primaryKey`,value:[`sentinel_key`]},{table:`gateway_restart_sentinel`,kind:`indexes`,value:2},{table:`gateway_restart_sentinel`,kind:`checks`,value:0},{table:`github_personal_publication_requests`,kind:`table`,value:null},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`request_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`owner_profile_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`connection_generation`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`idempotency_key`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`request_digest`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`worktree_id`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`repository_fingerprint`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`identity_source`,type:`text`,nullable:!1,identity:!1,default:null,position:11}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`identity_profile_id`,type:`text`,nullable:!1,identity:!1,default:null,position:12}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`identity_account_id`,type:`bigint`,nullable:!1,identity:!1,default:null,position:13}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`identity_login`,type:`text`,nullable:!1,identity:!1,default:null,position:14}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`title`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`body`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:17}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`gateway_instance_id`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`execution_id`,type:`text`,nullable:!0,identity:!1,default:null,position:19}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`last_effect`,type:`text`,nullable:!0,identity:!1,default:null,position:20}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`effect_state`,type:`text`,nullable:!0,identity:!1,default:null,position:21}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`push_repository`,type:`text`,nullable:!1,identity:!1,default:null,position:22}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`repository`,type:`text`,nullable:!1,identity:!1,default:null,position:23}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`branch`,type:`text`,nullable:!1,identity:!1,default:null,position:24}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`base_branch`,type:`text`,nullable:!1,identity:!1,default:null,position:25}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`source_head_commit`,type:`text`,nullable:!1,identity:!1,default:null,position:26}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`source_index_tree`,type:`text`,nullable:!1,identity:!1,default:null,position:27}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`workspace_tree`,type:`text`,nullable:!1,identity:!1,default:null,position:28}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`head_commit`,type:`text`,nullable:!0,identity:!1,default:null,position:29}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`pull_request_url`,type:`text`,nullable:!0,identity:!1,default:null,position:30}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`error_code`,type:`text`,nullable:!0,identity:!1,default:null,position:31}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`next_action`,type:`text`,nullable:!0,identity:!1,default:null,position:32}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:33}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:34}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`reported_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:35}},{table:`github_personal_publication_requests`,kind:`column`,value:{name:`draft`,type:`bigint`,nullable:!0,identity:!1,default:null,position:36}},{table:`github_personal_publication_requests`,kind:`primaryKey`,value:[`request_id`]},{table:`github_personal_publication_requests`,kind:`unique`,value:[`owner_profile_id`,`session_id`,`idempotency_key`]},{table:`github_personal_publication_requests`,kind:`indexes`,value:4},{table:`github_personal_publication_requests`,kind:`checks`,value:37},{table:`github_publication_requests`,kind:`table`,value:null},{table:`github_publication_requests`,kind:`column`,value:{name:`request_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`github_publication_requests`,kind:`column`,value:{name:`idempotency_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`github_publication_requests`,kind:`column`,value:{name:`request_digest`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`github_publication_requests`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`github_publication_requests`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`github_publication_requests`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`github_publication_requests`,kind:`column`,value:{name:`worktree_id`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`github_publication_requests`,kind:`column`,value:{name:`repository_fingerprint`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`github_publication_requests`,kind:`column`,value:{name:`claim_id`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`github_publication_requests`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`github_publication_requests`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`github_publication_requests`,kind:`column`,value:{name:`owner_epoch`,type:`bigint`,nullable:!0,identity:!1,default:null,position:12}},{table:`github_publication_requests`,kind:`column`,value:{name:`placement_generation`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`github_publication_requests`,kind:`column`,value:{name:`identity_source`,type:`text`,nullable:!1,identity:!1,default:null,position:14}},{table:`github_publication_requests`,kind:`column`,value:{name:`identity_profile_id`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`github_publication_requests`,kind:`column`,value:{name:`identity_account_id`,type:`bigint`,nullable:!1,identity:!1,default:null,position:16}},{table:`github_publication_requests`,kind:`column`,value:{name:`identity_login`,type:`text`,nullable:!1,identity:!1,default:null,position:17}},{table:`github_publication_requests`,kind:`column`,value:{name:`title`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`github_publication_requests`,kind:`column`,value:{name:`body`,type:`text`,nullable:!0,identity:!1,default:null,position:19}},{table:`github_publication_requests`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:20}},{table:`github_publication_requests`,kind:`column`,value:{name:`gateway_instance_id`,type:`text`,nullable:!0,identity:!1,default:null,position:21}},{table:`github_publication_requests`,kind:`column`,value:{name:`repository`,type:`text`,nullable:!0,identity:!1,default:null,position:22}},{table:`github_publication_requests`,kind:`column`,value:{name:`branch`,type:`text`,nullable:!1,identity:!1,default:null,position:23}},{table:`github_publication_requests`,kind:`column`,value:{name:`base_branch`,type:`text`,nullable:!0,identity:!1,default:null,position:24}},{table:`github_publication_requests`,kind:`column`,value:{name:`source_head_commit`,type:`text`,nullable:!0,identity:!1,default:null,position:25}},{table:`github_publication_requests`,kind:`column`,value:{name:`source_index_tree`,type:`text`,nullable:!0,identity:!1,default:null,position:26}},{table:`github_publication_requests`,kind:`column`,value:{name:`workspace_tree`,type:`text`,nullable:!0,identity:!1,default:null,position:27}},{table:`github_publication_requests`,kind:`column`,value:{name:`head_commit`,type:`text`,nullable:!0,identity:!1,default:null,position:28}},{table:`github_publication_requests`,kind:`column`,value:{name:`pull_request_url`,type:`text`,nullable:!0,identity:!1,default:null,position:29}},{table:`github_publication_requests`,kind:`column`,value:{name:`error_code`,type:`text`,nullable:!0,identity:!1,default:null,position:30}},{table:`github_publication_requests`,kind:`column`,value:{name:`next_action`,type:`text`,nullable:!0,identity:!1,default:null,position:31}},{table:`github_publication_requests`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:32}},{table:`github_publication_requests`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:33}},{table:`github_publication_requests`,kind:`column`,value:{name:`reported_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:34}},{table:`github_publication_requests`,kind:`column`,value:{name:`draft`,type:`bigint`,nullable:!0,identity:!1,default:null,position:35}},{table:`github_publication_requests`,kind:`primaryKey`,value:[`request_id`]},{table:`github_publication_requests`,kind:`unique`,value:[`session_id`,`idempotency_key`]},{table:`github_publication_requests`,kind:`indexes`,value:3},{table:`github_publication_requests`,kind:`checks`,value:9},{table:`github_publication_session_lifecycles`,kind:`table`,value:null},{table:`github_publication_session_lifecycles`,kind:`column`,value:{name:`publication_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`github_publication_session_lifecycles`,kind:`column`,value:{name:`request_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`github_publication_session_lifecycles`,kind:`column`,value:{name:`lifecycle_revision`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`github_publication_session_lifecycles`,kind:`column`,value:{name:`requester_authority_json`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`github_publication_session_lifecycles`,kind:`primaryKey`,value:[`publication_kind`,`request_id`]},{table:`github_publication_session_lifecycles`,kind:`indexes`,value:1},{table:`github_publication_session_lifecycles`,kind:`checks`,value:1},{table:`github_repository_publication_requests`,kind:`table`,value:null},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`request_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`owner_profile_id`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`connection_generation`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`idempotency_key`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`request_digest`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`session_lifecycle_revision`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`requester_authority_json`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`workspace_id`,type:`text`,nullable:!1,identity:!1,default:null,position:11}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`checkpoint_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`checkpoint_digest`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`claim_id`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`owner_epoch`,type:`bigint`,nullable:!0,identity:!1,default:null,position:17}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`placement_generation`,type:`bigint`,nullable:!0,identity:!1,default:null,position:18}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`identity_source`,type:`text`,nullable:!1,identity:!1,default:null,position:19}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`identity_profile_id`,type:`text`,nullable:!0,identity:!1,default:null,position:20}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`identity_account_id`,type:`bigint`,nullable:!1,identity:!1,default:null,position:21}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`identity_login`,type:`text`,nullable:!1,identity:!1,default:null,position:22}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`title`,type:`text`,nullable:!0,identity:!1,default:null,position:23}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`body`,type:`text`,nullable:!0,identity:!1,default:null,position:24}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:25}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`gateway_instance_id`,type:`text`,nullable:!0,identity:!1,default:null,position:26}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`execution_id`,type:`text`,nullable:!0,identity:!1,default:null,position:27}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`last_effect`,type:`text`,nullable:!0,identity:!1,default:null,position:28}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`effect_state`,type:`text`,nullable:!0,identity:!1,default:null,position:29}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`push_repository`,type:`text`,nullable:!0,identity:!1,default:null,position:30}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`repository`,type:`text`,nullable:!0,identity:!1,default:null,position:31}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`branch`,type:`text`,nullable:!1,identity:!1,default:null,position:32}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`base_branch`,type:`text`,nullable:!0,identity:!1,default:null,position:33}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`source_head_commit`,type:`text`,nullable:!0,identity:!1,default:null,position:34}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`source_index_tree`,type:`text`,nullable:!0,identity:!1,default:null,position:35}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`workspace_tree`,type:`text`,nullable:!0,identity:!1,default:null,position:36}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`previous_head_commit`,type:`text`,nullable:!0,identity:!1,default:null,position:37}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`pushed_head_commit`,type:`text`,nullable:!0,identity:!1,default:null,position:38}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`head_commit`,type:`text`,nullable:!0,identity:!1,default:null,position:39}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`pull_request_url`,type:`text`,nullable:!0,identity:!1,default:null,position:40}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`error_code`,type:`text`,nullable:!0,identity:!1,default:null,position:41}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`next_action`,type:`text`,nullable:!0,identity:!1,default:null,position:42}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:43}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:44}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`reported_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:45}},{table:`github_repository_publication_requests`,kind:`column`,value:{name:`draft`,type:`bigint`,nullable:!0,identity:!1,default:null,position:46}},{table:`github_repository_publication_requests`,kind:`primaryKey`,value:[`request_id`]},{table:`github_repository_publication_requests`,kind:`indexes`,value:3},{table:`github_repository_publication_requests`,kind:`checks`,value:7},{table:`local_workspace_manifest_nodes`,kind:`table`,value:null},{table:`local_workspace_manifest_nodes`,kind:`column`,value:{name:`worktree_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`local_workspace_manifest_nodes`,kind:`column`,value:{name:`path`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`local_workspace_manifest_nodes`,kind:`column`,value:{name:`node_json`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`local_workspace_manifest_nodes`,kind:`primaryKey`,value:[`worktree_id`,`path`]},{table:`local_workspace_manifest_nodes`,kind:`foreignKey`,value:{columns:[`worktree_id`],target:`local_workspace_projections`,targetColumns:[`worktree_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`local_workspace_manifest_nodes`,kind:`indexes`,value:1},{table:`local_workspace_manifest_nodes`,kind:`checks`,value:0},{table:`local_workspace_projections`,kind:`table`,value:null},{table:`local_workspace_projections`,kind:`column`,value:{name:`worktree_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`local_workspace_projections`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`local_workspace_projections`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`local_workspace_projections`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`local_workspace_projections`,kind:`column`,value:{name:`lifecycle_revision`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`local_workspace_projections`,kind:`column`,value:{name:`projection_path`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`local_workspace_projections`,kind:`column`,value:{name:`base_commit`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`local_workspace_projections`,kind:`column`,value:{name:`source_paths_json`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`local_workspace_projections`,kind:`column`,value:{name:`baseline_json`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`local_workspace_projections`,kind:`column`,value:{name:`baseline_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`local_workspace_projections`,kind:`column`,value:{name:`pending_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`local_workspace_projections`,kind:`column`,value:{name:`pending_target`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`local_workspace_projections`,kind:`column`,value:{name:`paused_runtimes_json`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`local_workspace_projections`,kind:`column`,value:{name:`journal_json`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`local_workspace_projections`,kind:`column`,value:{name:`journal_pack`,type:`bytea`,nullable:!0,identity:!1,default:null,position:15}},{table:`local_workspace_projections`,kind:`column`,value:{name:`revision`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:16}},{table:`local_workspace_projections`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:17}},{table:`local_workspace_projections`,kind:`column`,value:{name:`checkpoint_json`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`local_workspace_projections`,kind:`column`,value:{name:`tree_root_digest`,type:`bytea`,nullable:!0,identity:!1,default:null,position:19}},{table:`local_workspace_projections`,kind:`column`,value:{name:`source_paths_digest`,type:`bytea`,nullable:!0,identity:!1,default:null,position:20}},{table:`local_workspace_projections`,kind:`column`,value:{name:`canonical_fingerprints`,type:`bytea`,nullable:!0,identity:!1,default:null,position:21}},{table:`local_workspace_projections`,kind:`column`,value:{name:`projection_fingerprints`,type:`bytea`,nullable:!0,identity:!1,default:null,position:22}},{table:`local_workspace_projections`,kind:`primaryKey`,value:[`worktree_id`]},{table:`local_workspace_projections`,kind:`unique`,value:[`projection_path`]},{table:`local_workspace_projections`,kind:`indexes`,value:2},{table:`local_workspace_projections`,kind:`checks`,value:5},{table:`local_workspace_source_path_sets`,kind:`table`,value:null},{table:`local_workspace_source_path_sets`,kind:`column`,value:{name:`path_digest`,type:`bytea`,nullable:!1,identity:!1,default:null,position:1}},{table:`local_workspace_source_path_sets`,kind:`column`,value:{name:`paths_zstd`,type:`bytea`,nullable:!1,identity:!1,default:null,position:2}},{table:`local_workspace_source_path_sets`,kind:`column`,value:{name:`sweep_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`local_workspace_source_path_sets`,kind:`primaryKey`,value:[`path_digest`]},{table:`local_workspace_source_path_sets`,kind:`indexes`,value:1},{table:`local_workspace_source_path_sets`,kind:`checks`,value:1},{table:`local_workspace_tree_packs`,kind:`table`,value:null},{table:`local_workspace_tree_packs`,kind:`column`,value:{name:`tree_digest`,type:`bytea`,nullable:!1,identity:!1,default:null,position:1}},{table:`local_workspace_tree_packs`,kind:`column`,value:{name:`records_json`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`local_workspace_tree_packs`,kind:`column`,value:{name:`children_json`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`local_workspace_tree_packs`,kind:`column`,value:{name:`sweep_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`local_workspace_tree_packs`,kind:`primaryKey`,value:[`tree_digest`]},{table:`local_workspace_tree_packs`,kind:`indexes`,value:1},{table:`local_workspace_tree_packs`,kind:`checks`,value:1},{table:`macos_port_guardian_records`,kind:`table`,value:null},{table:`macos_port_guardian_records`,kind:`column`,value:{name:`pid`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`macos_port_guardian_records`,kind:`column`,value:{name:`port`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`macos_port_guardian_records`,kind:`column`,value:{name:`command`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`macos_port_guardian_records`,kind:`column`,value:{name:`mode`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`macos_port_guardian_records`,kind:`column`,value:{name:`timestamp`,type:`double precision`,nullable:!1,identity:!1,default:null,position:5}},{table:`macos_port_guardian_records`,kind:`primaryKey`,value:[`pid`]},{table:`macos_port_guardian_records`,kind:`indexes`,value:2},{table:`macos_port_guardian_records`,kind:`checks`,value:0},{table:`managed_outgoing_image_records`,kind:`table`,value:null},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`attachment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`message_id`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`created_at`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`updated_at`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`retention_class`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`alt`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`original_media_root`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`original_media_id`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`original_media_subdir`,type:`text`,nullable:!1,identity:!1,default:null,position:11}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`original_content_type`,type:`text`,nullable:!1,identity:!1,default:null,position:12}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`original_width`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`original_height`,type:`bigint`,nullable:!0,identity:!1,default:null,position:14}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`original_size_bytes`,type:`bigint`,nullable:!0,identity:!1,default:null,position:15}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`original_filename`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`record_json`,type:`text`,nullable:!1,identity:!1,default:null,position:17}},{table:`managed_outgoing_image_records`,kind:`column`,value:{name:`cleanup_pending`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:18}},{table:`managed_outgoing_image_records`,kind:`primaryKey`,value:[`attachment_id`]},{table:`managed_outgoing_image_records`,kind:`indexes`,value:5},{table:`managed_outgoing_image_records`,kind:`checks`,value:1},{table:`mcp_oauth_pending_authorizations`,kind:`table`,value:null},{table:`mcp_oauth_pending_authorizations`,kind:`column`,value:{name:`state`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`mcp_oauth_pending_authorizations`,kind:`column`,value:{name:`store_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`mcp_oauth_pending_authorizations`,kind:`column`,value:{name:`create_time`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`mcp_oauth_pending_authorizations`,kind:`primaryKey`,value:[`state`]},{table:`mcp_oauth_pending_authorizations`,kind:`indexes`,value:1},{table:`mcp_oauth_pending_authorizations`,kind:`checks`,value:0},{table:`mcp_oauth_stores`,kind:`table`,value:null},{table:`mcp_oauth_stores`,kind:`column`,value:{name:`store_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`mcp_oauth_stores`,kind:`column`,value:{name:`format_version`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`mcp_oauth_stores`,kind:`column`,value:{name:`store_json`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`mcp_oauth_stores`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`mcp_oauth_stores`,kind:`primaryKey`,value:[`store_key`]},{table:`mcp_oauth_stores`,kind:`indexes`,value:1},{table:`mcp_oauth_stores`,kind:`checks`,value:1},{table:`meeting_transcript_sessions`,kind:`table`,value:null},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`started_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:1}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`started_at`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`selector`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`export_key`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`session_slug`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`provider_id`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`title`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`source_json`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`source_account_id`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`source_guild_id`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`source_channel_id`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`source_meeting_url`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`source_thread_ts`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`source_file_id`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`stopped_at`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`metadata_json`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`metadata_agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`export_manifest_json`,type:`text`,nullable:!1,identity:!1,default:`'{}'`,position:19}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`export_pending_json`,type:`text`,nullable:!1,identity:!1,default:`'[]'`,position:20}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`next_utterance_seq`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:21}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:22}},{table:`meeting_transcript_sessions`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:23}},{table:`meeting_transcript_sessions`,kind:`primaryKey`,value:[`session_id`,`started_at`]},{table:`meeting_transcript_sessions`,kind:`unique`,value:[`selector`]},{table:`meeting_transcript_sessions`,kind:`indexes`,value:10},{table:`meeting_transcript_sessions`,kind:`checks`,value:3},{table:`meeting_transcript_summaries`,kind:`table`,value:null},{table:`meeting_transcript_summaries`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`meeting_transcript_summaries`,kind:`column`,value:{name:`session_started_at`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`meeting_transcript_summaries`,kind:`column`,value:{name:`generated_at`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`meeting_transcript_summaries`,kind:`column`,value:{name:`summary_json`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`meeting_transcript_summaries`,kind:`column`,value:{name:`overview`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`meeting_transcript_summaries`,kind:`column`,value:{name:`markdown`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`meeting_transcript_summaries`,kind:`column`,value:{name:`utterance_count`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`meeting_transcript_summaries`,kind:`primaryKey`,value:[`session_id`,`session_started_at`]},{table:`meeting_transcript_summaries`,kind:`foreignKey`,value:{columns:[`session_id`,`session_started_at`],target:`meeting_transcript_sessions`,targetColumns:[`session_id`,`started_at`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`meeting_transcript_summaries`,kind:`indexes`,value:1},{table:`meeting_transcript_summaries`,kind:`checks`,value:2},{table:`meeting_transcript_utterances`,kind:`table`,value:null},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`session_started_at`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`sequence`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`utterance_id`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`started_at`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`ended_at`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`speaker_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`speaker_label`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`text`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`final`,type:`bigint`,nullable:!0,identity:!1,default:null,position:10}},{table:`meeting_transcript_utterances`,kind:`column`,value:{name:`metadata_json`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`meeting_transcript_utterances`,kind:`primaryKey`,value:[`session_id`,`session_started_at`,`sequence`]},{table:`meeting_transcript_utterances`,kind:`foreignKey`,value:{columns:[`session_id`,`session_started_at`],target:`meeting_transcript_sessions`,targetColumns:[`session_id`,`started_at`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`meeting_transcript_utterances`,kind:`indexes`,value:2},{table:`meeting_transcript_utterances`,kind:`checks`,value:2},{table:`migration_runs`,kind:`table`,value:null},{table:`migration_runs`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`migration_runs`,kind:`column`,value:{name:`started_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`migration_runs`,kind:`column`,value:{name:`finished_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:3}},{table:`migration_runs`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`migration_runs`,kind:`column`,value:{name:`report_json`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`migration_runs`,kind:`primaryKey`,value:[`id`]},{table:`migration_runs`,kind:`indexes`,value:2},{table:`migration_runs`,kind:`checks`,value:0},{table:`migration_sources`,kind:`table`,value:null},{table:`migration_sources`,kind:`column`,value:{name:`source_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`migration_sources`,kind:`column`,value:{name:`migration_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`migration_sources`,kind:`column`,value:{name:`source_path`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`migration_sources`,kind:`column`,value:{name:`target_table`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`migration_sources`,kind:`column`,value:{name:`source_sha256`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`migration_sources`,kind:`column`,value:{name:`source_size_bytes`,type:`bigint`,nullable:!0,identity:!1,default:null,position:6}},{table:`migration_sources`,kind:`column`,value:{name:`source_record_count`,type:`bigint`,nullable:!0,identity:!1,default:null,position:7}},{table:`migration_sources`,kind:`column`,value:{name:`last_run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`migration_sources`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`migration_sources`,kind:`column`,value:{name:`imported_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`migration_sources`,kind:`column`,value:{name:`removed_source`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:11}},{table:`migration_sources`,kind:`column`,value:{name:`report_json`,type:`text`,nullable:!1,identity:!1,default:null,position:12}},{table:`migration_sources`,kind:`primaryKey`,value:[`source_key`]},{table:`migration_sources`,kind:`foreignKey`,value:{columns:[`last_run_id`],target:`migration_runs`,targetColumns:[`id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`migration_sources`,kind:`indexes`,value:3},{table:`migration_sources`,kind:`checks`,value:0},{table:`native_hook_relay_bridges`,kind:`table`,value:null},{table:`native_hook_relay_bridges`,kind:`column`,value:{name:`relay_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`native_hook_relay_bridges`,kind:`column`,value:{name:`pid`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`native_hook_relay_bridges`,kind:`column`,value:{name:`hostname`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`native_hook_relay_bridges`,kind:`column`,value:{name:`port`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`native_hook_relay_bridges`,kind:`column`,value:{name:`token`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`native_hook_relay_bridges`,kind:`column`,value:{name:`expires_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`native_hook_relay_bridges`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`native_hook_relay_bridges`,kind:`primaryKey`,value:[`relay_id`]},{table:`native_hook_relay_bridges`,kind:`indexes`,value:2},{table:`native_hook_relay_bridges`,kind:`checks`,value:0},{table:`node_worker_launch_boots`,kind:`table`,value:null},{table:`node_worker_launch_boots`,kind:`column`,value:{name:`launch_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`node_worker_launch_boots`,kind:`column`,value:{name:`boot_id`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`node_worker_launch_boots`,kind:`primaryKey`,value:[`launch_id`]},{table:`node_worker_launch_boots`,kind:`foreignKey`,value:{columns:[`launch_id`],target:`node_worker_launches`,targetColumns:[`launch_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`node_worker_launch_boots`,kind:`indexes`,value:1},{table:`node_worker_launch_boots`,kind:`checks`,value:1},{table:`node_worker_launch_cleanup`,kind:`table`,value:null},{table:`node_worker_launch_cleanup`,kind:`column`,value:{name:`launch_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`node_worker_launch_cleanup`,kind:`column`,value:{name:`cleanup_mode`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`node_worker_launch_cleanup`,kind:`column`,value:{name:`lineage_settled`,type:`bigint`,nullable:!0,identity:!1,default:null,position:3}},{table:`node_worker_launch_cleanup`,kind:`primaryKey`,value:[`launch_id`]},{table:`node_worker_launch_cleanup`,kind:`foreignKey`,value:{columns:[`launch_id`],target:`node_worker_launches`,targetColumns:[`launch_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`node_worker_launch_cleanup`,kind:`indexes`,value:1},{table:`node_worker_launch_cleanup`,kind:`checks`,value:2},{table:`node_worker_launch_containers`,kind:`table`,value:null},{table:`node_worker_launch_containers`,kind:`column`,value:{name:`launch_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`node_worker_launch_containers`,kind:`column`,value:{name:`container_json`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`node_worker_launch_containers`,kind:`primaryKey`,value:[`launch_id`]},{table:`node_worker_launch_containers`,kind:`indexes`,value:1},{table:`node_worker_launch_containers`,kind:`checks`,value:0},{table:`node_worker_launch_process_scopes`,kind:`table`,value:null},{table:`node_worker_launch_process_scopes`,kind:`column`,value:{name:`launch_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`node_worker_launch_process_scopes`,kind:`column`,value:{name:`scope_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`node_worker_launch_process_scopes`,kind:`column`,value:{name:`descendants_reaped`,type:`bigint`,nullable:!0,identity:!1,default:null,position:3}},{table:`node_worker_launch_process_scopes`,kind:`primaryKey`,value:[`launch_id`]},{table:`node_worker_launch_process_scopes`,kind:`foreignKey`,value:{columns:[`launch_id`],target:`node_worker_launches`,targetColumns:[`launch_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`node_worker_launch_process_scopes`,kind:`indexes`,value:1},{table:`node_worker_launch_process_scopes`,kind:`checks`,value:2},{table:`node_worker_launches`,kind:`table`,value:null},{table:`node_worker_launches`,kind:`column`,value:{name:`launch_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`node_worker_launches`,kind:`column`,value:{name:`plan_hash`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`node_worker_launches`,kind:`column`,value:{name:`gateway_namespace`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`node_worker_launches`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`node_worker_launches`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`node_worker_launches`,kind:`column`,value:{name:`owner_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`node_worker_launches`,kind:`column`,value:{name:`placement_generation`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`node_worker_launches`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`node_worker_launches`,kind:`column`,value:{name:`state`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`node_worker_launches`,kind:`column`,value:{name:`supervisor_pid`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`node_worker_launches`,kind:`column`,value:{name:`supervisor_start_time`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`node_worker_launches`,kind:`column`,value:{name:`worker_pid`,type:`bigint`,nullable:!0,identity:!1,default:null,position:12}},{table:`node_worker_launches`,kind:`column`,value:{name:`worker_start_time`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`node_worker_launches`,kind:`column`,value:{name:`result_json`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`node_worker_launches`,kind:`column`,value:{name:`error_text`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`node_worker_launches`,kind:`column`,value:{name:`completed_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:16}},{table:`node_worker_launches`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:17}},{table:`node_worker_launches`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:18}},{table:`node_worker_launches`,kind:`primaryKey`,value:[`launch_id`]},{table:`node_worker_launches`,kind:`indexes`,value:2},{table:`node_worker_launches`,kind:`checks`,value:20},{table:`node_worker_prepared_workspaces`,kind:`table`,value:null},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`preparation_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`cache_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`gateway_namespace`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`workspace_dir`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`home_dir`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`source_manifest_ref`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`prepared_manifest_ref`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`state`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`owner_epoch`,type:`bigint`,nullable:!0,identity:!1,default:null,position:12}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:13}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`bound_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:14}},{table:`node_worker_prepared_workspaces`,kind:`column`,value:{name:`retired_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:15}},{table:`node_worker_prepared_workspaces`,kind:`primaryKey`,value:[`preparation_key`]},{table:`node_worker_prepared_workspaces`,kind:`unique`,value:[`workspace_dir`]},{table:`node_worker_prepared_workspaces`,kind:`indexes`,value:2},{table:`node_worker_prepared_workspaces`,kind:`checks`,value:15},{table:`node_worker_turns`,kind:`table`,value:null},{table:`node_worker_turns`,kind:`column`,value:{name:`turn_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`node_worker_turns`,kind:`column`,value:{name:`owner_launch_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`node_worker_turns`,kind:`column`,value:{name:`plan_hash`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`node_worker_turns`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`node_worker_turns`,kind:`column`,value:{name:`state`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`node_worker_turns`,kind:`column`,value:{name:`result_json`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`node_worker_turns`,kind:`column`,value:{name:`error_text`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`node_worker_turns`,kind:`column`,value:{name:`completed_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:8}},{table:`node_worker_turns`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`node_worker_turns`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`node_worker_turns`,kind:`primaryKey`,value:[`turn_id`]},{table:`node_worker_turns`,kind:`foreignKey`,value:{columns:[`owner_launch_id`],target:`node_worker_launches`,targetColumns:[`launch_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`node_worker_turns`,kind:`indexes`,value:3},{table:`node_worker_turns`,kind:`checks`,value:10},{table:`official_external_plugin_catalog_snapshots`,kind:`table`,value:null},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`feed_url`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`body`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`status`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`etag`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`last_modified`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`checksum`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`saved_at`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`trust_mode`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`trust_key_id`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`trust_signature_count`,type:`bigint`,nullable:!0,identity:!1,default:null,position:10}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`trust_threshold`,type:`bigint`,nullable:!0,identity:!1,default:null,position:11}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`trust_verified_at`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`official_external_plugin_catalog_snapshots`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:13}},{table:`official_external_plugin_catalog_snapshots`,kind:`primaryKey`,value:[`feed_url`]},{table:`official_external_plugin_catalog_snapshots`,kind:`indexes`,value:2},{table:`official_external_plugin_catalog_snapshots`,kind:`checks`,value:0},{table:`operator_approval_execution_identities`,kind:`table`,value:null},{table:`operator_approval_execution_identities`,kind:`column`,value:{name:`approval_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`operator_approval_execution_identities`,kind:`column`,value:{name:`source_context_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`operator_approval_execution_identities`,kind:`column`,value:{name:`source_execution_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`operator_approval_execution_identities`,kind:`primaryKey`,value:[`approval_id`]},{table:`operator_approval_execution_identities`,kind:`foreignKey`,value:{columns:[`approval_id`],target:`operator_approvals`,targetColumns:[`approval_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`operator_approval_execution_identities`,kind:`indexes`,value:1},{table:`operator_approval_execution_identities`,kind:`checks`,value:2},{table:`operator_approval_standing_grant_generations`,kind:`table`,value:null},{table:`operator_approval_standing_grant_generations`,kind:`column`,value:{name:`grant_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`operator_approval_standing_grant_generations`,kind:`column`,value:{name:`job_definition_generation`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`operator_approval_standing_grant_generations`,kind:`primaryKey`,value:[`grant_id`]},{table:`operator_approval_standing_grant_generations`,kind:`foreignKey`,value:{columns:[`grant_id`],target:`operator_approval_standing_grants`,targetColumns:[`grant_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`operator_approval_standing_grant_generations`,kind:`indexes`,value:1},{table:`operator_approval_standing_grant_generations`,kind:`checks`,value:1},{table:`operator_approval_standing_grants`,kind:`table`,value:null},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`grant_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`minted_by_approval_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`cron_job_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`job_config_revision`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`operation_binding`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`expires_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:8}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`revoked_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:9}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`revoked_by`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`last_used_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:11}},{table:`operator_approval_standing_grants`,kind:`column`,value:{name:`use_count`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:12}},{table:`operator_approval_standing_grants`,kind:`primaryKey`,value:[`grant_id`]},{table:`operator_approval_standing_grants`,kind:`foreignKey`,value:{columns:[`minted_by_approval_id`],target:`operator_approvals`,targetColumns:[`approval_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`operator_approval_standing_grants`,kind:`indexes`,value:2},{table:`operator_approval_standing_grants`,kind:`checks`,value:6},{table:`operator_approvals`,kind:`table`,value:null},{table:`operator_approvals`,kind:`column`,value:{name:`cursor_id`,type:`bigint`,nullable:!1,identity:!1,default:null,position:1}},{table:`operator_approvals`,kind:`column`,value:{name:`approval_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`operator_approvals`,kind:`column`,value:{name:`resolution_ref`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`operator_approvals`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`operator_approvals`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`operator_approvals`,kind:`column`,value:{name:`presentation_json`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`operator_approvals`,kind:`column`,value:{name:`requested_by_device_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`operator_approvals`,kind:`column`,value:{name:`requested_by_client_id`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`operator_approvals`,kind:`column`,value:{name:`requested_by_device_token_auth`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:9}},{table:`operator_approvals`,kind:`column`,value:{name:`reviewer_device_ids_json`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`operator_approvals`,kind:`column`,value:{name:`source_agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`operator_approvals`,kind:`column`,value:{name:`source_session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`operator_approvals`,kind:`column`,value:{name:`source_session_id`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`operator_approvals`,kind:`column`,value:{name:`source_run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`operator_approvals`,kind:`column`,value:{name:`source_tool_call_id`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`operator_approvals`,kind:`column`,value:{name:`source_tool_name`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`operator_approvals`,kind:`column`,value:{name:`audience_session_keys_json`,type:`text`,nullable:!1,identity:!1,default:null,position:17}},{table:`operator_approvals`,kind:`column`,value:{name:`runtime_epoch`,type:`text`,nullable:!1,identity:!1,default:null,position:18}},{table:`operator_approvals`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:19}},{table:`operator_approvals`,kind:`column`,value:{name:`expires_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:20}},{table:`operator_approvals`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:21}},{table:`operator_approvals`,kind:`column`,value:{name:`decision`,type:`text`,nullable:!0,identity:!1,default:null,position:22}},{table:`operator_approvals`,kind:`column`,value:{name:`terminal_reason`,type:`text`,nullable:!0,identity:!1,default:null,position:23}},{table:`operator_approvals`,kind:`column`,value:{name:`resolved_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:24}},{table:`operator_approvals`,kind:`column`,value:{name:`resolver_kind`,type:`text`,nullable:!0,identity:!1,default:null,position:25}},{table:`operator_approvals`,kind:`column`,value:{name:`resolver_id`,type:`text`,nullable:!0,identity:!1,default:null,position:26}},{table:`operator_approvals`,kind:`column`,value:{name:`consumed_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:27}},{table:`operator_approvals`,kind:`column`,value:{name:`consumed_by`,type:`text`,nullable:!0,identity:!1,default:null,position:28}},{table:`operator_approvals`,kind:`primaryKey`,value:[`approval_id`]},{table:`operator_approvals`,kind:`indexes`,value:8},{table:`operator_approvals`,kind:`checks`,value:16},{table:`outbound_media_provenance`,kind:`table`,value:null},{table:`outbound_media_provenance`,kind:`column`,value:{name:`realpath`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`outbound_media_provenance`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`outbound_media_provenance`,kind:`column`,value:{name:`version`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`outbound_media_provenance`,kind:`column`,value:{name:`sha256`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`outbound_media_provenance`,kind:`column`,value:{name:`size_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`outbound_media_provenance`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`outbound_media_provenance`,kind:`primaryKey`,value:[`realpath`]},{table:`outbound_media_provenance`,kind:`indexes`,value:1},{table:`outbound_media_provenance`,kind:`checks`,value:0},{table:`outbound_message_execution_bindings`,kind:`table`,value:null},{table:`outbound_message_execution_bindings`,kind:`column`,value:{name:`event_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`outbound_message_execution_bindings`,kind:`column`,value:{name:`context_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`outbound_message_execution_bindings`,kind:`column`,value:{name:`execution_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`outbound_message_execution_bindings`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`outbound_message_execution_bindings`,kind:`primaryKey`,value:[`event_id`]},{table:`outbound_message_execution_bindings`,kind:`foreignKey`,value:{columns:[`event_id`],target:`audit_events`,targetColumns:[`event_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`outbound_message_execution_bindings`,kind:`indexes`,value:2},{table:`outbound_message_execution_bindings`,kind:`checks`,value:3},{table:`outbound_message_progress`,kind:`table`,value:null},{table:`outbound_message_progress`,kind:`column`,value:{name:`sequence`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`outbound_message_progress`,kind:`column`,value:{name:`progress_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`outbound_message_progress`,kind:`column`,value:{name:`source_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`outbound_message_progress`,kind:`column`,value:{name:`source_sequence`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`outbound_message_progress`,kind:`column`,value:{name:`schema_version`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`outbound_message_progress`,kind:`column`,value:{name:`occurred_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`outbound_message_progress`,kind:`column`,value:{name:`action`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`outbound_message_progress`,kind:`column`,value:{name:`outcome`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`outbound_message_progress`,kind:`column`,value:{name:`actor_type`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`outbound_message_progress`,kind:`column`,value:{name:`actor_id`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`outbound_message_progress`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`outbound_message_progress`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`outbound_message_progress`,kind:`column`,value:{name:`context_id`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`outbound_message_progress`,kind:`column`,value:{name:`execution_id`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`outbound_message_progress`,kind:`column`,value:{name:`channel`,type:`text`,nullable:!1,identity:!1,default:null,position:15}},{table:`outbound_message_progress`,kind:`column`,value:{name:`conversation_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:16}},{table:`outbound_message_progress`,kind:`column`,value:{name:`duration_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:17}},{table:`outbound_message_progress`,kind:`column`,value:{name:`account_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`outbound_message_progress`,kind:`column`,value:{name:`conversation_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:19}},{table:`outbound_message_progress`,kind:`column`,value:{name:`target_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:20}},{table:`outbound_message_progress`,kind:`primaryKey`,value:[`sequence`]},{table:`outbound_message_progress`,kind:`unique`,value:[`progress_id`]},{table:`outbound_message_progress`,kind:`unique`,value:[`source_id`]},{table:`outbound_message_progress`,kind:`unique`,value:[`occurred_at`,`progress_id`]},{table:`outbound_message_progress`,kind:`indexes`,value:6},{table:`outbound_message_progress`,kind:`checks`,value:14},{table:`plugin_binding_approvals`,kind:`table`,value:null},{table:`plugin_binding_approvals`,kind:`column`,value:{name:`plugin_root`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`plugin_binding_approvals`,kind:`column`,value:{name:`channel`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`plugin_binding_approvals`,kind:`column`,value:{name:`account_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`plugin_binding_approvals`,kind:`column`,value:{name:`plugin_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`plugin_binding_approvals`,kind:`column`,value:{name:`plugin_name`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`plugin_binding_approvals`,kind:`column`,value:{name:`approved_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`plugin_binding_approvals`,kind:`primaryKey`,value:[`plugin_root`,`channel`,`account_id`]},{table:`plugin_binding_approvals`,kind:`indexes`,value:2},{table:`plugin_binding_approvals`,kind:`checks`,value:0},{table:`plugin_blob_entries`,kind:`table`,value:null},{table:`plugin_blob_entries`,kind:`column`,value:{name:`plugin_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`plugin_blob_entries`,kind:`column`,value:{name:`namespace`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`plugin_blob_entries`,kind:`column`,value:{name:`entry_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`plugin_blob_entries`,kind:`column`,value:{name:`metadata_json`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`plugin_blob_entries`,kind:`column`,value:{name:`blob`,type:`bytea`,nullable:!1,identity:!1,default:null,position:5}},{table:`plugin_blob_entries`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`plugin_blob_entries`,kind:`column`,value:{name:`expires_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:7}},{table:`plugin_blob_entries`,kind:`primaryKey`,value:[`plugin_id`,`namespace`,`entry_key`]},{table:`plugin_blob_entries`,kind:`indexes`,value:3},{table:`plugin_blob_entries`,kind:`checks`,value:0},{table:`plugin_state_entries`,kind:`table`,value:null},{table:`plugin_state_entries`,kind:`column`,value:{name:`plugin_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`plugin_state_entries`,kind:`column`,value:{name:`namespace`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`plugin_state_entries`,kind:`column`,value:{name:`entry_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`plugin_state_entries`,kind:`column`,value:{name:`value_json`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`plugin_state_entries`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`plugin_state_entries`,kind:`column`,value:{name:`expires_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:6}},{table:`plugin_state_entries`,kind:`primaryKey`,value:[`plugin_id`,`namespace`,`entry_key`]},{table:`plugin_state_entries`,kind:`indexes`,value:3},{table:`plugin_state_entries`,kind:`checks`,value:0},{table:`projects`,kind:`table`,value:null},{table:`projects`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`projects`,kind:`column`,value:{name:`display_name`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`projects`,kind:`column`,value:{name:`repo_root`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`projects`,kind:`column`,value:{name:`origin_url`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`projects`,kind:`column`,value:{name:`source`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`projects`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`projects`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`projects`,kind:`primaryKey`,value:[`id`]},{table:`projects`,kind:`indexes`,value:1},{table:`projects`,kind:`checks`,value:1},{table:`sandbox_persistent_execs`,kind:`table`,value:null},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`owner_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`source_identity`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`attempt_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`owner_json`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`backend_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`backend_target_json`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`workspace_binding_json`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`container_id`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`container_name`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`container_started_at`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`revision`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`phase`,type:`text`,nullable:!1,identity:!1,default:null,position:12}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`receipt_json`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`error`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:15}},{table:`sandbox_persistent_execs`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:16}},{table:`sandbox_persistent_execs`,kind:`primaryKey`,value:[`owner_key`]},{table:`sandbox_persistent_execs`,kind:`unique`,value:[`attempt_id`]},{table:`sandbox_persistent_execs`,kind:`indexes`,value:5},{table:`sandbox_persistent_execs`,kind:`checks`,value:4},{table:`sandbox_registry_entries`,kind:`table`,value:null},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`registry_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`container_name`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`backend_id`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`runtime_label`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`image`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:7}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`last_used_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:8}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`config_label_kind`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`config_hash`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`cdp_port`,type:`bigint`,nullable:!0,identity:!1,default:null,position:11}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`no_vnc_port`,type:`bigint`,nullable:!0,identity:!1,default:null,position:12}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`entry_json`,type:`text`,nullable:!1,identity:!1,default:null,position:13}},{table:`sandbox_registry_entries`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:14}},{table:`sandbox_registry_entries`,kind:`primaryKey`,value:[`registry_kind`,`container_name`]},{table:`sandbox_registry_entries`,kind:`indexes`,value:4},{table:`sandbox_registry_entries`,kind:`checks`,value:0},{table:`schema_meta`,kind:`table`,value:null},{table:`schema_meta`,kind:`column`,value:{name:`meta_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`schema_meta`,kind:`column`,value:{name:`role`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`schema_meta`,kind:`column`,value:{name:`schema_version`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`schema_meta`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`schema_meta`,kind:`column`,value:{name:`app_version`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`schema_meta`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`schema_meta`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`schema_meta`,kind:`primaryKey`,value:[`meta_key`]},{table:`schema_meta`,kind:`indexes`,value:1},{table:`schema_meta`,kind:`checks`,value:0},{table:`secret_store_entries`,kind:`table`,value:null},{table:`secret_store_entries`,kind:`column`,value:{name:`scope_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`secret_store_entries`,kind:`column`,value:{name:`scope_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`secret_store_entries`,kind:`column`,value:{name:`name`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`secret_store_entries`,kind:`column`,value:{name:`value`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`secret_store_entries`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`secret_store_entries`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`secret_store_entries`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`secret_store_entries`,kind:`column`,value:{name:`updated_by`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`secret_store_entries`,kind:`column`,value:{name:`deleted_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:9}},{table:`secret_store_entries`,kind:`column`,value:{name:`allowed_hosts`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`secret_store_entries`,kind:`primaryKey`,value:[`scope_kind`,`scope_id`,`name`]},{table:`secret_store_entries`,kind:`indexes`,value:2},{table:`secret_store_entries`,kind:`checks`,value:5},{table:`session_groups`,kind:`table`,value:null},{table:`session_groups`,kind:`column`,value:{name:`name`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_groups`,kind:`column`,value:{name:`position`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_groups`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_groups`,kind:`column`,value:{name:`cwd`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`session_groups`,kind:`column`,value:{name:`worktree`,type:`bigint`,nullable:!0,identity:!1,default:null,position:5}},{table:`session_groups`,kind:`primaryKey`,value:[`name`]},{table:`session_groups`,kind:`indexes`,value:1},{table:`session_groups`,kind:`checks`,value:0},{table:`session_repository_workspaces`,kind:`table`,value:null},{table:`session_repository_workspaces`,kind:`column`,value:{name:`workspace_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`url`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`requested_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`run_setup_script`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:6}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`base_commit`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`base_manifest_hash`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`branch`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`checkpoint_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`manifest_hash`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`revision`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:13}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:14}},{table:`session_repository_workspaces`,kind:`column`,value:{name:`disk_authority_json`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`session_repository_workspaces`,kind:`primaryKey`,value:[`workspace_id`]},{table:`session_repository_workspaces`,kind:`unique`,value:[`agent_id`,`session_key`]},{table:`session_repository_workspaces`,kind:`indexes`,value:2},{table:`session_repository_workspaces`,kind:`checks`,value:11},{table:`session_state_events`,kind:`table`,value:null},{table:`session_state_events`,kind:`column`,value:{name:`sequence`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`session_state_events`,kind:`column`,value:{name:`dedupe_key`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`session_state_events`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_state_events`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`session_state_events`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`session_state_events`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`session_state_events`,kind:`column`,value:{name:`actor_type`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`session_state_events`,kind:`column`,value:{name:`actor_id`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`session_state_events`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`session_state_events`,kind:`column`,value:{name:`occurred_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`session_state_events`,kind:`column`,value:{name:`summary`,type:`text`,nullable:!1,identity:!1,default:null,position:11}},{table:`session_state_events`,kind:`column`,value:{name:`payload_json`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`session_state_events`,kind:`primaryKey`,value:[`sequence`]},{table:`session_state_events`,kind:`unique`,value:[`dedupe_key`]},{table:`session_state_events`,kind:`indexes`,value:4},{table:`session_state_events`,kind:`checks`,value:0},{table:`session_state_heads`,kind:`table`,value:null},{table:`session_state_heads`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_state_heads`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_state_heads`,kind:`column`,value:{name:`last_sequence`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_state_heads`,kind:`column`,value:{name:`pruned_max_sequence`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:4}},{table:`session_state_heads`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`session_state_heads`,kind:`primaryKey`,value:[`session_key`,`agent_id`]},{table:`session_state_heads`,kind:`indexes`,value:1},{table:`session_state_heads`,kind:`checks`,value:0},{table:`session_upstream_links`,kind:`table`,value:null},{table:`session_upstream_links`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_upstream_links`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_upstream_links`,kind:`column`,value:{name:`catalog_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_upstream_links`,kind:`column`,value:{name:`host_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`session_upstream_links`,kind:`column`,value:{name:`thread_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`session_upstream_links`,kind:`column`,value:{name:`upstream_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`session_upstream_links`,kind:`column`,value:{name:`upstream_ref_json`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`session_upstream_links`,kind:`column`,value:{name:`last_marker_json`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`session_upstream_links`,kind:`column`,value:{name:`last_scanned_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:9}},{table:`session_upstream_links`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`session_upstream_links`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`session_upstream_links`,kind:`primaryKey`,value:[`session_key`,`agent_id`]},{table:`session_upstream_links`,kind:`indexes`,value:2},{table:`session_upstream_links`,kind:`checks`,value:0},{table:`session_watch_cursors`,kind:`table`,value:null},{table:`session_watch_cursors`,kind:`column`,value:{name:`watcher_session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_watch_cursors`,kind:`column`,value:{name:`watcher_store_path`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`session_watch_cursors`,kind:`column`,value:{name:`target_session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_watch_cursors`,kind:`column`,value:{name:`last_seen_sequence`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:4}},{table:`session_watch_cursors`,kind:`column`,value:{name:`notified_sequence`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:5}},{table:`session_watch_cursors`,kind:`column`,value:{name:`material_sequence`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:6}},{table:`session_watch_cursors`,kind:`column`,value:{name:`provenance`,type:`text`,nullable:!1,identity:!1,default:`'explicit'`,position:7}},{table:`session_watch_cursors`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`session_watch_cursors`,kind:`primaryKey`,value:[`watcher_session_key`,`target_session_key`]},{table:`session_watch_cursors`,kind:`indexes`,value:2},{table:`session_watch_cursors`,kind:`checks`,value:1},{table:`skill_library_entries`,kind:`table`,value:null},{table:`skill_library_entries`,kind:`column`,value:{name:`skill_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`skill_library_entries`,kind:`column`,value:{name:`owner_profile_id`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`skill_library_entries`,kind:`column`,value:{name:`author_profile_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`skill_library_entries`,kind:`column`,value:{name:`slug`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`skill_library_entries`,kind:`column`,value:{name:`current_revision`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`skill_library_entries`,kind:`column`,value:{name:`shared`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`skill_library_entries`,kind:`column`,value:{name:`enabled`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`skill_library_entries`,kind:`column`,value:{name:`removed`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`skill_library_entries`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`skill_library_entries`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`skill_library_entries`,kind:`primaryKey`,value:[`skill_id`]},{table:`skill_library_entries`,kind:`indexes`,value:1},{table:`skill_library_entries`,kind:`checks`,value:0},{table:`skill_library_events`,kind:`table`,value:null},{table:`skill_library_events`,kind:`column`,value:{name:`event_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`skill_library_events`,kind:`column`,value:{name:`skill_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`skill_library_events`,kind:`column`,value:{name:`revision`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`skill_library_events`,kind:`column`,value:{name:`action`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`skill_library_events`,kind:`column`,value:{name:`actor_profile_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`skill_library_events`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`skill_library_events`,kind:`primaryKey`,value:[`event_id`]},{table:`skill_library_events`,kind:`indexes`,value:1},{table:`skill_library_events`,kind:`checks`,value:0},{table:`skill_library_revisions`,kind:`table`,value:null},{table:`skill_library_revisions`,kind:`column`,value:{name:`skill_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`skill_library_revisions`,kind:`column`,value:{name:`revision`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`skill_library_revisions`,kind:`column`,value:{name:`description`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`skill_library_revisions`,kind:`column`,value:{name:`files_json`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`skill_library_revisions`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`skill_library_revisions`,kind:`primaryKey`,value:[`skill_id`,`revision`]},{table:`skill_library_revisions`,kind:`indexes`,value:1},{table:`skill_library_revisions`,kind:`checks`,value:0},{table:`skill_library_uploads`,kind:`table`,value:null},{table:`skill_library_uploads`,kind:`column`,value:{name:`upload_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`skill_library_uploads`,kind:`column`,value:{name:`owner_profile_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`skill_library_uploads`,kind:`column`,value:{name:`slug`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`skill_library_uploads`,kind:`column`,value:{name:`size_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`skill_library_uploads`,kind:`column`,value:{name:`sha256`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`skill_library_uploads`,kind:`column`,value:{name:`archive_blob`,type:`bytea`,nullable:!1,identity:!1,default:null,position:6}},{table:`skill_library_uploads`,kind:`column`,value:{name:`expires_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`skill_library_uploads`,kind:`column`,value:{name:`published_skill_id`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`skill_library_uploads`,kind:`primaryKey`,value:[`upload_id`]},{table:`skill_library_uploads`,kind:`indexes`,value:1},{table:`skill_library_uploads`,kind:`checks`,value:0},{table:`skill_upload_chunks`,kind:`table`,value:null},{table:`skill_upload_chunks`,kind:`column`,value:{name:`upload_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`skill_upload_chunks`,kind:`column`,value:{name:`byte_offset`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`skill_upload_chunks`,kind:`column`,value:{name:`size_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`skill_upload_chunks`,kind:`column`,value:{name:`chunk_blob`,type:`bytea`,nullable:!1,identity:!1,default:null,position:4}},{table:`skill_upload_chunks`,kind:`primaryKey`,value:[`upload_id`,`byte_offset`]},{table:`skill_upload_chunks`,kind:`foreignKey`,value:{columns:[`upload_id`],target:`skill_uploads`,targetColumns:[`upload_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`skill_upload_chunks`,kind:`indexes`,value:1},{table:`skill_upload_chunks`,kind:`checks`,value:3},{table:`skill_uploads`,kind:`table`,value:null},{table:`skill_uploads`,kind:`column`,value:{name:`upload_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`skill_uploads`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`skill_uploads`,kind:`column`,value:{name:`slug`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`skill_uploads`,kind:`column`,value:{name:`force`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`skill_uploads`,kind:`column`,value:{name:`size_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`skill_uploads`,kind:`column`,value:{name:`sha256`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`skill_uploads`,kind:`column`,value:{name:`actual_sha256`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`skill_uploads`,kind:`column`,value:{name:`received_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`skill_uploads`,kind:`column`,value:{name:`archive_blob`,type:`bytea`,nullable:!1,identity:!1,default:null,position:9}},{table:`skill_uploads`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`skill_uploads`,kind:`column`,value:{name:`expires_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`skill_uploads`,kind:`column`,value:{name:`committed`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`skill_uploads`,kind:`column`,value:{name:`committed_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`skill_uploads`,kind:`column`,value:{name:`idempotency_key_hash`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`skill_uploads`,kind:`primaryKey`,value:[`upload_id`]},{table:`skill_uploads`,kind:`unique`,value:[`idempotency_key_hash`]},{table:`skill_uploads`,kind:`indexes`,value:4},{table:`skill_uploads`,kind:`checks`,value:0},{table:`skill_usage`,kind:`table`,value:null},{table:`skill_usage`,kind:`column`,value:{name:`skill_file`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`skill_usage`,kind:`column`,value:{name:`skill_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`skill_usage`,kind:`column`,value:{name:`skill_name`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`skill_usage`,kind:`column`,value:{name:`skill_source`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`skill_usage`,kind:`column`,value:{name:`first_used_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`skill_usage`,kind:`column`,value:{name:`last_used_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`skill_usage`,kind:`column`,value:{name:`use_count`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`skill_usage`,kind:`column`,value:{name:`last_agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`skill_usage`,kind:`primaryKey`,value:[`skill_file`]},{table:`skill_usage`,kind:`indexes`,value:1},{table:`skill_usage`,kind:`checks`,value:0},{table:`skill_workshop_changes`,kind:`table`,value:null},{table:`skill_workshop_changes`,kind:`column`,value:{name:`cursor_id`,type:`bigint`,nullable:!1,identity:!1,default:null,position:1}},{table:`skill_workshop_changes`,kind:`column`,value:{name:`change_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`skill_workshop_changes`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`skill_workshop_changes`,kind:`column`,value:{name:`skill_name`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`skill_workshop_changes`,kind:`column`,value:{name:`action`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`skill_workshop_changes`,kind:`column`,value:{name:`actor`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`skill_workshop_changes`,kind:`column`,value:{name:`summary`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`skill_workshop_changes`,kind:`column`,value:{name:`version_id`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`skill_workshop_changes`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`skill_workshop_changes`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`skill_workshop_changes`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`skill_workshop_changes`,kind:`primaryKey`,value:[`change_id`]},{table:`skill_workshop_changes`,kind:`indexes`,value:3},{table:`skill_workshop_changes`,kind:`checks`,value:2},{table:`state_leases`,kind:`table`,value:null},{table:`state_leases`,kind:`column`,value:{name:`scope`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`state_leases`,kind:`column`,value:{name:`lease_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`state_leases`,kind:`column`,value:{name:`owner`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`state_leases`,kind:`column`,value:{name:`expires_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:4}},{table:`state_leases`,kind:`column`,value:{name:`heartbeat_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:5}},{table:`state_leases`,kind:`column`,value:{name:`payload_json`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`state_leases`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`state_leases`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`state_leases`,kind:`primaryKey`,value:[`scope`,`lease_key`]},{table:`state_leases`,kind:`indexes`,value:3},{table:`state_leases`,kind:`checks`,value:0},{table:`subagent_runs`,kind:`table`,value:null},{table:`subagent_runs`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`subagent_runs`,kind:`column`,value:{name:`child_session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`subagent_runs`,kind:`column`,value:{name:`controller_session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`subagent_runs`,kind:`column`,value:{name:`controller_store_path`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`subagent_runs`,kind:`column`,value:{name:`requester_session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`subagent_runs`,kind:`column`,value:{name:`requester_store_path`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`subagent_runs`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`subagent_runs`,kind:`column`,value:{name:`payload_json`,type:`text`,nullable:!1,identity:!1,default:`'{}'`,position:8}},{table:`subagent_runs`,kind:`primaryKey`,value:[`run_id`]},{table:`subagent_runs`,kind:`indexes`,value:4},{table:`subagent_runs`,kind:`checks`,value:0},{table:`task_delivery_state`,kind:`table`,value:null},{table:`task_delivery_state`,kind:`column`,value:{name:`task_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`task_delivery_state`,kind:`column`,value:{name:`requester_origin_json`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`task_delivery_state`,kind:`column`,value:{name:`last_notified_event_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:3}},{table:`task_delivery_state`,kind:`primaryKey`,value:[`task_id`]},{table:`task_delivery_state`,kind:`foreignKey`,value:{columns:[`task_id`],target:`task_runs`,targetColumns:[`task_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`task_delivery_state`,kind:`indexes`,value:1},{table:`task_delivery_state`,kind:`checks`,value:0},{table:`task_runs`,kind:`table`,value:null},{table:`task_runs`,kind:`column`,value:{name:`task_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`task_runs`,kind:`column`,value:{name:`runtime`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`task_runs`,kind:`column`,value:{name:`task_kind`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`task_runs`,kind:`column`,value:{name:`source_id`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`task_runs`,kind:`column`,value:{name:`requester_session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`task_runs`,kind:`column`,value:{name:`owner_key`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`task_runs`,kind:`column`,value:{name:`scope_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`task_runs`,kind:`column`,value:{name:`child_session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`task_runs`,kind:`column`,value:{name:`parent_flow_id`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`task_runs`,kind:`column`,value:{name:`parent_task_id`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`task_runs`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`task_runs`,kind:`column`,value:{name:`requester_agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`task_runs`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`task_runs`,kind:`column`,value:{name:`execution_owner_host`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`task_runs`,kind:`column`,value:{name:`execution_owner_pid`,type:`bigint`,nullable:!0,identity:!1,default:null,position:15}},{table:`task_runs`,kind:`column`,value:{name:`execution_owner_start_identity`,type:`bigint`,nullable:!0,identity:!1,default:null,position:16}},{table:`task_runs`,kind:`column`,value:{name:`label`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`task_runs`,kind:`column`,value:{name:`task`,type:`text`,nullable:!1,identity:!1,default:null,position:18}},{table:`task_runs`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:19}},{table:`task_runs`,kind:`column`,value:{name:`delivery_status`,type:`text`,nullable:!1,identity:!1,default:null,position:20}},{table:`task_runs`,kind:`column`,value:{name:`notify_policy`,type:`text`,nullable:!1,identity:!1,default:null,position:21}},{table:`task_runs`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:22}},{table:`task_runs`,kind:`column`,value:{name:`started_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:23}},{table:`task_runs`,kind:`column`,value:{name:`ended_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:24}},{table:`task_runs`,kind:`column`,value:{name:`last_event_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:25}},{table:`task_runs`,kind:`column`,value:{name:`cleanup_after`,type:`bigint`,nullable:!0,identity:!1,default:null,position:26}},{table:`task_runs`,kind:`column`,value:{name:`tool_use_count`,type:`bigint`,nullable:!0,identity:!1,default:null,position:27}},{table:`task_runs`,kind:`column`,value:{name:`last_tool_name`,type:`text`,nullable:!0,identity:!1,default:null,position:28}},{table:`task_runs`,kind:`column`,value:{name:`error`,type:`text`,nullable:!0,identity:!1,default:null,position:29}},{table:`task_runs`,kind:`column`,value:{name:`progress_summary`,type:`text`,nullable:!0,identity:!1,default:null,position:30}},{table:`task_runs`,kind:`column`,value:{name:`terminal_summary`,type:`text`,nullable:!0,identity:!1,default:null,position:31}},{table:`task_runs`,kind:`column`,value:{name:`terminal_outcome`,type:`text`,nullable:!0,identity:!1,default:null,position:32}},{table:`task_runs`,kind:`column`,value:{name:`detail_json`,type:`text`,nullable:!0,identity:!1,default:null,position:33}},{table:`task_runs`,kind:`primaryKey`,value:[`task_id`]},{table:`task_runs`,kind:`indexes`,value:4},{table:`task_runs`,kind:`checks`,value:0},{table:`template_cron_refs`,kind:`table`,value:null},{table:`template_cron_refs`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`template_cron_refs`,kind:`column`,value:{name:`manifest_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`template_cron_refs`,kind:`column`,value:{name:`schema_version`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`template_cron_refs`,kind:`column`,value:{name:`declaration_key`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`template_cron_refs`,kind:`column`,value:{name:`scheduler_job_id`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`template_cron_refs`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`template_cron_refs`,kind:`column`,value:{name:`job_json`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`template_cron_refs`,kind:`column`,value:{name:`error`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`template_cron_refs`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`template_cron_refs`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`template_cron_refs`,kind:`primaryKey`,value:[`agent_id`,`manifest_id`]},{table:`template_cron_refs`,kind:`unique`,value:[`declaration_key`]},{table:`template_cron_refs`,kind:`unique`,value:[`scheduler_job_id`]},{table:`template_cron_refs`,kind:`indexes`,value:3},{table:`template_cron_refs`,kind:`checks`,value:0},{table:`template_installs`,kind:`table`,value:null},{table:`template_installs`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`template_installs`,kind:`column`,value:{name:`schema_version`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`template_installs`,kind:`column`,value:{name:`source_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`template_installs`,kind:`column`,value:{name:`template_name`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`template_installs`,kind:`column`,value:{name:`template_version`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`template_installs`,kind:`column`,value:{name:`package_root`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`template_installs`,kind:`column`,value:{name:`manifest_path`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`template_installs`,kind:`column`,value:{name:`integrity_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`template_installs`,kind:`column`,value:{name:`integrity`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`template_installs`,kind:`column`,value:{name:`source_byte_length`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`template_installs`,kind:`column`,value:{name:`manifest_schema_version`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`template_installs`,kind:`column`,value:{name:`plan_integrity`,type:`text`,nullable:!1,identity:!1,default:null,position:12}},{table:`template_installs`,kind:`column`,value:{name:`workspace`,type:`text`,nullable:!1,identity:!1,default:null,position:13}},{table:`template_installs`,kind:`column`,value:{name:`agent_config_digest`,type:`text`,nullable:!1,identity:!1,default:null,position:14}},{table:`template_installs`,kind:`column`,value:{name:`agent_owned_paths_json`,type:`text`,nullable:!1,identity:!1,default:null,position:15}},{table:`template_installs`,kind:`column`,value:{name:`bootstrap_source_path`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`template_installs`,kind:`column`,value:{name:`bootstrap_content_digest`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`template_installs`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:18}},{table:`template_installs`,kind:`column`,value:{name:`added_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:19}},{table:`template_installs`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:20}},{table:`template_installs`,kind:`primaryKey`,value:[`agent_id`]},{table:`template_installs`,kind:`unique`,value:[`workspace`]},{table:`template_installs`,kind:`indexes`,value:2},{table:`template_installs`,kind:`checks`,value:1},{table:`template_mcp_server_refs`,kind:`table`,value:null},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`name`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`schema_version`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`config_digest`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`relationship`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`origin`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`independent_owner`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:7}},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`error`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`template_mcp_server_refs`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`template_mcp_server_refs`,kind:`primaryKey`,value:[`agent_id`,`name`]},{table:`template_mcp_server_refs`,kind:`indexes`,value:1},{table:`template_mcp_server_refs`,kind:`checks`,value:3},{table:`template_package_refs`,kind:`table`,value:null},{table:`template_package_refs`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`template_package_refs`,kind:`column`,value:{name:`package_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`template_package_refs`,kind:`column`,value:{name:`package_source`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`template_package_refs`,kind:`column`,value:{name:`package_ref`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`template_package_refs`,kind:`column`,value:{name:`package_version`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`template_package_refs`,kind:`column`,value:{name:`package_integrity`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`template_package_refs`,kind:`column`,value:{name:`schema_version`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`template_package_refs`,kind:`column`,value:{name:`template_name`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`template_package_refs`,kind:`column`,value:{name:`package_status`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`template_package_refs`,kind:`column`,value:{name:`relationship`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`template_package_refs`,kind:`column`,value:{name:`origin`,type:`text`,nullable:!1,identity:!1,default:null,position:11}},{table:`template_package_refs`,kind:`column`,value:{name:`independent_owner`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`template_package_refs`,kind:`column`,value:{name:`extension_id`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`template_package_refs`,kind:`column`,value:{name:`extension_format`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`template_package_refs`,kind:`column`,value:{name:`extension_detected_format`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`template_package_refs`,kind:`column`,value:{name:`extension_mapped_json`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`template_package_refs`,kind:`column`,value:{name:`extension_unavailable_json`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`template_package_refs`,kind:`column`,value:{name:`extension_adapter_identity`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`template_package_refs`,kind:`column`,value:{name:`installed_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:19}},{table:`template_package_refs`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:20}},{table:`template_package_refs`,kind:`primaryKey`,value:[`agent_id`,`package_kind`,`package_source`,`package_ref`,`package_version`]},{table:`template_package_refs`,kind:`indexes`,value:1},{table:`template_package_refs`,kind:`checks`,value:3},{table:`template_workspace_files`,kind:`table`,value:null},{table:`template_workspace_files`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`template_workspace_files`,kind:`column`,value:{name:`target_path`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`template_workspace_files`,kind:`column`,value:{name:`schema_version`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`template_workspace_files`,kind:`column`,value:{name:`workspace`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`template_workspace_files`,kind:`column`,value:{name:`source_path`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`template_workspace_files`,kind:`column`,value:{name:`content_digest`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`template_workspace_files`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`template_workspace_files`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`template_workspace_files`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`template_workspace_files`,kind:`primaryKey`,value:[`agent_id`,`target_path`]},{table:`template_workspace_files`,kind:`indexes`,value:1},{table:`template_workspace_files`,kind:`checks`,value:0},{table:`update_runs`,kind:`table`,value:null},{table:`update_runs`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`update_runs`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`update_runs`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`update_runs`,kind:`column`,value:{name:`trigger`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`update_runs`,kind:`column`,value:{name:`phase`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`update_runs`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`update_runs`,kind:`column`,value:{name:`reason`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`update_runs`,kind:`column`,value:{name:`origin_json`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`update_runs`,kind:`column`,value:{name:`target_json`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`update_runs`,kind:`column`,value:{name:`before_json`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`update_runs`,kind:`column`,value:{name:`after_json`,type:`text`,nullable:!1,identity:!1,default:null,position:11}},{table:`update_runs`,kind:`column`,value:{name:`steps_json`,type:`text`,nullable:!1,identity:!1,default:null,position:12}},{table:`update_runs`,kind:`column`,value:{name:`verification_json`,type:`text`,nullable:!1,identity:!1,default:null,position:13}},{table:`update_runs`,kind:`column`,value:{name:`repair_json`,type:`text`,nullable:!1,identity:!1,default:null,position:14}},{table:`update_runs`,kind:`column`,value:{name:`confirmed_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:15}},{table:`update_runs`,kind:`column`,value:{name:`finished_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:16}},{table:`update_runs`,kind:`column`,value:{name:`downtime_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:17}},{table:`update_runs`,kind:`primaryKey`,value:[`run_id`]},{table:`update_runs`,kind:`indexes`,value:3},{table:`update_runs`,kind:`checks`,value:11},{table:`user_background_images`,kind:`table`,value:null},{table:`user_background_images`,kind:`column`,value:{name:`profile_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`user_background_images`,kind:`column`,value:{name:`asset_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`user_background_images`,kind:`column`,value:{name:`image`,type:`bytea`,nullable:!1,identity:!1,default:null,position:3}},{table:`user_background_images`,kind:`column`,value:{name:`width`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`user_background_images`,kind:`column`,value:{name:`height`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`user_background_images`,kind:`primaryKey`,value:[`profile_id`]},{table:`user_background_images`,kind:`unique`,value:[`asset_id`]},{table:`user_background_images`,kind:`foreignKey`,value:{columns:[`profile_id`],target:`user_profiles`,targetColumns:[`id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`user_background_images`,kind:`indexes`,value:2},{table:`user_background_images`,kind:`checks`,value:3},{table:`user_preferences`,kind:`table`,value:null},{table:`user_preferences`,kind:`column`,value:{name:`profile_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`user_preferences`,kind:`column`,value:{name:`pref_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`user_preferences`,kind:`column`,value:{name:`value_json`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`user_preferences`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`user_preferences`,kind:`primaryKey`,value:[`profile_id`,`pref_key`]},{table:`user_preferences`,kind:`indexes`,value:1},{table:`user_preferences`,kind:`checks`,value:0},{table:`user_profile_emails`,kind:`table`,value:null},{table:`user_profile_emails`,kind:`column`,value:{name:`email`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`user_profile_emails`,kind:`column`,value:{name:`profile_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`user_profile_emails`,kind:`column`,value:{name:`binding_id`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`user_profile_emails`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`user_profile_emails`,kind:`primaryKey`,value:[`email`]},{table:`user_profile_emails`,kind:`indexes`,value:2},{table:`user_profile_emails`,kind:`checks`,value:0},{table:`user_profile_identities`,kind:`table`,value:null},{table:`user_profile_identities`,kind:`column`,value:{name:`provider`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`user_profile_identities`,kind:`column`,value:{name:`subject`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`user_profile_identities`,kind:`column`,value:{name:`profile_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`user_profile_identities`,kind:`column`,value:{name:`canonical_login`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`user_profile_identities`,kind:`column`,value:{name:`verified_email_json`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`user_profile_identities`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`user_profile_identities`,kind:`column`,value:{name:`authorization_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`user_profile_identities`,kind:`column`,value:{name:`authorization_basis_json`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`user_profile_identities`,kind:`primaryKey`,value:[`provider`,`subject`]},{table:`user_profile_identities`,kind:`indexes`,value:3},{table:`user_profile_identities`,kind:`checks`,value:0},{table:`user_profiles`,kind:`table`,value:null},{table:`user_profiles`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`user_profiles`,kind:`column`,value:{name:`display_name`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`user_profiles`,kind:`column`,value:{name:`primary_github_account_id`,type:`bigint`,nullable:!0,identity:!1,default:null,position:3}},{table:`user_profiles`,kind:`column`,value:{name:`avatar`,type:`bytea`,nullable:!0,identity:!1,default:null,position:4}},{table:`user_profiles`,kind:`column`,value:{name:`avatar_mime`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`user_profiles`,kind:`column`,value:{name:`avatar_sha256`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`user_profiles`,kind:`column`,value:{name:`merged_into`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`user_profiles`,kind:`column`,value:{name:`role`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`user_profiles`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`user_profiles`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`user_profiles`,kind:`primaryKey`,value:[`id`]},{table:`user_profiles`,kind:`indexes`,value:1},{table:`user_profiles`,kind:`checks`,value:0},{table:`web_push_approval_deliveries`,kind:`table`,value:null},{table:`web_push_approval_deliveries`,kind:`column`,value:{name:`approval_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`web_push_approval_deliveries`,kind:`column`,value:{name:`subscription_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`web_push_approval_deliveries`,kind:`column`,value:{name:`device_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`web_push_approval_deliveries`,kind:`column`,value:{name:`user_profile_id`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`web_push_approval_deliveries`,kind:`column`,value:{name:`prepared_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`web_push_approval_deliveries`,kind:`primaryKey`,value:[`approval_id`,`subscription_id`]},{table:`web_push_approval_deliveries`,kind:`foreignKey`,value:{columns:[`subscription_id`],target:`web_push_subscriptions`,targetColumns:[`subscription_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`web_push_approval_deliveries`,kind:`foreignKey`,value:{columns:[`approval_id`],target:`operator_approvals`,targetColumns:[`approval_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`web_push_approval_deliveries`,kind:`indexes`,value:2},{table:`web_push_approval_deliveries`,kind:`checks`,value:0},{table:`web_push_subscriptions`,kind:`table`,value:null},{table:`web_push_subscriptions`,kind:`column`,value:{name:`endpoint_hash`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`web_push_subscriptions`,kind:`column`,value:{name:`subscription_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`web_push_subscriptions`,kind:`column`,value:{name:`endpoint`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`web_push_subscriptions`,kind:`column`,value:{name:`p256dh`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`web_push_subscriptions`,kind:`column`,value:{name:`auth`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`web_push_subscriptions`,kind:`column`,value:{name:`device_id`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`web_push_subscriptions`,kind:`column`,value:{name:`user_profile_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`web_push_subscriptions`,kind:`column`,value:{name:`preferences_json`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`web_push_subscriptions`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`web_push_subscriptions`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`web_push_subscriptions`,kind:`primaryKey`,value:[`endpoint_hash`]},{table:`web_push_subscriptions`,kind:`unique`,value:[`subscription_id`]},{table:`web_push_subscriptions`,kind:`indexes`,value:3},{table:`web_push_subscriptions`,kind:`checks`,value:0},{table:`worker_environment_credentials`,kind:`table`,value:null},{table:`worker_environment_credentials`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_environment_credentials`,kind:`column`,value:{name:`credential_hash`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_environment_credentials`,kind:`column`,value:{name:`bundle_hash`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_environment_credentials`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`worker_environment_credentials`,kind:`column`,value:{name:`rpc_set_version`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_environment_credentials`,kind:`column`,value:{name:`owner_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`worker_environment_credentials`,kind:`column`,value:{name:`expires_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`worker_environment_credentials`,kind:`column`,value:{name:`delivered_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:8}},{table:`worker_environment_credentials`,kind:`primaryKey`,value:[`environment_id`]},{table:`worker_environment_credentials`,kind:`unique`,value:[`credential_hash`]},{table:`worker_environment_credentials`,kind:`foreignKey`,value:{columns:[`environment_id`],target:`worker_environments`,targetColumns:[`environment_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`worker_environment_credentials`,kind:`indexes`,value:2},{table:`worker_environment_credentials`,kind:`checks`,value:4},{table:`worker_environment_session_attachments`,kind:`table`,value:null},{table:`worker_environment_session_attachments`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_environment_session_attachments`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_environment_session_attachments`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_environment_session_attachments`,kind:`column`,value:{name:`session_lifecycle_revision`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`worker_environment_session_attachments`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_environment_session_attachments`,kind:`column`,value:{name:`generation`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`worker_environment_session_attachments`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`worker_environment_session_attachments`,kind:`column`,value:{name:`last_used_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`worker_environment_session_attachments`,kind:`column`,value:{name:`closed_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:9}},{table:`worker_environment_session_attachments`,kind:`primaryKey`,value:[`session_id`]},{table:`worker_environment_session_attachments`,kind:`unique`,value:[`environment_id`]},{table:`worker_environment_session_attachments`,kind:`foreignKey`,value:{columns:[`environment_id`],target:`worker_environments`,targetColumns:[`environment_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`worker_environment_session_attachments`,kind:`indexes`,value:3},{table:`worker_environment_session_attachments`,kind:`checks`,value:1},{table:`worker_environment_ssh_fallback_ports`,kind:`table`,value:null},{table:`worker_environment_ssh_fallback_ports`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_environment_ssh_fallback_ports`,kind:`column`,value:{name:`position`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_environment_ssh_fallback_ports`,kind:`column`,value:{name:`port`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_environment_ssh_fallback_ports`,kind:`primaryKey`,value:[`environment_id`,`position`]},{table:`worker_environment_ssh_fallback_ports`,kind:`unique`,value:[`environment_id`,`port`]},{table:`worker_environment_ssh_fallback_ports`,kind:`foreignKey`,value:{columns:[`environment_id`],target:`worker_environments`,targetColumns:[`environment_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`worker_environment_ssh_fallback_ports`,kind:`indexes`,value:2},{table:`worker_environment_ssh_fallback_ports`,kind:`checks`,value:2},{table:`worker_environments`,kind:`table`,value:null},{table:`worker_environments`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_environments`,kind:`column`,value:{name:`provider_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_environments`,kind:`column`,value:{name:`profile_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_environments`,kind:`column`,value:{name:`profile_snapshot_json`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`worker_environments`,kind:`column`,value:{name:`last_activated_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:5}},{table:`worker_environments`,kind:`column`,value:{name:`preparation_key`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`worker_environments`,kind:`column`,value:{name:`preparation_purpose`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`worker_environments`,kind:`column`,value:{name:`preparation_demand_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:8}},{table:`worker_environments`,kind:`column`,value:{name:`preparation_expires_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:9}},{table:`worker_environments`,kind:`column`,value:{name:`preparation_consumed_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:10}},{table:`worker_environments`,kind:`column`,value:{name:`provision_operation_id`,type:`text`,nullable:!1,identity:!1,default:null,position:11}},{table:`worker_environments`,kind:`column`,value:{name:`lease_id`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`worker_environments`,kind:`column`,value:{name:`node_setup_id`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`worker_environments`,kind:`column`,value:{name:`node_device_id`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`worker_environments`,kind:`column`,value:{name:`ssh_host`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`worker_environments`,kind:`column`,value:{name:`ssh_port`,type:`bigint`,nullable:!0,identity:!1,default:null,position:16}},{table:`worker_environments`,kind:`column`,value:{name:`ssh_user`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`worker_environments`,kind:`column`,value:{name:`ssh_host_key`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`worker_environments`,kind:`column`,value:{name:`ssh_key_ref_json`,type:`text`,nullable:!0,identity:!1,default:null,position:19}},{table:`worker_environments`,kind:`column`,value:{name:`desktop_json`,type:`text`,nullable:!0,identity:!1,default:null,position:20}},{table:`worker_environments`,kind:`column`,value:{name:`state`,type:`text`,nullable:!1,identity:!1,default:null,position:21}},{table:`worker_environments`,kind:`column`,value:{name:`bootstrap_bundle_hash`,type:`text`,nullable:!0,identity:!1,default:null,position:22}},{table:`worker_environments`,kind:`column`,value:{name:`bootstrap_openclaw_version`,type:`text`,nullable:!0,identity:!1,default:null,position:23}},{table:`worker_environments`,kind:`column`,value:{name:`bootstrap_protocol_features_json`,type:`text`,nullable:!0,identity:!1,default:null,position:24}},{table:`worker_environments`,kind:`column`,value:{name:`bootstrap_install_kind`,type:`text`,nullable:!0,identity:!1,default:null,position:25}},{table:`worker_environments`,kind:`column`,value:{name:`owner_epoch`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:26}},{table:`worker_environments`,kind:`column`,value:{name:`teardown_terminal_state`,type:`text`,nullable:!0,identity:!1,default:null,position:27}},{table:`worker_environments`,kind:`column`,value:{name:`attached_session_ids_json`,type:`text`,nullable:!1,identity:!1,default:`'[]'`,position:28}},{table:`worker_environments`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:29}},{table:`worker_environments`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:30}},{table:`worker_environments`,kind:`column`,value:{name:`state_changed_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:31}},{table:`worker_environments`,kind:`column`,value:{name:`idle_since_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:32}},{table:`worker_environments`,kind:`column`,value:{name:`destroy_requested_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:33}},{table:`worker_environments`,kind:`column`,value:{name:`last_error`,type:`text`,nullable:!0,identity:!1,default:null,position:34}},{table:`worker_environments`,kind:`column`,value:{name:`shared_host`,type:`bigint`,nullable:!0,identity:!1,default:null,position:35}},{table:`worker_environments`,kind:`column`,value:{name:`resource_receipt_json`,type:`text`,nullable:!0,identity:!1,default:null,position:36}},{table:`worker_environments`,kind:`column`,value:{name:`retention_json`,type:`text`,nullable:!0,identity:!1,default:null,position:37}},{table:`worker_environments`,kind:`column`,value:{name:`provision_source_json`,type:`text`,nullable:!0,identity:!1,default:null,position:38}},{table:`worker_environments`,kind:`primaryKey`,value:[`environment_id`]},{table:`worker_environments`,kind:`unique`,value:[`provision_operation_id`]},{table:`worker_environments`,kind:`indexes`,value:4},{table:`worker_environments`,kind:`checks`,value:5},{table:`worker_inference_turns`,kind:`table`,value:null},{table:`worker_inference_turns`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_inference_turns`,kind:`column`,value:{name:`run_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_inference_turns`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_inference_turns`,kind:`column`,value:{name:`turn_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`worker_inference_turns`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_inference_turns`,kind:`column`,value:{name:`request_hash`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`worker_inference_turns`,kind:`column`,value:{name:`state`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`worker_inference_turns`,kind:`column`,value:{name:`terminal_json`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`worker_inference_turns`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`worker_inference_turns`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`worker_inference_turns`,kind:`primaryKey`,value:[`session_id`,`run_epoch`,`run_id`,`turn_id`]},{table:`worker_inference_turns`,kind:`foreignKey`,value:{columns:[`environment_id`],target:`worker_environments`,targetColumns:[`environment_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`worker_inference_turns`,kind:`indexes`,value:2},{table:`worker_inference_turns`,kind:`checks`,value:5},{table:`worker_session_placement_moves`,kind:`table`,value:null},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`operation_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`source_generation`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`source_environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`source_owner_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`target_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`target_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`target_machine_class`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`target_os`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`abandon_source`,type:`bigint`,nullable:!0,identity:!1,default:null,position:10}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`last_error`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`worker_session_placement_moves`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:13}},{table:`worker_session_placement_moves`,kind:`primaryKey`,value:[`operation_id`]},{table:`worker_session_placement_moves`,kind:`unique`,value:[`session_id`]},{table:`worker_session_placement_moves`,kind:`foreignKey`,value:{columns:[`session_id`],target:`worker_session_placements`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`worker_session_placement_moves`,kind:`indexes`,value:2},{table:`worker_session_placement_moves`,kind:`checks`,value:5},{table:`worker_session_placements`,kind:`table`,value:null},{table:`worker_session_placements`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_session_placements`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_session_placements`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_session_placements`,kind:`column`,value:{name:`execution_mode`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`worker_session_placements`,kind:`column`,value:{name:`state`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_session_placements`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`worker_session_placements`,kind:`column`,value:{name:`transition_generation`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:7}},{table:`worker_session_placements`,kind:`column`,value:{name:`active_owner_epoch`,type:`bigint`,nullable:!0,identity:!1,default:null,position:8}},{table:`worker_session_placements`,kind:`column`,value:{name:`workspace_base_manifest_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`worker_session_placements`,kind:`column`,value:{name:`remote_workspace_dir`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`worker_session_placements`,kind:`column`,value:{name:`worker_bundle_hash`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`worker_session_placements`,kind:`column`,value:{name:`last_transcript_ack_cursor`,type:`bigint`,nullable:!0,identity:!1,default:null,position:12}},{table:`worker_session_placements`,kind:`column`,value:{name:`last_live_event_ack_cursor`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`worker_session_placements`,kind:`column`,value:{name:`recovery_error`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`worker_session_placements`,kind:`column`,value:{name:`turn_claim_owner`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`worker_session_placements`,kind:`column`,value:{name:`turn_claim_id`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`worker_session_placements`,kind:`column`,value:{name:`turn_claim_run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`worker_session_placements`,kind:`column`,value:{name:`turn_claim_generation`,type:`bigint`,nullable:!0,identity:!1,default:null,position:18}},{table:`worker_session_placements`,kind:`column`,value:{name:`turn_claim_owner_epoch`,type:`bigint`,nullable:!0,identity:!1,default:null,position:19}},{table:`worker_session_placements`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:20}},{table:`worker_session_placements`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:21}},{table:`worker_session_placements`,kind:`column`,value:{name:`state_changed_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:22}},{table:`worker_session_placements`,kind:`column`,value:{name:`terminal_reason`,type:`text`,nullable:!0,identity:!1,default:null,position:23}},{table:`worker_session_placements`,kind:`column`,value:{name:`terminal_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:24}},{table:`worker_session_placements`,kind:`primaryKey`,value:[`session_id`]},{table:`worker_session_placements`,kind:`indexes`,value:4},{table:`worker_session_placements`,kind:`checks`,value:12},{table:`worker_session_tool_operations`,kind:`table`,value:null},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`source_session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`source_claim_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`tool_call_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`tool_name`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`request_digest`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`operation_seed`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`child_session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`result_json`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`gateway_instance_id`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`worker_session_tool_operations`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`worker_session_tool_operations`,kind:`primaryKey`,value:[`source_session_id`,`source_claim_id`,`tool_call_id`]},{table:`worker_session_tool_operations`,kind:`foreignKey`,value:{columns:[`source_session_id`],target:`worker_session_placements`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`worker_session_tool_operations`,kind:`indexes`,value:1},{table:`worker_session_tool_operations`,kind:`checks`,value:2},{table:`worker_transcript_commit_heads`,kind:`table`,value:null},{table:`worker_transcript_commit_heads`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_transcript_commit_heads`,kind:`column`,value:{name:`run_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_transcript_commit_heads`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_transcript_commit_heads`,kind:`column`,value:{name:`next_seq`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`worker_transcript_commit_heads`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_transcript_commit_heads`,kind:`primaryKey`,value:[`session_id`,`run_epoch`]},{table:`worker_transcript_commit_heads`,kind:`indexes`,value:1},{table:`worker_transcript_commit_heads`,kind:`checks`,value:3},{table:`worker_transcript_commits`,kind:`table`,value:null},{table:`worker_transcript_commits`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_transcript_commits`,kind:`column`,value:{name:`run_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_transcript_commits`,kind:`column`,value:{name:`seq`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_transcript_commits`,kind:`column`,value:{name:`request_hash`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`worker_transcript_commits`,kind:`column`,value:{name:`state`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_transcript_commits`,kind:`column`,value:{name:`result_json`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`worker_transcript_commits`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`worker_transcript_commits`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`worker_transcript_commits`,kind:`primaryKey`,value:[`session_id`,`run_epoch`,`seq`]},{table:`worker_transcript_commits`,kind:`foreignKey`,value:{columns:[`session_id`,`run_epoch`],target:`worker_transcript_commit_heads`,targetColumns:[`session_id`,`run_epoch`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`worker_transcript_commits`,kind:`indexes`,value:1},{table:`worker_transcript_commits`,kind:`checks`,value:6},{table:`worker_turn_tool_authorities`,kind:`table`,value:null},{table:`worker_turn_tool_authorities`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_turn_tool_authorities`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_turn_tool_authorities`,kind:`column`,value:{name:`owner_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_turn_tool_authorities`,kind:`column`,value:{name:`placement_generation`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`worker_turn_tool_authorities`,kind:`column`,value:{name:`claim_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_turn_tool_authorities`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`worker_turn_tool_authorities`,kind:`column`,value:{name:`tool_names_json`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`worker_turn_tool_authorities`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`worker_turn_tool_authorities`,kind:`primaryKey`,value:[`session_id`]},{table:`worker_turn_tool_authorities`,kind:`foreignKey`,value:{columns:[`session_id`],target:`worker_session_placements`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`worker_turn_tool_authorities`,kind:`indexes`,value:1},{table:`worker_turn_tool_authorities`,kind:`checks`,value:2},{table:`worker_workspace_pending_results`,kind:`table`,value:null},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`owner_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`placement_generation`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`claim_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`gateway_instance_id`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`recovery_requested_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:8}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`workspace_accepted_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:9}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`staged_result_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`repository_workspace_id`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`worker_workspace_pending_results`,kind:`column`,value:{name:`repository_disk_authority_json`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`worker_workspace_pending_results`,kind:`primaryKey`,value:[`session_id`]},{table:`worker_workspace_pending_results`,kind:`foreignKey`,value:{columns:[`session_id`],target:`worker_session_placements`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`worker_workspace_pending_results`,kind:`indexes`,value:1},{table:`worker_workspace_pending_results`,kind:`checks`,value:2},{table:`worker_workspace_reconciliations`,kind:`table`,value:null},{table:`worker_workspace_reconciliations`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worker_workspace_reconciliations`,kind:`column`,value:{name:`environment_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worker_workspace_reconciliations`,kind:`column`,value:{name:`owner_epoch`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`worker_workspace_reconciliations`,kind:`column`,value:{name:`placement_generation`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`worker_workspace_reconciliations`,kind:`column`,value:{name:`base_manifest_ref`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`worker_workspace_reconciliations`,kind:`column`,value:{name:`current_manifest_ref`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`worker_workspace_reconciliations`,kind:`column`,value:{name:`plan_json`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`worker_workspace_reconciliations`,kind:`column`,value:{name:`base_pack`,type:`bytea`,nullable:!1,identity:!1,default:null,position:8}},{table:`worker_workspace_reconciliations`,kind:`column`,value:{name:`created_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`worker_workspace_reconciliations`,kind:`primaryKey`,value:[`session_id`]},{table:`worker_workspace_reconciliations`,kind:`foreignKey`,value:{columns:[`session_id`],target:`worker_session_placements`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`worker_workspace_reconciliations`,kind:`indexes`,value:1},{table:`worker_workspace_reconciliations`,kind:`checks`,value:3},{table:`workspace_generated_bootstrap_hashes`,kind:`table`,value:null},{table:`workspace_generated_bootstrap_hashes`,kind:`column`,value:{name:`workspace_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`workspace_generated_bootstrap_hashes`,kind:`column`,value:{name:`filename`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`workspace_generated_bootstrap_hashes`,kind:`column`,value:{name:`sha256`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`workspace_generated_bootstrap_hashes`,kind:`primaryKey`,value:[`workspace_key`,`filename`]},{table:`workspace_generated_bootstrap_hashes`,kind:`foreignKey`,value:{columns:[`workspace_key`],target:`workspace_setup_state`,targetColumns:[`workspace_key`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`workspace_generated_bootstrap_hashes`,kind:`indexes`,value:1},{table:`workspace_generated_bootstrap_hashes`,kind:`checks`,value:0},{table:`workspace_path_aliases`,kind:`table`,value:null},{table:`workspace_path_aliases`,kind:`column`,value:{name:`alias_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`workspace_path_aliases`,kind:`column`,value:{name:`alias_path`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`workspace_path_aliases`,kind:`column`,value:{name:`workspace_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`workspace_path_aliases`,kind:`column`,value:{name:`workspace_path`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`workspace_path_aliases`,kind:`column`,value:{name:`updated_at_ms`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`workspace_path_aliases`,kind:`primaryKey`,value:[`alias_key`]},{table:`workspace_path_aliases`,kind:`indexes`,value:2},{table:`workspace_path_aliases`,kind:`checks`,value:0},{table:`workspace_setup_state`,kind:`table`,value:null},{table:`workspace_setup_state`,kind:`column`,value:{name:`workspace_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`workspace_setup_state`,kind:`column`,value:{name:`workspace_path`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`workspace_setup_state`,kind:`column`,value:{name:`version`,type:`bigint`,nullable:!0,identity:!1,default:null,position:3}},{table:`workspace_setup_state`,kind:`column`,value:{name:`bootstrap_seeded_at`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`workspace_setup_state`,kind:`column`,value:{name:`setup_completed_at`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`workspace_setup_state`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:6}},{table:`workspace_setup_state`,kind:`column`,value:{name:`attested_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:7}},{table:`workspace_setup_state`,kind:`column`,value:{name:`attestation_updated_at_ms`,type:`bigint`,nullable:!0,identity:!1,default:null,position:8}},{table:`workspace_setup_state`,kind:`column`,value:{name:`bootstrap_deferred`,type:`bigint`,nullable:!0,identity:!1,default:null,position:9}},{table:`workspace_setup_state`,kind:`primaryKey`,value:[`workspace_key`]},{table:`workspace_setup_state`,kind:`indexes`,value:2},{table:`workspace_setup_state`,kind:`checks`,value:1},{table:`worktree_provisioned_file_chunks`,kind:`table`,value:null},{table:`worktree_provisioned_file_chunks`,kind:`column`,value:{name:`worktree_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worktree_provisioned_file_chunks`,kind:`column`,value:{name:`path`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worktree_provisioned_file_chunks`,kind:`column`,value:{name:`chunk_index`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`worktree_provisioned_file_chunks`,kind:`column`,value:{name:`data`,type:`bytea`,nullable:!1,identity:!1,default:null,position:4}},{table:`worktree_provisioned_file_chunks`,kind:`primaryKey`,value:[`worktree_id`,`path`,`chunk_index`]},{table:`worktree_provisioned_file_chunks`,kind:`indexes`,value:1},{table:`worktree_provisioned_file_chunks`,kind:`checks`,value:1},{table:`worktree_templates`,kind:`table`,value:null},{table:`worktree_templates`,kind:`column`,value:{name:`cache_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worktree_templates`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worktree_templates`,kind:`column`,value:{name:`repo_root`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`worktree_templates`,kind:`column`,value:{name:`common_dir`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`worktree_templates`,kind:`column`,value:{name:`worktree_root`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`worktree_templates`,kind:`column`,value:{name:`path`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`worktree_templates`,kind:`column`,value:{name:`backend`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`worktree_templates`,kind:`column`,value:{name:`source_commit`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`worktree_templates`,kind:`column`,value:{name:`content_key`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`worktree_templates`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`worktree_templates`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`worktree_templates`,kind:`column`,value:{name:`last_used_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`worktree_templates`,kind:`primaryKey`,value:[`cache_key`]},{table:`worktree_templates`,kind:`unique`,value:[`id`]},{table:`worktree_templates`,kind:`indexes`,value:2},{table:`worktree_templates`,kind:`checks`,value:1},{table:`worktrees`,kind:`table`,value:null},{table:`worktrees`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`worktrees`,kind:`column`,value:{name:`repo_fingerprint`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`worktrees`,kind:`column`,value:{name:`repo_root`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`worktrees`,kind:`column`,value:{name:`path`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`worktrees`,kind:`column`,value:{name:`branch`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`worktrees`,kind:`column`,value:{name:`base_ref`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`worktrees`,kind:`column`,value:{name:`owner_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`worktrees`,kind:`column`,value:{name:`owner_id`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`worktrees`,kind:`column`,value:{name:`snapshot_ref`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`worktrees`,kind:`column`,value:{name:`provisioned_paths_json`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`worktrees`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`worktrees`,kind:`column`,value:{name:`last_active_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`worktrees`,kind:`column`,value:{name:`removed_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`worktrees`,kind:`column`,value:{name:`run_end_cleanup_json`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`worktrees`,kind:`column`,value:{name:`gc_protection_json`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`worktrees`,kind:`primaryKey`,value:[`id`]},{table:`worktrees`,kind:`indexes`,value:3},{table:`worktrees`,kind:`checks`,value:1}];return Object.defineProperty(this,"expectedCatalog",{value:e,enumerable:!0,configurable:!0,writable:!0}),e}},au=`Use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.`;function isStatePostgres(){return stateEngineInput()!==void 0}function assertStateFileSnapshotAllowed(){stateEngineInput()&&Fa(`postgres`,`file-snapshot`)}function inspectStateSqlite(e){let t=K(e)??Qa(e);return{hasEngineAnchor:t.tables.has(`openclaw_engine_anchor`),hasExistingData:[...t.tables,...t.views,...t.triggers.keys()].some(e=>e!==`openclaw_engine_anchor`&&!e.startsWith(`sqlite_`))}}function admitStatePostgres(e,t){if(!t&&we(e)?.startupReady)return;let n=withPostgresSchemaAdmissionRetry(e,()=>{let t=gs(e);if(!t)throw new PostgresSchemaAdmissionUnavailableError(`Missing PostgreSQL state admission. ${au}`);return t}),r=new Set(n.catalog.filter(e=>e.kind===`table`).map(e=>e.table)),i=new Set(Q.fragments.flatMap(e=>e.tables.some(e=>r.has(e))?[]:e.tables));if(n.version===40&&Ao(n.catalog.filter(e=>!e.kind.endsWith(`Definition`)&&e.table!==`openclaw_schema_meta`),Q.expectedCatalog.filter(e=>!i.has(e.table))),t){let t=Date.now();e.prepare(`INSERT INTO schema_meta
        (meta_key, role, schema_version, agent_id, app_version, created_at, updated_at)
        VALUES ('primary', 'global', ?, NULL, ?, ?, ?)`).run(40,J,t,t),writeStateSchemaContentVersion(e)}let a=e.prepare(`SELECT schema_version, role, agent_id FROM schema_meta WHERE meta_key = 'primary'`).get(),o=e.prepare(`SELECT value_json FROM config_machine_state WHERE state_key = 'state.schema.contentVersion'`).get(),s;try{let e=o?.value_json;if(e!=null&&typeof e!=`string`)throw Error(`Invalid PostgreSQL state content marker`);s=parseStateSchemaContentVersion(e)}catch{throw Error(`PostgreSQL state metadata mismatch. ${au}`)}if(a?.schema_version!==n.version||a.role!==`global`||a.agent_id!==null||s>n.version)throw Error(`PostgreSQL state metadata mismatch. ${au}`);Ut(e,{userVersion:n.version,contentVersion:n.version}),at(e,!0)}function statePostgresVersionSql(e){return`UPDATE schema_meta
        SET schema_version = ${e},
          app_version = '${J.replaceAll(`'`,`''`)}',
          updated_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint)
        WHERE meta_key = 'primary';
        INSERT INTO config_machine_state (state_key, value_json, updated_at_ms)
        VALUES ('state.schema.contentVersion', '${e}',
          CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint))
        ON CONFLICT (state_key) DO UPDATE
          SET value_json = EXCLUDED.value_json, updated_at_ms = EXCLUDED.updated_at_ms;`}function createStatePostgresMigrations(){let e={postgres:ou.postgres,postgresFragments:ou.postgresFragments},t=withLegacyWorkerProvisionSource(e.postgres),n=withLegacyWorkspaceBootstrapDeferred(t),r={...e,postgres:t,postgresWithoutOptionalColumn:{table:`workspace_setup_state`,column:`bootstrap_deferred`,sql:n}},i={...e,postgres:withLegacyWorkerRetention(n)},a={postgres:withLegacyRepositoryDiskAuthority(i.postgres),postgresFragments:i.postgresFragments.map(e=>({...e,sql:withLegacyRepositoryDiskAuthority(e.sql)}))},o={postgres:withLegacyWorkerResourceReceipts(a.postgres),postgresFragments:a.postgresFragments},s={postgres:withLegacyTemplateStateSchema(o.postgres),postgresFragments:o.postgresFragments.map(e=>({...e,tables:e.tables.map(legacyTemplateStateIdentifier),sql:withLegacyTemplateStateSchema(e.sql)}))},c={postgres:withLegacyLocalWorkspaceCas(s.postgres),postgresFragments:s.postgresFragments.map(e=>({...e,tables:e.tables.filter(e=>!Fl.some(t=>t===e)),sql:withLegacyLocalWorkspaceCas(e.sql)}))},l={postgres:withLegacyPostgresIndexOrdering(c.postgres,`schema-nullability`),postgresFragments:c.postgresFragments.map(e=>({...e,sql:withLegacyPostgresIndexOrdering(e.sql,`schema-nullability`)}))},u={postgres:withLegacyPostgresIndexOrdering(l.postgres),postgresFragments:l.postgresFragments.map(e=>({...e,sql:withLegacyPostgresIndexOrdering(e.sql)}))},d={postgres:withLegacyLocalWorkspaceManifests(u.postgres),postgresFragments:u.postgresFragments.map(e=>({...e,tables:e.tables.filter(e=>e!==`local_workspace_manifest_nodes`),sql:withLegacyLocalWorkspaceManifests(e.sql)}))},f={...d,postgres:`${d.postgres}\n${Q.clientCredentialSource.sql}`},p={postgres:withLegacyPublicationDraft(f.postgres),postgresFragments:f.postgresFragments.map(e=>({...e,sql:withLegacyPublicationDraft(e.sql)}))},m={...p,postgres:p.postgres.replace(/CREATE INDEX "idx_state_leases_owner"[^;]*;/u,Q.preWriteIndexesV27Sql.state_leases)+Q.preWriteIndexesV27Sql.skill_usage+Q.preWriteIndexesV27Sql.acp_replay_events,postgresFragments:p.postgresFragments};return[{version:25,sql:Q.operatorRecoveryV25Sql,fromSchema:m,schema:m},{version:26,fromSchema:m,schema:m,sql:statePostgresVersionSql(26)},{version:27,fromSchema:m,schema:p,sql:`${Q.writeIndexesV27Sql}
        ${statePostgresVersionSql(27)}`},{version:28,fromSchema:p,schema:f,sql:`ALTER TABLE IF EXISTS github_publication_requests ADD COLUMN draft bigint;
        ALTER TABLE IF EXISTS github_personal_publication_requests ADD COLUMN draft bigint;
        ALTER TABLE IF EXISTS github_repository_publication_requests ADD COLUMN draft bigint;
        ${statePostgresVersionSql(28)}`},{version:29,fromSchema:f,schema:d,sql:Q.clientCredentialV29Sql},{version:30,fromSchema:d,schema:d,sql:statePostgresVersionSql(30)},{version:31,fromSchema:d,schema:u,sql:`DO $workspace$
        DECLARE baseline_constraint text;
        BEGIN
          IF to_regclass('local_workspace_projections') IS NOT NULL THEN
            SELECT conname INTO STRICT baseline_constraint FROM pg_constraint
              WHERE conrelid = 'local_workspace_projections'::regclass AND contype = 'c'
                AND pg_get_constraintdef(oid) LIKE '%baseline_json%baseline_ref%';
            EXECUTE format('ALTER TABLE local_workspace_projections DROP CONSTRAINT %I', baseline_constraint);
            ALTER TABLE local_workspace_projections
              ADD COLUMN checkpoint_json text COLLATE "C",
              ADD CHECK (baseline_json IS NULL OR baseline_ref IS NOT NULL);
            CREATE TABLE local_workspace_manifest_nodes (
              worktree_id text COLLATE "C" NOT NULL,
              path text COLLATE "C" NOT NULL,
              node_json text COLLATE "C" NOT NULL,
              PRIMARY KEY (worktree_id, path),
              FOREIGN KEY (worktree_id) REFERENCES local_workspace_projections(worktree_id)
                ON DELETE CASCADE
            );
          END IF;
        END $workspace$;
        ${statePostgresVersionSql(31)}`},{version:32,fromSchema:u,schema:l,sql:`${postgresIndexOrderingMigration([l.postgres,...l.postgresFragments.map(e=>e.sql)].join(`
`))}
        ${statePostgresVersionSql(32)}`},{version:33,fromSchema:l,schema:c,sql:`${postgresIndexOrderingMigration([c.postgres,...c.postgresFragments.map(e=>e.sql)].join(`
`),`schema-nullability`)}
        ${statePostgresVersionSql(33)}`},{version:34,fromSchema:c,schema:c,sql:statePostgresVersionSql(34)},{version:35,fromSchema:c,schema:s,sql:`${Q.workspaceCasV35Sql}\n${statePostgresVersionSql(35)}`},{version:36,fromSchema:s,schema:o,sql:`${Xl}\n${statePostgresVersionSql(36)}`},{version:37,fromSchema:o,schema:a,sql:`ALTER TABLE worker_environments ADD COLUMN resource_receipt_json text COLLATE "C";
        ${statePostgresVersionSql(37)}`},{version:38,fromSchema:a,schema:i,sql:`ALTER TABLE IF EXISTS session_repository_workspaces ADD COLUMN disk_authority_json text COLLATE "C";
        ALTER TABLE worker_workspace_pending_results ADD COLUMN repository_disk_authority_json text COLLATE "C";
        ${statePostgresVersionSql(38)}`},{version:39,fromSchema:i,schema:r,sql:`ALTER TABLE worker_environments ADD COLUMN retention_json text COLLATE "C";
        ${statePostgresVersionSql(39)}`},{version:40,fromSchema:r,schema:e,sql:`ALTER TABLE workspace_setup_state ADD COLUMN IF NOT EXISTS bootstrap_deferred bigint;
        ALTER TABLE worker_environments ADD COLUMN provision_source_json text COLLATE "C";
        UPDATE worker_environments
        SET provision_source_json = '{"kind":"unavailable"}'
        WHERE (state IN ('requested', 'provisioning') AND lease_id IS NULL
          OR state = 'bootstrapping' AND owner_epoch = 0)
          AND provision_source_json IS NULL;
        ${statePostgresVersionSql(40)}`}]}const ou={id:`state`,version:40,sqlite:``,get postgres(){let e=Q.eagerSql;return Object.defineProperty(this,"postgres",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get postgresFragments(){let e=Q.fragments.map(e=>{let{activation:t}=e;if(t!==`first-use`&&t!==`version-additive`)throw Error(`Unknown PostgreSQL state fragment activation: ${t}`);return{id:e.id,tables:e.tables,sql:e.sql,dependencies:e.dependencies,activation:t}});return Object.defineProperty(this,"postgresFragments",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get postgresMigrations(){let e=createStatePostgresMigrations();return Object.defineProperty(this,"postgresMigrations",{value:e,enumerable:!0,configurable:!0,writable:!0}),e}};function ensureStatePostgresFragment(e,t){let n=gs(e);if(!n)throw new PostgresSchemaAdmissionUnavailableError(`Missing PostgreSQL state admission. ${au}`);let r=Q.fragments.find(e=>e.tables.includes(t));if(!r){if(Q.expectedCatalog.some(e=>e.kind===`table`&&e.table===t)&&n.catalog.some(e=>e.kind===`table`&&e.table===t))return;throw Error(`No PostgreSQL state fragment owns ${t}`)}let i=r.tables.filter(e=>n.version>=35||!Fl.some(t=>t===e));if(i.every(e=>n.catalog.some(t=>t.kind===`table`&&t.table===e)))return;for(let t of r.dependencies){let n=Q.fragments.find(e=>e.id===t);if(!n)throw Error(`Unknown state fragment dependency ${t}`);ensureStatePostgresFragment(e,n.tables[0])}if(!da(e,{commit:()=>gi(e),invalidate:()=>gi(e)}))throw Error(`PostgreSQL state fragments require the owner's transaction`);let a=e.prepare(`SELECT 1 AS present FROM pg_catalog.pg_class
    WHERE relnamespace = ?::regnamespace AND relname IN (${i.map(()=>`?`).join(`, `)})
    LIMIT 1`).get(n.namespace,...i),o=Ua(e);if(!o)throw new PostgresSchemaAdmissionUnavailableError(`Missing PostgreSQL state admission. ${au}`);if(wr(e),a){io({db:e,namespace:n.namespace,storeId:n.storeId,store:n.store,version:n.version,schema:o,preserveSchemaSeal:!0}),admitStatePostgres(e,!1);return}let s=n.version<38?withLegacyRepositoryDiskAuthority(r.sql):r.sql,c=n.version<36?withLegacyTemplateStateSchema(s):s,l=n.version<35?withLegacyLocalWorkspaceCas(c):c;e.exec(n.version<33?withLegacyPostgresIndexOrdering(l,n.version<32?`sqlite`:`schema-nullability`):l),io({db:e,namespace:n.namespace,storeId:n.storeId,store:n.store,version:n.version,schema:ou,recordSchema:!0}),admitStatePostgres(e,!1)}function openExistingStatePostgresConnection(e,t){if(stateEngineInput())return openExistingStatePostgresConnectionFromAnchor(Xt(e,{existingOnly:!0,expectedIdentity:t}),e)}function openExistingStatePostgresConnectionFromAnchor(e,t){let n;try{let r=stateEngineInput();if(!r)throw Error(`PostgreSQL state inspection requires the configured state connection.`);admitStateSchemaFacts(e,t);let i=openEngineStore({anchor:e,schema:ou,input:r,inspectSqlite:()=>inspectStateSqlite(e),prepareAnchor:()=>{},openSqlite:()=>{},existingOnly:!0,reusePostgresConnection:!0,existingVersion:!0,admitPostgres:admitStatePostgres,closeOnFailure:(e,t)=>{throw n=e,t}});if(!z(i))throw Error(`Expected PostgreSQL state connection`);return n=i,{database:{db:n,path:t},close(){return G(j.closeUnpublishedOpenClawStateDatabaseHandle({db:i,path:t}),`PostgreSQL state connection cleanup failed.`),!i.isOpen&&!e.isOpen}}}catch(r){let i=j.closeUnpublishedOpenClawStateDatabaseHandle({db:n??e,path:t});throw i.length?Zr([r,...i],`PostgreSQL state connection acquisition and cleanup failed.`,r):r}}function estimateAcpSessionRowBytes(e){return Buffer.byteLength(e.sessionId,`utf8`)+Buffer.byteLength(e.sessionKey,`utf8`)+Buffer.byteLength(e.cwd,`utf8`)+32}function estimateAcpEventRowBytes(e){return Buffer.byteLength(e.sessionId,`utf8`)+Buffer.byteLength(e.sessionKey,`utf8`)+Buffer.byteLength(e.runId??``,`utf8`)+Buffer.byteLength(e.updateJson,`utf8`)+32}function buildApprovalResolutionRef(e){return Ps(`${e.approvalKind}\0${e.approvalId}`)}const su=BigInt(2**53-1);function coerceRequiredSqliteNumber(e){return typeof e==`bigint`?Number(e):e}function normalizeSqliteNumber(e){return typeof e==`bigint`?e>su||e<-su?void 0:Number(e):typeof e==`number`?e:void 0}function readJsonObjectMembers(e){JSON.parse(e);let t=[];for(let n=0;n<e.length;){let r=e[n];if(/\s/u.test(r)){n++;continue}let i=n++;if(r===`"`)for(;n<e.length;){let t=e[n++];if(t===`\\`)n++;else if(t===`"`)break}else if(!`{}[],:`.includes(r))for(;n<e.length&&!/[\s{}[\],:]/u.test(e[n]);)n++;t.push(e.slice(i,n))}let n=/* @__PURE__ */ new Map;if(t[0]!==`{`)return n;for(let e=1;;){let r=t[e];if(r===void 0||r===`}`)break;let i=JSON.parse(r);e+=2;let a=e,o=0;do{let n=t[e++];n===`{`||n===`[`?o++:(n===`}`||n===`]`)&&o--}while(o>0);typeof i==`string`&&!n.has(i)&&n.set(i,t.slice(a,e).join(``)),t[e]===`,`&&e++}return n}function deriveDeliveryQueueRetentionColumns(e,t){let n={retention_id_prefix:null,retention_max_age_ms:null,retention_max_entries:null};try{let r=readJsonObjectMembers(t).get(`completionRetention`);if(!r?.startsWith(`{`))return n;let i=readJsonObjectMembers(r),a=i.get(`idPrefix`),o=a?.startsWith(`"`)?JSON.parse(a):a?.startsWith(`[`)||a?.startsWith(`{`)?a:void 0,s=typeof o==`string`?o:void 0,integer=e=>{let t=e===`true`?1:e&&/^-?\d+$/u.test(e)?Number(e):NaN;return Number.isSafeInteger(t)&&t>=1?t:void 0},c=integer(i.get(`maxAgeMs`)),l=integer(i.get(`maxEntries`));return s&&!s.includes(`\0`)&&e.startsWith(s)&&c!==void 0&&l!==void 0?{retention_id_prefix:s,retention_max_age_ms:c,retention_max_entries:l}:n}catch{return n}}R(Symbol.for(`openclaw.outboundDeliveryEnqueued`),()=>({onEnqueued:e=>{}}));const cu={name:`state.failed-delivery-queue-health`,read:e=>e};function boundedDeliveryReceipts(e){return w(e).selectFrom(`delivery_queue_entries`).select([`queue_name`,`id`,`enqueued_at`,`retention_id_prefix as id_prefix`,`retention_max_age_ms as max_age_ms`,`retention_max_entries as max_entries`]).where(`status`,`in`,[`completed`,`failed`]).where(`recovery_state`,`=`,`completed_bounded`).where(`retention_id_prefix`,`is not`,null)}function pruneDeliveryQueueTombstones(e,t,n){let r=boundedDeliveryReceipts(e);n&&(r=r.where(`queue_name`,`=`,n.queueName).where(`retention_id_prefix`,`=`,n.idPrefix));let i=w(e),a=A(e,i.with(`policies`,()=>r).with(`ranked`,e=>e.selectFrom(`policies`).selectAll().select(e=>e.fn.agg(`row_number`,[]).over(e=>e.partitionBy([`queue_name`,`id_prefix`]).orderBy(`enqueued_at`,`desc`).orderBy(`id`,`desc`)).as(`retention_rank`))).deleteFrom(`delivery_queue_entries`).where(e=>e(e.refTuple(`queue_name`,`id`),`in`,e.selectFrom(`ranked`).select([`queue_name`,`id`]).where(e=>e.or([e(`enqueued_at`,`<`,e(e.val(t),`-`,e.ref(`max_age_ms`))),e(`retention_rank`,`>`,e.ref(`max_entries`))])).$asTuple(`queue_name`,`id`))));(a.numAffectedRows??0n)>0n&&fi(e,cu,void 0);let o=!n&&pruneOrdinaryDeliveryReceipts(e,t);return(a.numAffectedRows??0n)>0n||o}function pruneOrdinaryDeliveryReceipts(e,t){return(A(e,w(e).deleteFrom(`delivery_queue_entries`).where(`status`,`=`,`completed`).where(`enqueued_at`,`<`,t-2592e6).where(e=>e.or([e(`recovery_state`,`is`,null),e(`recovery_state`,`not in`,[`completed_permanent`,`completed_bounded`])]))).numAffectedRows??0n)>0n}r(()=>({})),r(()=>({}));function parseDeliveryQueueCompletionRetention(e,t){if(e===`permanent`)return e;let n=L(e);if(!n)return;let r=typeof n.idPrefix==`string`?n.idPrefix:``,i=jn(n.maxAgeMs),a=jn(n.maxEntries);if(r&&t.startsWith(r)&&i!==void 0&&a!==void 0)return{idPrefix:r,maxAgeMs:i,maxEntries:a}}const finite=e=>typeof e==`number`&&Number.isFinite(e);function inferDeliveryQueueFailureRetention(e,t,n,r=!1){let i=parseDeliveryQueueCompletionRetention(e.completionRetention,t)??parseDeliveryQueueCompletionRetention(e.failureRetention,t);if(i)return i;let a=L(L(e.terminalPolicy)?.fence);if(a?.kind===`none`)return;let o=a?.kind===`permanent`?`permanent`:parseDeliveryQueueCompletionRetention(a,t);if(o)return o;let s=n===`outbound-preparing-v1`||n===`outbound-legacy-preparing-v1`||n===`outbound-prepared-migration-v1`||e.retainOnFailure===!0||L(e.deliveryCompletion)!==null||n===`session`&&finite(e.availableAt),c=r&&(typeof e.platformSendAttemptId==`string`&&e.platformSendAttemptId.length>0||finite(e.platformSendStartedAt)||e.recoveryState===`send_attempt_started`||e.recoveryState===`unknown_after_send`||n===`session`&&(finite(e.deliveryStartedAt)||typeof e.settlementOutcome==`string`&&e.settlementOutcome.length>0||finite(e.acknowledgedAt)));return s||c?`permanent`:void 0}function projectDeliveryQueueTerminalEntry(e,t,n,r){let i=Number.isSafeInteger(e.retryCount)&&e.retryCount>=0?e.retryCount:0,a=r===`permanent`?`completed_permanent`:r?`completed_bounded`:void 0;return{id:e.id,enqueuedAt:t,retryCount:i,...n===`completed`?{acknowledgedAt:t}:{failedAt:t},...r?{completionRetention:r}:{},...a?{recoveryState:a}:{}}}function nonNegativeSafeInteger(e){let t=typeof e==`bigint`?Number(e):e;return typeof t==`number`&&Number.isSafeInteger(t)&&t>=0?t:void 0}function compactLegacyDeliveryQueueFailures(e){let t=Date.now(),n=e.prepare(`UPDATE delivery_queue_entries SET entry_json = @entryJson,
      retention_id_prefix = @retention_id_prefix, retention_max_age_ms = @retention_max_age_ms,
      retention_max_entries = @retention_max_entries
      WHERE queue_name = @queueName AND id = @id AND status = 'pending' AND entry_json = @previousJson`),r=e.prepare(`SELECT queue_name, id, status, retry_count, entry_json, updated_at, failed_at, recovery_state
       FROM delivery_queue_entries WHERE status IN ('pending', 'failed')`);r.setReadBigInts(!0);let i=r.all(),a=e.prepare(`DELETE FROM delivery_queue_entries WHERE queue_name = ? AND id = ? AND status = 'failed'`),o=e.prepare(`UPDATE delivery_queue_entries
        SET entry_kind = NULL, session_key = NULL, channel = NULL, target = NULL,
            account_id = NULL, retry_count = @retryCount, last_attempt_at = NULL,
            last_error = NULL, platform_send_started_at = NULL, entry_json = @entryJson,
            retention_id_prefix = @retention_id_prefix, retention_max_age_ms = @retention_max_age_ms,
            retention_max_entries = @retention_max_entries,
            enqueued_at = @failedAt, failed_at = @failedAt, recovery_state = @recoveryState
      WHERE queue_name = @queueName AND id = @id AND status = 'failed'`);for(let e of i){if(e.recovery_state===`settlement_pending`)continue;let r=safeParseJsonRecord(String(e.entry_json)),i=r??{},s=String(e.queue_name),c=String(e.id);if(e.status===`pending`){if(i.retainOnFailure!==!0&&inferDeliveryQueueFailureRetention(i,c,s,!0)){let t=JSON.stringify({...i,retainOnFailure:!0});n.run({entryJson:t,queueName:s,id:c,previousJson:String(e.entry_json),...deriveDeliveryQueueRetentionColumns(c,t)})}continue}let l=nonNegativeSafeInteger(e.failed_at)??nonNegativeSafeInteger(e.updated_at)??t,u=Math.max(nonNegativeSafeInteger(e.retry_count)??0,nonNegativeSafeInteger(i.retryCount)??0),d=r?inferDeliveryQueueFailureRetention(i,c,s,!0):`permanent`;if(!d){a.run(s,c);continue}let f=projectDeliveryQueueTerminalEntry({id:c,retryCount:u},l,`failed`,d),p=JSON.stringify(f);o.run({retryCount:u,entryJson:p,...deriveDeliveryQueueRetentionColumns(c,p),failedAt:l,recoveryState:f.recoveryState??null,queueName:s,id:c})}pruneDeliveryQueueTombstones(e,t)}function tableSql$1(e){let t=K(e);if(t)return t.tableSql.get(`operator_approvals`)??void 0;let n=e.prepare(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'operator_approvals'`).get();return typeof n?.sql==`string`?n.sql:void 0}function hasCanonicalOperatorApprovalKinds(e){return!M(e,`operator_approvals`)||/kind\s+text\s+not\s+null\s+check\s*\(\s*kind\s+in\s*\(\s*'exec'\s*,\s*'plugin'\s*,\s*'system-agent'\s*\)\s*\)/.test(tableSql$1(e)?.toLowerCase()??``)}function assertCanonicalOperatorApprovalKinds(e,t){if(!hasCanonicalOperatorApprovalKinds(e))throw new N(`OpenClaw state database ${t} has a legacy operator approval schema; run openclaw doctor --fix to migrate it.`)}function isCanonicalOperatorApprovalKind(e){return e===`exec`||e===`plugin`||e===`system-agent`}function ensureOperatorApprovalResolutionRefs(e){M(e,`operator_approvals`)&&O(e,()=>{k(e,`operator_approvals`,`resolution_ref TEXT`);let t=e.prepare(`SELECT approval_id, kind, resolution_ref FROM operator_approvals`).all(),n=e.prepare(`UPDATE operator_approvals SET resolution_ref = ? WHERE approval_id = ?`);for(let e of t){if(typeof e.approval_id!=`string`||!isCanonicalOperatorApprovalKind(e.kind))throw Error(`operator approval row cannot be assigned a transport reference`);let t=buildApprovalResolutionRef({approvalId:e.approval_id,approvalKind:e.kind});e.resolution_ref!==t&&n.run(t,e.approval_id)}if(e.prepare(`SELECT canonical.approval_id
         FROM operator_approvals AS canonical
         JOIN operator_approvals AS referenced
           ON canonical.approval_id = referenced.resolution_ref
         WHERE canonical.approval_id <> referenced.approval_id
         LIMIT 1`).get())throw Error(`operator approval ids conflict with durable transport references`);e.exec(`
      CREATE UNIQUE INDEX IF NOT EXISTS idx_operator_approvals_resolution_ref
        ON operator_approvals(resolution_ref);
    `)})}function nullableTextValue(e,t){if(!e||!Object.hasOwn(e,t))return;let n=e[t];return typeof n==`string`||n===null?n:void 0}function repairLegacySubagentRetainedResults(e){if(!M(e,`subagent_runs`))return;let repair=()=>{let t=P(e,`subagent_runs`,`pending_final_delivery_payload_json`),n=e.prepare(t?`SELECT run_id, payload_json, pending_final_delivery_payload_json FROM subagent_runs`:`SELECT run_id, payload_json FROM subagent_runs`).all(),r=e.prepare(`UPDATE subagent_runs
          SET payload_json = ?
        WHERE run_id = ?`);for(let e of n){let t=safeParseJsonRecord(e.payload_json)??null,n=t?L(t.parentCompletion):null,i=n?.completionTarget===`parent`?n:t,a=i?L(i.completion):null;if(!i||!a)continue;let o=L(i.delivery),s=o?L(o.payload):null,c=e.pending_final_delivery_payload_json?safeParseJsonRecord(e.pending_final_delivery_payload_json)??null:null;if(!(s&&(Object.hasOwn(s,`frozenResultText`)||Object.hasOwn(s,`fallbackFrozenResultText`))||c&&(Object.hasOwn(c,`frozenResultText`)||Object.hasOwn(c,`fallbackFrozenResultText`))))continue;let l=nullableTextValue(s,`frozenResultText`)??nullableTextValue(c,`frozenResultText`),u=nullableTextValue(s,`fallbackFrozenResultText`)??nullableTextValue(c,`fallbackFrozenResultText`);nullableTextValue(a,`resultText`)==null&&l!==void 0&&(a.resultText=l),nullableTextValue(a,`fallbackResultText`)==null&&u!==void 0&&(a.fallbackResultText=u),delete s?.frozenResultText,delete s?.fallbackFrozenResultText,r.run(JSON.stringify(t),e.run_id)}};e.isTransaction?repair():O(e,repair)}function repairLegacySubagentExecutionPayloads(e){M(e,`subagent_runs`)&&e.exec(`
    UPDATE subagent_runs
    SET payload_json = json_remove(
      CASE
        WHEN json_extract(payload_json, '$.pauseReason') = 'sessions_yield'
          AND json_extract(payload_json, '$.execution.status') <> 'terminal'
          AND json_type(payload_json, '$.endedAt') IN ('integer', 'real')
        THEN json_remove(json_set(
          payload_json,
          '$.execution.status', 'terminal',
          '$.execution.endedAt', json_extract(payload_json, '$.endedAt')
        ), '$.execution.outcome')
        WHEN (json_type(payload_json, '$.killReconciliation') = 'object'
          OR json_extract(payload_json, '$.endedReason') = 'subagent-killed')
          AND json_extract(payload_json, '$.execution.status') <> 'terminal'
          AND json_type(payload_json, '$.endedAt') IN ('integer', 'real')
          AND json_type(payload_json, '$.outcome') = 'object'
        THEN json_set(
          payload_json,
          '$.execution.status', 'terminal',
          '$.execution.endedAt', json_extract(payload_json, '$.endedAt'),
          '$.execution.outcome', json_extract(payload_json, '$.outcome')
        )
        ELSE payload_json
      END,
      '$.startedAt', '$.endedAt', '$.outcome'
    )
    WHERE json_valid(payload_json)
      AND (json_type(payload_json, '$.startedAt') IS NOT NULL
        OR json_type(payload_json, '$.endedAt') IS NOT NULL
        OR json_type(payload_json, '$.outcome') IS NOT NULL);
  `)}function backfillAcpReplayEstimatedBytes(e,t=!1){if(!M(e,`acp_replay_events`)||!P(e,`acp_replay_events`,`estimated_bytes`))return;let n=`state.repair.acpReplayUtf8Accounting`,r=M(e,`config_machine_state`)?w(e):void 0;if(!t&&r&&C(e,r.selectFrom(`config_machine_state`).select(`state_key`).where(`state_key`,`=`,n)))return;let i=w(e),a=e.prepare(`UPDATE acp_replay_events SET estimated_bytes = ? WHERE session_id = ? AND seq = ?`);for(let t of xe(e,i.selectFrom(`acp_replay_events`).select([`session_id`,`seq`,`session_key`,`run_id`,`update_json`,`estimated_bytes`]))){let e=estimateAcpEventRowBytes({sessionId:t.session_id,sessionKey:t.session_key,runId:t.run_id,updateJson:t.update_json});coerceRequiredSqliteNumber(t.estimated_bytes)!==e&&a.run(e,t.session_id,t.seq)}let o=e.prepare(`UPDATE acp_replay_sessions SET estimated_bytes = ? WHERE session_id = ?`);for(let t of xe(e,i.selectFrom(`acp_replay_sessions as s`).select([`s.session_id`,`s.session_key`,`s.cwd`,`s.estimated_bytes`]).select(e=>e.fn.coalesce(e.selectFrom(`acp_replay_events as e`).select(e=>e.fn.sum(`e.estimated_bytes`).as(`total`)).whereRef(`e.session_id`,`=`,`s.session_id`),e.val(0)).as(`event_bytes`)))){let e=estimateAcpSessionRowBytes({sessionId:t.session_id,sessionKey:t.session_key,cwd:t.cwd})+coerceRequiredSqliteNumber(t.event_bytes);coerceRequiredSqliteNumber(t.estimated_bytes)!==e&&o.run(e,t.session_id)}r&&A(e,r.insertInto(`config_machine_state`).values({state_key:n,value_json:`true`,updated_at_ms:Date.now()}).onConflict(e=>e.column(`state_key`).doNothing()))}function backfillCronRunLogEntryJson(e){if(!M(e,`cron_run_logs`)||!P(e,`cron_run_logs`,`entry_json`))return;let t=e.prepare(`SELECT store_key, job_id, seq, ts
         FROM cron_run_logs
        WHERE entry_json = '{}'`).all();if(t.length===0)return;let n=e.prepare(`UPDATE cron_run_logs
        SET entry_json = ?
      WHERE store_key = ? AND job_id = ? AND seq = ?`);for(let e of t)n.run(JSON.stringify({ts:coerceRequiredSqliteNumber(e.ts),jobId:e.job_id,action:`finished`}),e.store_key,e.job_id,e.seq)}function textField(e,t){let n=e?.[t];return typeof n==`string`&&n.trim()?n:null}function backfillCronJobsFromJobJson(e){if(!M(e,`cron_jobs`)||!P(e,`cron_jobs`,`job_json`)||!P(e,`cron_jobs`,`payload_kind`))return;let t=e.prepare(`SELECT store_key, job_id, job_json, updated_at
         FROM cron_jobs
        WHERE payload_kind = 'message'
           OR name = ''`).all();if(t.length===0)return;let n=e.prepare(`UPDATE cron_jobs
        SET name = ?,
            enabled = ?,
            agent_id = ?,
            payload_kind = ?,
            runtime_updated_at_ms = ?
      WHERE store_key = ?
        AND job_id = ?`);for(let e of t){let t=safeParseJsonRecord(e.job_json)??null;if(!t)continue;let r=L(t.schedule),i=L(t.payload),a=textField(r,`kind`),o=textField(i,`kind`),s=a===`at`&&textField(r,`at`),c=a===`every`&&Rn(r?.everyMs)!=null,l=a===`cron`&&textField(r,`expr`),u=o===`systemEvent`&&textField(i,`text`),d=o===`agentTurn`&&textField(i,`message`);r&&i&&(s||c||l)&&(u||d)&&n.run(textField(t,`name`)??e.job_id,t.enabled===!1?0:1,textField(t,`agentId`),o,Rn(t.updatedAtMs)??(coerceRequiredSqliteNumber(e.updated_at)||0),e.store_key,e.job_id)}}function backfillDeliveryQueueEntriesFromEntryJson(e){if(!M(e,`delivery_queue_entries`)||!P(e,`delivery_queue_entries`,`entry_json`)||!P(e,`delivery_queue_entries`,`retry_count`))return;compactLegacyDeliveryQueueFailures(e);let t=e.prepare(`SELECT queue_name, id, entry_json
         FROM delivery_queue_entries
        WHERE status = 'pending'
          AND (retry_count = 0
            OR last_attempt_at IS NULL
            OR last_error IS NULL
            OR recovery_state IS NULL
            OR platform_send_started_at IS NULL
            OR entry_kind IS NULL
            OR session_key IS NULL
            OR channel IS NULL
            OR target IS NULL
            OR account_id IS NULL)`).all();if(t.length===0)return;let n=e.prepare(`UPDATE delivery_queue_entries
        SET entry_kind = COALESCE(?, entry_kind),
            session_key = COALESCE(?, session_key),
            channel = COALESCE(?, channel),
            target = COALESCE(?, target),
            account_id = COALESCE(?, account_id),
            retry_count = ?,
            last_attempt_at = COALESCE(?, last_attempt_at),
            last_error = COALESCE(?, last_error),
            recovery_state = COALESCE(?, recovery_state),
            platform_send_started_at = COALESCE(?, platform_send_started_at)
      WHERE queue_name = ?
        AND id = ?`);for(let e of t){let t=safeParseJsonRecord(e.entry_json)??null;if(!t)continue;let r=L(t.session),i=L(t.route),a=L(t.deliveryContext);n.run(textField(t,`kind`),textField(t,`sessionKey`)??textField(r,`key`),textField(t,`channel`)??textField(i,`channel`)??textField(a,`channel`),textField(t,`to`)??textField(i,`to`)??textField(a,`to`),textField(t,`accountId`)??textField(i,`accountId`)??textField(a,`accountId`),Jn(t.retryCount,{min:0})??0,Jn(t.lastAttemptAt,{min:0})??null,textField(t,`lastError`),textField(t,`recoveryState`),Jn(t.platformSendStartedAt,{min:0})??null,e.queue_name,e.id)}}const lu={local_workspace_projections:[B(H,`local_workspace_projections`),B(H,`local_workspace_manifest_nodes`),B(H,`local_workspace_tree_packs`),B(H,`local_workspace_source_path_sets`)].join(`
`),user_profiles:`
CREATE TABLE IF NOT EXISTS user_profiles (
  id TEXT NOT NULL PRIMARY KEY,
  display_name TEXT,
  primary_github_account_id INTEGER,
  avatar BLOB,
  avatar_mime TEXT,
  avatar_sha256 TEXT,
  merged_into TEXT,
  role TEXT,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS user_profile_emails (
  email TEXT NOT NULL PRIMARY KEY,
  profile_id TEXT NOT NULL,
  binding_id TEXT,
  created_at INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_user_profile_emails_profile_id
  ON user_profile_emails(profile_id);

${B(H,`user_profile_identities`)}
`,operator_approval_standing_grants:`
CREATE TABLE IF NOT EXISTS operator_approval_standing_grants (
  grant_id TEXT NOT NULL PRIMARY KEY CHECK (length(grant_id) > 0),
  minted_by_approval_id TEXT NOT NULL
    REFERENCES operator_approvals(approval_id) ON DELETE CASCADE,
  agent_id TEXT NOT NULL CHECK (length(agent_id) > 0),
  cron_job_id TEXT NOT NULL CHECK (length(cron_job_id) > 0),
  job_config_revision TEXT NOT NULL CHECK (length(job_config_revision) > 0),
  operation_binding TEXT NOT NULL CHECK (length(operation_binding) > 0),
  created_at_ms INTEGER NOT NULL,
  expires_at_ms INTEGER CHECK (expires_at_ms IS NULL OR expires_at_ms >= created_at_ms),
  revoked_at_ms INTEGER,
  revoked_by TEXT,
  last_used_at_ms INTEGER,
  use_count INTEGER NOT NULL DEFAULT 0
) STRICT;

CREATE INDEX IF NOT EXISTS idx_operator_approval_standing_grants_binding
  ON operator_approval_standing_grants(agent_id, cron_job_id, operation_binding, created_at_ms DESC);

CREATE TABLE IF NOT EXISTS operator_approval_standing_grant_generations (
  grant_id TEXT NOT NULL PRIMARY KEY
    REFERENCES operator_approval_standing_grants(grant_id) ON DELETE CASCADE,
  job_definition_generation INTEGER NOT NULL CHECK (job_definition_generation >= 1)
) STRICT;
`,worker_environment_session_attachments:`
CREATE TABLE IF NOT EXISTS worker_environment_session_attachments (
  session_id TEXT PRIMARY KEY,
  session_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  session_lifecycle_revision TEXT,
  environment_id TEXT NOT NULL UNIQUE,
  generation INTEGER NOT NULL CHECK (generation >= 1),
  created_at_ms INTEGER NOT NULL,
  last_used_at_ms INTEGER NOT NULL,
  closed_at_ms INTEGER,
  FOREIGN KEY (environment_id) REFERENCES worker_environments(environment_id) ON DELETE CASCADE
) STRICT;
CREATE INDEX IF NOT EXISTS worker_environment_session_attachments_session_key
ON worker_environment_session_attachments(agent_id, session_key);
`};function getOpenClawStateFeatureSchemaSql(e,t){return t===void 0&&lu[e]?lu[e]:e===`skill_library_entries`&&t===void 0?B(H,e,{endMarker:`-- End profile-owned skill library.`,includeEndMarker:!1,errorMessage:`Canonical skill library schema missing.`}):B(e===`user_profile_emails`?lu.user_profiles:H,e,t)}const uu=/* @__PURE__ */ new Map;function ensureTable(e,t,n){if(z(e))return ensureStatePostgresFragment(e,t);let r=uu.get(t);if(!r){let e=getOpenClawStateFeatureSchemaSql(t,n);r=createSqliteSchemaEnsurer(()=>e,{tables:getCanonicalSqliteTableNames(e),indexes:getCanonicalSqliteNamedIndexNames(e)}),uu.set(t,r)}r(e)}function assertAgentDeletionJournalAvailable(e){if(!P(e,`agent_deletion_journal`,`agent_id`))throw Error(`Agent deletion journal missing; run openclaw doctor --fix to reconstruct it before restoring or deleting agents.`)}function ensureAgentDatabaseLeaseSchema(e){P(e,`agent_database_leases`,`provenance`)||(ensureTable(e,`agent_database_leases`),k(e,`agent_database_leases`,`provenance TEXT`))}function ensureWorkerSessionToolStateSchema(e){ensureTable(e,`worker_turn_tool_authorities`),ensureTable(e,`worker_session_tool_operations`)}function ensureFirstUseAdditiveStateColumnsForStrictMigration(e){for(let{columnName:t,dataType:n,tableName:r}of hl)k(e,r,`${t} ${n}`)}function ensureColumns(e,t){let n=[];for(let[r,i]of t){let t=i.trim().split(/\s+/,1)[0];t&&k(e,r,i)&&n.push({tableName:r,columnName:t})}return n}function ensureAdditiveStateColumns(e,t){let n=t===`repair`;ensureWorkerSessionToolStateSchema(e);for(let{columnName:t,dataType:n,tableName:r}of ml)k(e,r,`${t} ${n}`);k(e,...Z.packageUpdatedAt[0])&&e.exec(`UPDATE template_package_refs SET updated_at_ms = installed_at_ms;`),ensureColumns(e,Z.packageIntegrity);let r=k(e,...Z.diagnosticSequence[0]);r&&e.exec(`
      WITH ranked AS (
        SELECT
          rowid AS event_rowid,
          ROW_NUMBER() OVER (
            PARTITION BY scope
            ORDER BY created_at ASC, rowid ASC
          ) AS sequence
        FROM diagnostic_events
      )
      UPDATE diagnostic_events
      SET sequence = (
        SELECT ranked.sequence
        FROM ranked
        WHERE ranked.event_rowid = diagnostic_events.rowid
      );
    `),(r||n)&&e.exec(`DROP INDEX IF EXISTS idx_diagnostic_events_scope_created;`);let i=ensureColumns(e,Z.cronRunLogs);(n||i.some(({tableName:e})=>e===`cron_run_logs`))&&backfillCronRunLogEntryJson(e);let a=ensureColumns(e,Z.acpReplay).length>0;(a||n)&&backfillAcpReplayEstimatedBytes(e,a);let o=ensureColumns(e,Z.cronJobs);(n||o.some(({columnName:e})=>[`name`,`enabled`,`agent_id`,`payload_kind`,`runtime_updated_at_ms`].includes(e)))&&backfillCronJobsFromJobJson(e);let s=ensureColumns(e,Z.deliveryQueue);(n||s.some(({tableName:e})=>e===`delivery_queue_entries`))&&backfillDeliveryQueueEntriesFromEntryJson(e),k(e,...Z.originalMediaRoot[0]),ensureColumns(e,Z.beforeTaskAttribution),ensureColumns(e,Z.taskRequester),ensureColumns(e,Z.taskRunDetails),n&&(repairLegacySubagentExecutionPayloads(e),repairLegacySubagentRetainedResults(e)),ensureColumns(e,Z.workerEnvironments),(n||!P(e,`operator_approvals`,`resolution_ref`))&&ensureOperatorApprovalResolutionRefs(e)}function createSqliteCommitReceipt(e){return{version:1,operationId:rc(),source:e.source,domain:e.domain,facts:new Map([...new Set(e.keys)].map(t=>[t,e.readFact(t)]))}}function hasSqliteCommitReceiptCoverage(e,t){if(!I(e)||e.version!==1||typeof e.operationId!=`string`||!e.operationId||e.domain!==t.domain||!I(e.source)||e.source.identity!==t.source.identity||e.source.incarnation!==t.source.incarnation||!(e.facts instanceof Map))return!1;let n=new Set(t.keys),r=e.facts;return r.size===n.size&&[...n].every(e=>{let t=r.get(e);return I(t)&&(t.kind===`absent`||t.kind===`unchanged`||t.kind===`unknown`||t.kind===`postimage`&&`value`in t)})}function readSqliteCommitReceipt(e,t){if(!I(e)||!I(e.source)||typeof e.source.identity!=`string`||typeof e.source.incarnation!=`string`||!(e.facts instanceof Map)||!hasSqliteCommitReceiptCoverage(e,{source:t.source??{identity:e.source.identity,incarnation:e.source.incarnation},domain:t.domain,keys:t.keys??[...e.facts.keys()]})||![...e.facts].every(([e,n])=>typeof e==`string`&&t.isFact(e,n)))throw Error(t.invalidReceiptMessage??`State domain commit receipt is invalid`);return e}const du=R(Symbol.for(`openclaw.stateDomainPublicationBatch`),()=>({current:void 0}));function createStateDomainPublication(e){let t=createKeyedStateDomainPublication({domain:e.domain,sourceIdentity:e.sourceIdentity,isFact:(t,n)=>n.kind===`absent`||n.kind===`postimage`&&e.isValue(n.value)&&e.keyOf(n.value)===t});return{...t,stagePostimages(n,r){t.stagePostimages(n,r.map(t=>[e.keyOf(t),t]))}}}function createKeyedStateDomainPublication(e){let t=R(Symbol.for(`openclaw.stateDomainPublication.${e.domain}`),()=>({sources:/* @__PURE__ */ new WeakMap,facts:/* @__PURE__ */ new Set,installingFacts:0})),sourceFor=n=>{let r=hr(n),i=t.sources.get(r);return i||(i={identity:e.sourceIdentity?.(n)??m(n)?.key??Symbol(e.domain),incarnation:rc()},t.sources.set(r,i)),i},receiptFor=(t,n)=>createSqliteCommitReceipt({source:sourceFor(t),domain:e.domain,keys:[...n.keys()],readFact:e=>n.get(e)}),install=n=>{let r=[];t.installingFacts++;try{Ur(t.facts,n,e=>r.push(e))}finally{t.installingFacts--}if(r.length)throw AggregateError(r,e.installFailureMessage??`State domain fact installation failed`)},publication=e=>{let t={kind:`committed`,receipt:e};return{installFacts:()=>install(t),invalidate(){t={kind:`unknown`,identity:e.source.identity},install(t)},notify(){}}},stage=(n,r)=>{if(e.mutationDuringInstallMessage&&t.installingFacts)throw Error(e.mutationDuringInstallMessage);if(!r.size)return;let i=t.capture;if(i&&hr(i.db)===hr(n)){let e=new Map([...r.keys()].map(e=>[e,i.facts.get(e)]));if(!da(n,{stage(){for(let[e,t]of r)i.facts.set(e,t)},commit(){},rollback(){for(let[t,n]of e)n?i.facts.set(t,n):i.facts.delete(t)}}))throw Error(`State domain capture requires its owning transaction`)}let a=publication(receiptFor(n,r));!Pi(n,a)&&!n.isTransaction&&ki(a)},readReceipt=(t,n=e.isFact)=>readSqliteCommitReceipt(t,{domain:e.domain,isFact:n,invalidReceiptMessage:e.invalidReceiptMessage});return{receipt:receiptFor,readReceipt,stageFacts:stage,stagePostimages(e,t){stage(e,new Map(t.map(([e,t])=>[e,{kind:`postimage`,value:structuredClone(t)}])))},stageDeletions(e,t){stage(e,new Map(t.map(e=>[e,{kind:`absent`}])))},capture(e,n){let r=t.capture,i=r&&hr(r.db)===hr(e)?r:{db:e,facts:/* @__PURE__ */ new Map};t.capture=i;try{return{result:n(),receipt:receiptFor(e,i.facts)}}finally{t.capture=r}},bound(e){return gc(e).byteLength<=8388608?e:{kind:`unknown`,identity:e.source.identity}},subscribeFacts:e=>Yi(t.facts,e),begin(n,r=e.isFact){let i=rc(),a=/* @__PURE__ */ new Set,o=!1,s=!1,c=!1,l=!1,u=Yi(t.facts,e=>{if(!o){if(e.kind===`committed`&&e.receipt.source.identity===n.identity)for(let t of e.receipt.facts.keys())a.add(t);else e.kind===`unknown`&&e.identity===n.identity&&(s=!0)}});try{n.publishPending!==!1&&install({kind:`pending`,identity:n.identity,operationId:i})}catch(e){u();try{install({kind:`settled`,identity:n.identity,operationId:i})}catch{}throw e}return{committed(t,i){try{if(n.assertCurrent(),l)throw Error(e.closedMessage??`State domain publication owner is closed`);if(I(t)&&t.kind===`unknown`&&t.identity===n.identity)install({kind:`unknown`,identity:n.identity});else{let i=readReceipt(t,r);if(i.source.identity!==n.identity)throw Error(e.changedOwnerMessage??`State domain commit receipt changed owner`);let c=publication({...i,facts:new Map([...i.facts].map(([e,t])=>[e,s||a.has(e)?{kind:`unknown`}:t]))}),l={...c,installFacts(){o=!0;try{c.installFacts()}finally{o=!1}}};du.current?du.current.push(l):ki(l)}c=!0,i?.()}catch(e){throw install({kind:`unknown`,identity:n.identity}),e}finally{o=!1}},finish(e,t=!1){if(!l){l=!0,u();try{e&&(c||t)||install({kind:`unknown`,identity:n.identity})}finally{n.publishPending!==!1&&install({kind:`settled`,identity:n.identity,operationId:i})}}}}}}}createStateDomainPublication({domain:`agent-provenance`,keyOf:e=>e.agentId,isValue:e=>I(e)&&typeof e.agentId==`string`&&(e.createdVia===`operator`||e.createdVia===`agent`||e.createdVia===`template`)&&(e.creatorAgentId===null||typeof e.creatorAgentId==`string`)&&typeof e.createdAtMs==`number`}),createStateDomainPublication({domain:`agent-deletion-journal`,keyOf:e=>e.agentId,isValue:e=>I(e)&&typeof e.agentId==`string`&&typeof e.operationId==`string`&&typeof e.cleanupCompleted==`boolean`});const fu=R(Symbol.for(`openclaw.stateSchemaMutationConflictError`),()=>class extends Error{constructor(e,t){super(`OpenClaw refused shared state schema mutation at ${e} because another Gateway owns that state directory. Stop that Gateway or perform the update through its managed restart path, then retry.`,{cause:t}),this.name=`StateSchemaMutationConflictError`}});function acquireSchemaMaintenanceLease({databasePath:e,busyTimeoutMs:t}){if(la(e))return;let n=Ns(e),r=nn(n);if(r)r.assertCurrent();else try{return dt(n,{busyTimeoutMs:t})}catch(e){throw e instanceof Ca?new fu(n,e):e}}function withStateDatabaseSchemaMaintenance(e,t){let n=acquireSchemaMaintenanceLease(e);return n?pr(n,`state schema mutation`,()=>n.run(t)):t()}async function withStateDatabaseSchemaMaintenanceAsync(e,t){let n=acquireSchemaMaintenanceLease(e);if(!n)return await t();let r;try{r={value:await n.run(t)}}catch(e){r={error:e}}try{n.release()}catch(e){throw`error`in r?Zr([r.error,e],`state schema mutation and resource release both failed`,r.error):new Ta(`state schema mutation completed, but releasing its resource failed`,e)}if(`error`in r)throw r.error;return r.value}function parseStateLeaseProcessOwner(e){let t=safeParseJsonRecord(e??``)?.owner;if(!I(t))return null;let{pid:n,host:r,startedAt:i}=t;return typeof n!=`number`||!Number.isSafeInteger(n)||n<=0||typeof r!=`string`||!r||i!==null&&(typeof i!=`number`||!Number.isSafeInteger(i)||i<0)?null:{pid:n,host:r,startedAt:i,...t.machineIdentity===void 0?{}:{machineIdentity:ye.safeParse(t.machineIdentity).data??null},...t.processNamespace===void 0?{}:{processNamespace:p.safeParse(t.processNamespace).data??null}}}function readStateLeaseProcessOwnerStatus(e,t){if(!e)return`unknown`;let n=St(e.processNamespace,{ownerHost:e.host,machineIdentity:e.machineIdentity,readGatewayHeartbeat:t===void 0?void 0:()=>t});return n===`same`?readSameNamespaceProcessOwnerStatus(e):n}function readSameNamespaceProcessOwnerStatus(e){if(Ts(e.pid))return`dead`;let t=ws(e.pid);return e.startedAt===null||t===null?`unknown`:t===e.startedAt?`live`:`dead`}const pu=Pe().int().min(0).max(2**53-1);an(`reason`,[D({reason:s(`expired`),expiresAt:pu,expiredByMs:pu,heartbeatAgeMs:pu,renewalTimerLateByMs:pu.optional()}),D({reason:s(`replaced`),owner:s(`[redacted]`)}),D({reason:s(`missing`)}),D({reason:s(`storage-failed`)}),D({reason:s(`admission-failed`)})]);function readOpenClawStateLease(e,t){return C(e,w(e).selectFrom(`state_leases`).select([`owner`,`created_at as createdAt`,`expires_at as expiresAt`,`heartbeat_at as heartbeatAt`,`payload_json as payloadJson`]).where(`scope`,`=`,t.scope).where(`lease_key`,`=`,t.key))}const mu={scope:`gateway-owner`,key:`global`};function parseSupervisor(e){if(e===null)return null;if(!I(e)||e.kind!==`launchd`&&e.kind!==`systemd`&&e.kind!==`schtasks`&&e.kind!==`external`||e.name!==null&&(typeof e.name!=`string`||!e.name.trim()))throw Error(`Gateway owner lease supervisor could not be verified`);return{kind:e.kind,name:e.name}}function readGatewayOwnerLeaseFromDatabase(e,t){if(M(e,`state_leases`))return decodeGatewayOwnerLease(readOpenClawStateLease(e,mu),t)}function decodeGatewayOwnerLease(e,t){if(!e)return;let n=parseStateLeaseProcessOwner(e.payloadJson),r=safeParseJsonRecord(e.payloadJson??``);if(!n||!r||typeof r.port!=`number`||!Number.isInteger(r.port)||r.port<=0||r.port>65535||r.mode!==`foreground`&&r.mode!==`supervised`)throw Error(`Gateway owner lease identity could not be verified`);if(t!==void 0&&r.port!==t)return;let i=parseSupervisor(r.supervisor);if(r.mode===`foreground`!=(i===null))throw Error(`Gateway owner lease supervisor does not match its listener mode`);return{...n,owner:e.owner,heartbeatAt:e.heartbeatAt??e.createdAt,port:r.port,mode:r.mode,supervisor:i,...typeof r.listeningAt==`number`?{listeningAt:r.listeningAt}:{},...typeof r.stateDatabaseProvenance==`string`?{stateDatabaseProvenance:r.stateDatabaseProvenance}:{},state:readStateLeaseProcessOwnerStatus(n,e.heartbeatAt??e.createdAt),expired:e.expiresAt===null||e.expiresAt<=Date.now(),...n.processNamespace===void 0?{expiresAt:e.expiresAt}:{}}}function hasLegacyCronRunLogs(e){let t=K(e);return t?t.tables.has(`cron_run_logs`):!!e.prepare(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'cron_run_logs' LIMIT 1`).get()}let hu;function bootFingerprint(e,t){return[ac(),e,t,J].join(`\0`)}function mayShareAgentDatabaseFile(e,t){if(e===t)return!0;try{let n=Y.statSync(e,{bigint:!0,throwIfNoEntry:!1}),r=Y.statSync(t,{bigint:!0,throwIfNoEntry:!1});return!n||!r||n.dev===r.dev&&n.ino===r.ino}catch{return!0}}function createAgentDatabaseLeaseStaleReasonReader(){let e;return t=>{if(Ts(t.owner_pid))return`owner-pid-dead`;if(t.owner_start_time===null){if(t.opened_at<=0)return;if(e===void 0)try{e=yt(process.env)()}catch{e=null}return me(t.opened_at,e??void 0)?`owner-prior-boot`:void 0}let n=ws(t.owner_pid);return n!==null&&t.owner_start_time!==n?`owner-start-time-changed`:void 0}}function readAgentDatabaseLeaseProvenance(e){try{if(hu===void 0&&(hu=null,[`linux`,`darwin`,`win32`].includes(process.platform))){let e=yt(process.env)(),t=e.platform===`linux`?Y.readlinkSync(`/proc/self/ns/pid`):e.platform;hu=bootFingerprint(e.identity,t)}if(!hu)return null;let t=Y.statSync(e,{bigint:!0});return t.isFile()?`process-v1:${nc(`sha256`).update(`${hu}\0${t.dev}:${t.ino}`).digest(`hex`)}`:null}catch{return null}}const gu=S().refine(e=>!e.includes(`\0`),`Must not contain NUL`),_u=Lt([gu,oe(gu).min(1).refine(e=>!!e[0]?.length,`Executable must not be empty`)]),vu=Lt([_u,x(S(),_u)]),yu=S().regex(/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u),bu=S().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),xu=x(bu,D({description:S().optional(),documentationUrl:S().optional()}).passthrough()).refine(e=>Object.keys(e).length<=16,`At most 16 setup secrets may be requested`),Su=x(S().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),gu),Cu=D({source:Se([`devcontainer`,`script`,`detected`,`none`]),identity:yu.optional(),inputs:x(S(),yu),env:x(S().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),gu.nullable()),secretNames:oe(bu).max(16).optional(),ignoredPropertiesNote:S().optional(),onCreate:vu.optional(),updateContent:vu.optional(),postCreate:vu.optional(),postStart:vu.optional(),detectedInstall:vu.optional()}).strict();D({onCreateCommand:vu.optional(),updateContentCommand:vu.optional(),postCreateCommand:vu.optional(),postStartCommand:vu.optional(),secrets:xu.optional(),containerEnv:Su.optional(),remoteEnv:x(S().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),gu.nullable()).optional()}).passthrough();const wu=S().regex(/^[a-f0-9]{64}$/u),Tu=D({nodeBootstrapSha256:wu,enabledPluginIds:oe(S().min(1).max(256)).max(256),workerBundleHash:wu,workerArchiveSha256:wu,openclawVersion:S().min(1).max(128),protocolFeatures:oe(S().min(1).max(128)).max(64)}).strict(),Eu=D({machineClass:S().min(1).max(256),platform:S().min(1).max(64),arch:S().min(1).max(64).optional(),profileKey:wu.optional()}).strict(),Du=D({key:wu,cacheKey:wu,contractVersion:Lt([s(1),s(2)]),setupRecipe:S().regex(/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u).optional(),runSetupScript:fe().optional(),recipe:Cu.optional(),target:Eu,artifacts:Tu}).strict(),Ou=Du.omit({setupRecipe:!0,runSetupScript:!0,recipe:!0}).extend({source:Se([`empty`,`image`])});function readWorkerProjectPreparation(e){if(!I(e)||e.preparation===void 0)return;let t=Du.safeParse(e.preparation);if(!t.success)throw Error(`Worker project preparation identity is invalid`);return t.data}function readWorkerPreparation(e){if(e.runtimePreparation===void 0)return readWorkerProjectPreparation(e.project);let t=Ou.safeParse(e.runtimePreparation);if(!t.success||e.project!==void 0)throw Error(`Worker runtime preparation identity is invalid`);return t.data}function historicalImageQuery(e){return w(e).selectFrom(`worker_environments`).select([`environment_id`,`profile_snapshot_json`]).where(t=>t(se(e,t.ref(`profile_snapshot_json`)),`=`,1)).where(t=>t(E(e,t.ref(`profile_snapshot_json`),t.val(`$.project.kind`)),`=`,`image`))}function migrateHistoricalImageReserveSnapshots(e){if(!M(e,`worker_environments`))return[];let t=A(e,historicalImageQuery(e)).rows;for(let n of t){if(typeof n.profile_snapshot_json!=`string`||typeof n.environment_id!=`string`)throw Error(`Historical image reserve row is invalid`);let t=JSON.parse(n.profile_snapshot_json),r=I(t)?t.project:void 0;if(!I(t)||!I(r)||r.kind!==`image`||typeof r.key!=`string`||!/^[a-f0-9]{64}$/u.test(r.key)||!I(r.preparation)||t.runtimePreparation!==void 0||t.historicalProfileSnapshotJson!==void 0)throw Error(`Historical image reserve snapshot has conflicting or invalid preparation`);t.runtimePreparation={...r.preparation,source:`empty`},delete t.project,readWorkerPreparation(t),t.historicalProfileSnapshotJson=n.profile_snapshot_json,A(e,w(e).updateTable(`worker_environments`).set({profile_snapshot_json:JSON.stringify(t)}).where(`environment_id`,`=`,n.environment_id))}return t.length>0?[`Migrated historical image reserves with original snapshot evidence retained`]:[]}const ku=[`device_identities`,`device_auth_tokens`,`gateway_origin_device_tokens`,`exec_approvals_config`],Au=`CREATE TABLE device_identities (
  identity_key TEXT NOT NULL PRIMARY KEY,
  device_id TEXT NOT NULL,
  public_key_pem TEXT NOT NULL,
  private_key_pem TEXT NOT NULL,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;
CREATE INDEX idx_device_identities_device
  ON device_identities(device_id, updated_at_ms DESC);
CREATE TABLE device_auth_tokens (
  device_id TEXT NOT NULL,
  role TEXT NOT NULL,
  token TEXT NOT NULL,
  scopes_json TEXT NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (device_id, role)
) STRICT;
CREATE INDEX idx_device_auth_tokens_updated
  ON device_auth_tokens(updated_at_ms DESC, device_id, role);
CREATE TABLE gateway_origin_device_tokens (
  gateway_scope TEXT NOT NULL,
  device_id TEXT NOT NULL,
  role TEXT NOT NULL,
  token TEXT NOT NULL,
  scopes_json TEXT NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (gateway_scope, device_id, role)
) STRICT;
CREATE TABLE native_exec_socket_credentials (
  socket_key TEXT NOT NULL PRIMARY KEY CHECK (socket_key = 'current'),
  socket_path TEXT,
  socket_token TEXT,
  updated_at_ms INTEGER NOT NULL
) STRICT;
CREATE TABLE client_credential_migration (
  version INTEGER PRIMARY KEY CHECK (version = 1),
  source_store TEXT NOT NULL,
  phase TEXT NOT NULL CHECK (phase IN ('copied', 'complete')),
  updated_at_ms INTEGER NOT NULL
) STRICT;`;function migrateCronDeliveryAttemptState(e,t){return t<20&&M(e,`cron_run_receipts`)?k(e,`cron_run_receipts`,`delivery_attempt_state TEXT NOT NULL DEFAULT 'unknown' CHECK (delivery_attempt_state IN ('unknown', 'not-started', 'started'))`):!1}const ju={version:21,tables:[`meeting_transcript_sessions`,`meeting_transcript_summaries`,`delivery_queue_entries`],columns:[...[`source_account_id`,`source_guild_id`,`source_channel_id`,`source_meeting_url`,`source_thread_ts`,`source_file_id`,`metadata_agent_id`].map(e=>`meeting_transcript_sessions.${e}`),`meeting_transcript_summaries.overview`,`delivery_queue_entries.retention_id_prefix`,`delivery_queue_entries.retention_max_age_ms`,`delivery_queue_entries.retention_max_entries`],migrate:migratePredicateColumnsV21,applied:`Derived meeting transcript selectors and bounded delivery retention columns (v21)`};function migratePredicateColumnsV21(e,t){let n=t===21&&ju.columns.some(t=>{let n=t.indexOf(`.`),r=t.slice(0,n);return M(e,r)&&!P(e,r,t.slice(n+1))});if(t>=21&&!n)return!1;let r=!1,text=(e,t)=>`CASE WHEN json_valid(${e}) THEN CASE WHEN json_type(${e}, '${t}') = 'text' THEN json_extract(${e}, '${t}') END END`;if(M(e,`meeting_transcript_sessions`)){let t=[`accountId`,`guildId`,`channelId`,`meetingUrl`,`threadTs`,`fileId`],n=[`source_account_id`,`source_guild_id`,`source_channel_id`,`source_meeting_url`,`source_thread_ts`,`source_file_id`];for(let t of[...n,`metadata_agent_id`])r=k(e,`meeting_transcript_sessions`,`${t} TEXT`)||r;e.exec(`UPDATE meeting_transcript_sessions SET
      ${n.map((e,n)=>`${e} = ${text(`source_json`,`$.${t[n]}`)}`).join(`,`)},
      metadata_agent_id = ${text(`metadata_json`,`$.agentId`)}`)}return M(e,`meeting_transcript_summaries`)&&(r=k(e,`meeting_transcript_summaries`,`overview TEXT`)||r,e.exec(`UPDATE meeting_transcript_summaries SET overview = ${text(`summary_json`,`$.overview`)}`)),M(e,`delivery_queue_entries`)&&(r=k(e,`delivery_queue_entries`,`retention_id_prefix TEXT`)||r,r=k(e,`delivery_queue_entries`,`retention_max_age_ms INTEGER`)||r,r=k(e,`delivery_queue_entries`,`retention_max_entries INTEGER`)||r,e.exec(`UPDATE delivery_queue_entries SET
      (retention_id_prefix, retention_max_age_ms, retention_max_entries) = (
        SELECT id_prefix, max_age_ms, max_entries FROM (
          SELECT json_extract(entry_json, '$.completionRetention.idPrefix') id_prefix,
            json_extract(entry_json, '$.completionRetention.maxAgeMs') max_age_ms,
            json_extract(entry_json, '$.completionRetention.maxEntries') max_entries
          WHERE json_valid(entry_json)
            AND json_type(entry_json, '$.completionRetention') = 'object'
        ) WHERE typeof(id_prefix) = 'text' AND id_prefix <> ''
          AND substr(id, 1, length(id_prefix)) = id_prefix
          AND typeof(max_age_ms) = 'integer' AND max_age_ms BETWEEN 1 AND 9007199254740991
          AND typeof(max_entries) = 'integer' AND max_entries BETWEEN 1 AND 9007199254740991
      )`)),r}const Mu=`worker_session_placements`,Nu=`repository_preparation TEXT`;function migrateHistoricalRepositoryPreparation(e){if(!P(e,Mu,`repository_preparation`))return!1;let t=B(H,Mu).replace(`  remote_workspace_dir TEXT,`,`  `+Nu+`,
  remote_workspace_dir TEXT,`),n=Pt(e)(Mu),r=ha(t,Mu);if(n?.strict===1&&n.withoutRowid===0&&uc(n.definition,r))return!1;let i=t.replace(Nu+`,`,Nu+` CHECK (repository_preparation IN ('pending', 'ready', 'failed')),`).replace(`  CHECK (
    (state IN`,`  CHECK (repository_preparation IS NULL OR (repository_preparation = 'ready' AND workspace_base_manifest_ref IS NOT NULL) OR (repository_preparation = 'failed' AND state IN ('starting', 'active', 'draining', 'reconciling', 'reclaimed', 'failed')) OR (repository_preparation = 'pending' AND workspace_base_manifest_ref IS NULL AND state IN ('starting', 'active', 'draining', 'reconciling', 'reclaimed', 'failed'))),
  CHECK (
    (state IN`).replaceAll(`AND workspace_base_manifest_ref IS NOT NULL AND remote_workspace_dir`,`AND (workspace_base_manifest_ref IS NOT NULL OR repository_preparation IS 'pending' OR repository_preparation IS 'failed') AND remote_workspace_dir`);if(!n||n.strict!==1||n.withoutRowid!==0||!uc(n.definition,ha(i,Mu)))throw Error(`Unrecognized historical worker placement schema; preserve the store for explicit recovery.`);if(e.prepare(`SELECT 1 FROM worker_session_placements WHERE repository_preparation IN ('pending', 'failed') AND turn_claim_owner = 'worker' LIMIT 1`).get())throw Error(`Historical repository preparation retains a worker turn claim; reconcile its owned cleanup before migrating.`);let a=to(e).filter(e=>e.tbl_name===Mu&&(e.type===`index`||e.type===`trigger`)&&e.sql!==null),o=n.columns.map(e=>e.name),s=o.map(e=>e===`state`?`CASE WHEN repository_preparation IN ('pending', 'failed') THEN 'failed' ELSE state END`:e===`recovery_error`?`CASE WHEN repository_preparation IN ('pending', 'failed') THEN 'Historical repository preparation ' || repository_preparation || ' (previous placement ' || state || '); owned cleanup required before recovery.' || CASE WHEN recovery_error IS NULL THEN '' ELSE ' ' || recovery_error END ELSE recovery_error END`:W(e));e.exec(t.replace(`CREATE TABLE IF NOT EXISTS `+Mu,`CREATE TABLE worker_session_placements_historical_migration`)+` INSERT INTO worker_session_placements_historical_migration (rowid, `+o.map(W).join(`, `)+`) SELECT rowid, `+s.join(`, `)+` FROM worker_session_placements; DROP TABLE worker_session_placements; ALTER TABLE worker_session_placements_historical_migration RENAME TO worker_session_placements;`);for(let t of a){if(typeof t.sql!=`string`)throw Error(`Historical worker placement schema object is invalid`);e.exec(t.sql)}return!0}function migrateHistoricalStateImports(e,t,n=`version`){if(n===`version`&&t>22)return[];let r=[],i=t===21&&migrateHistoricalRepositoryPreparation(e);return i&&r.push(`Preserved historical worker placement evidence and fenced incomplete repository preparation`),(t===21||i)&&migratePredicateColumnsV21(e,21)&&r.push(ju.applied),(n===`doctor`||t<=22)&&r.push(...migrateHistoricalImageReserveSnapshots(e)),r}const Pu=[{version:32,tables:[],columns:[],migrate:()=>!1,applied:`Aligned PostgreSQL non-null index ordering (v32)`},{version:33,tables:[],columns:[],migrate:()=>!1,applied:`Aligned PostgreSQL partial-index ordering (v33)`}];function migrateMeetingTranscriptStartTime(e,t){if(t>=23||!M(e,`meeting_transcript_sessions`))return!1;let n=k(e,`meeting_transcript_sessions`,`started_at_ms INTEGER`),r=xe(e,w(e).selectFrom(`meeting_transcript_sessions`).select([`session_id`,`started_at`])),i=e.prepare(`UPDATE meeting_transcript_sessions SET started_at_ms = ? WHERE session_id = ? AND started_at = ?`);for(let e of r)i.run($n(e.started_at)??null,e.session_id,e.started_at),n=!0;return n}const Fu=-(2**53-1);function getAuditRecordKysely(e){return w(e)}function parseAuditRecord(e){return{key:e.event_key,value:JSON.parse(e.payload_json),createdAt:e.created_at,sequence:e.sequence}}function readAuditWriteState(e){let t=C(e.database,getAuditRecordKysely(e.database).selectFrom(`diagnostic_events`).select(t=>[t.fn.max(`sequence`).filterWhere(`sequence`,e.legacy?`<`:`>=`,0).as(`sequence`),t.fn.countAll().as(`count`),t.fn.countAll().filterWhere(`event_key`,`=`,e.key??``).as(`keyCount`)]).where(`scope`,`=`,e.scope)),n=(t?.sequence??(e.legacy?Fu:0))+1;if(!Number.isSafeInteger(n)||e.legacy&&n>=0)throw Error(`Audit sequence exhausted for scope ${e.scope}`);return{nextSequence:n,count:coerceRequiredSqliteNumber(t?.count??0),keyExists:coerceRequiredSqliteNumber(t?.keyCount??0)>0}}function pruneAuditRecords(e){let t=e.count-e.maxEntries;if(t<=0)return;let n=e.protectedKey,r=getAuditRecordKysely(e.database).selectFrom(`diagnostic_events`).select(`event_key`).where(`scope`,`=`,e.scope),i=(n===void 0?r:r.where(`event_key`,`!=`,n)).orderBy(`sequence`,`asc`).limit(t);A(e.database,getAuditRecordKysely(e.database).deleteFrom(`diagnostic_events`).where(`scope`,`=`,e.scope).where(`event_key`,`in`,i))}function prepareSqliteAuditRecord(e,t){let n=JSON.stringify(t.value);if(n===void 0)throw Error(`Audit record ${e}/${t.key} is not JSON-serializable`);return{event_key:t.key,payload_json:n,created_at:t.createdAt}}function createAuditRecordInsert(e){return v(e,t=>getAuditRecordKysely(e).insertInto(`diagnostic_events`).values({scope:t(e=>e.scope),event_key:t(e=>e.event_key),payload_json:t(e=>e.payload_json),created_at:t(e=>e.created_at),sequence:t(e=>e.sequence)}).onConflict(e=>e.columns([`scope`,`event_key`]).doNothing()))}const Iu=r(createAuditRecordInsert);function createSqliteAuditRecordKernel(e,t){let n=t.scope,r=t.maxEntries,prune=(t,i)=>pruneAuditRecords({database:e,scope:n,maxEntries:r,count:t,protectedKey:i}),selectEntries=()=>getAuditRecordKysely(e).selectFrom(`diagnostic_events`).select([`event_key`,`payload_json`,`created_at`,`sequence`]).where(`scope`,`=`,n);function insertRecord(t){return Number(Iu(e)({...t,scope:n}).numAffectedRows??0)}function upsertPreparedRecord(t){let r=readAuditWriteState({database:e,scope:n,legacy:!1,key:t.event_key});A(e,getAuditRecordKysely(e).insertInto(`diagnostic_events`).values({scope:n,event_key:t.event_key,payload_json:t.payload_json,created_at:t.created_at,sequence:r.nextSequence}).onConflict(e=>e.columns([`scope`,`event_key`]).doUpdateSet({payload_json:t.payload_json,created_at:t.created_at}))),prune(r.count+ +!r.keyExists,t.event_key)}function deleteRecord(t){A(e,getAuditRecordKysely(e).deleteFrom(`diagnostic_events`).where(`scope`,`=`,n).where(`event_key`,`=`,t))}return{register(t){let r=readAuditWriteState({database:e,scope:n,legacy:!1}),i=insertRecord({...t,sequence:r.nextSequence});prune(r.count+i,t.event_key)},upsert:upsertPreparedRecord,delete:deleteRecord,compareAndSet(t,r,i){return(C(e,getAuditRecordKysely(e).selectFrom(`diagnostic_events`).select(`payload_json`).where(`scope`,`=`,n).where(`event_key`,`=`,t))?.payload_json??null)===r&&(i?upsertPreparedRecord(i):deleteRecord(t),!0)},registerLegacyMany(t){let r=readAuditWriteState({database:e,scope:n,legacy:!0}),i=r.nextSequence,a=r.count;for(let e of t)a+=insertRecord({...e,sequence:i}),i+=1;prune(a)},entries(){return A(e,selectEntries().orderBy(`sequence`,`asc`)).rows.map(e=>{let{sequence:t,...n}=parseAuditRecord(e);return n})},latest(t){let n=selectEntries(),r=t.beforeSequence===void 0?n:n.where(`sequence`,`<`,t.beforeSequence);return A(e,r.orderBy(`sequence`,`desc`).limit(t.limit)).rows.map(e=>parseAuditRecord(e))}}}const Lu=[[`failure_delivery_mode`,`mode`],[`failure_delivery_channel`,`channel`],[`failure_delivery_to`,`to`],[`failure_delivery_account_id`,`accountId`]];function reprojectLegacyCronJson(e){let t=Lu.map(([t])=>P(e,`cron_jobs`,t)?W(t):`NULL AS ${W(t)}`),n=P(e,`cron_jobs`,`last_run_status`)?`last_run_status`:`NULL AS last_run_status`,r=e.prepare(`SELECT store_key, job_id, enabled, job_json, state_json, ${n}, ${t.join(`, `)}
         FROM cron_jobs`).all(),i=e.prepare(`UPDATE cron_jobs SET job_json = ?, state_json = ? WHERE store_key = ? AND job_id = ?`);for(let e of r){if(typeof e.store_key!=`string`||typeof e.job_id!=`string`||typeof e.job_json!=`string`||typeof e.state_json!=`string`)throw Error(`OpenClaw v12 cron job row is not canonical`);let t=L(safeParseJson(e.job_json)),n=L(safeParseJson(e.state_json));if(!t||!n)continue;let r=!1,a=L(t.delivery),o=L(a?.failureDestination);if((!Object.hasOwn(t,`delivery`)||a!==null)&&(!a||!Object.hasOwn(a,`failureDestination`)||o!==null)){let n=a??{},i=o??{};for(let[t,n]of Lu){let a=e[t];typeof a!=`string`||Object.hasOwn(i,n)||(i[n]=a===``?null:a,r=!0)}r&&(n.failureDestination=i,t.delivery=n)}typeof t.enabled!=`boolean`&&(t.enabled=e.enabled!==0,r=!0);let s=Object.hasOwn(n,`lastStatus`);!Object.hasOwn(n,`lastRunStatus`)&&(s||typeof e.last_run_status==`string`)&&(n.lastRunStatus=s?n.lastStatus:e.last_run_status,r=!0),r&&i.run(JSON.stringify(t),JSON.stringify(n),e.store_key,e.job_id)}}function rebuildJsonCanonicalTable(e,t){let n=`${t}_migration_v13`;if(M(e,n))throw Error(`OpenClaw v13 migration table already exists: ${n}`);let r=B(H,t,{errorMessage:`Canonical ${t} schema block is missing`}).replace(`CREATE TABLE IF NOT EXISTS ${t} (`,`CREATE TABLE ${n} (`);e.exec(r);let i=e.prepare(`PRAGMA table_xinfo(${n})`).all().flatMap(e=>e.hidden===0&&typeof e.name==`string`?[e.name]:[]),a=i.map(n=>pl.some(e=>e.tableName===t&&e.columnName===n)&&!P(e,t,n)?`NULL`:W(n));e.exec(`INSERT INTO ${n} (${i.map(W).join(`, `)}) SELECT ${a.join(`, `)} FROM ${t};`),e.exec(`DROP TABLE ${t};`),e.exec(`ALTER TABLE ${n} RENAME TO ${t};`)}function migrateJsonCanonicalWideRowsV13(e,t){if(t>=13)return!1;let n=!1;M(e,`cron_jobs`)&&P(e,`cron_jobs`,`schedule_kind`)&&(reprojectLegacyCronJson(e),rebuildJsonCanonicalTable(e,`cron_jobs`),n=!0);let r=M(e,`workspace_setup_state`),i=M(e,`workspace_attestations`);if(r&&!P(e,`workspace_setup_state`,`attested_at_ms`)&&(e.exec(`ALTER TABLE workspace_setup_state ADD COLUMN attested_at_ms INTEGER;`),e.exec(`ALTER TABLE workspace_setup_state ADD COLUMN attestation_updated_at_ms INTEGER;`),rebuildJsonCanonicalTable(e,`workspace_setup_state`),n=!0),i){e.exec(`
      UPDATE workspace_setup_state
         SET attested_at_ms = (
               SELECT attested_at_ms FROM workspace_attestations
                WHERE workspace_attestations.workspace_key = workspace_setup_state.workspace_key
             ),
             attestation_updated_at_ms = (
               SELECT updated_at_ms FROM workspace_attestations
                WHERE workspace_attestations.workspace_key = workspace_setup_state.workspace_key
             )
       WHERE workspace_key IN (SELECT workspace_key FROM workspace_attestations);
    `);let t=M(e,`workspace_path_aliases`)?`(SELECT alias.workspace_path FROM workspace_path_aliases alias
           WHERE alias.workspace_key = a.workspace_key LIMIT 1)`:`NULL`;e.exec(`
      INSERT INTO workspace_setup_state (
        workspace_key, workspace_path, attested_at_ms, attestation_updated_at_ms
      )
      SELECT a.workspace_key,
             ${t},
             a.attested_at_ms,
             a.updated_at_ms
        FROM workspace_attestations a
       WHERE a.workspace_key NOT IN (SELECT workspace_key FROM workspace_setup_state);
    `),e.exec(`DROP TABLE workspace_attestations;`),n=!0}(r||i)&&M(e,`workspace_generated_bootstrap_hashes`)&&(rebuildJsonCanonicalTable(e,`workspace_generated_bootstrap_hashes`),e.exec(`
      DELETE FROM workspace_generated_bootstrap_hashes
       WHERE workspace_key NOT IN (SELECT workspace_key FROM workspace_setup_state);
    `));for(let[t,r,i]of[[`auth_profile_stores`,`store_json`,`authProfiles.store`],[`auth_profile_state`,`state_json`,`authProfiles.state`]])M(e,t)&&(e.prepare(`INSERT INTO config_machine_state (state_key, value_json, updated_at_ms)
       SELECT ?, ${r}, updated_at FROM ${t} WHERE store_key = 'shared'
       ON CONFLICT(state_key) DO NOTHING`).run(i),e.exec(`DROP TABLE ${t};`),n=!0);if(M(e,`installed_plugin_index`)){let t=e.prepare(`SELECT * FROM installed_plugin_index WHERE index_key = 'installed-plugin-index'`).get();if(t){let n=L(safeParseJson(String(t.install_records_json))),r=safeParseJson(String(t.plugins_json)),i=safeParseJson(String(t.diagnostics_json));if(!n||!Array.isArray(r)||!Array.isArray(i)){let n=`plugins.installedIndex.quarantine`,r=`Preserved invalid legacy installed_plugin_index row in diagnostic_events (${n}). Run openclaw doctor --fix or openclaw plugins registry --refresh to repair the plugin index; inspect the preserved row if install records need recovery.`;createSqliteAuditRecordKernel(e,{scope:n,maxEntries:2**53-1}).register(prepareSqliteAuditRecord(n,{key:nc(`sha256`).update(JSON.stringify(t)).digest(`hex`),value:{level:`warn`,message:r,raw:t},createdAt:Date.now()})),ya(e,()=>er(`state/db`).warn(r))}let a={version:Number(t.version),...typeof t.warning==`string`&&t.warning?{warning:t.warning}:{},hostContractVersion:t.host_contract_version,compatRegistryVersion:t.compat_registry_version,migrationVersion:Number(t.migration_version),policyHash:t.policy_hash,generatedAtMs:Number(t.generated_at_ms),...typeof t.workspace_dir==`string`?{workspaceDir:t.workspace_dir}:{},...typeof t.refresh_reason==`string`&&t.refresh_reason?{refreshReason:t.refresh_reason}:{},installRecords:n,plugins:r,diagnostics:i};e.prepare(`INSERT INTO config_machine_state (state_key, value_json, updated_at_ms)
         VALUES (?, ?, ?) ON CONFLICT(state_key) DO NOTHING`).run(`plugins.installedIndex`,JSON.stringify({revision:Number(t.updated_at_ms),index:a}),Number(t.updated_at_ms))}e.exec(`DROP TABLE installed_plugin_index;`),n=!0}return M(e,`subagent_runs`)&&P(e,`subagent_runs`,`task`)&&(repairLegacySubagentRetainedResults(e),rebuildJsonCanonicalTable(e,`subagent_runs`),n=!0),n}const Ru=[`operator_approvals`,`cron_run_receipts`,`execution_decision_facts`,`skill_workshop_changes`];function migratePortableIdentityColumnsV22(e,t){if(t>=22)return!1;let n=!1,r=K(e)??Qa(e);for(let t of Ru){if(!M(e,t)||P(e,t,`cursor_id`))continue;let i=r.tableSql.get(t);if(typeof i!=`string`)throw Error(`Missing v22 cursor migration schema: ${t}`);let a=W(`${t}_migration_v22`),o=W(t),s=[...qe(e,t)].map(W).join(`, `);e.exec(`CREATE TABLE ${a} (cursor_id INTEGER NOT NULL, ${i.slice(i.indexOf(`(`)+1)};
      INSERT INTO ${a} (rowid, ${s}, cursor_id) SELECT rowid, ${s}, rowid FROM ${o} ORDER BY rowid;
      DROP TABLE ${o};
      ALTER TABLE ${a} RENAME TO ${o};`);for(let n of[...r.indexDefinitions.values(),...r.triggers.values()])n.table===t&&typeof n.sql==`string`&&e.exec(n.sql);n=!0}if(M(e,`acp_sessions`)){n=k(e,`acp_sessions`,`resume_agent_session_id TEXT`)||n,n=k(e,`acp_sessions`,`resume_acpx_session_id TEXT`)||n;let t=`CASE WHEN json_valid(identity_json) THEN identity_json END`,r=`char(9,10,11,12,13,32,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279)`;e.exec(`UPDATE acp_sessions SET
      resume_agent_session_id = CASE WHEN json_type(${t}, '$.agentSessionId') = 'text'
        THEN trim(json_extract(${t}, '$.agentSessionId'), ${r}) END,
      resume_acpx_session_id = CASE WHEN json_type(${t}, '$.acpxSessionId') = 'text'
        THEN trim(json_extract(${t}, '$.acpxSessionId'), ${r}) END;
      DROP INDEX IF EXISTS idx_acp_sessions_resume_agent;
      DROP INDEX IF EXISTS idx_acp_sessions_resume_acpx;`)}return n}function migrateTaskRunIndexesV24(e,t){return t>=24?!1:(e.exec(`
    DROP INDEX IF EXISTS idx_task_runs_run_id;
    DROP INDEX IF EXISTS idx_task_runs_status;
    DROP INDEX IF EXISTS idx_task_runs_runtime_status;
    DROP INDEX IF EXISTS idx_task_runs_cleanup_after;
    DROP INDEX IF EXISTS idx_task_runs_last_event_at;
    DROP INDEX IF EXISTS idx_task_runs_owner_key;
    DROP INDEX IF EXISTS idx_task_runs_parent_flow_id;
    DROP INDEX IF EXISTS idx_task_runs_child_session_key;
    DROP INDEX IF EXISTS idx_task_runs_requester_session_key;
    DROP INDEX IF EXISTS idx_task_runs_runtime_source_ended;
    DROP INDEX IF EXISTS idx_task_runs_runtime_ended;
`),!0)}function migrateSqliteTableWithoutRowid(e,t){let n=K(e)??Qa(e),r=n.tableSql.get(t);if(!r)return!1;let i=hi(r,`(`),a=pi(r,i),o=r.slice(a+1).replace(/;\s*$/u,``).trim();if(/\bWITHOUT\s+ROWID\b/iu.test(o))return!1;let s=W(t),c=W(`${t}_without_rowid_migration`),l=[...qe(e,t)].map(W).join(`, `);e.exec(`CREATE TABLE ${c} ${r.slice(i,a+1)}
      ${o?`${o}, `:``}WITHOUT ROWID;
    INSERT INTO ${c} (${l}) SELECT ${l} FROM ${s};
    DROP TABLE ${s};
    ALTER TABLE ${c} RENAME TO ${s};`);for(let r of[...n.indexDefinitions.values(),...n.triggers.values()])r.table===t&&typeof r.sql==`string`&&e.exec(r.sql);return!0}function withLegacyStateHeadLayout(e){return e.replace(/(CREATE TABLE IF NOT EXISTS session_state_heads \([\s\S]*?\n\) STRICT), WITHOUT ROWID;/u,`$1;`)}function migrateSessionStateHeadLayoutV26(e,t){return t<26&&migrateSqliteTableWithoutRowid(e,`session_state_heads`)}function withLegacyStateWriteIndexes(e){return`${e.replace(/ON state_leases\(owner\);/u,`ON state_leases(owner, updated_at DESC);`)}
CREATE INDEX IF NOT EXISTS idx_skill_usage_key
  ON skill_usage(skill_key, skill_file);
CREATE INDEX IF NOT EXISTS idx_acp_replay_events_session_seq
  ON acp_replay_events(session_id, seq);
`}function migrateStateWriteIndexesV27(e,t){return t>=27?!1:(e.exec(`
  DROP INDEX IF EXISTS idx_acp_replay_events_session_seq;
  DROP INDEX IF EXISTS idx_skill_usage_key;
  DROP INDEX IF EXISTS idx_state_leases_owner;
`),!0)}const zu=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,Bu={name:`state.external-ownership`,read(e){if(e===null)return null;if(I(e)&&e.version===1&&e.mode===`external`&&typeof e.managerId==`string`&&typeof e.claimedAt==`number`)return{version:1,mode:`external`,managerId:e.managerId,claimedAt:e.claimedAt}}};function isOpenClawStateWriteContentionError(e){return e instanceof Ca||e instanceof fu||Oa(e)}function parseExternalOwnership(e,t){let n;try{n=JSON.parse(e)}catch{throw new yi(t,`reserved value is not valid JSON`)}let r=I(n)?n:void 0,i=r?Object.keys(r).toSorted().join(`,`):``,a=r?.managerId,o=r?.claimedAt;if(i!==`claimedAt,managerId,mode,version`||r?.version!==1||r?.mode!==`external`||typeof a!=`string`||!zu.test(a)||typeof o!=`number`||!Number.isSafeInteger(o)||o<0||o>864e13)throw new yi(t,`reserved value does not match the version 1 external ownership contract`);return{version:1,mode:`external`,managerId:a,claimedAt:o}}function inspectOpenClawStateOwnershipFromDatabase(e,t,n=!1){try{if(!n&&!M(e,`config_machine_state`))return null;let r=n||z(e)?`SELECT value_json FROM config_machine_state WHERE state_key = ? LIMIT 1`:`SELECT value_json FROM config_machine_state NOT INDEXED WHERE state_key = ? LIMIT 1`,i=e.prepare(r).get(`gateway.supervision`);if(!i)return null;if(typeof i.value_json!=`string`)throw new yi(t,`reserved value is not text`);return parseExternalOwnership(i.value_json,t)}catch(e){throw Jo(e,t)}}function assertOwnershipAllowsWrite(e,t,n){if(e&&!He(n))throw new Vi(t,e.managerId)}function assertOpenClawStateWriteAllowed(e){let t=X.resolve(e.databasePath);Je(t);let n=e.inspectOwnership?void 0:V(e.database,Bu);if(n===void 0){let r=inspectOpenClawStateOwnershipFromDatabase(e.database,t,e.schemaReady);n=e.inspectOwnership?void 0:V(e.database,Bu),n===void 0&&(n=r,fi(e.database,Bu,n))}assertOwnershipAllowsWrite(n,t,e.env??process.env)}const Vu=/* @__PURE__ */ new Map;function getOpenClawStateRuntimeSchema(e,t=H){let{includeVersionLazyAdditiveTables:n,includeAgentDeletionJournal:r=!0}=e,i=`${n}:${r}:${t===`

CREATE TABLE IF NOT EXISTS mcp_oauth_stores (
  store_key TEXT NOT NULL PRIMARY KEY,
  format_version INTEGER NOT NULL CHECK (format_version = 1),
  store_json TEXT NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS mcp_oauth_pending_authorizations (
  state TEXT NOT NULL PRIMARY KEY,
  store_key TEXT NOT NULL,
  create_time INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS diagnostic_events (
  scope TEXT NOT NULL,
  event_key TEXT NOT NULL,
  payload_json TEXT NOT NULL,
  created_at INTEGER NOT NULL,
  sequence INTEGER NOT NULL DEFAULT 0,
  PRIMARY KEY (scope, event_key)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_diagnostic_events_scope_sequence
  ON diagnostic_events(scope, sequence, event_key);

CREATE TABLE IF NOT EXISTS skill_usage (
  skill_file TEXT NOT NULL PRIMARY KEY,
  skill_key TEXT NOT NULL,
  skill_name TEXT NOT NULL,
  skill_source TEXT NOT NULL,
  first_used_at_ms INTEGER NOT NULL,
  last_used_at_ms INTEGER NOT NULL,
  use_count INTEGER NOT NULL,
  last_agent_id TEXT
) STRICT;

-- Profile-owned skill library: additive, absent until first publication/import.
CREATE TABLE IF NOT EXISTS skill_library_entries (
  skill_id TEXT NOT NULL PRIMARY KEY,
  owner_profile_id TEXT,
  author_profile_id TEXT NOT NULL,
  slug TEXT NOT NULL,
  current_revision TEXT NOT NULL,
  shared INT NOT NULL,
  enabled INT NOT NULL,
  removed INT NOT NULL,
  created_at INT NOT NULL,
  updated_at INT NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS skill_library_revisions (
  skill_id TEXT NOT NULL,
  revision TEXT NOT NULL,
  description TEXT NOT NULL,
  files_json TEXT NOT NULL,
  created_at INT NOT NULL,
  PRIMARY KEY (skill_id, revision)
) STRICT;
CREATE TABLE IF NOT EXISTS skill_library_events (
  event_id TEXT NOT NULL PRIMARY KEY,
  skill_id TEXT NOT NULL,
  revision TEXT NOT NULL,
  action TEXT NOT NULL,
  actor_profile_id TEXT NOT NULL,
  created_at INT NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS skill_library_uploads (
  upload_id TEXT NOT NULL PRIMARY KEY,
  owner_profile_id TEXT NOT NULL,
  slug TEXT NOT NULL,
  size_bytes INT NOT NULL,
  sha256 TEXT NOT NULL,
  archive_blob BLOB NOT NULL,
  expires_at INT NOT NULL,
  published_skill_id TEXT
) STRICT;
-- End profile-owned skill library.

CREATE TABLE IF NOT EXISTS skill_workshop_changes (
  cursor_id INTEGER NOT NULL,
  change_id TEXT NOT NULL PRIMARY KEY,
  agent_id TEXT NOT NULL,
  skill_name TEXT NOT NULL,
  action TEXT NOT NULL CHECK (action IN ('create', 'patch', 'write_file', 'remove_file', 'archive', 'restore')),
  actor TEXT NOT NULL CHECK (actor IN ('agent', 'review', 'curator', 'user')),
  summary TEXT NOT NULL,
  version_id TEXT,
  session_key TEXT,
  run_id TEXT,
  created_at_ms INTEGER NOT NULL
) STRICT;

CREATE UNIQUE INDEX IF NOT EXISTS skill_workshop_changes_cursor_id_idx
  ON skill_workshop_changes(cursor_id);

CREATE INDEX IF NOT EXISTS idx_skill_workshop_changes_agent_time
  ON skill_workshop_changes(agent_id, created_at_ms);

CREATE TABLE IF NOT EXISTS audit_events (
  sequence INTEGER PRIMARY KEY AUTOINCREMENT,
  event_id TEXT NOT NULL UNIQUE,
  source_id TEXT NOT NULL UNIQUE,
  schema_version INTEGER NOT NULL DEFAULT 1,
  source_sequence INTEGER NOT NULL,
  occurred_at INTEGER NOT NULL,
  kind TEXT NOT NULL,
  action TEXT NOT NULL,
  status TEXT NOT NULL,
  error_code TEXT,
  actor_type TEXT NOT NULL,
  actor_id TEXT NOT NULL,
  agent_id TEXT,
  session_key TEXT,
  session_id TEXT,
  run_id TEXT,
  tool_call_id TEXT,
  tool_name TEXT,
  direction TEXT,
  channel TEXT,
  conversation_kind TEXT,
  message_outcome TEXT,
  reason_code TEXT,
  delivery_kind TEXT,
  failure_stage TEXT,
  duration_ms INTEGER,
  result_count INTEGER,
  account_ref TEXT,
  conversation_ref TEXT,
  message_ref TEXT,
  target_ref TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_audit_events_time
  ON audit_events(occurred_at DESC, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_agent_sequence
  ON audit_events(agent_id, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_session_sequence
  ON audit_events(session_key, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_run_sequence
  ON audit_events(run_id, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_kind_sequence
  ON audit_events(kind, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_status_sequence
  ON audit_events(status, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_channel_sequence
  ON audit_events(channel, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_direction_sequence
  ON audit_events(direction, sequence DESC);

CREATE TABLE IF NOT EXISTS outbound_message_execution_bindings (
  event_id TEXT NOT NULL PRIMARY KEY,
  context_id TEXT NOT NULL CHECK (length(context_id) BETWEEN 1 AND 256),
  execution_id TEXT NOT NULL CHECK (length(execution_id) BETWEEN 1 AND 256),
  run_id TEXT NOT NULL CHECK (length(run_id) BETWEEN 1 AND 256),
  FOREIGN KEY (event_id) REFERENCES audit_events(event_id) ON DELETE CASCADE
) STRICT;
CREATE INDEX IF NOT EXISTS outbound_message_execution_bindings_execution_event_idx
  ON outbound_message_execution_bindings (context_id, execution_id, run_id, event_id);

CREATE TABLE IF NOT EXISTS outbound_message_progress (
  sequence INTEGER PRIMARY KEY AUTOINCREMENT,
  progress_id TEXT NOT NULL UNIQUE CHECK (length(progress_id) BETWEEN 1 AND 256),
  source_id TEXT NOT NULL UNIQUE CHECK (length(source_id) BETWEEN 1 AND 512),
  source_sequence INTEGER NOT NULL CHECK (source_sequence >= 1),
  schema_version INTEGER NOT NULL CHECK (schema_version = 1),
  occurred_at INTEGER NOT NULL CHECK (occurred_at >= 0),
  action TEXT NOT NULL CHECK (
    action IN ('message.outbound.queued', 'message.outbound.platform-started')
  ),
  outcome TEXT NOT NULL CHECK (outcome IN ('queued', 'platform_started')),
  actor_type TEXT NOT NULL CHECK (actor_type IN ('agent', 'system')),
  actor_id TEXT NOT NULL CHECK (length(actor_id) BETWEEN 1 AND 256),
  agent_id TEXT CHECK (agent_id IS NULL OR length(agent_id) BETWEEN 1 AND 256),
  run_id TEXT CHECK (run_id IS NULL OR length(run_id) BETWEEN 1 AND 256),
  context_id TEXT,
  execution_id TEXT,
  channel TEXT NOT NULL CHECK (length(channel) BETWEEN 1 AND 256),
  conversation_kind TEXT NOT NULL CHECK (
    conversation_kind IN ('direct', 'group', 'channel', 'unknown')
  ),
  duration_ms INTEGER CHECK (duration_ms IS NULL OR duration_ms >= 0),
  account_ref TEXT,
  conversation_ref TEXT,
  target_ref TEXT,
  UNIQUE (occurred_at, progress_id)
) STRICT;
CREATE INDEX IF NOT EXISTS outbound_message_progress_occurred_idx
  ON outbound_message_progress (occurred_at, sequence);
CREATE INDEX IF NOT EXISTS outbound_message_progress_run_occurred_idx
  ON outbound_message_progress (run_id, occurred_at, sequence);

CREATE TABLE IF NOT EXISTS audit_identity_keys (
  id INTEGER NOT NULL PRIMARY KEY CHECK (id = 1),
  key_id TEXT NOT NULL,
  key BLOB NOT NULL,
  created_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS config_revision_keys (
  id INTEGER NOT NULL PRIMARY KEY CHECK (id = 1),
  hmac_key BLOB NOT NULL CHECK (length(hmac_key) = 32)
) STRICT;

CREATE TABLE IF NOT EXISTS execution_identity_contexts (
  context_id TEXT NOT NULL PRIMARY KEY CHECK (length(context_id) BETWEEN 1 AND 256),
  execution_id TEXT NOT NULL UNIQUE CHECK (length(execution_id) BETWEEN 1 AND 256),
  run_id TEXT NOT NULL CHECK (length(run_id) BETWEEN 1 AND 256),
  created_at INTEGER NOT NULL CHECK (created_at >= 0),
  coverage_state TEXT NOT NULL CHECK (
    coverage_state IN ('attribution-only', 'unattributed', 'unknown', 'unsupported')
  ),
  context_bytes INTEGER NOT NULL CHECK (context_bytes BETWEEN 1 AND 16384),
  context_json TEXT NOT NULL CHECK (length(context_json) > 0),
  UNIQUE (created_at, context_id)
) STRICT;
CREATE INDEX IF NOT EXISTS execution_identity_contexts_run_created_idx
  ON execution_identity_contexts (run_id, created_at, execution_id);

CREATE TABLE IF NOT EXISTS execution_decision_facts (
  cursor_id INTEGER NOT NULL,
  receipt_id TEXT NOT NULL PRIMARY KEY CHECK (length(receipt_id) BETWEEN 1 AND 256),
  context_id TEXT NOT NULL CHECK (length(context_id) BETWEEN 1 AND 256),
  execution_id TEXT NOT NULL CHECK (length(execution_id) BETWEEN 1 AND 256),
  run_id TEXT NOT NULL CHECK (length(run_id) BETWEEN 1 AND 256),
  action_id TEXT CHECK (action_id IS NULL OR length(action_id) BETWEEN 1 AND 256),
  action_family TEXT NOT NULL CHECK (length(action_family) BETWEEN 1 AND 256),
  decision_outcome TEXT NOT NULL CHECK (
    decision_outcome IN ('allowed', 'denied', 'not-applicable', 'unknown')
  ),
  coverage_state TEXT NOT NULL CHECK (
    coverage_state IN ('enforced', 'attribution-only', 'unattributed', 'unknown', 'unsupported')
  ),
  reason_code TEXT NOT NULL CHECK (length(reason_code) BETWEEN 1 AND 256),
  owner TEXT NOT NULL CHECK (length(owner) BETWEEN 1 AND 256),
  source_ref TEXT NOT NULL CHECK (length(source_ref) BETWEEN 1 AND 256),
  occurred_at INTEGER NOT NULL CHECK (occurred_at >= 0),
  receipt_bytes INTEGER NOT NULL CHECK (receipt_bytes BETWEEN 1 AND 16384),
  receipt_json TEXT NOT NULL CHECK (length(receipt_json) > 0),
  UNIQUE (occurred_at, receipt_id)
) STRICT;
CREATE UNIQUE INDEX IF NOT EXISTS execution_decision_facts_cursor_id_idx
  ON execution_decision_facts(cursor_id);

CREATE INDEX IF NOT EXISTS execution_decision_facts_context_occurred_idx
  ON execution_decision_facts (context_id, occurred_at, receipt_id);
CREATE INDEX IF NOT EXISTS execution_decision_facts_run_occurred_idx
  ON execution_decision_facts (run_id, occurred_at, receipt_id);

-- Exact admission identity stays separate from owner-native lifecycle rows so
-- older readers retain byte-compatible cron/task/flow table definitions.
CREATE TABLE IF NOT EXISTS execution_owner_lifecycle_bindings (
  owner_kind TEXT NOT NULL,
  owner_id TEXT NOT NULL,
  context_id TEXT NOT NULL,
  execution_id TEXT NOT NULL,
  PRIMARY KEY (owner_kind, owner_id)
) STRICT;

CREATE TABLE IF NOT EXISTS session_state_events (
  sequence INTEGER PRIMARY KEY AUTOINCREMENT,
  dedupe_key TEXT UNIQUE,
  session_key TEXT NOT NULL,
  session_id TEXT,
  agent_id TEXT NOT NULL,
  kind TEXT NOT NULL,
  actor_type TEXT NOT NULL,
  actor_id TEXT,
  run_id TEXT,
  occurred_at INTEGER NOT NULL,
  summary TEXT NOT NULL,
  payload_json TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_session_state_events_session_sequence
  ON session_state_events(session_key, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_session_state_events_time
  ON session_state_events(occurred_at DESC, sequence DESC);

CREATE TABLE IF NOT EXISTS session_state_heads (
  session_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  last_sequence INTEGER NOT NULL,
  pruned_max_sequence INTEGER NOT NULL DEFAULT 0,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (session_key, agent_id)
) STRICT, WITHOUT ROWID;

-- Notifiable watcher identity is the bare session key, matching the process-local
-- system-event queue it feeds. Provenance distinguishes explicit immediate-wake
-- watches from ambient queue-only group watches. Other bare keys
-- (session.scope="global") are ambiguous across agents and excluded until watcher
-- identity is agent-scoped end-to-end.
CREATE TABLE IF NOT EXISTS session_watch_cursors (
  watcher_session_key TEXT NOT NULL,
  watcher_store_path TEXT,
  target_session_key TEXT NOT NULL,
  last_seen_sequence INTEGER NOT NULL DEFAULT 0,
  notified_sequence INTEGER NOT NULL DEFAULT 0,
  material_sequence INTEGER NOT NULL DEFAULT 0,
  provenance TEXT NOT NULL DEFAULT 'explicit' CHECK (provenance IN ('explicit', 'ambient-group')),
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (watcher_session_key, target_session_key)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_session_watch_cursors_target
  ON session_watch_cursors(target_session_key);

CREATE TABLE IF NOT EXISTS session_upstream_links (
  session_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  catalog_id TEXT NOT NULL,
  host_id TEXT NOT NULL,
  thread_id TEXT NOT NULL,
  upstream_kind TEXT NOT NULL,
  upstream_ref_json TEXT,
  last_marker_json TEXT,
  last_scanned_at INTEGER,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  -- (session_key, agent_id) composite identity: under session.scope="global" agents
  -- share bare keys; a key-only row would let one agent overwrite another's upstream.
  PRIMARY KEY (session_key, agent_id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_session_upstream_links_catalog_id
  ON session_upstream_links(catalog_id);

CREATE TABLE IF NOT EXISTS state_leases (
  scope TEXT NOT NULL,
  lease_key TEXT NOT NULL,
  owner TEXT NOT NULL,
  expires_at INTEGER,
  heartbeat_at INTEGER,
  payload_json TEXT,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (scope, lease_key)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_state_leases_expiry
  ON state_leases(expires_at, scope, lease_key)
  WHERE expires_at IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_state_leases_owner
  ON state_leases(owner);

CREATE TABLE IF NOT EXISTS exec_approvals_config (
  config_key TEXT NOT NULL PRIMARY KEY,
  raw_json TEXT NOT NULL,
  socket_path TEXT,
  has_socket_token INTEGER NOT NULL,
  default_security TEXT,
  default_ask TEXT,
  default_ask_fallback TEXT,
  auto_allow_skills INTEGER,
  agent_count INTEGER NOT NULL,
  allowlist_count INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS operator_approvals (
  cursor_id INTEGER NOT NULL,
  approval_id TEXT NOT NULL PRIMARY KEY CHECK (
    length(approval_id) > 0 AND approval_id NOT IN ('.', '..')
  ),
  resolution_ref TEXT NOT NULL CHECK (
    length(resolution_ref) = 43 AND resolution_ref NOT GLOB '*[^A-Za-z0-9_-]*'
  ),
  kind TEXT NOT NULL CHECK (kind IN ('exec', 'plugin', 'system-agent')),
  status TEXT NOT NULL CHECK (status IN ('pending', 'allowed', 'denied', 'expired', 'cancelled')),
  presentation_json TEXT NOT NULL,
  requested_by_device_id TEXT,
  requested_by_client_id TEXT,
  requested_by_device_token_auth INTEGER NOT NULL DEFAULT 0,
  reviewer_device_ids_json TEXT NOT NULL,
  source_agent_id TEXT,
  source_session_key TEXT,
  source_session_id TEXT,
  source_run_id TEXT,
  source_tool_call_id TEXT,
  source_tool_name TEXT,
  audience_session_keys_json TEXT NOT NULL,
  runtime_epoch TEXT NOT NULL,
  created_at_ms INTEGER NOT NULL,
  expires_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  decision TEXT CHECK (decision IN ('allow-once', 'allow-always', 'deny')),
  terminal_reason TEXT CHECK (
    terminal_reason IN (
      'user',
      'timeout',
      'malformed-verdict',
      'no-route',
      'run-aborted',
      'gateway-restart',
      'storage-corrupt'
    )
  ),
  resolved_at_ms INTEGER,
  resolver_kind TEXT CHECK (resolver_kind IN ('device', 'channel', 'runtime', 'system')),
  resolver_id TEXT,
  consumed_at_ms INTEGER,
  consumed_by TEXT,
  CHECK (expires_at_ms >= created_at_ms),
  CHECK (updated_at_ms >= created_at_ms),
  CHECK (resolved_at_ms IS NULL OR resolved_at_ms >= created_at_ms),
  CHECK (resolved_at_ms IS NULL OR resolved_at_ms <= updated_at_ms),
  CHECK (consumed_at_ms IS NULL OR consumed_at_ms >= resolved_at_ms),
  CHECK (consumed_at_ms IS NULL OR consumed_at_ms <= updated_at_ms),
  CHECK (requested_by_device_token_auth IN (0, 1)),
  CHECK (
    (
      status = 'pending'
      AND decision IS NULL
      AND terminal_reason IS NULL
      AND resolved_at_ms IS NULL
      AND resolver_kind IS NULL
      AND resolver_id IS NULL
      AND consumed_at_ms IS NULL
      AND consumed_by IS NULL
    )
    OR (
      status = 'allowed'
      AND decision IN ('allow-once', 'allow-always')
      AND terminal_reason = 'user'
      AND resolved_at_ms IS NOT NULL
      AND resolver_kind IS NOT NULL
    )
    OR (
      status = 'denied'
      AND decision = 'deny'
      AND terminal_reason IN ('user', 'malformed-verdict', 'no-route', 'storage-corrupt')
      AND resolved_at_ms IS NOT NULL
      AND resolver_kind IS NOT NULL
      AND consumed_at_ms IS NULL
      AND consumed_by IS NULL
    )
    OR (
      status = 'expired'
      AND decision = 'deny'
      AND terminal_reason = 'timeout'
      AND resolved_at_ms IS NOT NULL
      AND resolver_kind IS NOT NULL
      AND consumed_at_ms IS NULL
      AND consumed_by IS NULL
    )
    OR (
      status = 'cancelled'
      AND decision = 'deny'
      AND terminal_reason IN ('run-aborted', 'gateway-restart')
      AND resolved_at_ms IS NOT NULL
      AND resolver_kind IS NOT NULL
      AND consumed_at_ms IS NULL
      AND consumed_by IS NULL
    )
  ),
  CHECK (
    (consumed_at_ms IS NULL AND consumed_by IS NULL)
    OR (
      status = 'allowed'
      AND decision = 'allow-once'
      AND consumed_at_ms IS NOT NULL
      AND consumed_by IS NOT NULL
    )
  )
) STRICT;

CREATE UNIQUE INDEX IF NOT EXISTS idx_operator_approvals_cursor_id
  ON operator_approvals(cursor_id);

CREATE INDEX IF NOT EXISTS idx_operator_approvals_status_expiry
  ON operator_approvals(status, expires_at_ms, approval_id);

CREATE UNIQUE INDEX IF NOT EXISTS idx_operator_approvals_resolution_ref
  ON operator_approvals(resolution_ref);

CREATE INDEX IF NOT EXISTS idx_operator_approvals_source_session_created
  ON operator_approvals(source_session_key, created_at_ms DESC, approval_id);

CREATE INDEX IF NOT EXISTS idx_operator_approvals_source_run_resolved
  ON operator_approvals(source_run_id, resolved_at_ms, approval_id)
  WHERE source_run_id IS NOT NULL AND resolved_at_ms IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_operator_approvals_resolved
  ON operator_approvals(resolved_at_ms, approval_id)
  WHERE resolved_at_ms IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_operator_approvals_runtime_pending
  ON operator_approvals(runtime_epoch, approval_id)
  WHERE status = 'pending';

CREATE TABLE IF NOT EXISTS operator_approval_execution_identities (
  approval_id TEXT NOT NULL PRIMARY KEY
    REFERENCES operator_approvals(approval_id) ON DELETE CASCADE,
  source_context_id TEXT NOT NULL CHECK (
    length(source_context_id) BETWEEN 1 AND 256 AND source_context_id = trim(source_context_id)
  ),
  source_execution_id TEXT NOT NULL CHECK (
    length(source_execution_id) BETWEEN 1 AND 256 AND source_execution_id = trim(source_execution_id)
  )
) STRICT;

CREATE TABLE IF NOT EXISTS operator_approval_standing_grants (
  grant_id TEXT NOT NULL PRIMARY KEY CHECK (length(grant_id) > 0),
  minted_by_approval_id TEXT NOT NULL
    REFERENCES operator_approvals(approval_id) ON DELETE CASCADE,
  agent_id TEXT NOT NULL CHECK (length(agent_id) > 0),
  cron_job_id TEXT NOT NULL CHECK (length(cron_job_id) > 0),
  job_config_revision TEXT NOT NULL CHECK (length(job_config_revision) > 0),
  operation_binding TEXT NOT NULL CHECK (length(operation_binding) > 0),
  created_at_ms INTEGER NOT NULL,
  expires_at_ms INTEGER CHECK (expires_at_ms IS NULL OR expires_at_ms >= created_at_ms),
  revoked_at_ms INTEGER,
  revoked_by TEXT,
  last_used_at_ms INTEGER,
  use_count INTEGER NOT NULL DEFAULT 0
) STRICT;

CREATE INDEX IF NOT EXISTS idx_operator_approval_standing_grants_binding
  ON operator_approval_standing_grants(agent_id, cron_job_id, operation_binding, created_at_ms DESC);

CREATE TABLE IF NOT EXISTS operator_approval_standing_grant_generations (
  grant_id TEXT NOT NULL PRIMARY KEY
    REFERENCES operator_approval_standing_grants(grant_id) ON DELETE CASCADE,
  job_definition_generation INTEGER NOT NULL CHECK (job_definition_generation >= 1)
) STRICT;

CREATE TABLE IF NOT EXISTS schema_meta (
  meta_key TEXT NOT NULL PRIMARY KEY,
  role TEXT NOT NULL,
  schema_version INTEGER NOT NULL,
  agent_id TEXT,
  app_version TEXT,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS config_machine_state (
  state_key TEXT NOT NULL PRIMARY KEY,
  value_json TEXT NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS device_pairing_pending (
  request_id TEXT NOT NULL PRIMARY KEY,
  device_id TEXT NOT NULL,
  public_key TEXT NOT NULL,
  display_name TEXT,
  platform TEXT,
  device_family TEXT,
  client_id TEXT,
  client_mode TEXT,
  browser_origin TEXT,
  role TEXT,
  roles_json TEXT,
  scopes_json TEXT,
  remote_ip TEXT,
  silent INTEGER,
  is_repair INTEGER,
  ts INTEGER NOT NULL,
  refreshed_at_ms INTEGER
) STRICT;

CREATE INDEX IF NOT EXISTS idx_device_pairing_pending_device
  ON device_pairing_pending(device_id, ts DESC);

CREATE TABLE IF NOT EXISTS device_pairing_paired (
  device_id TEXT NOT NULL PRIMARY KEY,
  public_key TEXT NOT NULL,
  display_name TEXT,
  operator_label TEXT,
  platform TEXT,
  device_family TEXT,
  client_id TEXT,
  client_mode TEXT,
  browser_origin TEXT,
  role TEXT,
  roles_json TEXT,
  scopes_json TEXT,
  approved_scopes_json TEXT,
  remote_ip TEXT,
  tokens_json TEXT,
  approved_via TEXT,
  node_surface_json TEXT,
  pending_node_surface_json TEXT,
  created_at_ms INTEGER NOT NULL,
  approved_at_ms INTEGER NOT NULL,
  last_seen_at_ms INTEGER,
  last_seen_reason TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_device_pairing_paired_approved
  ON device_pairing_paired(approved_at_ms DESC, device_id);

CREATE TABLE IF NOT EXISTS device_bootstrap_tokens (
  token_key TEXT NOT NULL PRIMARY KEY,
  token TEXT NOT NULL,
  setup_id TEXT,
  ts INTEGER NOT NULL,
  device_id TEXT,
  public_key TEXT,
  profile_json TEXT,
  redeemed_profile_json TEXT,
  pending_profile_json TEXT,
  issued_at_ms INTEGER NOT NULL,
  last_used_at_ms INTEGER
) STRICT;

CREATE INDEX IF NOT EXISTS idx_device_bootstrap_tokens_ts
  ON device_bootstrap_tokens(ts);

-- Terminal outcome of a redeemed setup credential. The bootstrap row is deleted
-- on redemption, so this is the only durable proof a setup code succeeded; the
-- presenting client reconciles it when the completion broadcast is missed.
-- Non-secret only: never the bootstrap token or anything derived from it.
-- Bounded by retention to a handful of live rows, so the primary key is the
-- only access path worth having.
CREATE TABLE IF NOT EXISTS device_pair_setup_completions (
  setup_id TEXT NOT NULL PRIMARY KEY,
  device_id TEXT NOT NULL,
  device_name TEXT,
  access TEXT NOT NULL,
  completed_at_ms INTEGER NOT NULL,
  delivery_state TEXT NOT NULL CHECK (delivery_state IN ('uncertain', 'confirmed')),
  retain_until_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS device_pairing_join_codes (
  shortcode TEXT,
  payload_json TEXT,
  created_at_ms INTEGER,
  expires_at_ms INTEGER
) STRICT;

CREATE TABLE IF NOT EXISTS device_pairing_browser_requests (
  request_id TEXT NOT NULL PRIMARY KEY,
  code TEXT NOT NULL UNIQUE,
  device_id TEXT NOT NULL UNIQUE,
  public_key TEXT NOT NULL,
  remote_ip TEXT,
  user_agent TEXT,
  origin TEXT,
  status TEXT NOT NULL CHECK (status IN ('pending', 'approved', 'rejected')),
  approved_token_sha256 TEXT,
  created_at_ms INTEGER NOT NULL,
  expires_at_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS macos_port_guardian_records (
  pid INTEGER NOT NULL PRIMARY KEY,
  port INTEGER NOT NULL,
  command TEXT NOT NULL,
  mode TEXT NOT NULL,
  timestamp REAL NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_macos_port_guardian_records_port
  ON macos_port_guardian_records(port, timestamp DESC);

CREATE TABLE IF NOT EXISTS workspace_setup_state (
  workspace_key TEXT NOT NULL PRIMARY KEY,
  -- NULL only for attestation-only rows whose legacy source never recorded a
  -- path (orphan hashed-key attestations); setup rows always carry one.
  workspace_path TEXT,
  -- NULL setup columns mean an attestation-only row: replaceWorkspaceAttestation
  -- may record hashes before any setup milestone exists for the workspace.
  version INTEGER,
  bootstrap_seeded_at TEXT,
  setup_completed_at TEXT,
  updated_at INTEGER,
  attested_at_ms INTEGER,
  attestation_updated_at_ms INTEGER,
  bootstrap_deferred INTEGER,
  CHECK (version IS NULL OR workspace_path IS NOT NULL)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_workspace_setup_state_path
  ON workspace_setup_state(workspace_path);

CREATE TABLE IF NOT EXISTS workspace_path_aliases (
  alias_key TEXT NOT NULL PRIMARY KEY,
  alias_path TEXT NOT NULL,
  workspace_key TEXT NOT NULL,
  workspace_path TEXT NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_workspace_path_aliases_workspace
  ON workspace_path_aliases(workspace_key);



CREATE TABLE IF NOT EXISTS workspace_generated_bootstrap_hashes (
  workspace_key TEXT NOT NULL,
  filename TEXT NOT NULL,
  sha256 TEXT NOT NULL,
  PRIMARY KEY (workspace_key, filename),
  FOREIGN KEY (workspace_key) REFERENCES workspace_setup_state(workspace_key) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS native_hook_relay_bridges (
  relay_id TEXT NOT NULL PRIMARY KEY,
  pid INTEGER NOT NULL,
  hostname TEXT NOT NULL,
  port INTEGER NOT NULL,
  token TEXT NOT NULL,
  expires_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_native_hook_relay_bridges_expires
  ON native_hook_relay_bridges(expires_at_ms, relay_id);

CREATE TABLE IF NOT EXISTS managed_outgoing_image_records (
  attachment_id TEXT NOT NULL PRIMARY KEY,
  session_key TEXT NOT NULL,
  agent_id TEXT,
  message_id TEXT,
  created_at TEXT NOT NULL,
  updated_at TEXT,
  retention_class TEXT,
  alt TEXT NOT NULL,
  original_media_root TEXT NOT NULL,
  original_media_id TEXT NOT NULL,
  original_media_subdir TEXT NOT NULL,
  original_content_type TEXT NOT NULL,
  original_width INTEGER,
  original_height INTEGER,
  original_size_bytes INTEGER,
  original_filename TEXT,
  record_json TEXT NOT NULL,
  cleanup_pending INTEGER NOT NULL DEFAULT 0 CHECK (cleanup_pending IN (0, 1))
) STRICT;

CREATE INDEX IF NOT EXISTS idx_managed_outgoing_images_session
  ON managed_outgoing_image_records(session_key, created_at DESC, attachment_id);

CREATE INDEX IF NOT EXISTS idx_managed_outgoing_images_message
  ON managed_outgoing_image_records(session_key, message_id, attachment_id)
  WHERE message_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_managed_outgoing_images_agent_session
  ON managed_outgoing_image_records(session_key, agent_id, created_at DESC, attachment_id);

CREATE INDEX IF NOT EXISTS idx_managed_outgoing_images_agent_message
  ON managed_outgoing_image_records(session_key, agent_id, message_id, attachment_id)
  WHERE message_id IS NOT NULL;

CREATE TABLE IF NOT EXISTS channel_pairing_requests (
  channel_key TEXT NOT NULL,
  account_id TEXT NOT NULL,
  request_id TEXT NOT NULL,
  code TEXT NOT NULL,
  created_at TEXT NOT NULL,
  last_seen_at TEXT NOT NULL,
  meta_json TEXT,
  PRIMARY KEY (channel_key, account_id, request_id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_channel_pairing_requests_code
  ON channel_pairing_requests(channel_key, code);

CREATE INDEX IF NOT EXISTS idx_channel_pairing_requests_created
  ON channel_pairing_requests(channel_key, created_at, request_id);

CREATE TABLE IF NOT EXISTS channel_pairing_allow_entries (
  channel_key TEXT NOT NULL,
  account_id TEXT NOT NULL,
  entry TEXT NOT NULL,
  sort_order INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (channel_key, account_id, entry)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_channel_pairing_allow_account
  ON channel_pairing_allow_entries(channel_key, account_id, sort_order, entry);

CREATE TABLE IF NOT EXISTS web_push_subscriptions (
  endpoint_hash TEXT NOT NULL PRIMARY KEY,
  subscription_id TEXT NOT NULL UNIQUE,
  endpoint TEXT NOT NULL,
  p256dh TEXT NOT NULL,
  auth TEXT NOT NULL,
  device_id TEXT,
  user_profile_id TEXT,
  preferences_json TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_web_push_subscriptions_updated
  ON web_push_subscriptions(updated_at_ms DESC, subscription_id);

CREATE TABLE IF NOT EXISTS web_push_approval_deliveries (
  approval_id TEXT NOT NULL
    REFERENCES operator_approvals(approval_id) ON DELETE CASCADE,
  subscription_id TEXT NOT NULL
    REFERENCES web_push_subscriptions(subscription_id) ON DELETE CASCADE,
  device_id TEXT NOT NULL,
  user_profile_id TEXT,
  prepared_at_ms INTEGER NOT NULL,
  PRIMARY KEY (approval_id, subscription_id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_web_push_approval_deliveries_subscription
  ON web_push_approval_deliveries(subscription_id, approval_id);

CREATE TABLE IF NOT EXISTS apns_registrations (
  node_id TEXT NOT NULL PRIMARY KEY,
  transport TEXT NOT NULL,
  token TEXT,
  relay_handle TEXT,
  send_grant TEXT,
  installation_id TEXT,
  relay_origin TEXT,
  topic TEXT NOT NULL,
  environment TEXT NOT NULL,
  distribution TEXT,
  token_debug_suffix TEXT,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_apns_registrations_updated
  ON apns_registrations(updated_at_ms DESC, node_id);

CREATE TABLE IF NOT EXISTS apns_registration_tombstones (
  node_id TEXT NOT NULL PRIMARY KEY,
  deleted_at_ms INTEGER NOT NULL
) STRICT;

-- Node-host-owned launch journal. The descriptor and its credential remain
-- process memory only; this table records bounded supervision facts.
CREATE TABLE IF NOT EXISTS node_worker_launches (
  launch_id TEXT NOT NULL PRIMARY KEY
    CHECK (length(launch_id) BETWEEN 1 AND 256 AND instr(launch_id, char(0)) = 0),
  plan_hash TEXT NOT NULL
    CHECK (length(plan_hash) = 64 AND plan_hash NOT GLOB '*[^0-9a-f]*'),
  gateway_namespace TEXT NOT NULL
    CHECK (
      length(gateway_namespace) BETWEEN 1 AND 128
      AND gateway_namespace NOT GLOB '*[^A-Za-z0-9._-]*'
      AND gateway_namespace GLOB '[A-Za-z0-9]*'
    ),
  environment_id TEXT NOT NULL
    CHECK (length(environment_id) BETWEEN 1 AND 256 AND instr(environment_id, char(0)) = 0),
  session_id TEXT NOT NULL
    CHECK (length(session_id) BETWEEN 1 AND 256 AND instr(session_id, char(0)) = 0),
  owner_epoch INTEGER NOT NULL CHECK (owner_epoch BETWEEN 1 AND 9007199254740991),
  placement_generation INTEGER NOT NULL
    CHECK (placement_generation BETWEEN 0 AND 9007199254740991),
  run_id TEXT NOT NULL
    CHECK (length(run_id) BETWEEN 1 AND 256 AND instr(run_id, char(0)) = 0),
  state TEXT NOT NULL
    CHECK (state IN ('pending', 'running', 'completed', 'failed', 'interrupted', 'cancelled')),
  supervisor_pid INTEGER NOT NULL CHECK (supervisor_pid BETWEEN 1 AND 2147483647),
  supervisor_start_time INTEGER NOT NULL
    CHECK (supervisor_start_time BETWEEN 0 AND 9007199254740991),
  worker_pid INTEGER CHECK (worker_pid IS NULL OR worker_pid BETWEEN 1 AND 2147483647),
  worker_start_time INTEGER CHECK (
    worker_start_time IS NULL OR worker_start_time BETWEEN 0 AND 9007199254740991
  ),
  result_json TEXT CHECK (
    result_json IS NULL
    OR (
      length(CAST(result_json AS BLOB)) BETWEEN 1 AND 65536
      AND instr(result_json, char(0)) = 0
      AND json_valid(result_json)
    )
  ),
  error_text TEXT CHECK (
    error_text IS NULL
    OR (
      length(CAST(error_text AS BLOB)) BETWEEN 1 AND 4096
      AND instr(error_text, char(0)) = 0
      AND instr(error_text, char(10)) = 0
      AND instr(error_text, char(13)) = 0
    )
  ),
  completed_at_ms INTEGER CHECK (
    completed_at_ms IS NULL OR completed_at_ms BETWEEN 0 AND 9007199254740991
  ),
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms BETWEEN 0 AND 9007199254740991),
  updated_at_ms INTEGER NOT NULL CHECK (
    updated_at_ms BETWEEN created_at_ms AND 9007199254740991
  ),
  CHECK ((worker_pid IS NULL) = (worker_start_time IS NULL)),
  CHECK (
    (state = 'pending'
      AND worker_pid IS NULL AND result_json IS NULL AND error_text IS NULL
      AND completed_at_ms IS NULL)
    OR
    (state = 'running'
      AND worker_pid IS NOT NULL AND result_json IS NULL AND error_text IS NULL
      AND completed_at_ms IS NULL)
    OR
    (state = 'completed'
      AND result_json IS NOT NULL AND error_text IS NULL
      AND completed_at_ms BETWEEN created_at_ms AND updated_at_ms)
    OR
    (state IN ('failed', 'interrupted', 'cancelled')
      AND result_json IS NULL AND error_text IS NOT NULL
      AND completed_at_ms BETWEEN created_at_ms AND updated_at_ms)
  )
) STRICT;

CREATE INDEX IF NOT EXISTS idx_node_worker_launches_terminal_completed
  ON node_worker_launches(completed_at_ms, launch_id)
  WHERE completed_at_ms IS NOT NULL;

CREATE TABLE IF NOT EXISTS node_worker_launch_boots (
  launch_id TEXT NOT NULL PRIMARY KEY
    REFERENCES node_worker_launches(launch_id) ON DELETE CASCADE,
  boot_id TEXT CHECK (boot_id IS NULL OR length(boot_id) BETWEEN 1 AND 128)
) STRICT;

CREATE TABLE IF NOT EXISTS node_worker_launch_containers (
  launch_id TEXT PRIMARY KEY,
  container_json TEXT
) STRICT;

CREATE TABLE IF NOT EXISTS node_worker_launch_cleanup (
  launch_id TEXT NOT NULL PRIMARY KEY
    REFERENCES node_worker_launches(launch_id) ON DELETE CASCADE,
  cleanup_mode TEXT NOT NULL CHECK (cleanup_mode IN ('process-group', 'owned-anchor')),
  lineage_settled INTEGER CHECK (lineage_settled IS NULL OR lineage_settled = 1)
) STRICT;

-- Older readers retain owned-anchor custody: lineage EOF is not this certificate.
CREATE TABLE IF NOT EXISTS node_worker_launch_process_scopes (
  launch_id TEXT NOT NULL PRIMARY KEY
    REFERENCES node_worker_launches(launch_id) ON DELETE CASCADE,
  scope_kind TEXT NOT NULL CHECK (scope_kind = 'linux-subreaper'),
  descendants_reaped INTEGER CHECK (descendants_reaped IS NULL OR descendants_reaped = 1)
) STRICT;

-- Turn receipts have a shorter lifetime than their physical worker owner.
-- Keeping the launch running preserves capacity and predecessor cleanup semantics.
CREATE TABLE IF NOT EXISTS node_worker_turns (
  turn_id TEXT NOT NULL PRIMARY KEY
    CHECK (length(turn_id) BETWEEN 1 AND 256 AND instr(turn_id, char(0)) = 0),
  owner_launch_id TEXT NOT NULL
    REFERENCES node_worker_launches(launch_id) ON DELETE CASCADE,
  plan_hash TEXT NOT NULL
    CHECK (length(plan_hash) = 64 AND plan_hash NOT GLOB '*[^0-9a-f]*'),
  run_id TEXT NOT NULL
    CHECK (length(run_id) BETWEEN 1 AND 256 AND instr(run_id, char(0)) = 0),
  state TEXT NOT NULL
    CHECK (state IN ('running', 'completed', 'failed', 'interrupted', 'cancelled')),
  result_json TEXT CHECK (
    result_json IS NULL
    OR (
      length(CAST(result_json AS BLOB)) BETWEEN 1 AND 65536
      AND instr(result_json, char(0)) = 0
      AND json_valid(result_json)
    )
  ),
  error_text TEXT CHECK (
    error_text IS NULL
    OR (
      length(CAST(error_text AS BLOB)) BETWEEN 1 AND 4096
      AND instr(error_text, char(0)) = 0
      AND instr(error_text, char(10)) = 0
      AND instr(error_text, char(13)) = 0
    )
  ),
  completed_at_ms INTEGER CHECK (
    completed_at_ms IS NULL OR completed_at_ms BETWEEN 0 AND 9007199254740991
  ),
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms BETWEEN 0 AND 9007199254740991),
  updated_at_ms INTEGER NOT NULL CHECK (
    updated_at_ms BETWEEN created_at_ms AND 9007199254740991
  ),
  CHECK (
    (state = 'running'
      AND result_json IS NULL AND error_text IS NULL AND completed_at_ms IS NULL)
    OR
    (state = 'completed'
      AND result_json IS NOT NULL AND error_text IS NULL
      AND completed_at_ms BETWEEN created_at_ms AND updated_at_ms)
    OR
    (state IN ('failed', 'interrupted', 'cancelled')
      AND result_json IS NULL AND error_text IS NOT NULL
      AND completed_at_ms BETWEEN created_at_ms AND updated_at_ms)
  )
) STRICT;

CREATE INDEX IF NOT EXISTS idx_node_worker_turns_terminal_completed
  ON node_worker_turns(completed_at_ms, turn_id)
  WHERE completed_at_ms IS NOT NULL;

CREATE UNIQUE INDEX IF NOT EXISTS idx_node_worker_turns_active_owner
  ON node_worker_turns(owner_launch_id)
  WHERE state = 'running';

CREATE TABLE IF NOT EXISTS config_health_entries (
  config_path TEXT NOT NULL PRIMARY KEY,
  last_known_good_json TEXT,
  last_promoted_good_json TEXT,
  last_observed_suspicious_signature TEXT,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS clawhub_promotion_claims (
  slug TEXT NOT NULL PRIMARY KEY,
  provider TEXT,
  model_keys_json TEXT NOT NULL,
  ends_at_ms INTEGER NOT NULL,
  claimed_at_ms INTEGER NOT NULL
) STRICT;



CREATE TABLE IF NOT EXISTS official_external_plugin_catalog_snapshots (
  feed_url TEXT NOT NULL PRIMARY KEY,
  body TEXT NOT NULL,
  status INTEGER NOT NULL,
  etag TEXT,
  last_modified TEXT,
  checksum TEXT NOT NULL,
  saved_at TEXT NOT NULL,
  trust_mode TEXT,
  trust_key_id TEXT,
  trust_signature_count INTEGER,
  trust_threshold INTEGER,
  trust_verified_at TEXT,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_official_external_plugin_catalog_snapshots_updated
  ON official_external_plugin_catalog_snapshots(updated_at_ms DESC, feed_url);

CREATE TABLE IF NOT EXISTS update_runs (
  run_id TEXT PRIMARY KEY NOT NULL,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  trigger TEXT NOT NULL CHECK (trigger IN ('chat', 'control-ui', 'cli', 'campaign', 'mac-app', 'api')),
  phase TEXT NOT NULL CHECK (phase IN ('requested', 'staging', 'validating', 'repairing', 'activating', 'restarting', 'verifying', 'finished')),
  status TEXT NOT NULL CHECK (status IN ('running', 'succeeded', 'failed', 'rolled-back', 'skipped')),
  reason TEXT,
  origin_json TEXT NOT NULL CHECK (length(CAST(origin_json AS BLOB)) <= 16384),
  target_json TEXT NOT NULL CHECK (length(CAST(target_json AS BLOB)) <= 16384),
  before_json TEXT NOT NULL CHECK (length(CAST(before_json AS BLOB)) <= 16384),
  after_json TEXT NOT NULL CHECK (length(CAST(after_json AS BLOB)) <= 16384),
  steps_json TEXT NOT NULL CHECK (length(CAST(steps_json AS BLOB)) <= 16384),
  verification_json TEXT NOT NULL CHECK (length(CAST(verification_json AS BLOB)) <= 16384),
  repair_json TEXT NOT NULL CHECK (length(CAST(repair_json AS BLOB)) <= 16384),
  confirmed_at_ms INTEGER,
  finished_at_ms INTEGER,
  downtime_ms INTEGER,
  CHECK ((status = 'running' AND phase != 'finished' AND finished_at_ms IS NULL) OR
    (status != 'running' AND phase = 'finished' AND finished_at_ms IS NOT NULL))
) STRICT;

CREATE INDEX IF NOT EXISTS idx_update_runs_created
  ON update_runs(created_at_ms DESC, run_id);
CREATE INDEX IF NOT EXISTS idx_update_runs_active
  ON update_runs(status, created_at_ms DESC, run_id);

CREATE TABLE IF NOT EXISTS gateway_restart_sentinel (
  sentinel_key TEXT NOT NULL PRIMARY KEY,
  version INTEGER NOT NULL,
  kind TEXT NOT NULL,
  status TEXT NOT NULL,
  ts INTEGER NOT NULL,
  session_key TEXT,
  thread_id TEXT,
  delivery_channel TEXT,
  delivery_to TEXT,
  delivery_account_id TEXT,
  message TEXT,
  continuation_json TEXT,
  doctor_hint TEXT,
  stats_json TEXT,
  payload_json TEXT NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_gateway_restart_sentinel_ts
  ON gateway_restart_sentinel(ts DESC, sentinel_key);

CREATE TABLE IF NOT EXISTS gateway_restart_intent (
  intent_key TEXT NOT NULL PRIMARY KEY,
  kind TEXT NOT NULL,
  pid INTEGER NOT NULL,
  created_at INTEGER NOT NULL,
  reason TEXT,
  force INTEGER,
  wait_ms INTEGER,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS gateway_restart_handoff (
  handoff_key TEXT NOT NULL PRIMARY KEY,
  kind TEXT NOT NULL,
  version INTEGER NOT NULL,
  intent_id TEXT NOT NULL,
  pid INTEGER NOT NULL,
  process_instance_id TEXT,
  created_at INTEGER NOT NULL,
  expires_at INTEGER NOT NULL,
  reason TEXT,
  restart_trace_started_at INTEGER,
  restart_trace_last_at INTEGER,
  source TEXT NOT NULL,
  restart_kind TEXT NOT NULL,
  supervisor_mode TEXT NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_gateway_restart_handoff_expiry
  ON gateway_restart_handoff(expires_at, pid);

CREATE TABLE IF NOT EXISTS gateway_boot_lifecycle (
  boot_id TEXT NOT NULL PRIMARY KEY,
  pid INTEGER NOT NULL,
  started_at_ms INTEGER NOT NULL,
  completed_at_ms INTEGER,
  outcome TEXT,
  startup_reason TEXT,
  reason TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_gateway_boot_lifecycle_started
  ON gateway_boot_lifecycle(started_at_ms);

CREATE TABLE IF NOT EXISTS acp_sessions (
  session_key TEXT NOT NULL PRIMARY KEY,
  session_id TEXT,
  backend TEXT NOT NULL,
  agent TEXT NOT NULL,
  runtime_session_name TEXT NOT NULL,
  identity_json TEXT,
  resume_agent_session_id TEXT,
  resume_acpx_session_id TEXT,
  mode TEXT NOT NULL,
  runtime_options_json TEXT,
  cwd TEXT,
  state TEXT NOT NULL,
  last_activity_at INTEGER NOT NULL,
  last_error TEXT,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_acp_sessions_state_activity
  ON acp_sessions(state, last_activity_at DESC, session_key);

CREATE INDEX IF NOT EXISTS idx_acp_sessions_agent_activity
  ON acp_sessions(agent, last_activity_at DESC, session_key);

CREATE INDEX IF NOT EXISTS idx_acp_sessions_resume_agent
  ON acp_sessions(resume_agent_session_id);

CREATE INDEX IF NOT EXISTS idx_acp_sessions_resume_acpx
  ON acp_sessions(resume_acpx_session_id);

CREATE TABLE IF NOT EXISTS acp_replay_sessions (
  session_id TEXT NOT NULL PRIMARY KEY,
  session_key TEXT NOT NULL,
  cwd TEXT NOT NULL,
  complete INTEGER NOT NULL,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  next_seq INTEGER NOT NULL,
  -- Running estimate of this session's ledger footprint (row overhead plus
  -- all event rows), maintained at insert/trim so budget checks never scan
  -- acp_replay_events (#100622).
  estimated_bytes INTEGER NOT NULL DEFAULT 0
) STRICT;

CREATE INDEX IF NOT EXISTS idx_acp_replay_sessions_key_updated
  ON acp_replay_sessions(session_key, complete, updated_at DESC, session_id);

CREATE INDEX IF NOT EXISTS idx_acp_replay_sessions_updated
  ON acp_replay_sessions(updated_at DESC, session_id);

CREATE TABLE IF NOT EXISTS acp_replay_events (
  session_id TEXT NOT NULL,
  seq INTEGER NOT NULL,
  at INTEGER NOT NULL,
  session_key TEXT NOT NULL,
  run_id TEXT,
  update_json TEXT NOT NULL,
  estimated_bytes INTEGER NOT NULL DEFAULT 0,
  PRIMARY KEY (session_id, seq),
  FOREIGN KEY (session_id) REFERENCES acp_replay_sessions(session_id) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS agent_databases (
  agent_id TEXT NOT NULL,
  path TEXT NOT NULL,
  schema_version INTEGER NOT NULL,
  last_seen_at INTEGER NOT NULL,
  size_bytes INTEGER,
  PRIMARY KEY (agent_id, path)
) STRICT;

CREATE TABLE IF NOT EXISTS agent_deletion_journal (
  agent_id TEXT PRIMARY KEY,
  operation_id TEXT NOT NULL DEFAULT '',
  phase TEXT,
  agent_dir TEXT NOT NULL,
  workspace_dir TEXT NOT NULL,
  sessions_dir TEXT NOT NULL,
  database_paths_json TEXT NOT NULL DEFAULT '[]',
  cleanup_paths_json TEXT NOT NULL DEFAULT '[]',
  created_at INTEGER NOT NULL,
  cleanup_completed INTEGER NOT NULL DEFAULT 0,
  delete_files INTEGER NOT NULL DEFAULT 1
) STRICT;

CREATE TABLE IF NOT EXISTS agent_provenance (
  agent_id TEXT PRIMARY KEY,
  created_via TEXT NOT NULL CHECK (created_via IN ('operator', 'agent', 'template')),
  creator_agent_id TEXT,
  created_at_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS agent_database_leases (
  lease_id TEXT PRIMARY KEY,
  agent_id TEXT NOT NULL,
  path TEXT NOT NULL,
  owner_pid INTEGER NOT NULL,
  owner_start_time INTEGER,
  opened_at INTEGER NOT NULL,
  provenance TEXT
) STRICT;

CREATE TABLE IF NOT EXISTS plugin_state_entries (
  plugin_id TEXT NOT NULL,
  namespace TEXT NOT NULL,
  entry_key TEXT NOT NULL,
  value_json TEXT NOT NULL,
  created_at INTEGER NOT NULL,
  expires_at INTEGER,
  PRIMARY KEY (plugin_id, namespace, entry_key)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_plugin_state_expiry
  ON plugin_state_entries(expires_at)
  WHERE expires_at IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_plugin_state_listing
  ON plugin_state_entries(plugin_id, namespace, created_at, entry_key, expires_at);

CREATE TABLE IF NOT EXISTS channel_ingress_events (
  queue_name TEXT NOT NULL,
  event_id TEXT NOT NULL,
  channel_id TEXT NOT NULL,
  account_id TEXT NOT NULL,
  status TEXT NOT NULL,
  lane_key TEXT,
  payload_json TEXT NOT NULL,
  metadata_json TEXT,
  received_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  claim_token TEXT,
  claim_owner TEXT,
  claimed_at INTEGER,
  attempts INTEGER NOT NULL DEFAULT 0,
  last_attempt_at INTEGER,
  last_error TEXT,
  failed_reason TEXT,
  failed_at INTEGER,
  completed_at INTEGER,
  completed_metadata_json TEXT,
  PRIMARY KEY (queue_name, event_id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_channel_ingress_pending
  ON channel_ingress_events(queue_name, status, received_at, event_id);

CREATE INDEX IF NOT EXISTS idx_channel_ingress_claims
  ON channel_ingress_events(queue_name, status, claimed_at);

CREATE INDEX IF NOT EXISTS idx_channel_ingress_lane
  ON channel_ingress_events(queue_name, status, lane_key);

CREATE TABLE IF NOT EXISTS plugin_blob_entries (
  plugin_id TEXT NOT NULL,
  namespace TEXT NOT NULL,
  entry_key TEXT NOT NULL,
  metadata_json TEXT NOT NULL,
  blob BLOB NOT NULL,
  created_at INTEGER NOT NULL,
  expires_at INTEGER,
  PRIMARY KEY (plugin_id, namespace, entry_key)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_plugin_blob_expiry
  ON plugin_blob_entries(expires_at)
  WHERE expires_at IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_plugin_blob_listing
  ON plugin_blob_entries(plugin_id, namespace, created_at, entry_key);

CREATE TABLE IF NOT EXISTS skill_uploads (
  upload_id TEXT NOT NULL PRIMARY KEY,
  kind TEXT NOT NULL,
  slug TEXT NOT NULL,
  force INTEGER NOT NULL,
  size_bytes INTEGER NOT NULL,
  sha256 TEXT,
  actual_sha256 TEXT,
  received_bytes INTEGER NOT NULL,
  archive_blob BLOB NOT NULL,
  created_at INTEGER NOT NULL,
  expires_at INTEGER NOT NULL,
  committed INTEGER NOT NULL,
  committed_at INTEGER,
  idempotency_key_hash TEXT UNIQUE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_skill_uploads_expiry
  ON skill_uploads(expires_at);

CREATE INDEX IF NOT EXISTS idx_skill_uploads_idempotency
  ON skill_uploads(idempotency_key_hash)
  WHERE idempotency_key_hash IS NOT NULL;

CREATE TABLE IF NOT EXISTS skill_upload_chunks (
  upload_id TEXT NOT NULL,
  byte_offset INTEGER NOT NULL CHECK (byte_offset >= 0),
  size_bytes INTEGER NOT NULL CHECK (size_bytes > 0),
  chunk_blob BLOB NOT NULL,
  PRIMARY KEY (upload_id, byte_offset),
  FOREIGN KEY (upload_id) REFERENCES skill_uploads(upload_id) ON DELETE CASCADE,
  CHECK (length(chunk_blob) = size_bytes)
) STRICT;

CREATE TABLE IF NOT EXISTS capture_sessions (
  id TEXT NOT NULL PRIMARY KEY,
  started_at INTEGER NOT NULL,
  ended_at INTEGER,
  mode TEXT NOT NULL,
  source_scope TEXT NOT NULL,
  source_process TEXT NOT NULL,
  proxy_url TEXT
) STRICT;

CREATE TABLE IF NOT EXISTS capture_blobs (
  blob_id TEXT NOT NULL PRIMARY KEY,
  content_type TEXT,
  encoding TEXT NOT NULL,
  size_bytes INTEGER NOT NULL,
  sha256 TEXT NOT NULL,
  data BLOB NOT NULL,
  created_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS capture_events (
  id INTEGER NOT NULL PRIMARY KEY,
  session_id TEXT NOT NULL,
  ts INTEGER NOT NULL,
  source_scope TEXT NOT NULL,
  source_process TEXT NOT NULL,
  protocol TEXT NOT NULL,
  direction TEXT NOT NULL,
  kind TEXT NOT NULL,
  flow_id TEXT NOT NULL,
  method TEXT,
  host TEXT,
  path TEXT,
  status INTEGER,
  close_code INTEGER,
  content_type TEXT,
  headers_json TEXT,
  data_text TEXT,
  data_blob_id TEXT,
  data_sha256 TEXT,
  error_text TEXT,
  meta_json TEXT,
  FOREIGN KEY (session_id) REFERENCES capture_sessions(id) ON DELETE CASCADE,
  FOREIGN KEY (data_blob_id) REFERENCES capture_blobs(blob_id) ON DELETE SET NULL
) STRICT;

CREATE INDEX IF NOT EXISTS capture_events_session_ts_idx
  ON capture_events(session_id, ts);

CREATE INDEX IF NOT EXISTS capture_events_flow_idx
  ON capture_events(flow_id, ts);

CREATE TABLE IF NOT EXISTS sandbox_registry_entries (
  registry_kind TEXT NOT NULL,
  container_name TEXT NOT NULL,
  session_key TEXT,
  backend_id TEXT,
  runtime_label TEXT,
  image TEXT,
  created_at_ms INTEGER,
  last_used_at_ms INTEGER,
  config_label_kind TEXT,
  config_hash TEXT,
  cdp_port INTEGER,
  no_vnc_port INTEGER,
  entry_json TEXT NOT NULL,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (registry_kind, container_name)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_sandbox_registry_updated
  ON sandbox_registry_entries(registry_kind, updated_at DESC, container_name);

CREATE INDEX IF NOT EXISTS idx_sandbox_registry_session
  ON sandbox_registry_entries(registry_kind, session_key, last_used_at_ms DESC, container_name)
  WHERE session_key IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_sandbox_registry_last_used
  ON sandbox_registry_entries(registry_kind, last_used_at_ms DESC, container_name)
  WHERE last_used_at_ms IS NOT NULL;

CREATE TABLE IF NOT EXISTS durable_background_processes (
  id TEXT NOT NULL PRIMARY KEY,
  record_json TEXT NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS sandbox_persistent_execs (
  owner_key TEXT NOT NULL PRIMARY KEY,
  source_identity TEXT NOT NULL,
  attempt_id TEXT NOT NULL UNIQUE,
  owner_json TEXT NOT NULL,
  backend_id TEXT NOT NULL CHECK (backend_id = 'docker'),
  backend_target_json TEXT NOT NULL,
  workspace_binding_json TEXT NOT NULL,
  container_id TEXT NOT NULL,
  container_name TEXT NOT NULL,
  container_started_at TEXT NOT NULL,
  revision INTEGER NOT NULL CHECK (revision > 0),
  phase TEXT NOT NULL CHECK (phase IN ('reserved', 'prepared', 'running', 'stopping', 'uncertain', 'stopped')),
  receipt_json TEXT,
  error TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  CHECK (phase NOT IN ('prepared', 'running') OR receipt_json IS NOT NULL)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_sandbox_persistent_execs_container
  ON sandbox_persistent_execs(container_id, owner_key);

CREATE INDEX IF NOT EXISTS idx_sandbox_persistent_execs_container_name
  ON sandbox_persistent_execs(container_name, owner_key);

CREATE INDEX IF NOT EXISTS idx_sandbox_persistent_execs_source
  ON sandbox_persistent_execs(source_identity, owner_key);

CREATE TABLE IF NOT EXISTS cron_jobs (
  store_key TEXT NOT NULL,
  job_id TEXT NOT NULL,
  declaration_key TEXT,
  owner_agent_id TEXT,
  name TEXT NOT NULL,
  description TEXT,
  enabled INTEGER NOT NULL,
  agent_id TEXT,
  payload_kind TEXT NOT NULL,
  job_json TEXT NOT NULL,
  grant_definition_revision TEXT,
  grant_definition_generation INTEGER,
  grant_definition_updated_at INTEGER,
  state_json TEXT NOT NULL DEFAULT '{}',
  runtime_updated_at_ms INTEGER,
  schedule_identity TEXT,
  sort_order INTEGER NOT NULL DEFAULT 0,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (store_key, job_id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_cron_jobs_store_order
  ON cron_jobs(store_key, sort_order ASC, updated_at ASC, job_id);

-- One owner-native receipt is also the durable execution fence. Receipts
-- survive job deletion so operators can distinguish a run from log inference.
CREATE TABLE IF NOT EXISTS cron_run_receipts (
  cursor_id INTEGER NOT NULL,
  receipt_id TEXT PRIMARY KEY,
  store_key TEXT NOT NULL,
  job_id TEXT NOT NULL,
  config_revision TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  request_run_id TEXT,
  delivery_attempt_state TEXT NOT NULL DEFAULT 'unknown' CHECK (delivery_attempt_state IN ('unknown', 'not-started', 'started')),
  status TEXT NOT NULL,
  owner_pid INTEGER NOT NULL,
  owner_start_time INTEGER,
  started_at_ms INTEGER NOT NULL,
  finished_at_ms INTEGER,
  error_text TEXT,
  CHECK (status IN ('running', 'ok', 'error', 'skipped', 'interrupted', 'superseded')),
  CHECK (
    (status = 'running' AND finished_at_ms IS NULL)
    OR
    (status != 'running' AND finished_at_ms IS NOT NULL)
  )
) STRICT;

CREATE UNIQUE INDEX IF NOT EXISTS cron_run_receipts_cursor_id_idx
  ON cron_run_receipts(cursor_id);

CREATE UNIQUE INDEX IF NOT EXISTS idx_cron_run_receipts_active_job
  ON cron_run_receipts(store_key, job_id)
  WHERE status = 'running';

CREATE INDEX IF NOT EXISTS idx_cron_run_receipts_job_history
  ON cron_run_receipts(store_key, job_id, started_at_ms DESC, receipt_id DESC);

-- Retirement follows the receipt's retention without changing its released shape.
CREATE TABLE IF NOT EXISTS cron_run_trigger_state_retirements (
  receipt_id TEXT PRIMARY KEY
    REFERENCES cron_run_receipts(receipt_id) ON DELETE CASCADE
) STRICT;

-- Runtime-private authority is independent of job_json so downgraded writers
-- can rewrite recognized job config without erasing or silently widening it.
CREATE TABLE IF NOT EXISTS cron_job_runtime_authorities (
  store_key TEXT NOT NULL,
  job_id TEXT NOT NULL,
  authority_json TEXT,
  authority_input_fingerprint TEXT,
  recovery_required INTEGER NOT NULL,
  PRIMARY KEY (store_key, job_id),
  FOREIGN KEY (store_key, job_id)
    REFERENCES cron_jobs(store_key, job_id) ON DELETE CASCADE,
  CHECK (recovery_required IN (0, 1)),
  CHECK (
    (recovery_required = 0 AND authority_json IS NOT NULL AND authority_input_fingerprint IS NOT NULL)
    OR
    (recovery_required = 1 AND authority_json IS NULL AND authority_input_fingerprint IS NULL)
  )
) STRICT;

-- Scratch is separate from cron_jobs so scheduler state writes and downgraded
-- full-row replacement preserve it. New builds prune rows explicitly on job removal.
-- content NULL is a tombstone: it keeps the revision lineage monotonic across
-- unset/recreate so stale compare-and-swap writes cannot resurrect old content.
CREATE TABLE IF NOT EXISTS cron_job_scratch (
  store_key TEXT NOT NULL,
  job_id TEXT NOT NULL,
  content TEXT,
  revision INTEGER NOT NULL,
  source_sha256 TEXT,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (store_key, job_id),
  CHECK (revision >= 1),
  CHECK (content IS NULL OR length(CAST(content AS BLOB)) <= 262144)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_cron_job_scratch_store_updated
  ON cron_job_scratch(store_key, updated_at_ms DESC, job_id);

CREATE TABLE IF NOT EXISTS delivery_queue_entries (
  queue_name TEXT NOT NULL,
  id TEXT NOT NULL,
  status TEXT NOT NULL,
  entry_kind TEXT,
  session_key TEXT,
  channel TEXT,
  target TEXT,
  account_id TEXT,
  retry_count INTEGER NOT NULL DEFAULT 0,
  last_attempt_at INTEGER,
  last_error TEXT,
  recovery_state TEXT,
  platform_send_started_at INTEGER,
  entry_json TEXT NOT NULL,
  retention_id_prefix TEXT,
  retention_max_age_ms INTEGER,
  retention_max_entries INTEGER,
  enqueued_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  failed_at INTEGER,
  PRIMARY KEY (queue_name, id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_delivery_queue_pending
  ON delivery_queue_entries(queue_name, status, enqueued_at, id);

CREATE INDEX IF NOT EXISTS idx_delivery_queue_failed
  ON delivery_queue_entries(status, queue_name, failed_at, id);

CREATE INDEX IF NOT EXISTS idx_delivery_queue_session
  ON delivery_queue_entries(queue_name, status, session_key, enqueued_at, id)
  WHERE session_key IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_delivery_queue_target
  ON delivery_queue_entries(queue_name, status, channel, target, enqueued_at, id)
  WHERE channel IS NOT NULL AND target IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_delivery_queue_bounded_retention
  ON delivery_queue_entries(queue_name, retention_id_prefix, enqueued_at DESC, id DESC)
  WHERE status IN ('completed', 'failed') AND recovery_state = 'completed_bounded'
    AND retention_id_prefix IS NOT NULL;

CREATE TABLE IF NOT EXISTS task_runs (
  task_id TEXT NOT NULL PRIMARY KEY,
  runtime TEXT NOT NULL,
  task_kind TEXT,
  source_id TEXT,
  requester_session_key TEXT,
  owner_key TEXT NOT NULL,
  scope_kind TEXT NOT NULL,
  child_session_key TEXT,
  parent_flow_id TEXT,
  parent_task_id TEXT,
  agent_id TEXT,
  requester_agent_id TEXT,
  run_id TEXT,
  execution_owner_host TEXT,
  execution_owner_pid INTEGER,
  execution_owner_start_identity INTEGER,
  label TEXT,
  task TEXT NOT NULL,
  status TEXT NOT NULL,
  delivery_status TEXT NOT NULL,
  notify_policy TEXT NOT NULL,
  created_at INTEGER NOT NULL,
  started_at INTEGER,
  ended_at INTEGER,
  last_event_at INTEGER,
  cleanup_after INTEGER,
  tool_use_count INTEGER,
  last_tool_name TEXT,
  error TEXT,
  progress_summary TEXT,
  terminal_summary TEXT,
  terminal_outcome TEXT,
  detail_json TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_task_runs_runtime_run
  ON task_runs(runtime, run_id, source_id, created_at, task_id);
CREATE INDEX IF NOT EXISTS idx_task_runs_cron_runtime_order
  ON task_runs(runtime, created_at, task_id) WHERE runtime = 'cron';
CREATE INDEX IF NOT EXISTS idx_task_runs_cron_source_order
  ON task_runs(source_id, created_at, task_id) WHERE runtime = 'cron';

CREATE TABLE IF NOT EXISTS subagent_runs (
  run_id TEXT NOT NULL PRIMARY KEY,
  child_session_key TEXT NOT NULL,
  controller_session_key TEXT,
  controller_store_path TEXT,
  requester_session_key TEXT NOT NULL,
  requester_store_path TEXT,
  created_at INTEGER NOT NULL,
  payload_json TEXT NOT NULL DEFAULT '{}'
) STRICT;

CREATE INDEX IF NOT EXISTS idx_subagent_runs_child_session_key
  ON subagent_runs(child_session_key, created_at DESC, run_id);
CREATE INDEX IF NOT EXISTS idx_subagent_runs_requester_session_key
  ON subagent_runs(requester_session_key, created_at DESC, run_id);
CREATE INDEX IF NOT EXISTS idx_subagent_runs_controller_session_key
  ON subagent_runs(controller_session_key, created_at DESC, run_id);

CREATE TABLE IF NOT EXISTS current_conversation_bindings (
  binding_key TEXT NOT NULL PRIMARY KEY,
  binding_id TEXT NOT NULL,
  target_session_key TEXT NOT NULL,
  channel TEXT NOT NULL,
  account_id TEXT NOT NULL,
  conversation_kind TEXT NOT NULL,
  parent_conversation_id TEXT,
  conversation_id TEXT NOT NULL,
  target_kind TEXT NOT NULL,
  status TEXT NOT NULL,
  bound_at INTEGER NOT NULL,
  expires_at INTEGER,
  metadata_json TEXT,
  record_json TEXT NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_current_conversation_bindings_target
  ON current_conversation_bindings(target_session_key, updated_at DESC, binding_key);
CREATE INDEX IF NOT EXISTS idx_current_conversation_bindings_conversation
  ON current_conversation_bindings(channel, account_id, conversation_kind, conversation_id);
CREATE INDEX IF NOT EXISTS idx_current_conversation_bindings_expires
  ON current_conversation_bindings(expires_at, binding_key);

CREATE TABLE IF NOT EXISTS plugin_binding_approvals (
  plugin_root TEXT NOT NULL,
  channel TEXT NOT NULL,
  account_id TEXT NOT NULL,
  plugin_id TEXT NOT NULL,
  plugin_name TEXT,
  approved_at INTEGER NOT NULL,
  PRIMARY KEY (plugin_root, channel, account_id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_plugin_binding_approvals_plugin
  ON plugin_binding_approvals(plugin_id, approved_at DESC);

CREATE TABLE IF NOT EXISTS task_delivery_state (
  task_id TEXT NOT NULL PRIMARY KEY,
  requester_origin_json TEXT,
  last_notified_event_at INTEGER,
  FOREIGN KEY (task_id) REFERENCES task_runs(task_id) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS flow_runs (
  flow_id TEXT NOT NULL PRIMARY KEY,
  shape TEXT,
  sync_mode TEXT NOT NULL DEFAULT 'managed',
  owner_key TEXT NOT NULL,
  requester_origin_json TEXT,
  controller_id TEXT,
  revision INTEGER NOT NULL DEFAULT 0,
  status TEXT NOT NULL,
  notify_policy TEXT NOT NULL,
  goal TEXT NOT NULL,
  current_step TEXT,
  blocked_task_id TEXT,
  blocked_summary TEXT,
  state_json TEXT,
  wait_json TEXT,
  cancel_requested_at INTEGER,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  ended_at INTEGER
) STRICT;

CREATE INDEX IF NOT EXISTS idx_flow_runs_status ON flow_runs(status);
CREATE INDEX IF NOT EXISTS idx_flow_runs_owner_key ON flow_runs(owner_key);
CREATE INDEX IF NOT EXISTS idx_flow_runs_updated_at ON flow_runs(updated_at);

-- Durable meeting-capture sessions are gateway-global rather than agent-session
-- transcripts. JSON/JSONL files are doctor import inputs or explicit CLI exports.
CREATE TABLE IF NOT EXISTS meeting_transcript_sessions (
  started_at_ms INTEGER,
  session_id TEXT NOT NULL,
  started_at TEXT NOT NULL,
  selector TEXT NOT NULL UNIQUE,
  export_key TEXT NOT NULL,
  session_slug TEXT NOT NULL,
  provider_id TEXT NOT NULL,
  title TEXT,
  source_json TEXT NOT NULL,
  source_account_id TEXT,
  source_guild_id TEXT,
  source_channel_id TEXT,
  source_meeting_url TEXT,
  source_thread_ts TEXT,
  source_file_id TEXT,
  stopped_at TEXT,
  metadata_json TEXT,
  metadata_agent_id TEXT,
  export_manifest_json TEXT NOT NULL DEFAULT '{}',
  export_pending_json TEXT NOT NULL DEFAULT '[]',
  next_utterance_seq INTEGER NOT NULL DEFAULT 0 CHECK (next_utterance_seq >= 0),
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),
  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),
  PRIMARY KEY (session_id, started_at)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_started
  ON meeting_transcript_sessions(started_at DESC, session_id);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_chronology
  ON meeting_transcript_sessions(started_at_ms DESC, session_id ASC, started_at ASC);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_id
  ON meeting_transcript_sessions(session_id, started_at DESC);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_slug
  ON meeting_transcript_sessions(session_slug, started_at DESC);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_export_key
  ON meeting_transcript_sessions(export_key);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_source
  ON meeting_transcript_sessions(provider_id, source_account_id, source_guild_id,
    source_channel_id, source_meeting_url, source_thread_ts, source_file_id,
    stopped_at DESC, started_at DESC, session_id);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_account
  ON meeting_transcript_sessions(source_account_id);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_agent
  ON meeting_transcript_sessions(metadata_agent_id);

CREATE TABLE IF NOT EXISTS meeting_transcript_utterances (
  session_id TEXT NOT NULL,
  session_started_at TEXT NOT NULL,
  sequence INTEGER NOT NULL CHECK (sequence >= 0),
  utterance_id TEXT,
  started_at TEXT,
  ended_at TEXT,
  speaker_id TEXT,
  speaker_label TEXT,
  text TEXT NOT NULL,
  final INTEGER CHECK (final IN (0, 1)),
  metadata_json TEXT,
  PRIMARY KEY (session_id, session_started_at, sequence),
  FOREIGN KEY (session_id, session_started_at)
    REFERENCES meeting_transcript_sessions(session_id, started_at)
    ON DELETE CASCADE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_utterances_id
  ON meeting_transcript_utterances(session_id, session_started_at, utterance_id)
  WHERE utterance_id IS NOT NULL;

CREATE TABLE IF NOT EXISTS meeting_transcript_summaries (
  session_id TEXT NOT NULL,
  session_started_at TEXT NOT NULL,
  generated_at TEXT,
  summary_json TEXT,
  overview TEXT,
  markdown TEXT,
  utterance_count INTEGER NOT NULL CHECK (utterance_count >= 0),
  PRIMARY KEY (session_id, session_started_at),
  FOREIGN KEY (session_id, session_started_at)
    REFERENCES meeting_transcript_sessions(session_id, started_at)
    ON DELETE CASCADE,
  CHECK (summary_json IS NOT NULL OR markdown IS NOT NULL)
) STRICT;

CREATE TABLE IF NOT EXISTS migration_runs (
  id TEXT NOT NULL PRIMARY KEY,
  started_at INTEGER NOT NULL,
  finished_at INTEGER,
  status TEXT NOT NULL,
  report_json TEXT NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_migration_runs_started
  ON migration_runs(started_at DESC, id);

CREATE TABLE IF NOT EXISTS migration_sources (
  source_key TEXT NOT NULL PRIMARY KEY,
  migration_kind TEXT NOT NULL,
  source_path TEXT NOT NULL,
  target_table TEXT NOT NULL,
  source_sha256 TEXT,
  source_size_bytes INTEGER,
  source_record_count INTEGER,
  last_run_id TEXT NOT NULL,
  status TEXT NOT NULL,
  imported_at INTEGER NOT NULL,
  removed_source INTEGER NOT NULL DEFAULT 0,
  report_json TEXT NOT NULL,
  FOREIGN KEY (last_run_id) REFERENCES migration_runs(id) ON DELETE CASCADE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_migration_sources_path
  ON migration_sources(source_path, migration_kind, target_table);

CREATE INDEX IF NOT EXISTS idx_migration_sources_run
  ON migration_sources(last_run_id, source_path);

CREATE TABLE IF NOT EXISTS backup_runs (
  id TEXT NOT NULL PRIMARY KEY,
  created_at INTEGER NOT NULL,
  archive_path TEXT NOT NULL,
  status TEXT NOT NULL,
  manifest_json TEXT NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_backup_runs_created
  ON backup_runs(created_at DESC, id);

CREATE TABLE IF NOT EXISTS worktrees (
  id TEXT NOT NULL PRIMARY KEY,
  repo_fingerprint TEXT NOT NULL,
  repo_root TEXT NOT NULL,
  path TEXT NOT NULL,
  branch TEXT NOT NULL,
  base_ref TEXT NOT NULL,
  owner_kind TEXT NOT NULL CHECK (owner_kind IN ('manual', 'workboard', 'session')),
  owner_id TEXT,
  snapshot_ref TEXT,
  provisioned_paths_json TEXT,
  created_at INTEGER NOT NULL,
  last_active_at INTEGER NOT NULL,
  removed_at INTEGER,
  run_end_cleanup_json TEXT,
  gc_protection_json TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_worktrees_repo_fingerprint
  ON worktrees(repo_fingerprint);

CREATE INDEX IF NOT EXISTS idx_worktrees_removed_at
  ON worktrees(removed_at);

CREATE TABLE IF NOT EXISTS worktree_provisioned_file_chunks (
  worktree_id TEXT NOT NULL,
  path TEXT NOT NULL,
  chunk_index INTEGER NOT NULL CHECK (chunk_index >= 0),
  data BLOB NOT NULL,
  PRIMARY KEY (worktree_id, path, chunk_index)
) STRICT;

CREATE TABLE IF NOT EXISTS worktree_templates (
  cache_key TEXT NOT NULL PRIMARY KEY,
  id TEXT NOT NULL UNIQUE,
  repo_root TEXT NOT NULL,
  common_dir TEXT NOT NULL,
  worktree_root TEXT NOT NULL,
  path TEXT NOT NULL,
  backend TEXT NOT NULL,
  source_commit TEXT NOT NULL,
  content_key TEXT NOT NULL,
  status TEXT NOT NULL CHECK (status IN ('preparing', 'ready')),
  created_at INTEGER NOT NULL,
  last_used_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS projects (
  id TEXT NOT NULL PRIMARY KEY,
  display_name TEXT NOT NULL,
  repo_root TEXT NOT NULL,
  origin_url TEXT,
  source TEXT NOT NULL CHECK (source IN ('registered', 'cloned')),
  created_at_ms INT NOT NULL,
  updated_at_ms INT NOT NULL
) STRICT;

-- One explicitly retained, normalized private background per durable profile.
CREATE TABLE IF NOT EXISTS user_background_images (
  profile_id TEXT NOT NULL PRIMARY KEY REFERENCES user_profiles(id) ON DELETE CASCADE,
  asset_id TEXT NOT NULL UNIQUE,
  image BLOB NOT NULL CHECK (length(image) BETWEEN 1 AND 2097152),
  width INTEGER NOT NULL CHECK (width BETWEEN 1 AND 2560),
  height INTEGER NOT NULL CHECK (height BETWEEN 1 AND 2560)
) STRICT;

CREATE TABLE IF NOT EXISTS user_preferences (
  profile_id TEXT NOT NULL,
  pref_key TEXT NOT NULL,
  value_json TEXT NOT NULL,
  updated_at_ms INT NOT NULL,
  PRIMARY KEY (profile_id, pref_key)
) STRICT;

-- Gateway-owned custom session group catalog (names + display order).
-- Membership stays on each session entry's category field; this table only
-- owns which groups exist and how operator UIs order them.
CREATE TABLE IF NOT EXISTS session_groups (
  name TEXT NOT NULL PRIMARY KEY,
  position INTEGER NOT NULL,
  created_at INTEGER NOT NULL,
  cwd TEXT,
  worktree INTEGER
) STRICT;

-- Gateway-owned durable cloud worker lifecycle. Provider-specific execution
-- stays in plugins; this table records only core reconciliation facts.
CREATE TABLE IF NOT EXISTS worker_environments (
  environment_id TEXT NOT NULL PRIMARY KEY,
  provider_id TEXT NOT NULL,
  profile_id TEXT NOT NULL,
  profile_snapshot_json TEXT NOT NULL,
  last_activated_at_ms INTEGER,
  preparation_key TEXT,
  preparation_purpose TEXT,
  preparation_demand_at_ms INTEGER,
  preparation_expires_at_ms INTEGER,
  preparation_consumed_at_ms INTEGER CHECK (
    (preparation_key IS NULL AND preparation_demand_at_ms IS NULL
      AND preparation_expires_at_ms IS NULL AND preparation_consumed_at_ms IS NULL)
    OR
    (preparation_key IS NOT NULL AND length(preparation_key) = 64
      AND preparation_key NOT GLOB '*[^0-9a-f]*'
      AND preparation_demand_at_ms IS NOT NULL
      AND preparation_demand_at_ms BETWEEN 0 AND 9007199254740991
      AND preparation_expires_at_ms IS NOT NULL
      AND preparation_expires_at_ms > preparation_demand_at_ms
      AND preparation_expires_at_ms <= 9007199254740991
      AND (preparation_consumed_at_ms IS NULL
        OR (preparation_consumed_at_ms >= preparation_demand_at_ms
          AND preparation_consumed_at_ms < preparation_expires_at_ms)))
  ),
  provision_operation_id TEXT NOT NULL UNIQUE,
  lease_id TEXT,
  node_setup_id TEXT,
  node_device_id TEXT,
  ssh_host TEXT,
  ssh_port INTEGER CHECK (ssh_port IS NULL OR (ssh_port >= 1 AND ssh_port <= 65535)),
  ssh_user TEXT,
  ssh_host_key TEXT,
  ssh_key_ref_json TEXT,
  desktop_json TEXT,
  state TEXT NOT NULL CHECK (
    state IN (
      'requested',
      'provisioning',
      'bootstrapping',
      'ready',
      'attached',
      'idle',
      'draining',
      'destroying',
      'destroyed',
      'failed',
      'orphaned'
    )
  ),
  bootstrap_bundle_hash TEXT,
  bootstrap_openclaw_version TEXT,
  bootstrap_protocol_features_json TEXT,
  bootstrap_install_kind TEXT,
  owner_epoch INTEGER NOT NULL DEFAULT 0 CHECK (owner_epoch >= 0),
  teardown_terminal_state TEXT CHECK (teardown_terminal_state IN ('destroyed', 'failed')),
  attached_session_ids_json TEXT NOT NULL DEFAULT '[]',
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  state_changed_at_ms INTEGER NOT NULL,
  idle_since_at_ms INTEGER,
  destroy_requested_at_ms INTEGER,
  last_error TEXT,
  shared_host INTEGER,
  resource_receipt_json TEXT,
  retention_json TEXT,
  provision_source_json TEXT
) STRICT;

CREATE UNIQUE INDEX IF NOT EXISTS idx_worker_environments_provider_lease
  ON worker_environments(provider_id, lease_id)
  WHERE lease_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_worker_environments_terminal_changed
  ON worker_environments(state_changed_at_ms, environment_id);

-- A dedicated node registers its fixed build paths before ready, then binds
-- them once. The environment belongs to the Gateway's separate database.
CREATE TABLE IF NOT EXISTS node_worker_prepared_workspaces (
  preparation_key TEXT NOT NULL PRIMARY KEY CHECK (
    length(preparation_key) = 64 AND preparation_key NOT GLOB '*[^0-9a-f]*'
  ),
  cache_key TEXT NOT NULL CHECK (
    length(cache_key) = 64 AND cache_key NOT GLOB '*[^0-9a-f]*'
  ),
  gateway_namespace TEXT NOT NULL CHECK (length(gateway_namespace) > 0),
  workspace_dir TEXT NOT NULL UNIQUE CHECK (length(workspace_dir) > 0),
  home_dir TEXT NOT NULL CHECK (length(home_dir) > 0),
  source_manifest_ref TEXT NOT NULL CHECK (
    length(source_manifest_ref) = 71 AND substr(source_manifest_ref, 1, 7) = 'sha256:'
      AND substr(source_manifest_ref, 8) NOT GLOB '*[^0-9a-f]*'
  ),
  prepared_manifest_ref TEXT NOT NULL CHECK (
    length(prepared_manifest_ref) = 71 AND substr(prepared_manifest_ref, 1, 7) = 'sha256:'
      AND substr(prepared_manifest_ref, 8) NOT GLOB '*[^0-9a-f]*'
  ),
  state TEXT NOT NULL CHECK (state IN ('available', 'bound', 'retiring', 'retired')),
  environment_id TEXT NOT NULL CHECK (length(environment_id) > 0),
  session_id TEXT,
  session_key TEXT,
  owner_epoch INTEGER CHECK (owner_epoch BETWEEN 1 AND 9007199254740991),
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms BETWEEN 0 AND 9007199254740991),
  bound_at_ms INTEGER CHECK (bound_at_ms BETWEEN created_at_ms AND 9007199254740991),
  retired_at_ms INTEGER CHECK (
    retired_at_ms BETWEEN coalesce(bound_at_ms, created_at_ms) AND 9007199254740991
  ),
  CHECK (
    (session_id IS NULL AND session_key IS NULL AND owner_epoch IS NULL AND bound_at_ms IS NULL)
    OR
    (session_id IS NOT NULL AND length(session_id) > 0
      AND session_key IS NOT NULL AND length(session_key) > 0
      AND owner_epoch IS NOT NULL AND bound_at_ms IS NOT NULL)
  ),
  CHECK (
    (state = 'available' AND bound_at_ms IS NULL AND retired_at_ms IS NULL)
    OR (state = 'bound' AND bound_at_ms IS NOT NULL AND retired_at_ms IS NULL)
    OR (state = 'retiring' AND retired_at_ms IS NULL)
    OR (state = 'retired' AND retired_at_ms IS NOT NULL)
  )
) STRICT;

-- Provider-advertised fallback ports preserve stable retry order separately
-- from the downgrade-sensitive canonical worker environment row.
CREATE TABLE IF NOT EXISTS worker_environment_ssh_fallback_ports (
  environment_id TEXT NOT NULL,
  position INTEGER NOT NULL CHECK (position >= 0 AND position <= 9),
  port INTEGER NOT NULL CHECK (port >= 1 AND port <= 65535),
  PRIMARY KEY (environment_id, position),
  UNIQUE (environment_id, port),
  FOREIGN KEY (environment_id) REFERENCES worker_environments(environment_id) ON DELETE CASCADE
) STRICT;

-- Logical sessions own repository intent and accepted artifact references,
-- independently of the worker or rotating transcript session id.
CREATE TABLE IF NOT EXISTS session_repository_workspaces (
  workspace_id TEXT NOT NULL PRIMARY KEY CHECK (length(workspace_id) = 36),
  agent_id TEXT NOT NULL CHECK (length(agent_id) BETWEEN 1 AND 128),
  session_key TEXT NOT NULL CHECK (length(session_key) BETWEEN 1 AND 1024),
  url TEXT NOT NULL CHECK (length(url) BETWEEN 1 AND 4096),
  requested_ref TEXT CHECK (requested_ref IS NULL OR length(requested_ref) BETWEEN 1 AND 1024),
  run_setup_script INTEGER NOT NULL DEFAULT 0 CHECK (run_setup_script IN (0, 1)),
  base_commit TEXT CHECK (base_commit IS NULL OR length(base_commit) IN (40, 64)),
  base_manifest_hash TEXT,
  branch TEXT NOT NULL CHECK (length(branch) BETWEEN 1 AND 256),
  checkpoint_ref TEXT,
  manifest_hash TEXT,
  revision INTEGER NOT NULL CHECK (revision >= 0),
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  disk_authority_json TEXT,
  UNIQUE (agent_id, session_key),
  CHECK (base_manifest_hash IS NULL OR base_commit IS NOT NULL),
  CHECK ((checkpoint_ref IS NULL AND manifest_hash IS NULL)
    OR (checkpoint_ref IS NOT NULL AND manifest_hash IS NOT NULL AND base_manifest_hash IS NOT NULL))
) STRICT;

CREATE TABLE IF NOT EXISTS github_repository_publication_requests (
  request_id TEXT NOT NULL PRIMARY KEY,
  owner_profile_id TEXT,
  connection_generation TEXT,
  idempotency_key TEXT NOT NULL,
  request_digest TEXT NOT NULL,
  session_id TEXT NOT NULL,
  session_lifecycle_revision TEXT,
  requester_authority_json TEXT,
  session_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  workspace_id TEXT NOT NULL,
  checkpoint_ref TEXT,
  checkpoint_digest TEXT,
  claim_id TEXT,
  run_id TEXT,
  environment_id TEXT,
  owner_epoch INTEGER,
  placement_generation INTEGER,
  identity_source TEXT NOT NULL CHECK (identity_source IN ('system-detected', 'system-configured', 'agent-override', 'personal')),
  identity_profile_id TEXT,
  identity_account_id INTEGER NOT NULL,
  identity_login TEXT NOT NULL,
  title TEXT,
  body TEXT,
  status TEXT NOT NULL CHECK (status IN ('requested', 'publishing', 'needs_confirmation', 'published', 'failed')),
  gateway_instance_id TEXT,
  execution_id TEXT,
  last_effect TEXT CHECK (last_effect IN ('push', 'pull_request')),
  effect_state TEXT CHECK (effect_state IN ('dispatched', 'observed')),
  push_repository TEXT,
  repository TEXT,
  branch TEXT NOT NULL,
  base_branch TEXT,
  source_head_commit TEXT,
  source_index_tree TEXT,
  workspace_tree TEXT,
  previous_head_commit TEXT,
  pushed_head_commit TEXT,
  head_commit TEXT,
  pull_request_url TEXT,
  error_code TEXT,
  next_action TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  reported_at_ms INTEGER,
  draft INTEGER,
  CHECK ((identity_source = 'personal' AND owner_profile_id IS NOT NULL AND connection_generation IS NOT NULL)
    OR (identity_source <> 'personal' AND owner_profile_id IS NULL AND connection_generation IS NULL)),
  CHECK ((checkpoint_ref IS NULL AND checkpoint_digest IS NULL) OR (checkpoint_ref IS NOT NULL AND checkpoint_digest IS NOT NULL)),
  CHECK ((last_effect IS NULL AND effect_state IS NULL) OR (last_effect IS NOT NULL AND effect_state IS NOT NULL))
) STRICT;
CREATE UNIQUE INDEX IF NOT EXISTS idx_github_repository_publication_shared_request
  ON github_repository_publication_requests(session_id, idempotency_key) WHERE owner_profile_id IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS idx_github_repository_publication_personal_request
  ON github_repository_publication_requests(owner_profile_id, session_id, idempotency_key) WHERE owner_profile_id IS NOT NULL;

-- Session placement lives in the shared state database so local admission,
-- worker admission, and environment attachment use one durable authority.
CREATE TABLE IF NOT EXISTS worker_session_placements (
  session_id TEXT NOT NULL PRIMARY KEY,
  agent_id TEXT NOT NULL,
  session_key TEXT NOT NULL,
  execution_mode TEXT CHECK (execution_mode IN ('worker-turn', 'remote-exec')),
  state TEXT NOT NULL CHECK (
    state IN (
      'local',
      'requested',
      'provisioning',
      'syncing',
      'starting',
      'active',
      'draining',
      'reconciling',
      'reclaimed',
      'failed'
    )
  ),
  environment_id TEXT,
  transition_generation INTEGER NOT NULL DEFAULT 0 CHECK (transition_generation >= 0),
  active_owner_epoch INTEGER CHECK (active_owner_epoch IS NULL OR active_owner_epoch >= 1),
  workspace_base_manifest_ref TEXT,
  remote_workspace_dir TEXT,
  worker_bundle_hash TEXT,
  last_transcript_ack_cursor INTEGER CHECK (
    last_transcript_ack_cursor IS NULL OR last_transcript_ack_cursor >= 0
  ),
  last_live_event_ack_cursor INTEGER CHECK (
    last_live_event_ack_cursor IS NULL OR last_live_event_ack_cursor >= 0
  ),
  recovery_error TEXT,
  turn_claim_owner TEXT CHECK (turn_claim_owner IN ('local', 'worker')),
  turn_claim_id TEXT,
  turn_claim_run_id TEXT,
  turn_claim_generation INTEGER CHECK (
    turn_claim_generation IS NULL OR turn_claim_generation >= 0
  ),
  turn_claim_owner_epoch INTEGER CHECK (
    turn_claim_owner_epoch IS NULL OR turn_claim_owner_epoch >= 1
  ),
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  state_changed_at_ms INTEGER NOT NULL,
  terminal_reason TEXT,
  terminal_at_ms INTEGER,
  CHECK (
    (state IN ('local', 'requested')
      AND environment_id IS NULL AND active_owner_epoch IS NULL
      AND workspace_base_manifest_ref IS NULL AND remote_workspace_dir IS NULL
      AND worker_bundle_hash IS NULL
      AND last_transcript_ack_cursor IS NULL AND last_live_event_ack_cursor IS NULL
      AND recovery_error IS NULL)
    OR
    (state IS 'provisioning'
      AND active_owner_epoch IS NULL
      AND workspace_base_manifest_ref IS NULL AND remote_workspace_dir IS NULL
      AND worker_bundle_hash IS NULL
      AND last_transcript_ack_cursor IS NULL AND last_live_event_ack_cursor IS NULL
      AND recovery_error IS NULL)
    OR
    (state IS 'syncing'
      AND environment_id IS NOT NULL AND active_owner_epoch IS NULL
      AND workspace_base_manifest_ref IS NULL AND remote_workspace_dir IS NULL
      AND worker_bundle_hash IS NOT NULL
      AND last_transcript_ack_cursor IS NULL AND last_live_event_ack_cursor IS NULL
      AND recovery_error IS NULL)
    OR
    (state IS 'starting'
      AND environment_id IS NOT NULL AND active_owner_epoch IS NULL
      AND workspace_base_manifest_ref IS NOT NULL AND remote_workspace_dir IS NOT NULL
      AND worker_bundle_hash IS NOT NULL
      AND last_transcript_ack_cursor IS NULL AND last_live_event_ack_cursor IS NULL
      AND recovery_error IS NULL)
    OR
    (state IN ('active', 'draining', 'reconciling')
      AND environment_id IS NOT NULL AND active_owner_epoch IS NOT NULL
      AND workspace_base_manifest_ref IS NOT NULL AND remote_workspace_dir IS NOT NULL
      AND worker_bundle_hash IS NOT NULL AND recovery_error IS NULL)
    OR
    (state IS 'reclaimed'
      AND environment_id IS NOT NULL AND active_owner_epoch IS NOT NULL
      AND workspace_base_manifest_ref IS NOT NULL AND remote_workspace_dir IS NOT NULL
      AND worker_bundle_hash IS NOT NULL AND recovery_error IS NULL
      AND turn_claim_owner IS NULL AND turn_claim_id IS NULL AND turn_claim_run_id IS NULL
      AND turn_claim_generation IS NULL AND turn_claim_owner_epoch IS NULL)
    OR
    (state IS 'failed' AND recovery_error IS NOT NULL)
  ),
  CHECK (
    (turn_claim_owner IS NULL AND turn_claim_id IS NULL AND turn_claim_run_id IS NULL
      AND turn_claim_generation IS NULL AND turn_claim_owner_epoch IS NULL)
    OR
    (turn_claim_owner IS 'local' AND turn_claim_id IS NOT NULL
      AND turn_claim_run_id IS NOT NULL AND turn_claim_generation IS NOT NULL
      AND turn_claim_owner_epoch IS NULL)
    OR
    (turn_claim_owner IS 'worker' AND turn_claim_id IS NOT NULL
      AND turn_claim_run_id IS NOT NULL AND turn_claim_generation IS NOT NULL
      AND turn_claim_owner_epoch IS NOT NULL)
  ),
  CHECK (
    turn_claim_owner IS NULL
    OR
    (turn_claim_owner IS 'local' AND (
      state IN ('local', 'requested', 'failed')
      OR (state IN ('active', 'draining') AND execution_mode IS 'remote-exec')
    ))
    OR
    (turn_claim_owner IS 'worker' AND state IN ('active', 'draining')
      AND (execution_mode IS NULL OR execution_mode IS 'worker-turn')
      AND turn_claim_owner_epoch IS active_owner_epoch)
  )
) STRICT;

CREATE INDEX IF NOT EXISTS idx_worker_session_placements_session_key
  ON worker_session_placements(agent_id, session_key);

CREATE INDEX IF NOT EXISTS idx_worker_session_placements_reconcile
  ON worker_session_placements(updated_at_ms, session_id);

CREATE INDEX IF NOT EXISTS idx_worker_session_placements_environment
  ON worker_session_placements(environment_id)
  WHERE environment_id IS NOT NULL;

-- Planned placement moves retain their exact source CAS and bounded target
-- without widening the stable placement-state vocabulary. The opaque operation
-- id fences stale asynchronous completion; it is correlation, never authority.
CREATE TABLE IF NOT EXISTS worker_session_placement_moves (
  operation_id TEXT NOT NULL PRIMARY KEY,
  session_id TEXT NOT NULL UNIQUE
    REFERENCES worker_session_placements(session_id) ON DELETE CASCADE,
  source_generation INTEGER NOT NULL CHECK (source_generation >= 0),
  source_environment_id TEXT NOT NULL CHECK (
    length(source_environment_id) BETWEEN 1 AND 256
    AND source_environment_id = trim(source_environment_id)
  ),
  source_owner_epoch INTEGER NOT NULL CHECK (source_owner_epoch >= 1),
  target_kind TEXT NOT NULL CHECK (target_kind IN ('gateway', 'profile', 'device')),
  target_id TEXT,
  -- Keep these nullable columns constraint-free so lazy ALTER TABLE produces the
  -- same shape as fresh databases; placement-move code validates their values.
  target_machine_class TEXT,
  target_os TEXT,
  -- Explicit source abandonment is a durable operator decision. Keep the bit
  -- bare and nullable so same-version older readers can safely omit it.
  abandon_source INTEGER,
  last_error TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  CHECK (
    (target_kind IS 'gateway' AND target_id IS NULL)
    OR
    (target_kind IN ('profile', 'device')
      AND target_id IS NOT NULL
      AND length(target_id) BETWEEN 1 AND 256
      AND target_id = trim(target_id))
  )
) STRICT;

-- Worker-visible session RPC authority is persisted against the exact turn
-- claim. The launch descriptor is informative only; Gateway dispatch always
-- revalidates this record and the live placement claim before executing.
CREATE TABLE IF NOT EXISTS worker_turn_tool_authorities (
  session_id TEXT NOT NULL PRIMARY KEY,
  environment_id TEXT NOT NULL,
  owner_epoch INTEGER NOT NULL CHECK (owner_epoch >= 1),
  placement_generation INTEGER NOT NULL CHECK (placement_generation >= 0),
  claim_id TEXT NOT NULL,
  run_id TEXT NOT NULL,
  tool_names_json TEXT NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  FOREIGN KEY (session_id) REFERENCES worker_session_placements(session_id) ON DELETE CASCADE
) STRICT;

-- Tool-call ids are idempotency keys only within one exact source turn claim.
-- A running operation from another Gateway instance is ambiguous and is never
-- replayed. A persisted random seed separates durable downstream identities
-- from Gateway authentication keys and survives ordinary process restarts.
CREATE TABLE IF NOT EXISTS worker_session_tool_operations (
  source_session_id TEXT NOT NULL,
  source_claim_id TEXT NOT NULL,
  tool_call_id TEXT NOT NULL,
  tool_name TEXT NOT NULL CHECK (tool_name IN ('sessions_spawn', 'sessions_send')),
  request_digest TEXT NOT NULL,
  operation_seed TEXT NOT NULL,
  status TEXT NOT NULL CHECK (status IN ('running', 'succeeded', 'failed', 'unknown')),
  child_session_key TEXT,
  result_json TEXT,
  gateway_instance_id TEXT NOT NULL,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (source_session_id, source_claim_id, tool_call_id),
  FOREIGN KEY (source_session_id)
    REFERENCES worker_session_placements(session_id) ON DELETE CASCADE
) STRICT;

-- Local sandbox execution is a projection of a session-owned managed worktree.
-- No cascade: an older binary must not discard pending edits with a session row.
CREATE TABLE IF NOT EXISTS local_workspace_projections (
  worktree_id TEXT NOT NULL PRIMARY KEY,
  agent_id TEXT NOT NULL,
  session_key TEXT NOT NULL,
  session_id TEXT NOT NULL,
  lifecycle_revision TEXT,
  projection_path TEXT NOT NULL UNIQUE,
  base_commit TEXT NOT NULL,
  source_paths_json TEXT NOT NULL,
  baseline_json TEXT,
  baseline_ref TEXT,
  pending_ref TEXT,
  pending_target TEXT CHECK (pending_target IN ('canonical', 'projection')),
  paused_runtimes_json TEXT,
  journal_json TEXT,
  journal_pack BLOB CHECK (journal_pack IS NULL OR length(journal_pack) <= 268435456),
  revision INTEGER NOT NULL DEFAULT 0 CHECK (revision >= 0),
  created_at_ms INTEGER NOT NULL,
  checkpoint_json TEXT,
  tree_root_digest BLOB,
  source_paths_digest BLOB,
  canonical_fingerprints BLOB,
  projection_fingerprints BLOB,
  CHECK (baseline_json IS NULL OR baseline_ref IS NOT NULL),
  CHECK ((journal_json IS NULL) = (journal_pack IS NULL))
) STRICT;

-- The projection owner advances changed nodes and its root in one acceptance.
-- Legacy baseline_json remains only until that owner's resumable conversion.
CREATE TABLE IF NOT EXISTS local_workspace_manifest_nodes (
  worktree_id TEXT NOT NULL,
  path TEXT NOT NULL,
  node_json TEXT NOT NULL,
  PRIMARY KEY (worktree_id, path),
  FOREIGN KEY (worktree_id)
    REFERENCES local_workspace_projections(worktree_id) ON DELETE CASCADE
) STRICT;

-- Immutable subtrees and source inventories are shared across projections and revisions.
-- Large JSON packs measured 410k VFS reads/load WITHOUT ROWID versus 10k with rowid.
CREATE TABLE IF NOT EXISTS local_workspace_tree_packs (
  tree_digest BLOB NOT NULL PRIMARY KEY CHECK (length(tree_digest) = 32),
  records_json TEXT NOT NULL,
  children_json TEXT NOT NULL,
  sweep_epoch INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS local_workspace_source_path_sets (
  path_digest BLOB NOT NULL PRIMARY KEY CHECK (length(path_digest) = 32),
  paths_zstd BLOB NOT NULL,
  sweep_epoch INTEGER NOT NULL
) STRICT, WITHOUT ROWID;

-- A reconciliation journal is written before managed-worktree mutation. The
-- bounded Git base snapshot repairs any subset left by an interrupted apply.
CREATE TABLE IF NOT EXISTS worker_workspace_reconciliations (
  session_id TEXT NOT NULL PRIMARY KEY,
  environment_id TEXT NOT NULL,
  owner_epoch INTEGER NOT NULL CHECK (owner_epoch >= 1),
  placement_generation INTEGER NOT NULL CHECK (placement_generation >= 0),
  base_manifest_ref TEXT NOT NULL,
  current_manifest_ref TEXT NOT NULL,
  plan_json TEXT NOT NULL,
  base_pack BLOB NOT NULL CHECK (length(base_pack) <= 268435456),
  created_at_ms INTEGER NOT NULL,
  FOREIGN KEY (session_id) REFERENCES worker_session_placements(session_id) ON DELETE CASCADE
) STRICT;

-- A completed remote turn is fenced from stale-claim teardown until its
-- workspace result is durably reconciled into the managed worktree.
CREATE TABLE IF NOT EXISTS worker_workspace_pending_results (
  session_id TEXT NOT NULL PRIMARY KEY,
  environment_id TEXT NOT NULL,
  owner_epoch INTEGER NOT NULL CHECK (owner_epoch >= 1),
  placement_generation INTEGER NOT NULL CHECK (placement_generation >= 0),
  claim_id TEXT NOT NULL,
  run_id TEXT NOT NULL,
  gateway_instance_id TEXT NOT NULL,
  recovery_requested_at_ms INTEGER,
  workspace_accepted_at_ms INTEGER,
  staged_result_ref TEXT,
  repository_workspace_id TEXT,
  created_at_ms INTEGER NOT NULL,
  repository_disk_authority_json TEXT,
  FOREIGN KEY (session_id) REFERENCES worker_session_placements(session_id) ON DELETE CASCADE
) STRICT;

-- GitHub publication intent records the authoritative session worktree. Cloud
-- requests execute only after the exact turn claim's result is accepted locally.
-- Secrets stay in the effective Gateway-owned GitHub profile and never enter
-- this row or the worker protocol.
CREATE TABLE IF NOT EXISTS github_publication_requests (
  request_id TEXT NOT NULL PRIMARY KEY,
  idempotency_key TEXT NOT NULL,
  request_digest TEXT NOT NULL,
  session_id TEXT NOT NULL,
  session_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  worktree_id TEXT NOT NULL,
  repository_fingerprint TEXT NOT NULL,
  claim_id TEXT,
  run_id TEXT,
  environment_id TEXT,
  owner_epoch INTEGER CHECK (owner_epoch IS NULL OR owner_epoch >= 1),
  placement_generation INTEGER CHECK (
    placement_generation IS NULL OR placement_generation >= 0
  ),
  identity_source TEXT NOT NULL CHECK (
    identity_source IN ('system-detected', 'system-configured', 'agent-override')
  ),
  identity_profile_id TEXT,
  identity_account_id INTEGER NOT NULL CHECK (identity_account_id >= 1),
  identity_login TEXT NOT NULL,
  title TEXT,
  body TEXT,
  status TEXT NOT NULL CHECK (
    status IN ('requested', 'publishing', 'published', 'failed')
  ),
  gateway_instance_id TEXT,
  repository TEXT,
  branch TEXT NOT NULL,
  base_branch TEXT,
  source_head_commit TEXT,
  source_index_tree TEXT,
  workspace_tree TEXT,
  head_commit TEXT,
  pull_request_url TEXT,
  error_code TEXT,
  next_action TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  reported_at_ms INTEGER,
  draft INTEGER,
  UNIQUE (session_id, idempotency_key),
  CHECK (
    (claim_id IS NULL AND run_id IS NULL AND environment_id IS NULL
      AND owner_epoch IS NULL AND placement_generation IS NULL)
    OR
    (claim_id IS NOT NULL AND run_id IS NOT NULL AND placement_generation IS NOT NULL
      AND ((environment_id IS NULL AND owner_epoch IS NULL)
        OR (environment_id IS NOT NULL AND owner_epoch IS NOT NULL)))
  ),
  CHECK (
    (identity_source IS 'system-detected' AND identity_profile_id IS NULL)
    OR
    (identity_source IN ('system-configured', 'agent-override')
      AND identity_profile_id IS NOT NULL)
  ),
  CHECK (
    (source_head_commit IS NULL AND source_index_tree IS NULL AND workspace_tree IS NULL)
    OR
    (source_head_commit IS NOT NULL AND workspace_tree IS NOT NULL)
  ),
  CHECK (
    (status IS 'published' AND pull_request_url IS NOT NULL AND error_code IS NULL
      AND next_action IS NULL)
    OR
    (status IS 'failed' AND pull_request_url IS NULL AND error_code IS NOT NULL
      AND next_action IS NOT NULL)
    OR
    (status IN ('requested', 'publishing') AND pull_request_url IS NULL
      AND error_code IS NULL AND next_action IS NULL)
  )
) STRICT;

CREATE INDEX IF NOT EXISTS idx_github_publication_requests_pending
  ON github_publication_requests(status, updated_at_ms, request_id);

-- Personal requests cannot be interpreted or resumed by older shared publishers.
CREATE TABLE IF NOT EXISTS github_personal_publication_requests (
  request_id TEXT NOT NULL PRIMARY KEY CHECK (length(request_id) = 36),
  owner_profile_id TEXT NOT NULL CHECK (length(owner_profile_id) BETWEEN 1 AND 128),
  connection_generation TEXT NOT NULL CHECK (length(connection_generation) = 36),
  idempotency_key TEXT NOT NULL CHECK (length(idempotency_key) BETWEEN 1 AND 128),
  request_digest TEXT NOT NULL CHECK (length(request_digest) = 64),
  session_id TEXT NOT NULL CHECK (length(session_id) BETWEEN 1 AND 128),
  session_key TEXT NOT NULL CHECK (length(session_key) BETWEEN 1 AND 1024),
  agent_id TEXT NOT NULL CHECK (length(agent_id) BETWEEN 1 AND 128),
  worktree_id TEXT NOT NULL CHECK (length(worktree_id) BETWEEN 1 AND 128),
  repository_fingerprint TEXT NOT NULL CHECK (length(repository_fingerprint) BETWEEN 1 AND 256),
  identity_source TEXT NOT NULL CHECK (identity_source = 'personal'),
  identity_profile_id TEXT NOT NULL CHECK (length(identity_profile_id) = 36),
  identity_account_id INTEGER NOT NULL CHECK (identity_account_id >= 1),
  identity_login TEXT NOT NULL CHECK (length(identity_login) BETWEEN 1 AND 39),
  title TEXT CHECK (title IS NULL OR length(title) BETWEEN 1 AND 256),
  body TEXT CHECK (body IS NULL OR length(body) BETWEEN 1 AND 8192),
  status TEXT NOT NULL CHECK (status IN ('requested', 'publishing', 'needs_confirmation', 'published', 'failed')),
  gateway_instance_id TEXT CHECK (gateway_instance_id IS NULL OR length(gateway_instance_id) BETWEEN 1 AND 128),
  execution_id TEXT CHECK (execution_id IS NULL OR length(execution_id) = 36),
  last_effect TEXT CHECK (last_effect IS NULL OR last_effect IN ('push', 'pull_request')),
  effect_state TEXT CHECK (effect_state IS NULL OR effect_state IN ('dispatched', 'observed')),
  push_repository TEXT NOT NULL CHECK (length(push_repository) BETWEEN 3 AND 256),
  repository TEXT NOT NULL CHECK (length(repository) BETWEEN 3 AND 256),
  branch TEXT NOT NULL CHECK (length(branch) BETWEEN 1 AND 256),
  base_branch TEXT NOT NULL CHECK (length(base_branch) BETWEEN 1 AND 256),
  source_head_commit TEXT NOT NULL CHECK (length(source_head_commit) IN (40, 64)),
  source_index_tree TEXT NOT NULL CHECK (length(source_index_tree) IN (40, 64)),
  workspace_tree TEXT NOT NULL CHECK (length(workspace_tree) IN (40, 64)),
  head_commit TEXT CHECK (head_commit IS NULL OR length(head_commit) IN (40, 64)),
  pull_request_url TEXT CHECK (pull_request_url IS NULL OR length(pull_request_url) BETWEEN 1 AND 2048),
  error_code TEXT CHECK (error_code IS NULL OR length(error_code) BETWEEN 1 AND 64),
  next_action TEXT CHECK (next_action IS NULL OR length(next_action) BETWEEN 1 AND 1024),
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),
  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= created_at_ms),
  reported_at_ms INTEGER,
  draft INTEGER,
  UNIQUE (owner_profile_id, session_id, idempotency_key),
  CHECK ((status = 'publishing' AND gateway_instance_id IS NOT NULL AND execution_id IS NOT NULL) OR status <> 'publishing'),
  CHECK ((last_effect IS NULL AND effect_state IS NULL) OR (last_effect IS NOT NULL AND effect_state IS NOT NULL)),
  CHECK ((status = 'published' AND pull_request_url IS NOT NULL AND head_commit IS NOT NULL AND error_code IS NULL AND next_action IS NULL)
    OR (status = 'failed' AND error_code IS NOT NULL AND next_action IS NOT NULL)
    OR (status IN ('requested', 'publishing', 'needs_confirmation') AND error_code IS NULL AND next_action IS NULL))
) STRICT;
CREATE INDEX IF NOT EXISTS idx_github_personal_publication_owner_session
  ON github_personal_publication_requests(owner_profile_id, session_id, created_at_ms);
CREATE INDEX IF NOT EXISTS idx_github_personal_publication_pending
  ON github_personal_publication_requests(status, updated_at_ms, request_id);

-- Older readers validate both local receipt tables exactly. Their immutable
-- lifecycle binding stays in a first-use companion so those schemas remain readable.
CREATE TABLE IF NOT EXISTS github_publication_session_lifecycles (
  publication_kind TEXT NOT NULL CHECK (publication_kind IN ('shared', 'personal')),
  request_id TEXT NOT NULL,
  lifecycle_revision TEXT,
  requester_authority_json TEXT,
  PRIMARY KEY (publication_kind, request_id)
) STRICT;

-- One active, opaque admission credential per worker environment. Plaintext
-- may be retried until delivery acknowledgement but never enters durable state.
CREATE TABLE IF NOT EXISTS worker_environment_credentials (
  environment_id TEXT NOT NULL PRIMARY KEY,
  credential_hash TEXT NOT NULL UNIQUE,
  bundle_hash TEXT NOT NULL,
  session_id TEXT,
  rpc_set_version INTEGER NOT NULL CHECK (rpc_set_version >= 1),
  owner_epoch INTEGER NOT NULL CHECK (owner_epoch >= 0),
  expires_at_ms INTEGER NOT NULL CHECK (expires_at_ms >= 0),
  delivered_at_ms INTEGER CHECK (delivered_at_ms >= 0),
  FOREIGN KEY (environment_id) REFERENCES worker_environments(environment_id) ON DELETE CASCADE
) STRICT;

-- One durable sequence cursor per attached session owner epoch. The environment
-- binding prevents independent workers with coincident epochs from sharing replay state.
CREATE TABLE IF NOT EXISTS worker_transcript_commit_heads (
  session_id TEXT NOT NULL,
  run_epoch INTEGER NOT NULL CHECK (run_epoch >= 0),
  environment_id TEXT NOT NULL,
  next_seq INTEGER NOT NULL CHECK (next_seq >= 1),
  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),
  PRIMARY KEY (session_id, run_epoch)
) STRICT;

-- Pending rows preserve a claimed request across gateway restarts. Terminal rows
-- cache the exact result returned for deterministic at-least-once replay.
CREATE TABLE IF NOT EXISTS worker_transcript_commits (
  session_id TEXT NOT NULL,
  run_epoch INTEGER NOT NULL CHECK (run_epoch >= 0),
  seq INTEGER NOT NULL CHECK (seq >= 1),
  request_hash TEXT NOT NULL,
  state TEXT NOT NULL CHECK (state IN ('pending', 'terminal')),
  result_json TEXT,
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),
  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),
  PRIMARY KEY (session_id, run_epoch, seq),
  FOREIGN KEY (session_id, run_epoch)
    REFERENCES worker_transcript_commit_heads(session_id, run_epoch)
    ON DELETE CASCADE,
  CHECK (
    (state = 'pending' AND result_json IS NULL) OR
    (state = 'terminal' AND result_json IS NOT NULL)
  )
) STRICT;

-- Pending rows preserve a claimed inference turn across gateway restarts.
-- Terminal rows cache the exact outcome returned for deterministic replay.
CREATE TABLE IF NOT EXISTS worker_inference_turns (
  session_id TEXT NOT NULL,
  run_epoch INTEGER NOT NULL CHECK (run_epoch >= 0),
  run_id TEXT NOT NULL,
  turn_id TEXT NOT NULL,
  environment_id TEXT NOT NULL,
  request_hash TEXT NOT NULL,
  state TEXT NOT NULL CHECK (state IN ('pending', 'terminal')),
  terminal_json TEXT,
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),
  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),
  PRIMARY KEY (session_id, run_epoch, run_id, turn_id),
  FOREIGN KEY (environment_id) REFERENCES worker_environments(environment_id) ON DELETE CASCADE,
  CHECK (
    (state = 'pending' AND terminal_json IS NULL) OR
    (state = 'terminal' AND terminal_json IS NOT NULL)
  )
) STRICT;

CREATE UNIQUE INDEX IF NOT EXISTS idx_worker_inference_turns_pending_run
  ON worker_inference_turns(session_id, run_epoch, run_id)
  WHERE state = 'pending';

CREATE TABLE IF NOT EXISTS template_installs (
  agent_id TEXT NOT NULL PRIMARY KEY,
  schema_version TEXT NOT NULL,
  source_kind TEXT NOT NULL,
  template_name TEXT NOT NULL,
  template_version TEXT NOT NULL,
  package_root TEXT NOT NULL,
  manifest_path TEXT NOT NULL,
  integrity_kind TEXT NOT NULL,
  integrity TEXT NOT NULL,
  source_byte_length INTEGER NOT NULL,
  manifest_schema_version INTEGER NOT NULL,
  plan_integrity TEXT NOT NULL,
  workspace TEXT NOT NULL UNIQUE,
  agent_config_digest TEXT NOT NULL,
  agent_owned_paths_json TEXT NOT NULL,
  bootstrap_source_path TEXT,
  bootstrap_content_digest TEXT,
  status TEXT NOT NULL CHECK (
    status IN ('pending', 'workspace_ready', 'config_committed', 'complete', 'partial')
  ),
  added_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS template_workspace_files (
  agent_id TEXT NOT NULL,
  target_path TEXT NOT NULL,
  schema_version TEXT NOT NULL,
  workspace TEXT NOT NULL,
  source_path TEXT NOT NULL,
  content_digest TEXT NOT NULL,
  status TEXT NOT NULL,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (agent_id, target_path)
) STRICT;

CREATE TABLE IF NOT EXISTS template_package_refs (
  agent_id TEXT NOT NULL,
  package_kind TEXT NOT NULL,
  package_source TEXT NOT NULL,
  package_ref TEXT NOT NULL,
  package_version TEXT NOT NULL,
  package_integrity TEXT NOT NULL,
  schema_version TEXT NOT NULL,
  template_name TEXT NOT NULL,
  package_status TEXT NOT NULL,
  relationship TEXT NOT NULL CHECK (relationship IN ('managed', 'referenced')),
  origin TEXT NOT NULL CHECK (origin IN ('template-introduced', 'pre-existing')),
  independent_owner INTEGER NOT NULL CHECK (independent_owner IN (0, 1)),
  extension_id TEXT,
  extension_format TEXT,
  extension_detected_format TEXT,
  extension_mapped_json TEXT,
  extension_unavailable_json TEXT,
  extension_adapter_identity TEXT,
  installed_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (agent_id, package_kind, package_source, package_ref, package_version)
) STRICT;

CREATE TABLE IF NOT EXISTS template_cron_refs (
  agent_id TEXT NOT NULL,
  manifest_id TEXT NOT NULL,
  schema_version TEXT NOT NULL,
  declaration_key TEXT NOT NULL UNIQUE,
  scheduler_job_id TEXT UNIQUE,
  status TEXT NOT NULL,
  job_json TEXT NOT NULL,
  error TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (agent_id, manifest_id)
) STRICT;

CREATE TABLE IF NOT EXISTS template_mcp_server_refs (
  agent_id TEXT NOT NULL,
  name TEXT NOT NULL,
  schema_version TEXT NOT NULL,
  config_digest TEXT NOT NULL,
  relationship TEXT NOT NULL CHECK (relationship IN ('managed', 'referenced')),
  origin TEXT NOT NULL CHECK (origin IN ('template-introduced', 'pre-existing')),
  independent_owner INTEGER NOT NULL DEFAULT 0 CHECK (independent_owner IN (0, 1)),
  status TEXT NOT NULL,
  error TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (agent_id, name)
) STRICT;

CREATE TABLE IF NOT EXISTS user_profile_identities (
  provider TEXT NOT NULL,
  subject TEXT NOT NULL,
  profile_id TEXT NOT NULL,
  canonical_login TEXT,
  -- Host-scoped verified credit evidence; current profile bindings govern attribution.
  verified_email_json TEXT,
  created_at INTEGER NOT NULL,
  authorization_id TEXT,
  authorization_basis_json TEXT,
  PRIMARY KEY (provider, subject)
) STRICT;
CREATE INDEX IF NOT EXISTS idx_user_profile_identities_profile_id
  ON user_profile_identities(profile_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_profile_identities_authorization
  ON user_profile_identities(authorization_id);

CREATE TABLE IF NOT EXISTS outbound_media_provenance (
  realpath TEXT NOT NULL PRIMARY KEY,
  kind TEXT NOT NULL,
  version INTEGER NOT NULL,
  sha256 TEXT NOT NULL,
  size_bytes INTEGER NOT NULL,
  created_at_ms INTEGER NOT NULL
) STRICT;

-- scope_id is non-null because SQLite treats NULLs as distinct in unique indexes/PKs,
-- which would allow duplicate team rows. This PK also avoids a rebuild for identity scope.
CREATE TABLE IF NOT EXISTS secret_store_entries (
  scope_kind TEXT NOT NULL CHECK (scope_kind IN ('team', 'identity')),
  scope_id TEXT NOT NULL,
  name TEXT NOT NULL,
  value TEXT NOT NULL,
  kind TEXT NOT NULL CHECK (kind IN ('secret', 'env')),
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),
  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),
  updated_by TEXT,
  deleted_at_ms INTEGER,
  allowed_hosts TEXT,
  CHECK ((scope_kind = 'team' AND scope_id = '') OR (scope_kind = 'identity' AND length(scope_id) > 0)),
  PRIMARY KEY (scope_kind, scope_id, name)
) STRICT;
CREATE INDEX IF NOT EXISTS secret_store_entries_live_idx
  ON secret_store_entries (scope_kind, scope_id, name) WHERE deleted_at_ms IS NULL;
`?`current`:t}`,a=Vu.get(i);if(a!==void 0)return a;let o=t,s=[...n?cs:Mo,...r?[]:Oo],c=n?Vo:ko;for(let e of s)(t===`

CREATE TABLE IF NOT EXISTS mcp_oauth_stores (
  store_key TEXT NOT NULL PRIMARY KEY,
  format_version INTEGER NOT NULL CHECK (format_version = 1),
  store_json TEXT NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS mcp_oauth_pending_authorizations (
  state TEXT NOT NULL PRIMARY KEY,
  store_key TEXT NOT NULL,
  create_time INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS diagnostic_events (
  scope TEXT NOT NULL,
  event_key TEXT NOT NULL,
  payload_json TEXT NOT NULL,
  created_at INTEGER NOT NULL,
  sequence INTEGER NOT NULL DEFAULT 0,
  PRIMARY KEY (scope, event_key)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_diagnostic_events_scope_sequence
  ON diagnostic_events(scope, sequence, event_key);

CREATE TABLE IF NOT EXISTS skill_usage (
  skill_file TEXT NOT NULL PRIMARY KEY,
  skill_key TEXT NOT NULL,
  skill_name TEXT NOT NULL,
  skill_source TEXT NOT NULL,
  first_used_at_ms INTEGER NOT NULL,
  last_used_at_ms INTEGER NOT NULL,
  use_count INTEGER NOT NULL,
  last_agent_id TEXT
) STRICT;

-- Profile-owned skill library: additive, absent until first publication/import.
CREATE TABLE IF NOT EXISTS skill_library_entries (
  skill_id TEXT NOT NULL PRIMARY KEY,
  owner_profile_id TEXT,
  author_profile_id TEXT NOT NULL,
  slug TEXT NOT NULL,
  current_revision TEXT NOT NULL,
  shared INT NOT NULL,
  enabled INT NOT NULL,
  removed INT NOT NULL,
  created_at INT NOT NULL,
  updated_at INT NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS skill_library_revisions (
  skill_id TEXT NOT NULL,
  revision TEXT NOT NULL,
  description TEXT NOT NULL,
  files_json TEXT NOT NULL,
  created_at INT NOT NULL,
  PRIMARY KEY (skill_id, revision)
) STRICT;
CREATE TABLE IF NOT EXISTS skill_library_events (
  event_id TEXT NOT NULL PRIMARY KEY,
  skill_id TEXT NOT NULL,
  revision TEXT NOT NULL,
  action TEXT NOT NULL,
  actor_profile_id TEXT NOT NULL,
  created_at INT NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS skill_library_uploads (
  upload_id TEXT NOT NULL PRIMARY KEY,
  owner_profile_id TEXT NOT NULL,
  slug TEXT NOT NULL,
  size_bytes INT NOT NULL,
  sha256 TEXT NOT NULL,
  archive_blob BLOB NOT NULL,
  expires_at INT NOT NULL,
  published_skill_id TEXT
) STRICT;
-- End profile-owned skill library.

CREATE TABLE IF NOT EXISTS skill_workshop_changes (
  cursor_id INTEGER NOT NULL,
  change_id TEXT NOT NULL PRIMARY KEY,
  agent_id TEXT NOT NULL,
  skill_name TEXT NOT NULL,
  action TEXT NOT NULL CHECK (action IN ('create', 'patch', 'write_file', 'remove_file', 'archive', 'restore')),
  actor TEXT NOT NULL CHECK (actor IN ('agent', 'review', 'curator', 'user')),
  summary TEXT NOT NULL,
  version_id TEXT,
  session_key TEXT,
  run_id TEXT,
  created_at_ms INTEGER NOT NULL
) STRICT;

CREATE UNIQUE INDEX IF NOT EXISTS skill_workshop_changes_cursor_id_idx
  ON skill_workshop_changes(cursor_id);

CREATE INDEX IF NOT EXISTS idx_skill_workshop_changes_agent_time
  ON skill_workshop_changes(agent_id, created_at_ms);

CREATE TABLE IF NOT EXISTS audit_events (
  sequence INTEGER PRIMARY KEY AUTOINCREMENT,
  event_id TEXT NOT NULL UNIQUE,
  source_id TEXT NOT NULL UNIQUE,
  schema_version INTEGER NOT NULL DEFAULT 1,
  source_sequence INTEGER NOT NULL,
  occurred_at INTEGER NOT NULL,
  kind TEXT NOT NULL,
  action TEXT NOT NULL,
  status TEXT NOT NULL,
  error_code TEXT,
  actor_type TEXT NOT NULL,
  actor_id TEXT NOT NULL,
  agent_id TEXT,
  session_key TEXT,
  session_id TEXT,
  run_id TEXT,
  tool_call_id TEXT,
  tool_name TEXT,
  direction TEXT,
  channel TEXT,
  conversation_kind TEXT,
  message_outcome TEXT,
  reason_code TEXT,
  delivery_kind TEXT,
  failure_stage TEXT,
  duration_ms INTEGER,
  result_count INTEGER,
  account_ref TEXT,
  conversation_ref TEXT,
  message_ref TEXT,
  target_ref TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_audit_events_time
  ON audit_events(occurred_at DESC, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_agent_sequence
  ON audit_events(agent_id, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_session_sequence
  ON audit_events(session_key, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_run_sequence
  ON audit_events(run_id, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_kind_sequence
  ON audit_events(kind, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_status_sequence
  ON audit_events(status, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_channel_sequence
  ON audit_events(channel, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_audit_events_direction_sequence
  ON audit_events(direction, sequence DESC);

CREATE TABLE IF NOT EXISTS outbound_message_execution_bindings (
  event_id TEXT NOT NULL PRIMARY KEY,
  context_id TEXT NOT NULL CHECK (length(context_id) BETWEEN 1 AND 256),
  execution_id TEXT NOT NULL CHECK (length(execution_id) BETWEEN 1 AND 256),
  run_id TEXT NOT NULL CHECK (length(run_id) BETWEEN 1 AND 256),
  FOREIGN KEY (event_id) REFERENCES audit_events(event_id) ON DELETE CASCADE
) STRICT;
CREATE INDEX IF NOT EXISTS outbound_message_execution_bindings_execution_event_idx
  ON outbound_message_execution_bindings (context_id, execution_id, run_id, event_id);

CREATE TABLE IF NOT EXISTS outbound_message_progress (
  sequence INTEGER PRIMARY KEY AUTOINCREMENT,
  progress_id TEXT NOT NULL UNIQUE CHECK (length(progress_id) BETWEEN 1 AND 256),
  source_id TEXT NOT NULL UNIQUE CHECK (length(source_id) BETWEEN 1 AND 512),
  source_sequence INTEGER NOT NULL CHECK (source_sequence >= 1),
  schema_version INTEGER NOT NULL CHECK (schema_version = 1),
  occurred_at INTEGER NOT NULL CHECK (occurred_at >= 0),
  action TEXT NOT NULL CHECK (
    action IN ('message.outbound.queued', 'message.outbound.platform-started')
  ),
  outcome TEXT NOT NULL CHECK (outcome IN ('queued', 'platform_started')),
  actor_type TEXT NOT NULL CHECK (actor_type IN ('agent', 'system')),
  actor_id TEXT NOT NULL CHECK (length(actor_id) BETWEEN 1 AND 256),
  agent_id TEXT CHECK (agent_id IS NULL OR length(agent_id) BETWEEN 1 AND 256),
  run_id TEXT CHECK (run_id IS NULL OR length(run_id) BETWEEN 1 AND 256),
  context_id TEXT,
  execution_id TEXT,
  channel TEXT NOT NULL CHECK (length(channel) BETWEEN 1 AND 256),
  conversation_kind TEXT NOT NULL CHECK (
    conversation_kind IN ('direct', 'group', 'channel', 'unknown')
  ),
  duration_ms INTEGER CHECK (duration_ms IS NULL OR duration_ms >= 0),
  account_ref TEXT,
  conversation_ref TEXT,
  target_ref TEXT,
  UNIQUE (occurred_at, progress_id)
) STRICT;
CREATE INDEX IF NOT EXISTS outbound_message_progress_occurred_idx
  ON outbound_message_progress (occurred_at, sequence);
CREATE INDEX IF NOT EXISTS outbound_message_progress_run_occurred_idx
  ON outbound_message_progress (run_id, occurred_at, sequence);

CREATE TABLE IF NOT EXISTS audit_identity_keys (
  id INTEGER NOT NULL PRIMARY KEY CHECK (id = 1),
  key_id TEXT NOT NULL,
  key BLOB NOT NULL,
  created_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS config_revision_keys (
  id INTEGER NOT NULL PRIMARY KEY CHECK (id = 1),
  hmac_key BLOB NOT NULL CHECK (length(hmac_key) = 32)
) STRICT;

CREATE TABLE IF NOT EXISTS execution_identity_contexts (
  context_id TEXT NOT NULL PRIMARY KEY CHECK (length(context_id) BETWEEN 1 AND 256),
  execution_id TEXT NOT NULL UNIQUE CHECK (length(execution_id) BETWEEN 1 AND 256),
  run_id TEXT NOT NULL CHECK (length(run_id) BETWEEN 1 AND 256),
  created_at INTEGER NOT NULL CHECK (created_at >= 0),
  coverage_state TEXT NOT NULL CHECK (
    coverage_state IN ('attribution-only', 'unattributed', 'unknown', 'unsupported')
  ),
  context_bytes INTEGER NOT NULL CHECK (context_bytes BETWEEN 1 AND 16384),
  context_json TEXT NOT NULL CHECK (length(context_json) > 0),
  UNIQUE (created_at, context_id)
) STRICT;
CREATE INDEX IF NOT EXISTS execution_identity_contexts_run_created_idx
  ON execution_identity_contexts (run_id, created_at, execution_id);

CREATE TABLE IF NOT EXISTS execution_decision_facts (
  cursor_id INTEGER NOT NULL,
  receipt_id TEXT NOT NULL PRIMARY KEY CHECK (length(receipt_id) BETWEEN 1 AND 256),
  context_id TEXT NOT NULL CHECK (length(context_id) BETWEEN 1 AND 256),
  execution_id TEXT NOT NULL CHECK (length(execution_id) BETWEEN 1 AND 256),
  run_id TEXT NOT NULL CHECK (length(run_id) BETWEEN 1 AND 256),
  action_id TEXT CHECK (action_id IS NULL OR length(action_id) BETWEEN 1 AND 256),
  action_family TEXT NOT NULL CHECK (length(action_family) BETWEEN 1 AND 256),
  decision_outcome TEXT NOT NULL CHECK (
    decision_outcome IN ('allowed', 'denied', 'not-applicable', 'unknown')
  ),
  coverage_state TEXT NOT NULL CHECK (
    coverage_state IN ('enforced', 'attribution-only', 'unattributed', 'unknown', 'unsupported')
  ),
  reason_code TEXT NOT NULL CHECK (length(reason_code) BETWEEN 1 AND 256),
  owner TEXT NOT NULL CHECK (length(owner) BETWEEN 1 AND 256),
  source_ref TEXT NOT NULL CHECK (length(source_ref) BETWEEN 1 AND 256),
  occurred_at INTEGER NOT NULL CHECK (occurred_at >= 0),
  receipt_bytes INTEGER NOT NULL CHECK (receipt_bytes BETWEEN 1 AND 16384),
  receipt_json TEXT NOT NULL CHECK (length(receipt_json) > 0),
  UNIQUE (occurred_at, receipt_id)
) STRICT;
CREATE UNIQUE INDEX IF NOT EXISTS execution_decision_facts_cursor_id_idx
  ON execution_decision_facts(cursor_id);

CREATE INDEX IF NOT EXISTS execution_decision_facts_context_occurred_idx
  ON execution_decision_facts (context_id, occurred_at, receipt_id);
CREATE INDEX IF NOT EXISTS execution_decision_facts_run_occurred_idx
  ON execution_decision_facts (run_id, occurred_at, receipt_id);

-- Exact admission identity stays separate from owner-native lifecycle rows so
-- older readers retain byte-compatible cron/task/flow table definitions.
CREATE TABLE IF NOT EXISTS execution_owner_lifecycle_bindings (
  owner_kind TEXT NOT NULL,
  owner_id TEXT NOT NULL,
  context_id TEXT NOT NULL,
  execution_id TEXT NOT NULL,
  PRIMARY KEY (owner_kind, owner_id)
) STRICT;

CREATE TABLE IF NOT EXISTS session_state_events (
  sequence INTEGER PRIMARY KEY AUTOINCREMENT,
  dedupe_key TEXT UNIQUE,
  session_key TEXT NOT NULL,
  session_id TEXT,
  agent_id TEXT NOT NULL,
  kind TEXT NOT NULL,
  actor_type TEXT NOT NULL,
  actor_id TEXT,
  run_id TEXT,
  occurred_at INTEGER NOT NULL,
  summary TEXT NOT NULL,
  payload_json TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_session_state_events_session_sequence
  ON session_state_events(session_key, sequence DESC);

CREATE INDEX IF NOT EXISTS idx_session_state_events_time
  ON session_state_events(occurred_at DESC, sequence DESC);

CREATE TABLE IF NOT EXISTS session_state_heads (
  session_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  last_sequence INTEGER NOT NULL,
  pruned_max_sequence INTEGER NOT NULL DEFAULT 0,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (session_key, agent_id)
) STRICT, WITHOUT ROWID;

-- Notifiable watcher identity is the bare session key, matching the process-local
-- system-event queue it feeds. Provenance distinguishes explicit immediate-wake
-- watches from ambient queue-only group watches. Other bare keys
-- (session.scope="global") are ambiguous across agents and excluded until watcher
-- identity is agent-scoped end-to-end.
CREATE TABLE IF NOT EXISTS session_watch_cursors (
  watcher_session_key TEXT NOT NULL,
  watcher_store_path TEXT,
  target_session_key TEXT NOT NULL,
  last_seen_sequence INTEGER NOT NULL DEFAULT 0,
  notified_sequence INTEGER NOT NULL DEFAULT 0,
  material_sequence INTEGER NOT NULL DEFAULT 0,
  provenance TEXT NOT NULL DEFAULT 'explicit' CHECK (provenance IN ('explicit', 'ambient-group')),
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (watcher_session_key, target_session_key)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_session_watch_cursors_target
  ON session_watch_cursors(target_session_key);

CREATE TABLE IF NOT EXISTS session_upstream_links (
  session_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  catalog_id TEXT NOT NULL,
  host_id TEXT NOT NULL,
  thread_id TEXT NOT NULL,
  upstream_kind TEXT NOT NULL,
  upstream_ref_json TEXT,
  last_marker_json TEXT,
  last_scanned_at INTEGER,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  -- (session_key, agent_id) composite identity: under session.scope="global" agents
  -- share bare keys; a key-only row would let one agent overwrite another's upstream.
  PRIMARY KEY (session_key, agent_id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_session_upstream_links_catalog_id
  ON session_upstream_links(catalog_id);

CREATE TABLE IF NOT EXISTS state_leases (
  scope TEXT NOT NULL,
  lease_key TEXT NOT NULL,
  owner TEXT NOT NULL,
  expires_at INTEGER,
  heartbeat_at INTEGER,
  payload_json TEXT,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (scope, lease_key)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_state_leases_expiry
  ON state_leases(expires_at, scope, lease_key)
  WHERE expires_at IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_state_leases_owner
  ON state_leases(owner);

CREATE TABLE IF NOT EXISTS exec_approvals_config (
  config_key TEXT NOT NULL PRIMARY KEY,
  raw_json TEXT NOT NULL,
  socket_path TEXT,
  has_socket_token INTEGER NOT NULL,
  default_security TEXT,
  default_ask TEXT,
  default_ask_fallback TEXT,
  auto_allow_skills INTEGER,
  agent_count INTEGER NOT NULL,
  allowlist_count INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS operator_approvals (
  cursor_id INTEGER NOT NULL,
  approval_id TEXT NOT NULL PRIMARY KEY CHECK (
    length(approval_id) > 0 AND approval_id NOT IN ('.', '..')
  ),
  resolution_ref TEXT NOT NULL CHECK (
    length(resolution_ref) = 43 AND resolution_ref NOT GLOB '*[^A-Za-z0-9_-]*'
  ),
  kind TEXT NOT NULL CHECK (kind IN ('exec', 'plugin', 'system-agent')),
  status TEXT NOT NULL CHECK (status IN ('pending', 'allowed', 'denied', 'expired', 'cancelled')),
  presentation_json TEXT NOT NULL,
  requested_by_device_id TEXT,
  requested_by_client_id TEXT,
  requested_by_device_token_auth INTEGER NOT NULL DEFAULT 0,
  reviewer_device_ids_json TEXT NOT NULL,
  source_agent_id TEXT,
  source_session_key TEXT,
  source_session_id TEXT,
  source_run_id TEXT,
  source_tool_call_id TEXT,
  source_tool_name TEXT,
  audience_session_keys_json TEXT NOT NULL,
  runtime_epoch TEXT NOT NULL,
  created_at_ms INTEGER NOT NULL,
  expires_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  decision TEXT CHECK (decision IN ('allow-once', 'allow-always', 'deny')),
  terminal_reason TEXT CHECK (
    terminal_reason IN (
      'user',
      'timeout',
      'malformed-verdict',
      'no-route',
      'run-aborted',
      'gateway-restart',
      'storage-corrupt'
    )
  ),
  resolved_at_ms INTEGER,
  resolver_kind TEXT CHECK (resolver_kind IN ('device', 'channel', 'runtime', 'system')),
  resolver_id TEXT,
  consumed_at_ms INTEGER,
  consumed_by TEXT,
  CHECK (expires_at_ms >= created_at_ms),
  CHECK (updated_at_ms >= created_at_ms),
  CHECK (resolved_at_ms IS NULL OR resolved_at_ms >= created_at_ms),
  CHECK (resolved_at_ms IS NULL OR resolved_at_ms <= updated_at_ms),
  CHECK (consumed_at_ms IS NULL OR consumed_at_ms >= resolved_at_ms),
  CHECK (consumed_at_ms IS NULL OR consumed_at_ms <= updated_at_ms),
  CHECK (requested_by_device_token_auth IN (0, 1)),
  CHECK (
    (
      status = 'pending'
      AND decision IS NULL
      AND terminal_reason IS NULL
      AND resolved_at_ms IS NULL
      AND resolver_kind IS NULL
      AND resolver_id IS NULL
      AND consumed_at_ms IS NULL
      AND consumed_by IS NULL
    )
    OR (
      status = 'allowed'
      AND decision IN ('allow-once', 'allow-always')
      AND terminal_reason = 'user'
      AND resolved_at_ms IS NOT NULL
      AND resolver_kind IS NOT NULL
    )
    OR (
      status = 'denied'
      AND decision = 'deny'
      AND terminal_reason IN ('user', 'malformed-verdict', 'no-route', 'storage-corrupt')
      AND resolved_at_ms IS NOT NULL
      AND resolver_kind IS NOT NULL
      AND consumed_at_ms IS NULL
      AND consumed_by IS NULL
    )
    OR (
      status = 'expired'
      AND decision = 'deny'
      AND terminal_reason = 'timeout'
      AND resolved_at_ms IS NOT NULL
      AND resolver_kind IS NOT NULL
      AND consumed_at_ms IS NULL
      AND consumed_by IS NULL
    )
    OR (
      status = 'cancelled'
      AND decision = 'deny'
      AND terminal_reason IN ('run-aborted', 'gateway-restart')
      AND resolved_at_ms IS NOT NULL
      AND resolver_kind IS NOT NULL
      AND consumed_at_ms IS NULL
      AND consumed_by IS NULL
    )
  ),
  CHECK (
    (consumed_at_ms IS NULL AND consumed_by IS NULL)
    OR (
      status = 'allowed'
      AND decision = 'allow-once'
      AND consumed_at_ms IS NOT NULL
      AND consumed_by IS NOT NULL
    )
  )
) STRICT;

CREATE UNIQUE INDEX IF NOT EXISTS idx_operator_approvals_cursor_id
  ON operator_approvals(cursor_id);

CREATE INDEX IF NOT EXISTS idx_operator_approvals_status_expiry
  ON operator_approvals(status, expires_at_ms, approval_id);

CREATE UNIQUE INDEX IF NOT EXISTS idx_operator_approvals_resolution_ref
  ON operator_approvals(resolution_ref);

CREATE INDEX IF NOT EXISTS idx_operator_approvals_source_session_created
  ON operator_approvals(source_session_key, created_at_ms DESC, approval_id);

CREATE INDEX IF NOT EXISTS idx_operator_approvals_source_run_resolved
  ON operator_approvals(source_run_id, resolved_at_ms, approval_id)
  WHERE source_run_id IS NOT NULL AND resolved_at_ms IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_operator_approvals_resolved
  ON operator_approvals(resolved_at_ms, approval_id)
  WHERE resolved_at_ms IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_operator_approvals_runtime_pending
  ON operator_approvals(runtime_epoch, approval_id)
  WHERE status = 'pending';

CREATE TABLE IF NOT EXISTS operator_approval_execution_identities (
  approval_id TEXT NOT NULL PRIMARY KEY
    REFERENCES operator_approvals(approval_id) ON DELETE CASCADE,
  source_context_id TEXT NOT NULL CHECK (
    length(source_context_id) BETWEEN 1 AND 256 AND source_context_id = trim(source_context_id)
  ),
  source_execution_id TEXT NOT NULL CHECK (
    length(source_execution_id) BETWEEN 1 AND 256 AND source_execution_id = trim(source_execution_id)
  )
) STRICT;

CREATE TABLE IF NOT EXISTS operator_approval_standing_grants (
  grant_id TEXT NOT NULL PRIMARY KEY CHECK (length(grant_id) > 0),
  minted_by_approval_id TEXT NOT NULL
    REFERENCES operator_approvals(approval_id) ON DELETE CASCADE,
  agent_id TEXT NOT NULL CHECK (length(agent_id) > 0),
  cron_job_id TEXT NOT NULL CHECK (length(cron_job_id) > 0),
  job_config_revision TEXT NOT NULL CHECK (length(job_config_revision) > 0),
  operation_binding TEXT NOT NULL CHECK (length(operation_binding) > 0),
  created_at_ms INTEGER NOT NULL,
  expires_at_ms INTEGER CHECK (expires_at_ms IS NULL OR expires_at_ms >= created_at_ms),
  revoked_at_ms INTEGER,
  revoked_by TEXT,
  last_used_at_ms INTEGER,
  use_count INTEGER NOT NULL DEFAULT 0
) STRICT;

CREATE INDEX IF NOT EXISTS idx_operator_approval_standing_grants_binding
  ON operator_approval_standing_grants(agent_id, cron_job_id, operation_binding, created_at_ms DESC);

CREATE TABLE IF NOT EXISTS operator_approval_standing_grant_generations (
  grant_id TEXT NOT NULL PRIMARY KEY
    REFERENCES operator_approval_standing_grants(grant_id) ON DELETE CASCADE,
  job_definition_generation INTEGER NOT NULL CHECK (job_definition_generation >= 1)
) STRICT;

CREATE TABLE IF NOT EXISTS schema_meta (
  meta_key TEXT NOT NULL PRIMARY KEY,
  role TEXT NOT NULL,
  schema_version INTEGER NOT NULL,
  agent_id TEXT,
  app_version TEXT,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS config_machine_state (
  state_key TEXT NOT NULL PRIMARY KEY,
  value_json TEXT NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS device_pairing_pending (
  request_id TEXT NOT NULL PRIMARY KEY,
  device_id TEXT NOT NULL,
  public_key TEXT NOT NULL,
  display_name TEXT,
  platform TEXT,
  device_family TEXT,
  client_id TEXT,
  client_mode TEXT,
  browser_origin TEXT,
  role TEXT,
  roles_json TEXT,
  scopes_json TEXT,
  remote_ip TEXT,
  silent INTEGER,
  is_repair INTEGER,
  ts INTEGER NOT NULL,
  refreshed_at_ms INTEGER
) STRICT;

CREATE INDEX IF NOT EXISTS idx_device_pairing_pending_device
  ON device_pairing_pending(device_id, ts DESC);

CREATE TABLE IF NOT EXISTS device_pairing_paired (
  device_id TEXT NOT NULL PRIMARY KEY,
  public_key TEXT NOT NULL,
  display_name TEXT,
  operator_label TEXT,
  platform TEXT,
  device_family TEXT,
  client_id TEXT,
  client_mode TEXT,
  browser_origin TEXT,
  role TEXT,
  roles_json TEXT,
  scopes_json TEXT,
  approved_scopes_json TEXT,
  remote_ip TEXT,
  tokens_json TEXT,
  approved_via TEXT,
  node_surface_json TEXT,
  pending_node_surface_json TEXT,
  created_at_ms INTEGER NOT NULL,
  approved_at_ms INTEGER NOT NULL,
  last_seen_at_ms INTEGER,
  last_seen_reason TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_device_pairing_paired_approved
  ON device_pairing_paired(approved_at_ms DESC, device_id);

CREATE TABLE IF NOT EXISTS device_bootstrap_tokens (
  token_key TEXT NOT NULL PRIMARY KEY,
  token TEXT NOT NULL,
  setup_id TEXT,
  ts INTEGER NOT NULL,
  device_id TEXT,
  public_key TEXT,
  profile_json TEXT,
  redeemed_profile_json TEXT,
  pending_profile_json TEXT,
  issued_at_ms INTEGER NOT NULL,
  last_used_at_ms INTEGER
) STRICT;

CREATE INDEX IF NOT EXISTS idx_device_bootstrap_tokens_ts
  ON device_bootstrap_tokens(ts);

-- Terminal outcome of a redeemed setup credential. The bootstrap row is deleted
-- on redemption, so this is the only durable proof a setup code succeeded; the
-- presenting client reconciles it when the completion broadcast is missed.
-- Non-secret only: never the bootstrap token or anything derived from it.
-- Bounded by retention to a handful of live rows, so the primary key is the
-- only access path worth having.
CREATE TABLE IF NOT EXISTS device_pair_setup_completions (
  setup_id TEXT NOT NULL PRIMARY KEY,
  device_id TEXT NOT NULL,
  device_name TEXT,
  access TEXT NOT NULL,
  completed_at_ms INTEGER NOT NULL,
  delivery_state TEXT NOT NULL CHECK (delivery_state IN ('uncertain', 'confirmed')),
  retain_until_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS device_pairing_join_codes (
  shortcode TEXT,
  payload_json TEXT,
  created_at_ms INTEGER,
  expires_at_ms INTEGER
) STRICT;

CREATE TABLE IF NOT EXISTS device_pairing_browser_requests (
  request_id TEXT NOT NULL PRIMARY KEY,
  code TEXT NOT NULL UNIQUE,
  device_id TEXT NOT NULL UNIQUE,
  public_key TEXT NOT NULL,
  remote_ip TEXT,
  user_agent TEXT,
  origin TEXT,
  status TEXT NOT NULL CHECK (status IN ('pending', 'approved', 'rejected')),
  approved_token_sha256 TEXT,
  created_at_ms INTEGER NOT NULL,
  expires_at_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS macos_port_guardian_records (
  pid INTEGER NOT NULL PRIMARY KEY,
  port INTEGER NOT NULL,
  command TEXT NOT NULL,
  mode TEXT NOT NULL,
  timestamp REAL NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_macos_port_guardian_records_port
  ON macos_port_guardian_records(port, timestamp DESC);

CREATE TABLE IF NOT EXISTS workspace_setup_state (
  workspace_key TEXT NOT NULL PRIMARY KEY,
  -- NULL only for attestation-only rows whose legacy source never recorded a
  -- path (orphan hashed-key attestations); setup rows always carry one.
  workspace_path TEXT,
  -- NULL setup columns mean an attestation-only row: replaceWorkspaceAttestation
  -- may record hashes before any setup milestone exists for the workspace.
  version INTEGER,
  bootstrap_seeded_at TEXT,
  setup_completed_at TEXT,
  updated_at INTEGER,
  attested_at_ms INTEGER,
  attestation_updated_at_ms INTEGER,
  bootstrap_deferred INTEGER,
  CHECK (version IS NULL OR workspace_path IS NOT NULL)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_workspace_setup_state_path
  ON workspace_setup_state(workspace_path);

CREATE TABLE IF NOT EXISTS workspace_path_aliases (
  alias_key TEXT NOT NULL PRIMARY KEY,
  alias_path TEXT NOT NULL,
  workspace_key TEXT NOT NULL,
  workspace_path TEXT NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_workspace_path_aliases_workspace
  ON workspace_path_aliases(workspace_key);



CREATE TABLE IF NOT EXISTS workspace_generated_bootstrap_hashes (
  workspace_key TEXT NOT NULL,
  filename TEXT NOT NULL,
  sha256 TEXT NOT NULL,
  PRIMARY KEY (workspace_key, filename),
  FOREIGN KEY (workspace_key) REFERENCES workspace_setup_state(workspace_key) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS native_hook_relay_bridges (
  relay_id TEXT NOT NULL PRIMARY KEY,
  pid INTEGER NOT NULL,
  hostname TEXT NOT NULL,
  port INTEGER NOT NULL,
  token TEXT NOT NULL,
  expires_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_native_hook_relay_bridges_expires
  ON native_hook_relay_bridges(expires_at_ms, relay_id);

CREATE TABLE IF NOT EXISTS managed_outgoing_image_records (
  attachment_id TEXT NOT NULL PRIMARY KEY,
  session_key TEXT NOT NULL,
  agent_id TEXT,
  message_id TEXT,
  created_at TEXT NOT NULL,
  updated_at TEXT,
  retention_class TEXT,
  alt TEXT NOT NULL,
  original_media_root TEXT NOT NULL,
  original_media_id TEXT NOT NULL,
  original_media_subdir TEXT NOT NULL,
  original_content_type TEXT NOT NULL,
  original_width INTEGER,
  original_height INTEGER,
  original_size_bytes INTEGER,
  original_filename TEXT,
  record_json TEXT NOT NULL,
  cleanup_pending INTEGER NOT NULL DEFAULT 0 CHECK (cleanup_pending IN (0, 1))
) STRICT;

CREATE INDEX IF NOT EXISTS idx_managed_outgoing_images_session
  ON managed_outgoing_image_records(session_key, created_at DESC, attachment_id);

CREATE INDEX IF NOT EXISTS idx_managed_outgoing_images_message
  ON managed_outgoing_image_records(session_key, message_id, attachment_id)
  WHERE message_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_managed_outgoing_images_agent_session
  ON managed_outgoing_image_records(session_key, agent_id, created_at DESC, attachment_id);

CREATE INDEX IF NOT EXISTS idx_managed_outgoing_images_agent_message
  ON managed_outgoing_image_records(session_key, agent_id, message_id, attachment_id)
  WHERE message_id IS NOT NULL;

CREATE TABLE IF NOT EXISTS channel_pairing_requests (
  channel_key TEXT NOT NULL,
  account_id TEXT NOT NULL,
  request_id TEXT NOT NULL,
  code TEXT NOT NULL,
  created_at TEXT NOT NULL,
  last_seen_at TEXT NOT NULL,
  meta_json TEXT,
  PRIMARY KEY (channel_key, account_id, request_id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_channel_pairing_requests_code
  ON channel_pairing_requests(channel_key, code);

CREATE INDEX IF NOT EXISTS idx_channel_pairing_requests_created
  ON channel_pairing_requests(channel_key, created_at, request_id);

CREATE TABLE IF NOT EXISTS channel_pairing_allow_entries (
  channel_key TEXT NOT NULL,
  account_id TEXT NOT NULL,
  entry TEXT NOT NULL,
  sort_order INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (channel_key, account_id, entry)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_channel_pairing_allow_account
  ON channel_pairing_allow_entries(channel_key, account_id, sort_order, entry);

CREATE TABLE IF NOT EXISTS web_push_subscriptions (
  endpoint_hash TEXT NOT NULL PRIMARY KEY,
  subscription_id TEXT NOT NULL UNIQUE,
  endpoint TEXT NOT NULL,
  p256dh TEXT NOT NULL,
  auth TEXT NOT NULL,
  device_id TEXT,
  user_profile_id TEXT,
  preferences_json TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_web_push_subscriptions_updated
  ON web_push_subscriptions(updated_at_ms DESC, subscription_id);

CREATE TABLE IF NOT EXISTS web_push_approval_deliveries (
  approval_id TEXT NOT NULL
    REFERENCES operator_approvals(approval_id) ON DELETE CASCADE,
  subscription_id TEXT NOT NULL
    REFERENCES web_push_subscriptions(subscription_id) ON DELETE CASCADE,
  device_id TEXT NOT NULL,
  user_profile_id TEXT,
  prepared_at_ms INTEGER NOT NULL,
  PRIMARY KEY (approval_id, subscription_id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_web_push_approval_deliveries_subscription
  ON web_push_approval_deliveries(subscription_id, approval_id);

CREATE TABLE IF NOT EXISTS apns_registrations (
  node_id TEXT NOT NULL PRIMARY KEY,
  transport TEXT NOT NULL,
  token TEXT,
  relay_handle TEXT,
  send_grant TEXT,
  installation_id TEXT,
  relay_origin TEXT,
  topic TEXT NOT NULL,
  environment TEXT NOT NULL,
  distribution TEXT,
  token_debug_suffix TEXT,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_apns_registrations_updated
  ON apns_registrations(updated_at_ms DESC, node_id);

CREATE TABLE IF NOT EXISTS apns_registration_tombstones (
  node_id TEXT NOT NULL PRIMARY KEY,
  deleted_at_ms INTEGER NOT NULL
) STRICT;

-- Node-host-owned launch journal. The descriptor and its credential remain
-- process memory only; this table records bounded supervision facts.
CREATE TABLE IF NOT EXISTS node_worker_launches (
  launch_id TEXT NOT NULL PRIMARY KEY
    CHECK (length(launch_id) BETWEEN 1 AND 256 AND instr(launch_id, char(0)) = 0),
  plan_hash TEXT NOT NULL
    CHECK (length(plan_hash) = 64 AND plan_hash NOT GLOB '*[^0-9a-f]*'),
  gateway_namespace TEXT NOT NULL
    CHECK (
      length(gateway_namespace) BETWEEN 1 AND 128
      AND gateway_namespace NOT GLOB '*[^A-Za-z0-9._-]*'
      AND gateway_namespace GLOB '[A-Za-z0-9]*'
    ),
  environment_id TEXT NOT NULL
    CHECK (length(environment_id) BETWEEN 1 AND 256 AND instr(environment_id, char(0)) = 0),
  session_id TEXT NOT NULL
    CHECK (length(session_id) BETWEEN 1 AND 256 AND instr(session_id, char(0)) = 0),
  owner_epoch INTEGER NOT NULL CHECK (owner_epoch BETWEEN 1 AND 9007199254740991),
  placement_generation INTEGER NOT NULL
    CHECK (placement_generation BETWEEN 0 AND 9007199254740991),
  run_id TEXT NOT NULL
    CHECK (length(run_id) BETWEEN 1 AND 256 AND instr(run_id, char(0)) = 0),
  state TEXT NOT NULL
    CHECK (state IN ('pending', 'running', 'completed', 'failed', 'interrupted', 'cancelled')),
  supervisor_pid INTEGER NOT NULL CHECK (supervisor_pid BETWEEN 1 AND 2147483647),
  supervisor_start_time INTEGER NOT NULL
    CHECK (supervisor_start_time BETWEEN 0 AND 9007199254740991),
  worker_pid INTEGER CHECK (worker_pid IS NULL OR worker_pid BETWEEN 1 AND 2147483647),
  worker_start_time INTEGER CHECK (
    worker_start_time IS NULL OR worker_start_time BETWEEN 0 AND 9007199254740991
  ),
  result_json TEXT CHECK (
    result_json IS NULL
    OR (
      length(CAST(result_json AS BLOB)) BETWEEN 1 AND 65536
      AND instr(result_json, char(0)) = 0
      AND json_valid(result_json)
    )
  ),
  error_text TEXT CHECK (
    error_text IS NULL
    OR (
      length(CAST(error_text AS BLOB)) BETWEEN 1 AND 4096
      AND instr(error_text, char(0)) = 0
      AND instr(error_text, char(10)) = 0
      AND instr(error_text, char(13)) = 0
    )
  ),
  completed_at_ms INTEGER CHECK (
    completed_at_ms IS NULL OR completed_at_ms BETWEEN 0 AND 9007199254740991
  ),
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms BETWEEN 0 AND 9007199254740991),
  updated_at_ms INTEGER NOT NULL CHECK (
    updated_at_ms BETWEEN created_at_ms AND 9007199254740991
  ),
  CHECK ((worker_pid IS NULL) = (worker_start_time IS NULL)),
  CHECK (
    (state = 'pending'
      AND worker_pid IS NULL AND result_json IS NULL AND error_text IS NULL
      AND completed_at_ms IS NULL)
    OR
    (state = 'running'
      AND worker_pid IS NOT NULL AND result_json IS NULL AND error_text IS NULL
      AND completed_at_ms IS NULL)
    OR
    (state = 'completed'
      AND result_json IS NOT NULL AND error_text IS NULL
      AND completed_at_ms BETWEEN created_at_ms AND updated_at_ms)
    OR
    (state IN ('failed', 'interrupted', 'cancelled')
      AND result_json IS NULL AND error_text IS NOT NULL
      AND completed_at_ms BETWEEN created_at_ms AND updated_at_ms)
  )
) STRICT;

CREATE INDEX IF NOT EXISTS idx_node_worker_launches_terminal_completed
  ON node_worker_launches(completed_at_ms, launch_id)
  WHERE completed_at_ms IS NOT NULL;

CREATE TABLE IF NOT EXISTS node_worker_launch_boots (
  launch_id TEXT NOT NULL PRIMARY KEY
    REFERENCES node_worker_launches(launch_id) ON DELETE CASCADE,
  boot_id TEXT CHECK (boot_id IS NULL OR length(boot_id) BETWEEN 1 AND 128)
) STRICT;

CREATE TABLE IF NOT EXISTS node_worker_launch_containers (
  launch_id TEXT PRIMARY KEY,
  container_json TEXT
) STRICT;

CREATE TABLE IF NOT EXISTS node_worker_launch_cleanup (
  launch_id TEXT NOT NULL PRIMARY KEY
    REFERENCES node_worker_launches(launch_id) ON DELETE CASCADE,
  cleanup_mode TEXT NOT NULL CHECK (cleanup_mode IN ('process-group', 'owned-anchor')),
  lineage_settled INTEGER CHECK (lineage_settled IS NULL OR lineage_settled = 1)
) STRICT;

-- Older readers retain owned-anchor custody: lineage EOF is not this certificate.
CREATE TABLE IF NOT EXISTS node_worker_launch_process_scopes (
  launch_id TEXT NOT NULL PRIMARY KEY
    REFERENCES node_worker_launches(launch_id) ON DELETE CASCADE,
  scope_kind TEXT NOT NULL CHECK (scope_kind = 'linux-subreaper'),
  descendants_reaped INTEGER CHECK (descendants_reaped IS NULL OR descendants_reaped = 1)
) STRICT;

-- Turn receipts have a shorter lifetime than their physical worker owner.
-- Keeping the launch running preserves capacity and predecessor cleanup semantics.
CREATE TABLE IF NOT EXISTS node_worker_turns (
  turn_id TEXT NOT NULL PRIMARY KEY
    CHECK (length(turn_id) BETWEEN 1 AND 256 AND instr(turn_id, char(0)) = 0),
  owner_launch_id TEXT NOT NULL
    REFERENCES node_worker_launches(launch_id) ON DELETE CASCADE,
  plan_hash TEXT NOT NULL
    CHECK (length(plan_hash) = 64 AND plan_hash NOT GLOB '*[^0-9a-f]*'),
  run_id TEXT NOT NULL
    CHECK (length(run_id) BETWEEN 1 AND 256 AND instr(run_id, char(0)) = 0),
  state TEXT NOT NULL
    CHECK (state IN ('running', 'completed', 'failed', 'interrupted', 'cancelled')),
  result_json TEXT CHECK (
    result_json IS NULL
    OR (
      length(CAST(result_json AS BLOB)) BETWEEN 1 AND 65536
      AND instr(result_json, char(0)) = 0
      AND json_valid(result_json)
    )
  ),
  error_text TEXT CHECK (
    error_text IS NULL
    OR (
      length(CAST(error_text AS BLOB)) BETWEEN 1 AND 4096
      AND instr(error_text, char(0)) = 0
      AND instr(error_text, char(10)) = 0
      AND instr(error_text, char(13)) = 0
    )
  ),
  completed_at_ms INTEGER CHECK (
    completed_at_ms IS NULL OR completed_at_ms BETWEEN 0 AND 9007199254740991
  ),
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms BETWEEN 0 AND 9007199254740991),
  updated_at_ms INTEGER NOT NULL CHECK (
    updated_at_ms BETWEEN created_at_ms AND 9007199254740991
  ),
  CHECK (
    (state = 'running'
      AND result_json IS NULL AND error_text IS NULL AND completed_at_ms IS NULL)
    OR
    (state = 'completed'
      AND result_json IS NOT NULL AND error_text IS NULL
      AND completed_at_ms BETWEEN created_at_ms AND updated_at_ms)
    OR
    (state IN ('failed', 'interrupted', 'cancelled')
      AND result_json IS NULL AND error_text IS NOT NULL
      AND completed_at_ms BETWEEN created_at_ms AND updated_at_ms)
  )
) STRICT;

CREATE INDEX IF NOT EXISTS idx_node_worker_turns_terminal_completed
  ON node_worker_turns(completed_at_ms, turn_id)
  WHERE completed_at_ms IS NOT NULL;

CREATE UNIQUE INDEX IF NOT EXISTS idx_node_worker_turns_active_owner
  ON node_worker_turns(owner_launch_id)
  WHERE state = 'running';

CREATE TABLE IF NOT EXISTS config_health_entries (
  config_path TEXT NOT NULL PRIMARY KEY,
  last_known_good_json TEXT,
  last_promoted_good_json TEXT,
  last_observed_suspicious_signature TEXT,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS clawhub_promotion_claims (
  slug TEXT NOT NULL PRIMARY KEY,
  provider TEXT,
  model_keys_json TEXT NOT NULL,
  ends_at_ms INTEGER NOT NULL,
  claimed_at_ms INTEGER NOT NULL
) STRICT;



CREATE TABLE IF NOT EXISTS official_external_plugin_catalog_snapshots (
  feed_url TEXT NOT NULL PRIMARY KEY,
  body TEXT NOT NULL,
  status INTEGER NOT NULL,
  etag TEXT,
  last_modified TEXT,
  checksum TEXT NOT NULL,
  saved_at TEXT NOT NULL,
  trust_mode TEXT,
  trust_key_id TEXT,
  trust_signature_count INTEGER,
  trust_threshold INTEGER,
  trust_verified_at TEXT,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_official_external_plugin_catalog_snapshots_updated
  ON official_external_plugin_catalog_snapshots(updated_at_ms DESC, feed_url);

CREATE TABLE IF NOT EXISTS update_runs (
  run_id TEXT PRIMARY KEY NOT NULL,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  trigger TEXT NOT NULL CHECK (trigger IN ('chat', 'control-ui', 'cli', 'campaign', 'mac-app', 'api')),
  phase TEXT NOT NULL CHECK (phase IN ('requested', 'staging', 'validating', 'repairing', 'activating', 'restarting', 'verifying', 'finished')),
  status TEXT NOT NULL CHECK (status IN ('running', 'succeeded', 'failed', 'rolled-back', 'skipped')),
  reason TEXT,
  origin_json TEXT NOT NULL CHECK (length(CAST(origin_json AS BLOB)) <= 16384),
  target_json TEXT NOT NULL CHECK (length(CAST(target_json AS BLOB)) <= 16384),
  before_json TEXT NOT NULL CHECK (length(CAST(before_json AS BLOB)) <= 16384),
  after_json TEXT NOT NULL CHECK (length(CAST(after_json AS BLOB)) <= 16384),
  steps_json TEXT NOT NULL CHECK (length(CAST(steps_json AS BLOB)) <= 16384),
  verification_json TEXT NOT NULL CHECK (length(CAST(verification_json AS BLOB)) <= 16384),
  repair_json TEXT NOT NULL CHECK (length(CAST(repair_json AS BLOB)) <= 16384),
  confirmed_at_ms INTEGER,
  finished_at_ms INTEGER,
  downtime_ms INTEGER,
  CHECK ((status = 'running' AND phase != 'finished' AND finished_at_ms IS NULL) OR
    (status != 'running' AND phase = 'finished' AND finished_at_ms IS NOT NULL))
) STRICT;

CREATE INDEX IF NOT EXISTS idx_update_runs_created
  ON update_runs(created_at_ms DESC, run_id);
CREATE INDEX IF NOT EXISTS idx_update_runs_active
  ON update_runs(status, created_at_ms DESC, run_id);

CREATE TABLE IF NOT EXISTS gateway_restart_sentinel (
  sentinel_key TEXT NOT NULL PRIMARY KEY,
  version INTEGER NOT NULL,
  kind TEXT NOT NULL,
  status TEXT NOT NULL,
  ts INTEGER NOT NULL,
  session_key TEXT,
  thread_id TEXT,
  delivery_channel TEXT,
  delivery_to TEXT,
  delivery_account_id TEXT,
  message TEXT,
  continuation_json TEXT,
  doctor_hint TEXT,
  stats_json TEXT,
  payload_json TEXT NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_gateway_restart_sentinel_ts
  ON gateway_restart_sentinel(ts DESC, sentinel_key);

CREATE TABLE IF NOT EXISTS gateway_restart_intent (
  intent_key TEXT NOT NULL PRIMARY KEY,
  kind TEXT NOT NULL,
  pid INTEGER NOT NULL,
  created_at INTEGER NOT NULL,
  reason TEXT,
  force INTEGER,
  wait_ms INTEGER,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS gateway_restart_handoff (
  handoff_key TEXT NOT NULL PRIMARY KEY,
  kind TEXT NOT NULL,
  version INTEGER NOT NULL,
  intent_id TEXT NOT NULL,
  pid INTEGER NOT NULL,
  process_instance_id TEXT,
  created_at INTEGER NOT NULL,
  expires_at INTEGER NOT NULL,
  reason TEXT,
  restart_trace_started_at INTEGER,
  restart_trace_last_at INTEGER,
  source TEXT NOT NULL,
  restart_kind TEXT NOT NULL,
  supervisor_mode TEXT NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_gateway_restart_handoff_expiry
  ON gateway_restart_handoff(expires_at, pid);

CREATE TABLE IF NOT EXISTS gateway_boot_lifecycle (
  boot_id TEXT NOT NULL PRIMARY KEY,
  pid INTEGER NOT NULL,
  started_at_ms INTEGER NOT NULL,
  completed_at_ms INTEGER,
  outcome TEXT,
  startup_reason TEXT,
  reason TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_gateway_boot_lifecycle_started
  ON gateway_boot_lifecycle(started_at_ms);

CREATE TABLE IF NOT EXISTS acp_sessions (
  session_key TEXT NOT NULL PRIMARY KEY,
  session_id TEXT,
  backend TEXT NOT NULL,
  agent TEXT NOT NULL,
  runtime_session_name TEXT NOT NULL,
  identity_json TEXT,
  resume_agent_session_id TEXT,
  resume_acpx_session_id TEXT,
  mode TEXT NOT NULL,
  runtime_options_json TEXT,
  cwd TEXT,
  state TEXT NOT NULL,
  last_activity_at INTEGER NOT NULL,
  last_error TEXT,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_acp_sessions_state_activity
  ON acp_sessions(state, last_activity_at DESC, session_key);

CREATE INDEX IF NOT EXISTS idx_acp_sessions_agent_activity
  ON acp_sessions(agent, last_activity_at DESC, session_key);

CREATE INDEX IF NOT EXISTS idx_acp_sessions_resume_agent
  ON acp_sessions(resume_agent_session_id);

CREATE INDEX IF NOT EXISTS idx_acp_sessions_resume_acpx
  ON acp_sessions(resume_acpx_session_id);

CREATE TABLE IF NOT EXISTS acp_replay_sessions (
  session_id TEXT NOT NULL PRIMARY KEY,
  session_key TEXT NOT NULL,
  cwd TEXT NOT NULL,
  complete INTEGER NOT NULL,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  next_seq INTEGER NOT NULL,
  -- Running estimate of this session's ledger footprint (row overhead plus
  -- all event rows), maintained at insert/trim so budget checks never scan
  -- acp_replay_events (#100622).
  estimated_bytes INTEGER NOT NULL DEFAULT 0
) STRICT;

CREATE INDEX IF NOT EXISTS idx_acp_replay_sessions_key_updated
  ON acp_replay_sessions(session_key, complete, updated_at DESC, session_id);

CREATE INDEX IF NOT EXISTS idx_acp_replay_sessions_updated
  ON acp_replay_sessions(updated_at DESC, session_id);

CREATE TABLE IF NOT EXISTS acp_replay_events (
  session_id TEXT NOT NULL,
  seq INTEGER NOT NULL,
  at INTEGER NOT NULL,
  session_key TEXT NOT NULL,
  run_id TEXT,
  update_json TEXT NOT NULL,
  estimated_bytes INTEGER NOT NULL DEFAULT 0,
  PRIMARY KEY (session_id, seq),
  FOREIGN KEY (session_id) REFERENCES acp_replay_sessions(session_id) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS agent_databases (
  agent_id TEXT NOT NULL,
  path TEXT NOT NULL,
  schema_version INTEGER NOT NULL,
  last_seen_at INTEGER NOT NULL,
  size_bytes INTEGER,
  PRIMARY KEY (agent_id, path)
) STRICT;

CREATE TABLE IF NOT EXISTS agent_deletion_journal (
  agent_id TEXT PRIMARY KEY,
  operation_id TEXT NOT NULL DEFAULT '',
  phase TEXT,
  agent_dir TEXT NOT NULL,
  workspace_dir TEXT NOT NULL,
  sessions_dir TEXT NOT NULL,
  database_paths_json TEXT NOT NULL DEFAULT '[]',
  cleanup_paths_json TEXT NOT NULL DEFAULT '[]',
  created_at INTEGER NOT NULL,
  cleanup_completed INTEGER NOT NULL DEFAULT 0,
  delete_files INTEGER NOT NULL DEFAULT 1
) STRICT;

CREATE TABLE IF NOT EXISTS agent_provenance (
  agent_id TEXT PRIMARY KEY,
  created_via TEXT NOT NULL CHECK (created_via IN ('operator', 'agent', 'template')),
  creator_agent_id TEXT,
  created_at_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS agent_database_leases (
  lease_id TEXT PRIMARY KEY,
  agent_id TEXT NOT NULL,
  path TEXT NOT NULL,
  owner_pid INTEGER NOT NULL,
  owner_start_time INTEGER,
  opened_at INTEGER NOT NULL,
  provenance TEXT
) STRICT;

CREATE TABLE IF NOT EXISTS plugin_state_entries (
  plugin_id TEXT NOT NULL,
  namespace TEXT NOT NULL,
  entry_key TEXT NOT NULL,
  value_json TEXT NOT NULL,
  created_at INTEGER NOT NULL,
  expires_at INTEGER,
  PRIMARY KEY (plugin_id, namespace, entry_key)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_plugin_state_expiry
  ON plugin_state_entries(expires_at)
  WHERE expires_at IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_plugin_state_listing
  ON plugin_state_entries(plugin_id, namespace, created_at, entry_key, expires_at);

CREATE TABLE IF NOT EXISTS channel_ingress_events (
  queue_name TEXT NOT NULL,
  event_id TEXT NOT NULL,
  channel_id TEXT NOT NULL,
  account_id TEXT NOT NULL,
  status TEXT NOT NULL,
  lane_key TEXT,
  payload_json TEXT NOT NULL,
  metadata_json TEXT,
  received_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  claim_token TEXT,
  claim_owner TEXT,
  claimed_at INTEGER,
  attempts INTEGER NOT NULL DEFAULT 0,
  last_attempt_at INTEGER,
  last_error TEXT,
  failed_reason TEXT,
  failed_at INTEGER,
  completed_at INTEGER,
  completed_metadata_json TEXT,
  PRIMARY KEY (queue_name, event_id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_channel_ingress_pending
  ON channel_ingress_events(queue_name, status, received_at, event_id);

CREATE INDEX IF NOT EXISTS idx_channel_ingress_claims
  ON channel_ingress_events(queue_name, status, claimed_at);

CREATE INDEX IF NOT EXISTS idx_channel_ingress_lane
  ON channel_ingress_events(queue_name, status, lane_key);

CREATE TABLE IF NOT EXISTS plugin_blob_entries (
  plugin_id TEXT NOT NULL,
  namespace TEXT NOT NULL,
  entry_key TEXT NOT NULL,
  metadata_json TEXT NOT NULL,
  blob BLOB NOT NULL,
  created_at INTEGER NOT NULL,
  expires_at INTEGER,
  PRIMARY KEY (plugin_id, namespace, entry_key)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_plugin_blob_expiry
  ON plugin_blob_entries(expires_at)
  WHERE expires_at IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_plugin_blob_listing
  ON plugin_blob_entries(plugin_id, namespace, created_at, entry_key);

CREATE TABLE IF NOT EXISTS skill_uploads (
  upload_id TEXT NOT NULL PRIMARY KEY,
  kind TEXT NOT NULL,
  slug TEXT NOT NULL,
  force INTEGER NOT NULL,
  size_bytes INTEGER NOT NULL,
  sha256 TEXT,
  actual_sha256 TEXT,
  received_bytes INTEGER NOT NULL,
  archive_blob BLOB NOT NULL,
  created_at INTEGER NOT NULL,
  expires_at INTEGER NOT NULL,
  committed INTEGER NOT NULL,
  committed_at INTEGER,
  idempotency_key_hash TEXT UNIQUE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_skill_uploads_expiry
  ON skill_uploads(expires_at);

CREATE INDEX IF NOT EXISTS idx_skill_uploads_idempotency
  ON skill_uploads(idempotency_key_hash)
  WHERE idempotency_key_hash IS NOT NULL;

CREATE TABLE IF NOT EXISTS skill_upload_chunks (
  upload_id TEXT NOT NULL,
  byte_offset INTEGER NOT NULL CHECK (byte_offset >= 0),
  size_bytes INTEGER NOT NULL CHECK (size_bytes > 0),
  chunk_blob BLOB NOT NULL,
  PRIMARY KEY (upload_id, byte_offset),
  FOREIGN KEY (upload_id) REFERENCES skill_uploads(upload_id) ON DELETE CASCADE,
  CHECK (length(chunk_blob) = size_bytes)
) STRICT;

CREATE TABLE IF NOT EXISTS capture_sessions (
  id TEXT NOT NULL PRIMARY KEY,
  started_at INTEGER NOT NULL,
  ended_at INTEGER,
  mode TEXT NOT NULL,
  source_scope TEXT NOT NULL,
  source_process TEXT NOT NULL,
  proxy_url TEXT
) STRICT;

CREATE TABLE IF NOT EXISTS capture_blobs (
  blob_id TEXT NOT NULL PRIMARY KEY,
  content_type TEXT,
  encoding TEXT NOT NULL,
  size_bytes INTEGER NOT NULL,
  sha256 TEXT NOT NULL,
  data BLOB NOT NULL,
  created_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS capture_events (
  id INTEGER NOT NULL PRIMARY KEY,
  session_id TEXT NOT NULL,
  ts INTEGER NOT NULL,
  source_scope TEXT NOT NULL,
  source_process TEXT NOT NULL,
  protocol TEXT NOT NULL,
  direction TEXT NOT NULL,
  kind TEXT NOT NULL,
  flow_id TEXT NOT NULL,
  method TEXT,
  host TEXT,
  path TEXT,
  status INTEGER,
  close_code INTEGER,
  content_type TEXT,
  headers_json TEXT,
  data_text TEXT,
  data_blob_id TEXT,
  data_sha256 TEXT,
  error_text TEXT,
  meta_json TEXT,
  FOREIGN KEY (session_id) REFERENCES capture_sessions(id) ON DELETE CASCADE,
  FOREIGN KEY (data_blob_id) REFERENCES capture_blobs(blob_id) ON DELETE SET NULL
) STRICT;

CREATE INDEX IF NOT EXISTS capture_events_session_ts_idx
  ON capture_events(session_id, ts);

CREATE INDEX IF NOT EXISTS capture_events_flow_idx
  ON capture_events(flow_id, ts);

CREATE TABLE IF NOT EXISTS sandbox_registry_entries (
  registry_kind TEXT NOT NULL,
  container_name TEXT NOT NULL,
  session_key TEXT,
  backend_id TEXT,
  runtime_label TEXT,
  image TEXT,
  created_at_ms INTEGER,
  last_used_at_ms INTEGER,
  config_label_kind TEXT,
  config_hash TEXT,
  cdp_port INTEGER,
  no_vnc_port INTEGER,
  entry_json TEXT NOT NULL,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (registry_kind, container_name)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_sandbox_registry_updated
  ON sandbox_registry_entries(registry_kind, updated_at DESC, container_name);

CREATE INDEX IF NOT EXISTS idx_sandbox_registry_session
  ON sandbox_registry_entries(registry_kind, session_key, last_used_at_ms DESC, container_name)
  WHERE session_key IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_sandbox_registry_last_used
  ON sandbox_registry_entries(registry_kind, last_used_at_ms DESC, container_name)
  WHERE last_used_at_ms IS NOT NULL;

CREATE TABLE IF NOT EXISTS durable_background_processes (
  id TEXT NOT NULL PRIMARY KEY,
  record_json TEXT NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS sandbox_persistent_execs (
  owner_key TEXT NOT NULL PRIMARY KEY,
  source_identity TEXT NOT NULL,
  attempt_id TEXT NOT NULL UNIQUE,
  owner_json TEXT NOT NULL,
  backend_id TEXT NOT NULL CHECK (backend_id = 'docker'),
  backend_target_json TEXT NOT NULL,
  workspace_binding_json TEXT NOT NULL,
  container_id TEXT NOT NULL,
  container_name TEXT NOT NULL,
  container_started_at TEXT NOT NULL,
  revision INTEGER NOT NULL CHECK (revision > 0),
  phase TEXT NOT NULL CHECK (phase IN ('reserved', 'prepared', 'running', 'stopping', 'uncertain', 'stopped')),
  receipt_json TEXT,
  error TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  CHECK (phase NOT IN ('prepared', 'running') OR receipt_json IS NOT NULL)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_sandbox_persistent_execs_container
  ON sandbox_persistent_execs(container_id, owner_key);

CREATE INDEX IF NOT EXISTS idx_sandbox_persistent_execs_container_name
  ON sandbox_persistent_execs(container_name, owner_key);

CREATE INDEX IF NOT EXISTS idx_sandbox_persistent_execs_source
  ON sandbox_persistent_execs(source_identity, owner_key);

CREATE TABLE IF NOT EXISTS cron_jobs (
  store_key TEXT NOT NULL,
  job_id TEXT NOT NULL,
  declaration_key TEXT,
  owner_agent_id TEXT,
  name TEXT NOT NULL,
  description TEXT,
  enabled INTEGER NOT NULL,
  agent_id TEXT,
  payload_kind TEXT NOT NULL,
  job_json TEXT NOT NULL,
  grant_definition_revision TEXT,
  grant_definition_generation INTEGER,
  grant_definition_updated_at INTEGER,
  state_json TEXT NOT NULL DEFAULT '{}',
  runtime_updated_at_ms INTEGER,
  schedule_identity TEXT,
  sort_order INTEGER NOT NULL DEFAULT 0,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (store_key, job_id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_cron_jobs_store_order
  ON cron_jobs(store_key, sort_order ASC, updated_at ASC, job_id);

-- One owner-native receipt is also the durable execution fence. Receipts
-- survive job deletion so operators can distinguish a run from log inference.
CREATE TABLE IF NOT EXISTS cron_run_receipts (
  cursor_id INTEGER NOT NULL,
  receipt_id TEXT PRIMARY KEY,
  store_key TEXT NOT NULL,
  job_id TEXT NOT NULL,
  config_revision TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  request_run_id TEXT,
  delivery_attempt_state TEXT NOT NULL DEFAULT 'unknown' CHECK (delivery_attempt_state IN ('unknown', 'not-started', 'started')),
  status TEXT NOT NULL,
  owner_pid INTEGER NOT NULL,
  owner_start_time INTEGER,
  started_at_ms INTEGER NOT NULL,
  finished_at_ms INTEGER,
  error_text TEXT,
  CHECK (status IN ('running', 'ok', 'error', 'skipped', 'interrupted', 'superseded')),
  CHECK (
    (status = 'running' AND finished_at_ms IS NULL)
    OR
    (status != 'running' AND finished_at_ms IS NOT NULL)
  )
) STRICT;

CREATE UNIQUE INDEX IF NOT EXISTS cron_run_receipts_cursor_id_idx
  ON cron_run_receipts(cursor_id);

CREATE UNIQUE INDEX IF NOT EXISTS idx_cron_run_receipts_active_job
  ON cron_run_receipts(store_key, job_id)
  WHERE status = 'running';

CREATE INDEX IF NOT EXISTS idx_cron_run_receipts_job_history
  ON cron_run_receipts(store_key, job_id, started_at_ms DESC, receipt_id DESC);

-- Retirement follows the receipt's retention without changing its released shape.
CREATE TABLE IF NOT EXISTS cron_run_trigger_state_retirements (
  receipt_id TEXT PRIMARY KEY
    REFERENCES cron_run_receipts(receipt_id) ON DELETE CASCADE
) STRICT;

-- Runtime-private authority is independent of job_json so downgraded writers
-- can rewrite recognized job config without erasing or silently widening it.
CREATE TABLE IF NOT EXISTS cron_job_runtime_authorities (
  store_key TEXT NOT NULL,
  job_id TEXT NOT NULL,
  authority_json TEXT,
  authority_input_fingerprint TEXT,
  recovery_required INTEGER NOT NULL,
  PRIMARY KEY (store_key, job_id),
  FOREIGN KEY (store_key, job_id)
    REFERENCES cron_jobs(store_key, job_id) ON DELETE CASCADE,
  CHECK (recovery_required IN (0, 1)),
  CHECK (
    (recovery_required = 0 AND authority_json IS NOT NULL AND authority_input_fingerprint IS NOT NULL)
    OR
    (recovery_required = 1 AND authority_json IS NULL AND authority_input_fingerprint IS NULL)
  )
) STRICT;

-- Scratch is separate from cron_jobs so scheduler state writes and downgraded
-- full-row replacement preserve it. New builds prune rows explicitly on job removal.
-- content NULL is a tombstone: it keeps the revision lineage monotonic across
-- unset/recreate so stale compare-and-swap writes cannot resurrect old content.
CREATE TABLE IF NOT EXISTS cron_job_scratch (
  store_key TEXT NOT NULL,
  job_id TEXT NOT NULL,
  content TEXT,
  revision INTEGER NOT NULL,
  source_sha256 TEXT,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (store_key, job_id),
  CHECK (revision >= 1),
  CHECK (content IS NULL OR length(CAST(content AS BLOB)) <= 262144)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_cron_job_scratch_store_updated
  ON cron_job_scratch(store_key, updated_at_ms DESC, job_id);

CREATE TABLE IF NOT EXISTS delivery_queue_entries (
  queue_name TEXT NOT NULL,
  id TEXT NOT NULL,
  status TEXT NOT NULL,
  entry_kind TEXT,
  session_key TEXT,
  channel TEXT,
  target TEXT,
  account_id TEXT,
  retry_count INTEGER NOT NULL DEFAULT 0,
  last_attempt_at INTEGER,
  last_error TEXT,
  recovery_state TEXT,
  platform_send_started_at INTEGER,
  entry_json TEXT NOT NULL,
  retention_id_prefix TEXT,
  retention_max_age_ms INTEGER,
  retention_max_entries INTEGER,
  enqueued_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  failed_at INTEGER,
  PRIMARY KEY (queue_name, id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_delivery_queue_pending
  ON delivery_queue_entries(queue_name, status, enqueued_at, id);

CREATE INDEX IF NOT EXISTS idx_delivery_queue_failed
  ON delivery_queue_entries(status, queue_name, failed_at, id);

CREATE INDEX IF NOT EXISTS idx_delivery_queue_session
  ON delivery_queue_entries(queue_name, status, session_key, enqueued_at, id)
  WHERE session_key IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_delivery_queue_target
  ON delivery_queue_entries(queue_name, status, channel, target, enqueued_at, id)
  WHERE channel IS NOT NULL AND target IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_delivery_queue_bounded_retention
  ON delivery_queue_entries(queue_name, retention_id_prefix, enqueued_at DESC, id DESC)
  WHERE status IN ('completed', 'failed') AND recovery_state = 'completed_bounded'
    AND retention_id_prefix IS NOT NULL;

CREATE TABLE IF NOT EXISTS task_runs (
  task_id TEXT NOT NULL PRIMARY KEY,
  runtime TEXT NOT NULL,
  task_kind TEXT,
  source_id TEXT,
  requester_session_key TEXT,
  owner_key TEXT NOT NULL,
  scope_kind TEXT NOT NULL,
  child_session_key TEXT,
  parent_flow_id TEXT,
  parent_task_id TEXT,
  agent_id TEXT,
  requester_agent_id TEXT,
  run_id TEXT,
  execution_owner_host TEXT,
  execution_owner_pid INTEGER,
  execution_owner_start_identity INTEGER,
  label TEXT,
  task TEXT NOT NULL,
  status TEXT NOT NULL,
  delivery_status TEXT NOT NULL,
  notify_policy TEXT NOT NULL,
  created_at INTEGER NOT NULL,
  started_at INTEGER,
  ended_at INTEGER,
  last_event_at INTEGER,
  cleanup_after INTEGER,
  tool_use_count INTEGER,
  last_tool_name TEXT,
  error TEXT,
  progress_summary TEXT,
  terminal_summary TEXT,
  terminal_outcome TEXT,
  detail_json TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_task_runs_runtime_run
  ON task_runs(runtime, run_id, source_id, created_at, task_id);
CREATE INDEX IF NOT EXISTS idx_task_runs_cron_runtime_order
  ON task_runs(runtime, created_at, task_id) WHERE runtime = 'cron';
CREATE INDEX IF NOT EXISTS idx_task_runs_cron_source_order
  ON task_runs(source_id, created_at, task_id) WHERE runtime = 'cron';

CREATE TABLE IF NOT EXISTS subagent_runs (
  run_id TEXT NOT NULL PRIMARY KEY,
  child_session_key TEXT NOT NULL,
  controller_session_key TEXT,
  controller_store_path TEXT,
  requester_session_key TEXT NOT NULL,
  requester_store_path TEXT,
  created_at INTEGER NOT NULL,
  payload_json TEXT NOT NULL DEFAULT '{}'
) STRICT;

CREATE INDEX IF NOT EXISTS idx_subagent_runs_child_session_key
  ON subagent_runs(child_session_key, created_at DESC, run_id);
CREATE INDEX IF NOT EXISTS idx_subagent_runs_requester_session_key
  ON subagent_runs(requester_session_key, created_at DESC, run_id);
CREATE INDEX IF NOT EXISTS idx_subagent_runs_controller_session_key
  ON subagent_runs(controller_session_key, created_at DESC, run_id);

CREATE TABLE IF NOT EXISTS current_conversation_bindings (
  binding_key TEXT NOT NULL PRIMARY KEY,
  binding_id TEXT NOT NULL,
  target_session_key TEXT NOT NULL,
  channel TEXT NOT NULL,
  account_id TEXT NOT NULL,
  conversation_kind TEXT NOT NULL,
  parent_conversation_id TEXT,
  conversation_id TEXT NOT NULL,
  target_kind TEXT NOT NULL,
  status TEXT NOT NULL,
  bound_at INTEGER NOT NULL,
  expires_at INTEGER,
  metadata_json TEXT,
  record_json TEXT NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_current_conversation_bindings_target
  ON current_conversation_bindings(target_session_key, updated_at DESC, binding_key);
CREATE INDEX IF NOT EXISTS idx_current_conversation_bindings_conversation
  ON current_conversation_bindings(channel, account_id, conversation_kind, conversation_id);
CREATE INDEX IF NOT EXISTS idx_current_conversation_bindings_expires
  ON current_conversation_bindings(expires_at, binding_key);

CREATE TABLE IF NOT EXISTS plugin_binding_approvals (
  plugin_root TEXT NOT NULL,
  channel TEXT NOT NULL,
  account_id TEXT NOT NULL,
  plugin_id TEXT NOT NULL,
  plugin_name TEXT,
  approved_at INTEGER NOT NULL,
  PRIMARY KEY (plugin_root, channel, account_id)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_plugin_binding_approvals_plugin
  ON plugin_binding_approvals(plugin_id, approved_at DESC);

CREATE TABLE IF NOT EXISTS task_delivery_state (
  task_id TEXT NOT NULL PRIMARY KEY,
  requester_origin_json TEXT,
  last_notified_event_at INTEGER,
  FOREIGN KEY (task_id) REFERENCES task_runs(task_id) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS flow_runs (
  flow_id TEXT NOT NULL PRIMARY KEY,
  shape TEXT,
  sync_mode TEXT NOT NULL DEFAULT 'managed',
  owner_key TEXT NOT NULL,
  requester_origin_json TEXT,
  controller_id TEXT,
  revision INTEGER NOT NULL DEFAULT 0,
  status TEXT NOT NULL,
  notify_policy TEXT NOT NULL,
  goal TEXT NOT NULL,
  current_step TEXT,
  blocked_task_id TEXT,
  blocked_summary TEXT,
  state_json TEXT,
  wait_json TEXT,
  cancel_requested_at INTEGER,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  ended_at INTEGER
) STRICT;

CREATE INDEX IF NOT EXISTS idx_flow_runs_status ON flow_runs(status);
CREATE INDEX IF NOT EXISTS idx_flow_runs_owner_key ON flow_runs(owner_key);
CREATE INDEX IF NOT EXISTS idx_flow_runs_updated_at ON flow_runs(updated_at);

-- Durable meeting-capture sessions are gateway-global rather than agent-session
-- transcripts. JSON/JSONL files are doctor import inputs or explicit CLI exports.
CREATE TABLE IF NOT EXISTS meeting_transcript_sessions (
  started_at_ms INTEGER,
  session_id TEXT NOT NULL,
  started_at TEXT NOT NULL,
  selector TEXT NOT NULL UNIQUE,
  export_key TEXT NOT NULL,
  session_slug TEXT NOT NULL,
  provider_id TEXT NOT NULL,
  title TEXT,
  source_json TEXT NOT NULL,
  source_account_id TEXT,
  source_guild_id TEXT,
  source_channel_id TEXT,
  source_meeting_url TEXT,
  source_thread_ts TEXT,
  source_file_id TEXT,
  stopped_at TEXT,
  metadata_json TEXT,
  metadata_agent_id TEXT,
  export_manifest_json TEXT NOT NULL DEFAULT '{}',
  export_pending_json TEXT NOT NULL DEFAULT '[]',
  next_utterance_seq INTEGER NOT NULL DEFAULT 0 CHECK (next_utterance_seq >= 0),
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),
  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),
  PRIMARY KEY (session_id, started_at)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_started
  ON meeting_transcript_sessions(started_at DESC, session_id);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_chronology
  ON meeting_transcript_sessions(started_at_ms DESC, session_id ASC, started_at ASC);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_id
  ON meeting_transcript_sessions(session_id, started_at DESC);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_slug
  ON meeting_transcript_sessions(session_slug, started_at DESC);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_export_key
  ON meeting_transcript_sessions(export_key);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_source
  ON meeting_transcript_sessions(provider_id, source_account_id, source_guild_id,
    source_channel_id, source_meeting_url, source_thread_ts, source_file_id,
    stopped_at DESC, started_at DESC, session_id);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_account
  ON meeting_transcript_sessions(source_account_id);

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_agent
  ON meeting_transcript_sessions(metadata_agent_id);

CREATE TABLE IF NOT EXISTS meeting_transcript_utterances (
  session_id TEXT NOT NULL,
  session_started_at TEXT NOT NULL,
  sequence INTEGER NOT NULL CHECK (sequence >= 0),
  utterance_id TEXT,
  started_at TEXT,
  ended_at TEXT,
  speaker_id TEXT,
  speaker_label TEXT,
  text TEXT NOT NULL,
  final INTEGER CHECK (final IN (0, 1)),
  metadata_json TEXT,
  PRIMARY KEY (session_id, session_started_at, sequence),
  FOREIGN KEY (session_id, session_started_at)
    REFERENCES meeting_transcript_sessions(session_id, started_at)
    ON DELETE CASCADE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_meeting_transcript_utterances_id
  ON meeting_transcript_utterances(session_id, session_started_at, utterance_id)
  WHERE utterance_id IS NOT NULL;

CREATE TABLE IF NOT EXISTS meeting_transcript_summaries (
  session_id TEXT NOT NULL,
  session_started_at TEXT NOT NULL,
  generated_at TEXT,
  summary_json TEXT,
  overview TEXT,
  markdown TEXT,
  utterance_count INTEGER NOT NULL CHECK (utterance_count >= 0),
  PRIMARY KEY (session_id, session_started_at),
  FOREIGN KEY (session_id, session_started_at)
    REFERENCES meeting_transcript_sessions(session_id, started_at)
    ON DELETE CASCADE,
  CHECK (summary_json IS NOT NULL OR markdown IS NOT NULL)
) STRICT;

CREATE TABLE IF NOT EXISTS migration_runs (
  id TEXT NOT NULL PRIMARY KEY,
  started_at INTEGER NOT NULL,
  finished_at INTEGER,
  status TEXT NOT NULL,
  report_json TEXT NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_migration_runs_started
  ON migration_runs(started_at DESC, id);

CREATE TABLE IF NOT EXISTS migration_sources (
  source_key TEXT NOT NULL PRIMARY KEY,
  migration_kind TEXT NOT NULL,
  source_path TEXT NOT NULL,
  target_table TEXT NOT NULL,
  source_sha256 TEXT,
  source_size_bytes INTEGER,
  source_record_count INTEGER,
  last_run_id TEXT NOT NULL,
  status TEXT NOT NULL,
  imported_at INTEGER NOT NULL,
  removed_source INTEGER NOT NULL DEFAULT 0,
  report_json TEXT NOT NULL,
  FOREIGN KEY (last_run_id) REFERENCES migration_runs(id) ON DELETE CASCADE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_migration_sources_path
  ON migration_sources(source_path, migration_kind, target_table);

CREATE INDEX IF NOT EXISTS idx_migration_sources_run
  ON migration_sources(last_run_id, source_path);

CREATE TABLE IF NOT EXISTS backup_runs (
  id TEXT NOT NULL PRIMARY KEY,
  created_at INTEGER NOT NULL,
  archive_path TEXT NOT NULL,
  status TEXT NOT NULL,
  manifest_json TEXT NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_backup_runs_created
  ON backup_runs(created_at DESC, id);

CREATE TABLE IF NOT EXISTS worktrees (
  id TEXT NOT NULL PRIMARY KEY,
  repo_fingerprint TEXT NOT NULL,
  repo_root TEXT NOT NULL,
  path TEXT NOT NULL,
  branch TEXT NOT NULL,
  base_ref TEXT NOT NULL,
  owner_kind TEXT NOT NULL CHECK (owner_kind IN ('manual', 'workboard', 'session')),
  owner_id TEXT,
  snapshot_ref TEXT,
  provisioned_paths_json TEXT,
  created_at INTEGER NOT NULL,
  last_active_at INTEGER NOT NULL,
  removed_at INTEGER,
  run_end_cleanup_json TEXT,
  gc_protection_json TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_worktrees_repo_fingerprint
  ON worktrees(repo_fingerprint);

CREATE INDEX IF NOT EXISTS idx_worktrees_removed_at
  ON worktrees(removed_at);

CREATE TABLE IF NOT EXISTS worktree_provisioned_file_chunks (
  worktree_id TEXT NOT NULL,
  path TEXT NOT NULL,
  chunk_index INTEGER NOT NULL CHECK (chunk_index >= 0),
  data BLOB NOT NULL,
  PRIMARY KEY (worktree_id, path, chunk_index)
) STRICT;

CREATE TABLE IF NOT EXISTS worktree_templates (
  cache_key TEXT NOT NULL PRIMARY KEY,
  id TEXT NOT NULL UNIQUE,
  repo_root TEXT NOT NULL,
  common_dir TEXT NOT NULL,
  worktree_root TEXT NOT NULL,
  path TEXT NOT NULL,
  backend TEXT NOT NULL,
  source_commit TEXT NOT NULL,
  content_key TEXT NOT NULL,
  status TEXT NOT NULL CHECK (status IN ('preparing', 'ready')),
  created_at INTEGER NOT NULL,
  last_used_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS projects (
  id TEXT NOT NULL PRIMARY KEY,
  display_name TEXT NOT NULL,
  repo_root TEXT NOT NULL,
  origin_url TEXT,
  source TEXT NOT NULL CHECK (source IN ('registered', 'cloned')),
  created_at_ms INT NOT NULL,
  updated_at_ms INT NOT NULL
) STRICT;

-- One explicitly retained, normalized private background per durable profile.
CREATE TABLE IF NOT EXISTS user_background_images (
  profile_id TEXT NOT NULL PRIMARY KEY REFERENCES user_profiles(id) ON DELETE CASCADE,
  asset_id TEXT NOT NULL UNIQUE,
  image BLOB NOT NULL CHECK (length(image) BETWEEN 1 AND 2097152),
  width INTEGER NOT NULL CHECK (width BETWEEN 1 AND 2560),
  height INTEGER NOT NULL CHECK (height BETWEEN 1 AND 2560)
) STRICT;

CREATE TABLE IF NOT EXISTS user_preferences (
  profile_id TEXT NOT NULL,
  pref_key TEXT NOT NULL,
  value_json TEXT NOT NULL,
  updated_at_ms INT NOT NULL,
  PRIMARY KEY (profile_id, pref_key)
) STRICT;

-- Gateway-owned custom session group catalog (names + display order).
-- Membership stays on each session entry's category field; this table only
-- owns which groups exist and how operator UIs order them.
CREATE TABLE IF NOT EXISTS session_groups (
  name TEXT NOT NULL PRIMARY KEY,
  position INTEGER NOT NULL,
  created_at INTEGER NOT NULL,
  cwd TEXT,
  worktree INTEGER
) STRICT;

-- Gateway-owned durable cloud worker lifecycle. Provider-specific execution
-- stays in plugins; this table records only core reconciliation facts.
CREATE TABLE IF NOT EXISTS worker_environments (
  environment_id TEXT NOT NULL PRIMARY KEY,
  provider_id TEXT NOT NULL,
  profile_id TEXT NOT NULL,
  profile_snapshot_json TEXT NOT NULL,
  last_activated_at_ms INTEGER,
  preparation_key TEXT,
  preparation_purpose TEXT,
  preparation_demand_at_ms INTEGER,
  preparation_expires_at_ms INTEGER,
  preparation_consumed_at_ms INTEGER CHECK (
    (preparation_key IS NULL AND preparation_demand_at_ms IS NULL
      AND preparation_expires_at_ms IS NULL AND preparation_consumed_at_ms IS NULL)
    OR
    (preparation_key IS NOT NULL AND length(preparation_key) = 64
      AND preparation_key NOT GLOB '*[^0-9a-f]*'
      AND preparation_demand_at_ms IS NOT NULL
      AND preparation_demand_at_ms BETWEEN 0 AND 9007199254740991
      AND preparation_expires_at_ms IS NOT NULL
      AND preparation_expires_at_ms > preparation_demand_at_ms
      AND preparation_expires_at_ms <= 9007199254740991
      AND (preparation_consumed_at_ms IS NULL
        OR (preparation_consumed_at_ms >= preparation_demand_at_ms
          AND preparation_consumed_at_ms < preparation_expires_at_ms)))
  ),
  provision_operation_id TEXT NOT NULL UNIQUE,
  lease_id TEXT,
  node_setup_id TEXT,
  node_device_id TEXT,
  ssh_host TEXT,
  ssh_port INTEGER CHECK (ssh_port IS NULL OR (ssh_port >= 1 AND ssh_port <= 65535)),
  ssh_user TEXT,
  ssh_host_key TEXT,
  ssh_key_ref_json TEXT,
  desktop_json TEXT,
  state TEXT NOT NULL CHECK (
    state IN (
      'requested',
      'provisioning',
      'bootstrapping',
      'ready',
      'attached',
      'idle',
      'draining',
      'destroying',
      'destroyed',
      'failed',
      'orphaned'
    )
  ),
  bootstrap_bundle_hash TEXT,
  bootstrap_openclaw_version TEXT,
  bootstrap_protocol_features_json TEXT,
  bootstrap_install_kind TEXT,
  owner_epoch INTEGER NOT NULL DEFAULT 0 CHECK (owner_epoch >= 0),
  teardown_terminal_state TEXT CHECK (teardown_terminal_state IN ('destroyed', 'failed')),
  attached_session_ids_json TEXT NOT NULL DEFAULT '[]',
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  state_changed_at_ms INTEGER NOT NULL,
  idle_since_at_ms INTEGER,
  destroy_requested_at_ms INTEGER,
  last_error TEXT,
  shared_host INTEGER,
  resource_receipt_json TEXT,
  retention_json TEXT,
  provision_source_json TEXT
) STRICT;

CREATE UNIQUE INDEX IF NOT EXISTS idx_worker_environments_provider_lease
  ON worker_environments(provider_id, lease_id)
  WHERE lease_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_worker_environments_terminal_changed
  ON worker_environments(state_changed_at_ms, environment_id);

-- A dedicated node registers its fixed build paths before ready, then binds
-- them once. The environment belongs to the Gateway's separate database.
CREATE TABLE IF NOT EXISTS node_worker_prepared_workspaces (
  preparation_key TEXT NOT NULL PRIMARY KEY CHECK (
    length(preparation_key) = 64 AND preparation_key NOT GLOB '*[^0-9a-f]*'
  ),
  cache_key TEXT NOT NULL CHECK (
    length(cache_key) = 64 AND cache_key NOT GLOB '*[^0-9a-f]*'
  ),
  gateway_namespace TEXT NOT NULL CHECK (length(gateway_namespace) > 0),
  workspace_dir TEXT NOT NULL UNIQUE CHECK (length(workspace_dir) > 0),
  home_dir TEXT NOT NULL CHECK (length(home_dir) > 0),
  source_manifest_ref TEXT NOT NULL CHECK (
    length(source_manifest_ref) = 71 AND substr(source_manifest_ref, 1, 7) = 'sha256:'
      AND substr(source_manifest_ref, 8) NOT GLOB '*[^0-9a-f]*'
  ),
  prepared_manifest_ref TEXT NOT NULL CHECK (
    length(prepared_manifest_ref) = 71 AND substr(prepared_manifest_ref, 1, 7) = 'sha256:'
      AND substr(prepared_manifest_ref, 8) NOT GLOB '*[^0-9a-f]*'
  ),
  state TEXT NOT NULL CHECK (state IN ('available', 'bound', 'retiring', 'retired')),
  environment_id TEXT NOT NULL CHECK (length(environment_id) > 0),
  session_id TEXT,
  session_key TEXT,
  owner_epoch INTEGER CHECK (owner_epoch BETWEEN 1 AND 9007199254740991),
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms BETWEEN 0 AND 9007199254740991),
  bound_at_ms INTEGER CHECK (bound_at_ms BETWEEN created_at_ms AND 9007199254740991),
  retired_at_ms INTEGER CHECK (
    retired_at_ms BETWEEN coalesce(bound_at_ms, created_at_ms) AND 9007199254740991
  ),
  CHECK (
    (session_id IS NULL AND session_key IS NULL AND owner_epoch IS NULL AND bound_at_ms IS NULL)
    OR
    (session_id IS NOT NULL AND length(session_id) > 0
      AND session_key IS NOT NULL AND length(session_key) > 0
      AND owner_epoch IS NOT NULL AND bound_at_ms IS NOT NULL)
  ),
  CHECK (
    (state = 'available' AND bound_at_ms IS NULL AND retired_at_ms IS NULL)
    OR (state = 'bound' AND bound_at_ms IS NOT NULL AND retired_at_ms IS NULL)
    OR (state = 'retiring' AND retired_at_ms IS NULL)
    OR (state = 'retired' AND retired_at_ms IS NOT NULL)
  )
) STRICT;

-- Provider-advertised fallback ports preserve stable retry order separately
-- from the downgrade-sensitive canonical worker environment row.
CREATE TABLE IF NOT EXISTS worker_environment_ssh_fallback_ports (
  environment_id TEXT NOT NULL,
  position INTEGER NOT NULL CHECK (position >= 0 AND position <= 9),
  port INTEGER NOT NULL CHECK (port >= 1 AND port <= 65535),
  PRIMARY KEY (environment_id, position),
  UNIQUE (environment_id, port),
  FOREIGN KEY (environment_id) REFERENCES worker_environments(environment_id) ON DELETE CASCADE
) STRICT;

-- Logical sessions own repository intent and accepted artifact references,
-- independently of the worker or rotating transcript session id.
CREATE TABLE IF NOT EXISTS session_repository_workspaces (
  workspace_id TEXT NOT NULL PRIMARY KEY CHECK (length(workspace_id) = 36),
  agent_id TEXT NOT NULL CHECK (length(agent_id) BETWEEN 1 AND 128),
  session_key TEXT NOT NULL CHECK (length(session_key) BETWEEN 1 AND 1024),
  url TEXT NOT NULL CHECK (length(url) BETWEEN 1 AND 4096),
  requested_ref TEXT CHECK (requested_ref IS NULL OR length(requested_ref) BETWEEN 1 AND 1024),
  run_setup_script INTEGER NOT NULL DEFAULT 0 CHECK (run_setup_script IN (0, 1)),
  base_commit TEXT CHECK (base_commit IS NULL OR length(base_commit) IN (40, 64)),
  base_manifest_hash TEXT,
  branch TEXT NOT NULL CHECK (length(branch) BETWEEN 1 AND 256),
  checkpoint_ref TEXT,
  manifest_hash TEXT,
  revision INTEGER NOT NULL CHECK (revision >= 0),
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  disk_authority_json TEXT,
  UNIQUE (agent_id, session_key),
  CHECK (base_manifest_hash IS NULL OR base_commit IS NOT NULL),
  CHECK ((checkpoint_ref IS NULL AND manifest_hash IS NULL)
    OR (checkpoint_ref IS NOT NULL AND manifest_hash IS NOT NULL AND base_manifest_hash IS NOT NULL))
) STRICT;

CREATE TABLE IF NOT EXISTS github_repository_publication_requests (
  request_id TEXT NOT NULL PRIMARY KEY,
  owner_profile_id TEXT,
  connection_generation TEXT,
  idempotency_key TEXT NOT NULL,
  request_digest TEXT NOT NULL,
  session_id TEXT NOT NULL,
  session_lifecycle_revision TEXT,
  requester_authority_json TEXT,
  session_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  workspace_id TEXT NOT NULL,
  checkpoint_ref TEXT,
  checkpoint_digest TEXT,
  claim_id TEXT,
  run_id TEXT,
  environment_id TEXT,
  owner_epoch INTEGER,
  placement_generation INTEGER,
  identity_source TEXT NOT NULL CHECK (identity_source IN ('system-detected', 'system-configured', 'agent-override', 'personal')),
  identity_profile_id TEXT,
  identity_account_id INTEGER NOT NULL,
  identity_login TEXT NOT NULL,
  title TEXT,
  body TEXT,
  status TEXT NOT NULL CHECK (status IN ('requested', 'publishing', 'needs_confirmation', 'published', 'failed')),
  gateway_instance_id TEXT,
  execution_id TEXT,
  last_effect TEXT CHECK (last_effect IN ('push', 'pull_request')),
  effect_state TEXT CHECK (effect_state IN ('dispatched', 'observed')),
  push_repository TEXT,
  repository TEXT,
  branch TEXT NOT NULL,
  base_branch TEXT,
  source_head_commit TEXT,
  source_index_tree TEXT,
  workspace_tree TEXT,
  previous_head_commit TEXT,
  pushed_head_commit TEXT,
  head_commit TEXT,
  pull_request_url TEXT,
  error_code TEXT,
  next_action TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  reported_at_ms INTEGER,
  draft INTEGER,
  CHECK ((identity_source = 'personal' AND owner_profile_id IS NOT NULL AND connection_generation IS NOT NULL)
    OR (identity_source <> 'personal' AND owner_profile_id IS NULL AND connection_generation IS NULL)),
  CHECK ((checkpoint_ref IS NULL AND checkpoint_digest IS NULL) OR (checkpoint_ref IS NOT NULL AND checkpoint_digest IS NOT NULL)),
  CHECK ((last_effect IS NULL AND effect_state IS NULL) OR (last_effect IS NOT NULL AND effect_state IS NOT NULL))
) STRICT;
CREATE UNIQUE INDEX IF NOT EXISTS idx_github_repository_publication_shared_request
  ON github_repository_publication_requests(session_id, idempotency_key) WHERE owner_profile_id IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS idx_github_repository_publication_personal_request
  ON github_repository_publication_requests(owner_profile_id, session_id, idempotency_key) WHERE owner_profile_id IS NOT NULL;

-- Session placement lives in the shared state database so local admission,
-- worker admission, and environment attachment use one durable authority.
CREATE TABLE IF NOT EXISTS worker_session_placements (
  session_id TEXT NOT NULL PRIMARY KEY,
  agent_id TEXT NOT NULL,
  session_key TEXT NOT NULL,
  execution_mode TEXT CHECK (execution_mode IN ('worker-turn', 'remote-exec')),
  state TEXT NOT NULL CHECK (
    state IN (
      'local',
      'requested',
      'provisioning',
      'syncing',
      'starting',
      'active',
      'draining',
      'reconciling',
      'reclaimed',
      'failed'
    )
  ),
  environment_id TEXT,
  transition_generation INTEGER NOT NULL DEFAULT 0 CHECK (transition_generation >= 0),
  active_owner_epoch INTEGER CHECK (active_owner_epoch IS NULL OR active_owner_epoch >= 1),
  workspace_base_manifest_ref TEXT,
  remote_workspace_dir TEXT,
  worker_bundle_hash TEXT,
  last_transcript_ack_cursor INTEGER CHECK (
    last_transcript_ack_cursor IS NULL OR last_transcript_ack_cursor >= 0
  ),
  last_live_event_ack_cursor INTEGER CHECK (
    last_live_event_ack_cursor IS NULL OR last_live_event_ack_cursor >= 0
  ),
  recovery_error TEXT,
  turn_claim_owner TEXT CHECK (turn_claim_owner IN ('local', 'worker')),
  turn_claim_id TEXT,
  turn_claim_run_id TEXT,
  turn_claim_generation INTEGER CHECK (
    turn_claim_generation IS NULL OR turn_claim_generation >= 0
  ),
  turn_claim_owner_epoch INTEGER CHECK (
    turn_claim_owner_epoch IS NULL OR turn_claim_owner_epoch >= 1
  ),
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  state_changed_at_ms INTEGER NOT NULL,
  terminal_reason TEXT,
  terminal_at_ms INTEGER,
  CHECK (
    (state IN ('local', 'requested')
      AND environment_id IS NULL AND active_owner_epoch IS NULL
      AND workspace_base_manifest_ref IS NULL AND remote_workspace_dir IS NULL
      AND worker_bundle_hash IS NULL
      AND last_transcript_ack_cursor IS NULL AND last_live_event_ack_cursor IS NULL
      AND recovery_error IS NULL)
    OR
    (state IS 'provisioning'
      AND active_owner_epoch IS NULL
      AND workspace_base_manifest_ref IS NULL AND remote_workspace_dir IS NULL
      AND worker_bundle_hash IS NULL
      AND last_transcript_ack_cursor IS NULL AND last_live_event_ack_cursor IS NULL
      AND recovery_error IS NULL)
    OR
    (state IS 'syncing'
      AND environment_id IS NOT NULL AND active_owner_epoch IS NULL
      AND workspace_base_manifest_ref IS NULL AND remote_workspace_dir IS NULL
      AND worker_bundle_hash IS NOT NULL
      AND last_transcript_ack_cursor IS NULL AND last_live_event_ack_cursor IS NULL
      AND recovery_error IS NULL)
    OR
    (state IS 'starting'
      AND environment_id IS NOT NULL AND active_owner_epoch IS NULL
      AND workspace_base_manifest_ref IS NOT NULL AND remote_workspace_dir IS NOT NULL
      AND worker_bundle_hash IS NOT NULL
      AND last_transcript_ack_cursor IS NULL AND last_live_event_ack_cursor IS NULL
      AND recovery_error IS NULL)
    OR
    (state IN ('active', 'draining', 'reconciling')
      AND environment_id IS NOT NULL AND active_owner_epoch IS NOT NULL
      AND workspace_base_manifest_ref IS NOT NULL AND remote_workspace_dir IS NOT NULL
      AND worker_bundle_hash IS NOT NULL AND recovery_error IS NULL)
    OR
    (state IS 'reclaimed'
      AND environment_id IS NOT NULL AND active_owner_epoch IS NOT NULL
      AND workspace_base_manifest_ref IS NOT NULL AND remote_workspace_dir IS NOT NULL
      AND worker_bundle_hash IS NOT NULL AND recovery_error IS NULL
      AND turn_claim_owner IS NULL AND turn_claim_id IS NULL AND turn_claim_run_id IS NULL
      AND turn_claim_generation IS NULL AND turn_claim_owner_epoch IS NULL)
    OR
    (state IS 'failed' AND recovery_error IS NOT NULL)
  ),
  CHECK (
    (turn_claim_owner IS NULL AND turn_claim_id IS NULL AND turn_claim_run_id IS NULL
      AND turn_claim_generation IS NULL AND turn_claim_owner_epoch IS NULL)
    OR
    (turn_claim_owner IS 'local' AND turn_claim_id IS NOT NULL
      AND turn_claim_run_id IS NOT NULL AND turn_claim_generation IS NOT NULL
      AND turn_claim_owner_epoch IS NULL)
    OR
    (turn_claim_owner IS 'worker' AND turn_claim_id IS NOT NULL
      AND turn_claim_run_id IS NOT NULL AND turn_claim_generation IS NOT NULL
      AND turn_claim_owner_epoch IS NOT NULL)
  ),
  CHECK (
    turn_claim_owner IS NULL
    OR
    (turn_claim_owner IS 'local' AND (
      state IN ('local', 'requested', 'failed')
      OR (state IN ('active', 'draining') AND execution_mode IS 'remote-exec')
    ))
    OR
    (turn_claim_owner IS 'worker' AND state IN ('active', 'draining')
      AND (execution_mode IS NULL OR execution_mode IS 'worker-turn')
      AND turn_claim_owner_epoch IS active_owner_epoch)
  )
) STRICT;

CREATE INDEX IF NOT EXISTS idx_worker_session_placements_session_key
  ON worker_session_placements(agent_id, session_key);

CREATE INDEX IF NOT EXISTS idx_worker_session_placements_reconcile
  ON worker_session_placements(updated_at_ms, session_id);

CREATE INDEX IF NOT EXISTS idx_worker_session_placements_environment
  ON worker_session_placements(environment_id)
  WHERE environment_id IS NOT NULL;

-- Planned placement moves retain their exact source CAS and bounded target
-- without widening the stable placement-state vocabulary. The opaque operation
-- id fences stale asynchronous completion; it is correlation, never authority.
CREATE TABLE IF NOT EXISTS worker_session_placement_moves (
  operation_id TEXT NOT NULL PRIMARY KEY,
  session_id TEXT NOT NULL UNIQUE
    REFERENCES worker_session_placements(session_id) ON DELETE CASCADE,
  source_generation INTEGER NOT NULL CHECK (source_generation >= 0),
  source_environment_id TEXT NOT NULL CHECK (
    length(source_environment_id) BETWEEN 1 AND 256
    AND source_environment_id = trim(source_environment_id)
  ),
  source_owner_epoch INTEGER NOT NULL CHECK (source_owner_epoch >= 1),
  target_kind TEXT NOT NULL CHECK (target_kind IN ('gateway', 'profile', 'device')),
  target_id TEXT,
  -- Keep these nullable columns constraint-free so lazy ALTER TABLE produces the
  -- same shape as fresh databases; placement-move code validates their values.
  target_machine_class TEXT,
  target_os TEXT,
  -- Explicit source abandonment is a durable operator decision. Keep the bit
  -- bare and nullable so same-version older readers can safely omit it.
  abandon_source INTEGER,
  last_error TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  CHECK (
    (target_kind IS 'gateway' AND target_id IS NULL)
    OR
    (target_kind IN ('profile', 'device')
      AND target_id IS NOT NULL
      AND length(target_id) BETWEEN 1 AND 256
      AND target_id = trim(target_id))
  )
) STRICT;

-- Worker-visible session RPC authority is persisted against the exact turn
-- claim. The launch descriptor is informative only; Gateway dispatch always
-- revalidates this record and the live placement claim before executing.
CREATE TABLE IF NOT EXISTS worker_turn_tool_authorities (
  session_id TEXT NOT NULL PRIMARY KEY,
  environment_id TEXT NOT NULL,
  owner_epoch INTEGER NOT NULL CHECK (owner_epoch >= 1),
  placement_generation INTEGER NOT NULL CHECK (placement_generation >= 0),
  claim_id TEXT NOT NULL,
  run_id TEXT NOT NULL,
  tool_names_json TEXT NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  FOREIGN KEY (session_id) REFERENCES worker_session_placements(session_id) ON DELETE CASCADE
) STRICT;

-- Tool-call ids are idempotency keys only within one exact source turn claim.
-- A running operation from another Gateway instance is ambiguous and is never
-- replayed. A persisted random seed separates durable downstream identities
-- from Gateway authentication keys and survives ordinary process restarts.
CREATE TABLE IF NOT EXISTS worker_session_tool_operations (
  source_session_id TEXT NOT NULL,
  source_claim_id TEXT NOT NULL,
  tool_call_id TEXT NOT NULL,
  tool_name TEXT NOT NULL CHECK (tool_name IN ('sessions_spawn', 'sessions_send')),
  request_digest TEXT NOT NULL,
  operation_seed TEXT NOT NULL,
  status TEXT NOT NULL CHECK (status IN ('running', 'succeeded', 'failed', 'unknown')),
  child_session_key TEXT,
  result_json TEXT,
  gateway_instance_id TEXT NOT NULL,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (source_session_id, source_claim_id, tool_call_id),
  FOREIGN KEY (source_session_id)
    REFERENCES worker_session_placements(session_id) ON DELETE CASCADE
) STRICT;

-- Local sandbox execution is a projection of a session-owned managed worktree.
-- No cascade: an older binary must not discard pending edits with a session row.
CREATE TABLE IF NOT EXISTS local_workspace_projections (
  worktree_id TEXT NOT NULL PRIMARY KEY,
  agent_id TEXT NOT NULL,
  session_key TEXT NOT NULL,
  session_id TEXT NOT NULL,
  lifecycle_revision TEXT,
  projection_path TEXT NOT NULL UNIQUE,
  base_commit TEXT NOT NULL,
  source_paths_json TEXT NOT NULL,
  baseline_json TEXT,
  baseline_ref TEXT,
  pending_ref TEXT,
  pending_target TEXT CHECK (pending_target IN ('canonical', 'projection')),
  paused_runtimes_json TEXT,
  journal_json TEXT,
  journal_pack BLOB CHECK (journal_pack IS NULL OR length(journal_pack) <= 268435456),
  revision INTEGER NOT NULL DEFAULT 0 CHECK (revision >= 0),
  created_at_ms INTEGER NOT NULL,
  checkpoint_json TEXT,
  tree_root_digest BLOB,
  source_paths_digest BLOB,
  canonical_fingerprints BLOB,
  projection_fingerprints BLOB,
  CHECK (baseline_json IS NULL OR baseline_ref IS NOT NULL),
  CHECK ((journal_json IS NULL) = (journal_pack IS NULL))
) STRICT;

-- The projection owner advances changed nodes and its root in one acceptance.
-- Legacy baseline_json remains only until that owner's resumable conversion.
CREATE TABLE IF NOT EXISTS local_workspace_manifest_nodes (
  worktree_id TEXT NOT NULL,
  path TEXT NOT NULL,
  node_json TEXT NOT NULL,
  PRIMARY KEY (worktree_id, path),
  FOREIGN KEY (worktree_id)
    REFERENCES local_workspace_projections(worktree_id) ON DELETE CASCADE
) STRICT;

-- Immutable subtrees and source inventories are shared across projections and revisions.
-- Large JSON packs measured 410k VFS reads/load WITHOUT ROWID versus 10k with rowid.
CREATE TABLE IF NOT EXISTS local_workspace_tree_packs (
  tree_digest BLOB NOT NULL PRIMARY KEY CHECK (length(tree_digest) = 32),
  records_json TEXT NOT NULL,
  children_json TEXT NOT NULL,
  sweep_epoch INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS local_workspace_source_path_sets (
  path_digest BLOB NOT NULL PRIMARY KEY CHECK (length(path_digest) = 32),
  paths_zstd BLOB NOT NULL,
  sweep_epoch INTEGER NOT NULL
) STRICT, WITHOUT ROWID;

-- A reconciliation journal is written before managed-worktree mutation. The
-- bounded Git base snapshot repairs any subset left by an interrupted apply.
CREATE TABLE IF NOT EXISTS worker_workspace_reconciliations (
  session_id TEXT NOT NULL PRIMARY KEY,
  environment_id TEXT NOT NULL,
  owner_epoch INTEGER NOT NULL CHECK (owner_epoch >= 1),
  placement_generation INTEGER NOT NULL CHECK (placement_generation >= 0),
  base_manifest_ref TEXT NOT NULL,
  current_manifest_ref TEXT NOT NULL,
  plan_json TEXT NOT NULL,
  base_pack BLOB NOT NULL CHECK (length(base_pack) <= 268435456),
  created_at_ms INTEGER NOT NULL,
  FOREIGN KEY (session_id) REFERENCES worker_session_placements(session_id) ON DELETE CASCADE
) STRICT;

-- A completed remote turn is fenced from stale-claim teardown until its
-- workspace result is durably reconciled into the managed worktree.
CREATE TABLE IF NOT EXISTS worker_workspace_pending_results (
  session_id TEXT NOT NULL PRIMARY KEY,
  environment_id TEXT NOT NULL,
  owner_epoch INTEGER NOT NULL CHECK (owner_epoch >= 1),
  placement_generation INTEGER NOT NULL CHECK (placement_generation >= 0),
  claim_id TEXT NOT NULL,
  run_id TEXT NOT NULL,
  gateway_instance_id TEXT NOT NULL,
  recovery_requested_at_ms INTEGER,
  workspace_accepted_at_ms INTEGER,
  staged_result_ref TEXT,
  repository_workspace_id TEXT,
  created_at_ms INTEGER NOT NULL,
  repository_disk_authority_json TEXT,
  FOREIGN KEY (session_id) REFERENCES worker_session_placements(session_id) ON DELETE CASCADE
) STRICT;

-- GitHub publication intent records the authoritative session worktree. Cloud
-- requests execute only after the exact turn claim's result is accepted locally.
-- Secrets stay in the effective Gateway-owned GitHub profile and never enter
-- this row or the worker protocol.
CREATE TABLE IF NOT EXISTS github_publication_requests (
  request_id TEXT NOT NULL PRIMARY KEY,
  idempotency_key TEXT NOT NULL,
  request_digest TEXT NOT NULL,
  session_id TEXT NOT NULL,
  session_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  worktree_id TEXT NOT NULL,
  repository_fingerprint TEXT NOT NULL,
  claim_id TEXT,
  run_id TEXT,
  environment_id TEXT,
  owner_epoch INTEGER CHECK (owner_epoch IS NULL OR owner_epoch >= 1),
  placement_generation INTEGER CHECK (
    placement_generation IS NULL OR placement_generation >= 0
  ),
  identity_source TEXT NOT NULL CHECK (
    identity_source IN ('system-detected', 'system-configured', 'agent-override')
  ),
  identity_profile_id TEXT,
  identity_account_id INTEGER NOT NULL CHECK (identity_account_id >= 1),
  identity_login TEXT NOT NULL,
  title TEXT,
  body TEXT,
  status TEXT NOT NULL CHECK (
    status IN ('requested', 'publishing', 'published', 'failed')
  ),
  gateway_instance_id TEXT,
  repository TEXT,
  branch TEXT NOT NULL,
  base_branch TEXT,
  source_head_commit TEXT,
  source_index_tree TEXT,
  workspace_tree TEXT,
  head_commit TEXT,
  pull_request_url TEXT,
  error_code TEXT,
  next_action TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  reported_at_ms INTEGER,
  draft INTEGER,
  UNIQUE (session_id, idempotency_key),
  CHECK (
    (claim_id IS NULL AND run_id IS NULL AND environment_id IS NULL
      AND owner_epoch IS NULL AND placement_generation IS NULL)
    OR
    (claim_id IS NOT NULL AND run_id IS NOT NULL AND placement_generation IS NOT NULL
      AND ((environment_id IS NULL AND owner_epoch IS NULL)
        OR (environment_id IS NOT NULL AND owner_epoch IS NOT NULL)))
  ),
  CHECK (
    (identity_source IS 'system-detected' AND identity_profile_id IS NULL)
    OR
    (identity_source IN ('system-configured', 'agent-override')
      AND identity_profile_id IS NOT NULL)
  ),
  CHECK (
    (source_head_commit IS NULL AND source_index_tree IS NULL AND workspace_tree IS NULL)
    OR
    (source_head_commit IS NOT NULL AND workspace_tree IS NOT NULL)
  ),
  CHECK (
    (status IS 'published' AND pull_request_url IS NOT NULL AND error_code IS NULL
      AND next_action IS NULL)
    OR
    (status IS 'failed' AND pull_request_url IS NULL AND error_code IS NOT NULL
      AND next_action IS NOT NULL)
    OR
    (status IN ('requested', 'publishing') AND pull_request_url IS NULL
      AND error_code IS NULL AND next_action IS NULL)
  )
) STRICT;

CREATE INDEX IF NOT EXISTS idx_github_publication_requests_pending
  ON github_publication_requests(status, updated_at_ms, request_id);

-- Personal requests cannot be interpreted or resumed by older shared publishers.
CREATE TABLE IF NOT EXISTS github_personal_publication_requests (
  request_id TEXT NOT NULL PRIMARY KEY CHECK (length(request_id) = 36),
  owner_profile_id TEXT NOT NULL CHECK (length(owner_profile_id) BETWEEN 1 AND 128),
  connection_generation TEXT NOT NULL CHECK (length(connection_generation) = 36),
  idempotency_key TEXT NOT NULL CHECK (length(idempotency_key) BETWEEN 1 AND 128),
  request_digest TEXT NOT NULL CHECK (length(request_digest) = 64),
  session_id TEXT NOT NULL CHECK (length(session_id) BETWEEN 1 AND 128),
  session_key TEXT NOT NULL CHECK (length(session_key) BETWEEN 1 AND 1024),
  agent_id TEXT NOT NULL CHECK (length(agent_id) BETWEEN 1 AND 128),
  worktree_id TEXT NOT NULL CHECK (length(worktree_id) BETWEEN 1 AND 128),
  repository_fingerprint TEXT NOT NULL CHECK (length(repository_fingerprint) BETWEEN 1 AND 256),
  identity_source TEXT NOT NULL CHECK (identity_source = 'personal'),
  identity_profile_id TEXT NOT NULL CHECK (length(identity_profile_id) = 36),
  identity_account_id INTEGER NOT NULL CHECK (identity_account_id >= 1),
  identity_login TEXT NOT NULL CHECK (length(identity_login) BETWEEN 1 AND 39),
  title TEXT CHECK (title IS NULL OR length(title) BETWEEN 1 AND 256),
  body TEXT CHECK (body IS NULL OR length(body) BETWEEN 1 AND 8192),
  status TEXT NOT NULL CHECK (status IN ('requested', 'publishing', 'needs_confirmation', 'published', 'failed')),
  gateway_instance_id TEXT CHECK (gateway_instance_id IS NULL OR length(gateway_instance_id) BETWEEN 1 AND 128),
  execution_id TEXT CHECK (execution_id IS NULL OR length(execution_id) = 36),
  last_effect TEXT CHECK (last_effect IS NULL OR last_effect IN ('push', 'pull_request')),
  effect_state TEXT CHECK (effect_state IS NULL OR effect_state IN ('dispatched', 'observed')),
  push_repository TEXT NOT NULL CHECK (length(push_repository) BETWEEN 3 AND 256),
  repository TEXT NOT NULL CHECK (length(repository) BETWEEN 3 AND 256),
  branch TEXT NOT NULL CHECK (length(branch) BETWEEN 1 AND 256),
  base_branch TEXT NOT NULL CHECK (length(base_branch) BETWEEN 1 AND 256),
  source_head_commit TEXT NOT NULL CHECK (length(source_head_commit) IN (40, 64)),
  source_index_tree TEXT NOT NULL CHECK (length(source_index_tree) IN (40, 64)),
  workspace_tree TEXT NOT NULL CHECK (length(workspace_tree) IN (40, 64)),
  head_commit TEXT CHECK (head_commit IS NULL OR length(head_commit) IN (40, 64)),
  pull_request_url TEXT CHECK (pull_request_url IS NULL OR length(pull_request_url) BETWEEN 1 AND 2048),
  error_code TEXT CHECK (error_code IS NULL OR length(error_code) BETWEEN 1 AND 64),
  next_action TEXT CHECK (next_action IS NULL OR length(next_action) BETWEEN 1 AND 1024),
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),
  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= created_at_ms),
  reported_at_ms INTEGER,
  draft INTEGER,
  UNIQUE (owner_profile_id, session_id, idempotency_key),
  CHECK ((status = 'publishing' AND gateway_instance_id IS NOT NULL AND execution_id IS NOT NULL) OR status <> 'publishing'),
  CHECK ((last_effect IS NULL AND effect_state IS NULL) OR (last_effect IS NOT NULL AND effect_state IS NOT NULL)),
  CHECK ((status = 'published' AND pull_request_url IS NOT NULL AND head_commit IS NOT NULL AND error_code IS NULL AND next_action IS NULL)
    OR (status = 'failed' AND error_code IS NOT NULL AND next_action IS NOT NULL)
    OR (status IN ('requested', 'publishing', 'needs_confirmation') AND error_code IS NULL AND next_action IS NULL))
) STRICT;
CREATE INDEX IF NOT EXISTS idx_github_personal_publication_owner_session
  ON github_personal_publication_requests(owner_profile_id, session_id, created_at_ms);
CREATE INDEX IF NOT EXISTS idx_github_personal_publication_pending
  ON github_personal_publication_requests(status, updated_at_ms, request_id);

-- Older readers validate both local receipt tables exactly. Their immutable
-- lifecycle binding stays in a first-use companion so those schemas remain readable.
CREATE TABLE IF NOT EXISTS github_publication_session_lifecycles (
  publication_kind TEXT NOT NULL CHECK (publication_kind IN ('shared', 'personal')),
  request_id TEXT NOT NULL,
  lifecycle_revision TEXT,
  requester_authority_json TEXT,
  PRIMARY KEY (publication_kind, request_id)
) STRICT;

-- One active, opaque admission credential per worker environment. Plaintext
-- may be retried until delivery acknowledgement but never enters durable state.
CREATE TABLE IF NOT EXISTS worker_environment_credentials (
  environment_id TEXT NOT NULL PRIMARY KEY,
  credential_hash TEXT NOT NULL UNIQUE,
  bundle_hash TEXT NOT NULL,
  session_id TEXT,
  rpc_set_version INTEGER NOT NULL CHECK (rpc_set_version >= 1),
  owner_epoch INTEGER NOT NULL CHECK (owner_epoch >= 0),
  expires_at_ms INTEGER NOT NULL CHECK (expires_at_ms >= 0),
  delivered_at_ms INTEGER CHECK (delivered_at_ms >= 0),
  FOREIGN KEY (environment_id) REFERENCES worker_environments(environment_id) ON DELETE CASCADE
) STRICT;

-- One durable sequence cursor per attached session owner epoch. The environment
-- binding prevents independent workers with coincident epochs from sharing replay state.
CREATE TABLE IF NOT EXISTS worker_transcript_commit_heads (
  session_id TEXT NOT NULL,
  run_epoch INTEGER NOT NULL CHECK (run_epoch >= 0),
  environment_id TEXT NOT NULL,
  next_seq INTEGER NOT NULL CHECK (next_seq >= 1),
  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),
  PRIMARY KEY (session_id, run_epoch)
) STRICT;

-- Pending rows preserve a claimed request across gateway restarts. Terminal rows
-- cache the exact result returned for deterministic at-least-once replay.
CREATE TABLE IF NOT EXISTS worker_transcript_commits (
  session_id TEXT NOT NULL,
  run_epoch INTEGER NOT NULL CHECK (run_epoch >= 0),
  seq INTEGER NOT NULL CHECK (seq >= 1),
  request_hash TEXT NOT NULL,
  state TEXT NOT NULL CHECK (state IN ('pending', 'terminal')),
  result_json TEXT,
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),
  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),
  PRIMARY KEY (session_id, run_epoch, seq),
  FOREIGN KEY (session_id, run_epoch)
    REFERENCES worker_transcript_commit_heads(session_id, run_epoch)
    ON DELETE CASCADE,
  CHECK (
    (state = 'pending' AND result_json IS NULL) OR
    (state = 'terminal' AND result_json IS NOT NULL)
  )
) STRICT;

-- Pending rows preserve a claimed inference turn across gateway restarts.
-- Terminal rows cache the exact outcome returned for deterministic replay.
CREATE TABLE IF NOT EXISTS worker_inference_turns (
  session_id TEXT NOT NULL,
  run_epoch INTEGER NOT NULL CHECK (run_epoch >= 0),
  run_id TEXT NOT NULL,
  turn_id TEXT NOT NULL,
  environment_id TEXT NOT NULL,
  request_hash TEXT NOT NULL,
  state TEXT NOT NULL CHECK (state IN ('pending', 'terminal')),
  terminal_json TEXT,
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),
  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),
  PRIMARY KEY (session_id, run_epoch, run_id, turn_id),
  FOREIGN KEY (environment_id) REFERENCES worker_environments(environment_id) ON DELETE CASCADE,
  CHECK (
    (state = 'pending' AND terminal_json IS NULL) OR
    (state = 'terminal' AND terminal_json IS NOT NULL)
  )
) STRICT;

CREATE UNIQUE INDEX IF NOT EXISTS idx_worker_inference_turns_pending_run
  ON worker_inference_turns(session_id, run_epoch, run_id)
  WHERE state = 'pending';

CREATE TABLE IF NOT EXISTS template_installs (
  agent_id TEXT NOT NULL PRIMARY KEY,
  schema_version TEXT NOT NULL,
  source_kind TEXT NOT NULL,
  template_name TEXT NOT NULL,
  template_version TEXT NOT NULL,
  package_root TEXT NOT NULL,
  manifest_path TEXT NOT NULL,
  integrity_kind TEXT NOT NULL,
  integrity TEXT NOT NULL,
  source_byte_length INTEGER NOT NULL,
  manifest_schema_version INTEGER NOT NULL,
  plan_integrity TEXT NOT NULL,
  workspace TEXT NOT NULL UNIQUE,
  agent_config_digest TEXT NOT NULL,
  agent_owned_paths_json TEXT NOT NULL,
  bootstrap_source_path TEXT,
  bootstrap_content_digest TEXT,
  status TEXT NOT NULL CHECK (
    status IN ('pending', 'workspace_ready', 'config_committed', 'complete', 'partial')
  ),
  added_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS template_workspace_files (
  agent_id TEXT NOT NULL,
  target_path TEXT NOT NULL,
  schema_version TEXT NOT NULL,
  workspace TEXT NOT NULL,
  source_path TEXT NOT NULL,
  content_digest TEXT NOT NULL,
  status TEXT NOT NULL,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (agent_id, target_path)
) STRICT;

CREATE TABLE IF NOT EXISTS template_package_refs (
  agent_id TEXT NOT NULL,
  package_kind TEXT NOT NULL,
  package_source TEXT NOT NULL,
  package_ref TEXT NOT NULL,
  package_version TEXT NOT NULL,
  package_integrity TEXT NOT NULL,
  schema_version TEXT NOT NULL,
  template_name TEXT NOT NULL,
  package_status TEXT NOT NULL,
  relationship TEXT NOT NULL CHECK (relationship IN ('managed', 'referenced')),
  origin TEXT NOT NULL CHECK (origin IN ('template-introduced', 'pre-existing')),
  independent_owner INTEGER NOT NULL CHECK (independent_owner IN (0, 1)),
  extension_id TEXT,
  extension_format TEXT,
  extension_detected_format TEXT,
  extension_mapped_json TEXT,
  extension_unavailable_json TEXT,
  extension_adapter_identity TEXT,
  installed_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (agent_id, package_kind, package_source, package_ref, package_version)
) STRICT;

CREATE TABLE IF NOT EXISTS template_cron_refs (
  agent_id TEXT NOT NULL,
  manifest_id TEXT NOT NULL,
  schema_version TEXT NOT NULL,
  declaration_key TEXT NOT NULL UNIQUE,
  scheduler_job_id TEXT UNIQUE,
  status TEXT NOT NULL,
  job_json TEXT NOT NULL,
  error TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (agent_id, manifest_id)
) STRICT;

CREATE TABLE IF NOT EXISTS template_mcp_server_refs (
  agent_id TEXT NOT NULL,
  name TEXT NOT NULL,
  schema_version TEXT NOT NULL,
  config_digest TEXT NOT NULL,
  relationship TEXT NOT NULL CHECK (relationship IN ('managed', 'referenced')),
  origin TEXT NOT NULL CHECK (origin IN ('template-introduced', 'pre-existing')),
  independent_owner INTEGER NOT NULL DEFAULT 0 CHECK (independent_owner IN (0, 1)),
  status TEXT NOT NULL,
  error TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  PRIMARY KEY (agent_id, name)
) STRICT;

CREATE TABLE IF NOT EXISTS user_profile_identities (
  provider TEXT NOT NULL,
  subject TEXT NOT NULL,
  profile_id TEXT NOT NULL,
  canonical_login TEXT,
  -- Host-scoped verified credit evidence; current profile bindings govern attribution.
  verified_email_json TEXT,
  created_at INTEGER NOT NULL,
  authorization_id TEXT,
  authorization_basis_json TEXT,
  PRIMARY KEY (provider, subject)
) STRICT;
CREATE INDEX IF NOT EXISTS idx_user_profile_identities_profile_id
  ON user_profile_identities(profile_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_profile_identities_authorization
  ON user_profile_identities(authorization_id);

CREATE TABLE IF NOT EXISTS outbound_media_provenance (
  realpath TEXT NOT NULL PRIMARY KEY,
  kind TEXT NOT NULL,
  version INTEGER NOT NULL,
  sha256 TEXT NOT NULL,
  size_bytes INTEGER NOT NULL,
  created_at_ms INTEGER NOT NULL
) STRICT;

-- scope_id is non-null because SQLite treats NULLs as distinct in unique indexes/PKs,
-- which would allow duplicate team rows. This PK also avoids a rebuild for identity scope.
CREATE TABLE IF NOT EXISTS secret_store_entries (
  scope_kind TEXT NOT NULL CHECK (scope_kind IN ('team', 'identity')),
  scope_id TEXT NOT NULL,
  name TEXT NOT NULL,
  value TEXT NOT NULL,
  kind TEXT NOT NULL CHECK (kind IN ('secret', 'env')),
  created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),
  updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),
  updated_by TEXT,
  deleted_at_ms INTEGER,
  allowed_hosts TEXT,
  CHECK ((scope_kind = 'team' AND scope_id = '') OR (scope_kind = 'identity' AND length(scope_id) > 0)),
  PRIMARY KEY (scope_kind, scope_id, name)
) STRICT;
CREATE INDEX IF NOT EXISTS secret_store_entries_live_idx
  ON secret_store_entries (scope_kind, scope_id, name) WHERE deleted_at_ms IS NULL;
`||o.includes(`CREATE TABLE IF NOT EXISTS ${e} (`))&&(o=o.replace(B(o,e,{errorMessage:`lazy additive state schema block is missing for ${e}`}),``));for(let e of c){let t=o.indexOf(`CREATE INDEX IF NOT EXISTS ${e}`),n=o.indexOf(`CREATE UNIQUE INDEX IF NOT EXISTS ${e}`),r=t>=0?t:n,i=r>=0?o.indexOf(`;`,r):-1;if(r<0||i<0)throw Error(`lazy additive state schema index is missing for ${e}`);o=`${o.slice(0,r)}${o.slice(i+1)}`}return Vu.set(i,o),o}function getOpenClawStatePredecessorSchema(e){let t=H;for(let[n,r]of[[40,withLegacyWorkerProvisionSource],[40,withLegacyStateV40Additions],[39,withLegacyWorkerRetention],[38,withLegacyRepositoryDiskAuthority],[37,withLegacyWorkerResourceReceipts],[36,withLegacyTemplateStateSchema],[35,withLegacyLocalWorkspaceCas],[31,withLegacyLocalWorkspaceManifests],[27,withLegacyStateWriteIndexes],[26,withLegacyStateHeadLayout]])e<n&&(t=r(t));return t}const Hu=[...Mo,`worker_session_tool_operations`,`worker_turn_tool_authorities`],Uu=[`agent_database_leases`,`agent_deletion_journal`,`claw_cron_refs`,`claw_installs`,`claw_mcp_server_refs`,`claw_package_refs`,`claw_workspace_files`,`config_machine_state`,`cron_job_scratch`,`meeting_transcript_sessions`,`meeting_transcript_summaries`,`meeting_transcript_utterances`,`outbound_media_provenance`,`worker_environment_credentials`,`worker_transcript_commit_heads`,`worker_transcript_commits`,...Hu],Wu=pl.map(({columnName:e,tableName:t})=>`${t}.${e}`),Gu=hl.map(({columnName:e,tableName:t})=>`${t}.${e}`);new Set(Gu),[...ml.map(({columnName:e,tableName:t})=>`${t}.${e}`),...Object.values(Z).flat().map(([e,t])=>`${e}.${t.split(` `,1)[0]}`)];const Ku=[`worker_session_tool_operations`,`worker_turn_tool_authorities`];new Set(Ku);const qu=[`idx_meeting_transcript_utterances_id`,`idx_operator_approvals_source_run_resolved`,`idx_worker_session_placements_environment`],Ju=[`fleet_cells`],Yu={excludedTables:Ju,allowCompatibleAdditiveColumns:!0,allowedMissingTables:Oo,allowedMissingColumns:Gu,allowedColumnDefinitions:{"diagnostic_events.sequence":[`sequence INTEGER NOT NULL DEFAULT 0`],"template_package_refs.package_integrity":[`package_integrity TEXT NOT NULL DEFAULT 'sha256:0000000000000000000000000000000000000000000000000000000000000000'`],"template_package_refs.updated_at_ms":[`updated_at_ms INTEGER NOT NULL DEFAULT 0`],"cron_jobs.enabled":[`enabled INTEGER NOT NULL DEFAULT 1`],"cron_jobs.name":[`name TEXT NOT NULL DEFAULT ''`],"cron_jobs.payload_kind":[`payload_kind TEXT NOT NULL DEFAULT 'message'`],"current_conversation_bindings.conversation_kind":[`conversation_kind TEXT NOT NULL DEFAULT 'channel'`],"operator_approvals.resolution_ref":[`resolution_ref TEXT`],"worker_environments.desktop_json":[`desktop_json TEXT`],"worker_environments.bootstrap_install_kind":[`bootstrap_install_kind TEXT`],"worker_environments.shared_host":[`shared_host INTEGER CHECK (shared_host IN (0, 1))`],"worker_environments.node_setup_id":[`node_setup_id TEXT`],"worker_environments.node_device_id":[`node_device_id TEXT`],"worker_session_placements.terminal_reason":[`terminal_reason TEXT`],"worker_session_placements.terminal_at_ms":[`terminal_at_ms INTEGER`]}},Xu={...Yu,excludedTables:[...Ju,...Mo],excludedIndexes:ko};function findMissingLazyStateStartupColumn(e){for(let{tableName:t,columnName:n}of ml){if(!Xu.excludedTables?.includes(t))continue;let r=e(t);if(r&&!r.columns.some(e=>e.name===n))return{tableName:t,columnName:n}}}const Zu={...Yu,allowedMissingTables:[...Mo,...Ku,...Oo],allowedMissingIndexes:qu,allowedMissingColumns:Wu};var UpdateSchemaRefusalError=class extends Error{constructor(e,t,n){let{targetVersion:r}=n,i=n.recovery?.commands??[`openclaw gateway stop`,`npm install -g openclaw@${r} --allow-scripts=openclaw`,`openclaw doctor --fix`,`openclaw gateway start`],a=n.cause===void 0?``:` Deferral failed: ${Cs(n.cause).slice(0,600)}.`,o=`Doctor refused update-time schema repair driven by OpenClaw ${t}: this updater reopens the ledger with old code after migration, and version publication could not be deferred safely.`,s=`${e.map(e=>`${e.kind} database ${e.path}: on-disk schema ${e.foundVersion}, this build's schema ${e.supportedVersion}.`).join(` `)}${a} The blocked schema change was not applied.`;super(n.recovery?`${o} ${s}\n${n.recovery.message}`:[o,s,`Let the updater restore the previous package and exit. Then use an independent shell with the original service account, package prefix, profile, and state/config overrides.`,`Manual update: ${i.join(` && `)}.`,`Use the package manager that owns this install (pnpm: pnpm add -g --allow-build=openclaw openclaw@${r}; Bun: bun add -g --trust openclaw@${r}). On npm 11.15 and earlier, omit --allow-scripts=openclaw.`].join(`
`),n),this.databases=e,this.updaterVersion=t,this.code=`update-schema-bump-unfenced`,this.name=`UpdateSchemaRefusalError`,this.targetVersion=r,this.commands=i}};const Qu=`session_participants`,$u={agent:{30:[`trajectory_runtime_events`,`sqlite_stat1`,`sqlite_stat4`],27:[`context_engine_turn_outbox`,`sqlite_stat1`,`sqlite_stat4`],28:[`transcript_event_identities`,`session_windows`,`memory_entry_origins`,`sqlite_stat1`,`sqlite_stat4`],29:[`session_nodes`,`session_reactions`,`sqlite_stat1`,`sqlite_stat4`],31:[`memory_index_sources`,`memory_index_chunks`],32:[],33:[],34:[],35:[],36:[],37:[`session_transcript_cold_archive_chunks`],38:[],39:[`transcript_events`],40:[`session_creation_operations`],41:[`session_transcript_active_event_facts`],42:[`agent_tool_usage`]},state:{29:[...ku,`sqlite_stat1`,`sqlite_stat4`],23:[`meeting_transcript_sessions`,`worker_environments`],26:[`session_state_heads`,`sqlite_stat1`,`sqlite_stat4`],27:[`acp_replay_events`,`skill_usage`,`state_leases`,`sqlite_stat1`,`sqlite_stat4`],28:[`github_publication_requests`,`github_personal_publication_requests`,`github_repository_publication_requests`],30:[],31:[`local_workspace_projections`,`local_workspace_manifest_nodes`,`sqlite_stat1`,`sqlite_stat4`],32:[],33:[],34:[`config_machine_state`],35:[`local_workspace_projections`,`local_workspace_manifest_nodes`,`local_workspace_tree_packs`,`local_workspace_source_path_sets`],36:[`claw_installs`,`template_installs`,`claw_workspace_files`,`template_workspace_files`,`claw_package_refs`,`template_package_refs`,`claw_cron_refs`,`template_cron_refs`,`claw_mcp_server_refs`,`template_mcp_server_refs`,`agent_provenance`,`sqlite_stat1`,`sqlite_stat4`],37:[`worker_environments`],38:[`session_repository_workspaces`,`worker_workspace_pending_results`],39:[`worker_environments`],40:[`worker_environments`]}},ed=[`sqlite_stat1`,`sqlite_stat4`],td={agent:[`auth_profile_store`,`auth_profile_state`,`session_nodes`,`session_entry_snapshots`,`session_windows`,`session_key_contract`,`session_canonical_validation_pending`,`memory_index_chunks`,`memory_index_chunk_recall_metadata`,`memory_index_chunk_provenance`,`memory_index_sources`,`memory_index_paths_fts`,`memory_index_state`,...ed],state:[...ml.map(({tableName:e})=>e),...Object.values(Z).flatMap(e=>e.map(([e])=>e)),`audit_events`,`audit_identity_keys`,`operator_approvals`,`session_watch_cursors`,`subagent_runs`,`worker_session_placements`,`meeting_transcript_sessions`,`meeting_transcript_summaries`,`delivery_queue_entries`,`worker_turn_tool_authorities`,`worker_session_tool_operations`,`migration_runs`,`sqlite_sequence`,...ed]},nd={agent:{...$u.agent,39:[],10:[`session_transcript_active_events`,`session_transcript_index_state`],11:[`sessions`,`conversations`,`session_conversations`],13:[`transcript_rewrite_watermarks`],14:[`sessions`,`session_entries`,`session_routes`,`session_nodes`,`session_windows`,`session_transcript_generations`,`transcript_rewrite_watermarks`,`board_tabs`,`board_widgets`,`heartbeat_outcomes`,`session_members`,`session_transcript_index_state`],17:[`state_leases`],18:[`session_participants`],19:[`session_nodes`],21:[`session_key_contract`,`session_canonical_validation_pending`],22:[`session_transcript_fts_rows`],23:[`transcript_events`,`session_transcript_fts`,`session_transcript_fts_rows`,`session_transcript_index_state`,`memory_index_sources`,`memory_index_chunks`,`memory_index_chunks_fts`,`memory_index_chunk_recall_metadata`,`memory_embedding_cache`,`memory_index_meta`,`memory_index_state`,`cache_entries`],24:[`session_nodes`,`session_entry_snapshots`],25:[`session_pending_inputs`,`session_nodes`,`session_windows`,`session_key_contract`,`session_canonical_validation_pending`],26:[`session_nodes`,`context_engine_turn_outbox`,`transcript_events`]},state:{...$u.state,2:[`audit_events`,`audit_identity_keys`,`sqlite_sequence`],4:[`session_watch_cursors`],7:[`commitments`],8:[`worker_session_placements`],9:[`agent_databases`],10:[`agent_model_catalogs`,`android_notification_recent_packages`,`command_log_entries`,`diagnostic_stability_bundles`,`media_blobs`,`model_capability_cache`],11:[`skill_lifecycle`,`skill_workshop_proposal_origin_runs`],12:[`config_machine_state`,`skill_curator_state`,`update_check_state`,`clawhub_promotions_feed_state`,`model_catalog_remote`,`voicewake_triggers`,`voicewake_routing_routes`,`voicewake_routing_config`,`onboarding_recommendations`,`cron_store_epochs`,`tui_last_sessions`,`sidebar_sections`,`node_host_config`,`web_push_vapid_keys`],13:[`cron_jobs`,`subagent_runs`,`workspace_setup_state`,`workspace_attestations`,`workspace_generated_bootstrap_hashes`,`auth_profile_stores`,`auth_profile_state`,`installed_plugin_index`,`config_machine_state`,`diagnostic_events`],14:[`cron_jobs`],15:[`current_conversation_bindings`],17:[`worker_environments`],18:[`github_publication_session_lifecycles`,`github_repository_publication_requests`],20:[`cron_run_receipts`],21:[`meeting_transcript_sessions`,`meeting_transcript_summaries`,`delivery_queue_entries`,...ed],22:[`worker_session_placements`,`meeting_transcript_sessions`,`meeting_transcript_summaries`,`delivery_queue_entries`,`acp_sessions`,`operator_approvals`,`cron_run_receipts`,`execution_decision_facts`,`skill_workshop_changes`,...ed],24:[`task_runs`,...ed],25:[]}};function resolveSchemaMigrationIntegrityTables(e){if(e.kind===`agent`&&e.foundVersion>=38&&e.foundVersion<e.supportedVersion&&e.supportedVersion<=40)return[`schema_meta`];if(e.kind===`agent`&&e.foundVersion>=40&&e.foundVersion<e.supportedVersion&&e.supportedVersion<=42)return[`schema_meta`,...e.foundVersion<41?[`session_transcript_active_event_facts`]:[],...e.supportedVersion>=42?[`agent_tool_usage`]:[]];let t=/* @__PURE__ */ new Set([`schema_meta`]);if(e.foundVersion===e.supportedVersion)for(let n of td[e.kind])t.add(n);for(let n=e.foundVersion+1;n<=e.supportedVersion;n++)for(let r of nd[e.kind][n]??[])t.add(r);if(e.kind===`agent`){for(let{tableName:e}of ri)t.add(e);if(e.foundVersion<20&&(t.add(`board_widgets`),t.add(`memory_index_sources`),t.add(`memory_index_paths_fts`)),e.foundVersion<25)for(let e of td.agent)t.add(e)}else if(t.add(`config_machine_state`),e.foundVersion<20)for(let e of td.state)t.add(e);return[...t].toSorted()}function assertMigratedStateTableIntegrity(e,t,n,r=!1){let i=resolveSchemaMigrationIntegrityTables({kind:`state`,foundVersion:n,supportedVersion:40}),a=r?/* @__PURE__ */ new Set([...i,...td.state]):i;for(let n of a)M(e,n)&&$t(e,t,n)}function assertOpenClawStateDatabaseOwner(e,n){let r=t(e);if(r&&we(e))return{schema_version:r.userVersion};let i=M(e,`schema_meta`),a;try{a=i?e.prepare(`SELECT role, schema_version FROM schema_meta WHERE meta_key = 'primary' LIMIT 1`).get():void 0}catch(t){throw pt(e,`schema_meta`,[`meta_key`,`role`,`schema_version`],t)}if(a?.role!==`global`){let e=typeof a?.role==`string`?a.role:`missing`;throw new N(`OpenClaw state database ${n.pathname} has schema role ${e}; expected global. Run openclaw doctor --fix to inspect and repair its ownership.`)}return a}function assertOpenClawStateDatabaseForMaintenance(e,t,n){z(e)&&Fa(`postgres`,`repair`);let r=assertSupportedStateSchemaVersion(e,t.pathname,t.schemaVersions);if((t.schemaVersions?.contentVersion??readStateSchemaContentVersion(e))!==40)throw new N(`OpenClaw state database ${t.pathname} uses schema version ${r}; run openclaw doctor --fix before compacting it.`);let i=assertOpenClawStateDatabaseOwner(e,t);if(i?.schema_version!==r&&!Ve(e,i)){let e=typeof i?.schema_version==`number`?i.schema_version:`invalid`;throw new N(`OpenClaw state database ${t.pathname} metadata schema version ${e} does not match ${r}; run openclaw doctor --fix before compacting it.`)}assertSqliteSchemaContains(e,t.pathname,H,Zu,n)}function assertOpenClawStateDatabaseVersionForMigration(e,t){let n=Lo(e);if(readStateSchemaContentVersion(e)!==t.version)throw new N(`OpenClaw state database ${t.pathname} uses schema version ${n}; expected ${t.version} before migrating it.`);let r=assertOpenClawStateDatabaseOwner(e,t);if(r?.schema_version!==n){let e=typeof r?.schema_version==`number`?r.schema_version:`invalid`;throw new N(`OpenClaw state database ${t.pathname} metadata schema version ${e} does not match ${n}; repair the ownership metadata before migrating it.`)}assertSqliteSchemaTablesPresent(e,t.pathname,getOpenClawStatePredecessorSchema(t.version),{allowedMissingTables:[...t.version===5?Uu:t.version<13?Hu:Mo,...Oo]})}const rd=new Map(No.map(e=>[e,(t,n)=>assertOpenClawStateDatabaseVersionForMigration(t,{...n,version:e})]));function markCurrentStateSchemaVersion(e,t={}){if(!M(e,`audit_events`))return;let n=resolveStateSchemaVersionToPublish(e);if(Lo(e)!==n&&e.exec(`PRAGMA user_version = ${n};`),Ut(e,{userVersion:n,contentVersion:40}),M(e,`schema_meta`)&&[`meta_key`,`schema_version`,`updated_at`].every(t=>P(e,`schema_meta`,t))){let r=Date.now();if(t.createMetadataIfMissing){e.prepare(`INSERT INTO schema_meta (
           meta_key, role, schema_version, agent_id, app_version, created_at, updated_at
         ) VALUES ('primary', 'global', ?, NULL, NULL, ?, ?)
         ON CONFLICT(meta_key) DO UPDATE SET
           schema_version = excluded.schema_version,
           updated_at = excluded.updated_at
         WHERE schema_meta.schema_version IS NOT excluded.schema_version`).run(n,r,r);return}e.prepare(`UPDATE schema_meta SET schema_version = ?, updated_at = ? WHERE meta_key = 'primary' AND schema_version IS NOT ?`).run(n,r,n)}}function migrateCronCreatorNamespaces(e,t){return t>=14||!M(e,`cron_jobs`)?!1:(e.exec(`
    UPDATE cron_jobs
       SET job_json = json_set(job_json, '$.createdActor.source', 'unknown')
     WHERE json_valid(job_json)
       AND json_extract(job_json, '$.createdActor.type') = 'human';
  `),!0)}function migrateConversationBindingTargets(e,t){if(t>=15)return!1;let n=[`target_agent_id`,`target_session_id`].filter(t=>P(e,`current_conversation_bindings`,t));if(n.length===0)return!1;e.exec(`DROP INDEX IF EXISTS idx_current_conversation_bindings_target;`);for(let t of n)e.exec(`ALTER TABLE current_conversation_bindings DROP COLUMN ${t};`);return!0}function migratePreparedWorkerOwnership(e,t){if(t>=17||!M(e,`worker_environments`))return!1;let n=H.indexOf(`CREATE TABLE IF NOT EXISTS worker_environments (`),r=H.indexOf(`
) STRICT;`,n);if(n<0||r<n)throw Error(`OpenClaw worker environment schema marker is missing.`);let i=Ui(H.slice(n+48,r)).map(e=>e.trim()).filter(e=>e.startsWith(`last_activated_at_ms `)||e.startsWith(`preparation_`)),a=!1;for(let t of i)a=k(e,`worker_environments`,t)||a;return a}function migrateGitHubPublicationRequesterAuthority(e,t){if(t>=18)return!1;let n=!1;for(let t of[`github_publication_session_lifecycles`,`github_repository_publication_requests`])n=k(e,t,`requester_authority_json TEXT`)||n;return n}const id={version:22,tables:[`acp_sessions`,...Ru],columns:[`acp_sessions.resume_agent_session_id`,`acp_sessions.resume_acpx_session_id`,...Ru.map(e=>`${e}.cursor_id`)],migrate:migratePortableIdentityColumnsV22,applied:`Promoted portable ACP resume keys and cursor identities (v22)`},ad={version:23,tables:[`meeting_transcript_sessions`],columns:[`meeting_transcript_sessions.started_at_ms`],migrate:migrateMeetingTranscriptStartTime,applied:`Persisted normalized meeting transcript start times`},od={version:24,tables:[`task_runs`],columns:[],migrate:migrateTaskRunIndexesV24,applied:`Replaced retained task indexes with ordered cron history indexes (v24)`},sd={version:25,tables:[],columns:[],migrate:()=>!1,applied:`Required original operator authority for subagent recovery (v25)`},cd={version:26,tables:[`session_state_heads`],columns:[],migrate:migrateSessionStateHeadLayoutV26,applied:`Stored session state heads in their composite primary-key tree (v26)`},ld={version:27,tables:[`acp_replay_events`,`skill_usage`,`state_leases`],columns:[],migrate:migrateStateWriteIndexesV27,applied:`Removed redundant replay and skill indexes and narrowed the lease-owner index (v27)`},ud={version:29,tables:ku,columns:[],migrate:()=>!1,applied:`Moved client credentials and native socket material to the local owner (v29)`},dd={version:30,tables:[],columns:[],migrate:()=>!1,applied:`Fenced ordinary automation timing and delivery policies from older schedulers (v30)`},fd=[id,ad,{migrate:migrateJsonCanonicalWideRowsV13,applied:`Consolidated shared state tables (v13)`},{migrate:migrateCronCreatorNamespaces,applied:`Qualified historical cron creator attribution as unknown (v14)`},{migrate:migrateConversationBindingTargets,applied:`Removed redundant conversation binding target projections (v15)`},{migrate:migratePreparedWorkerOwnership,applied:`Recorded prepared worker ownership and one-use lifecycle (v17)`},{migrate:migrateGitHubPublicationRequesterAuthority,applied:`Added original requester authority to GitHub publication receipts (v18)`},{migrate:migrateCronDeliveryAttemptState,applied:`Recorded cron completion delivery attempt uncertainty (v20)`},od,cd,ld,Pl,Hl,n,Ll,Yl,...Ql,$l,eu];function migrateBoundedStateSchema(e,t,r){let i=[ju,id,ad,od,sd,cd,ld,Pl,ud,dd,Hl,...Pu,n,Ll,Yl,...Ql,$l,eu].filter(({version:e})=>e>t);if(t>=40||i.length!==40-t)return;let a=new Set(i.flatMap(e=>e.tables)),o=getCanonicalSqliteNamedIndexContracts(H).filter(e=>a.has(e.tableName)),s=getOpenClawStatePredecessorSchema(t);if(!r.versionMigrationOnly&&(M(e,`cron_run_logs`)||!i.includes(Pl)&&needsPublicationDraftMigration(e)||findMissingLazyStateStartupColumn(Pt(e))!==void 0||collectSqliteSchemaIssues(e,s,{...withLegacyTemplateStateCompatibility(Xu),allowedMissingColumns:[...Xu.allowedMissingColumns??[],...i.flatMap(e=>e.columns)].map(withLegacyTemplateStateSchema),allowedMissingIndexes:[...Xu.allowedMissingIndexes??[],...o.map(e=>e.name),`idx_acp_replay_events_session_seq`,`idx_skill_usage_key`],excludedIndexes:[...Xu.excludedIndexes??[],`idx_acp_sessions_resume_agent`,`idx_acp_sessions_resume_acpx`]}).length>0))return;let c=migrateHistoricalStateImports(e,t);for(let n of i)n.migrate(e,t,r),c.push(n.applied);for(let t of o)if(M(e,t.tableName)){let n=t.unique?`CREATE UNIQUE INDEX`:`CREATE INDEX`;e.exec(`${n} IF NOT EXISTS ${t.name} ${t.definition};`)}return c}function runStateSchemaMigrationTransaction(e,t,n,r,i){return runUpdateSqliteMigration(e,t,()=>{let a=Number(e.prepare(`PRAGMA foreign_keys`).get()?.foreign_keys)===1;a&&e.exec(`PRAGMA foreign_keys = OFF;`);try{return O(e,()=>{i?.();let r=Lo(e),a=r<40?readStateSchemaPublicationBlocker(e):void 0;if(!a)return n();try{if(!M(e,`config_machine_state`))throw Error(`Shared state schema publication requires config_machine_state.`);return n()}catch(e){throw e instanceof Ri?e:new UpdateSchemaRefusalError([{kind:`state`,path:t,foundVersion:r,supportedVersion:40}],a.updaterVersion,{targetVersion:J,cause:e})}},r)}finally{a&&e.isOpen&&e.exec(`PRAGMA foreign_keys = ON;`)}})}function writeCurrentStateSchemaMetadata(e,t){let n=w(e),r=resolveStateSchemaVersionToPublish(e);Lo(e)!==r&&e.exec(`PRAGMA user_version = ${r};`),Ut(e,{userVersion:r,contentVersion:40}),A(e,n.insertInto(`schema_meta`).values({meta_key:`primary`,role:`global`,schema_version:r,agent_id:null,app_version:J,created_at:t,updated_at:t}).onConflict(e=>e.column(`meta_key`).doUpdateSet({role:`global`,schema_version:r,agent_id:null,app_version:J,updated_at:t}).where(e=>e.or([e(`schema_meta.schema_version`,`!=`,r),e(`schema_meta.app_version`,`is not`,J),e(`schema_meta.role`,`!=`,`global`)]))))}function executeCanonicalStateSchema(e,t){e.exec(getOpenClawStateRuntimeSchema({...t,includeAgentDeletionJournal:t.includeAgentDeletionJournal??M(e,`agent_deletion_journal`)}))}const pd=[`audit_events`,`audit_identity_keys`].map(e=>({name:e,sql:qr(B(H,e))})),md=[`sequence`,`event_id`,`source_id`,`source_sequence`,`occurred_at`,`kind`,`action`,`status`,`error_code`,`actor_type`,`actor_id`,`agent_id`,`session_key`,`session_id`,`run_id`,`tool_call_id`,`tool_name`],hd=[...md.flatMap(e=>e===`source_id`?[e,`schema_version`]:[e]),`direction`,`channel`,`conversation_kind`,`message_outcome`,`reason_code`,`delivery_kind`,`failure_stage`,`duration_ms`,`result_count`,`account_ref`,`conversation_ref`,`message_ref`,`target_ref`];function tableHasCanonicalColumns(e,t,n,r,i){let a=e.prepare(`PRAGMA table_info(${t})`).all(),o=a.filter(e=>Number(e.pk??0)>0);return a.length===n.length&&a.every((e,t)=>e.name===n[t])&&o.length===1&&o[0]?.name===r&&i.every(e=>a.some(t=>t.name===e&&Number(t.notnull??0)===1))}function tableSql(e,t){let n=e.prepare(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?`).get(t);return typeof n?.sql==`string`?n.sql:void 0}function tableHasUniqueColumns(e,t,n){let r=e.prepare(`PRAGMA index_list(${t})`).all();return n.every(t=>r.some(n=>{if(Number(n.unique??0)!==1||typeof n.name!=`string`)return!1;let r=n.name.replaceAll(`'`,`''`),i=e.prepare(`PRAGMA index_info('${r}')`).all();return i.length===1&&i[0]?.name===t}))}function hasCanonicalAuditEventTable(e,t,n){let r=tableSql(e,`audit_events`)?.toLowerCase();return tableHasCanonicalColumns(e,`audit_events`,t,`sequence`,n)&&typeof r==`string`&&/\bsequence\s+integer\s+primary\s+key\s+autoincrement\b/.test(r)&&tableHasUniqueColumns(e,`audit_events`,[`event_id`,`source_id`])}function hasCanonicalAuditIdentityKeyTable(e){if(!M(e,`audit_identity_keys`))return!1;let t=tableSql(e,`audit_identity_keys`)?.toLowerCase();return tableHasCanonicalColumns(e,`audit_identity_keys`,[`id`,`key_id`,`key`,`created_at`],`id`,[`id`,`key_id`,`key`,`created_at`])&&typeof t==`string`&&/\bcheck\s*\(\s*id\s*=\s*1\s*\)/.test(t)}function hasCanonicalAuditEventsSchema(e){let t=K(e);return t&&pd.every(({name:e,sql:n})=>qr(t.tableSql.get(e)??null)===n)?!0:M(e,`audit_events`)?hasCanonicalAuditEventTable(e,hd,[`event_id`,`source_id`,`schema_version`,`source_sequence`,`occurred_at`,`kind`,`action`,`status`,`actor_type`,`actor_id`])&&hasCanonicalAuditIdentityKeyTable(e):Lo(e)<2&&!M(e,`audit_identity_keys`)}function canRepairLegacyAuditEventsSchema(e){return!M(e,`audit_events`)||M(e,`audit_events_migration_new`)||P(e,`audit_events`,`schema_version`)?!1:(!M(e,`audit_identity_keys`)||hasCanonicalAuditIdentityKeyTable(e))&&hasCanonicalAuditEventTable(e,md,[`event_id`,`source_id`,`source_sequence`,`occurred_at`,`kind`,`action`,`status`,`actor_type`,`actor_id`,`agent_id`,`run_id`])}const gd=[`skill_curator_state`,`update_check_state`,`clawhub_promotions_feed_state`,`model_catalog_remote`,`voicewake_triggers`,`voicewake_routing_routes`,`voicewake_routing_config`,`onboarding_recommendations`,`cron_store_epochs`,`tui_last_sessions`,`sidebar_sections`,`node_host_config`,`web_push_vapid_keys`];function createStateConfigMachineTable(e){e.exec(`
    CREATE TABLE IF NOT EXISTS config_machine_state (
      state_key TEXT NOT NULL PRIMARY KEY,
      value_json TEXT NOT NULL,
      updated_at_ms INTEGER NOT NULL
    ) STRICT;
  `)}function migrateSingletonStateFoldInV12(e,t){if(t>=12)return!1;createStateConfigMachineTable(e);let n=e.prepare(`INSERT INTO config_machine_state (state_key, value_json, updated_at_ms) VALUES (?, ?, ?) ON CONFLICT(state_key) DO NOTHING`);if(M(e,`update_check_state`)){let t=e.prepare(`SELECT * FROM update_check_state WHERE state_key = 'default'`).get();t&&n.run(`update.checkState`,JSON.stringify({lastCheckedAt:t.last_checked_at??void 0,lastNotifiedVersion:t.last_notified_version??void 0,lastNotifiedTag:t.last_notified_tag??void 0,lastAvailableVersion:t.last_available_version??void 0,lastAvailableTag:t.last_available_tag??void 0,autoInstallId:t.auto_install_id??void 0,autoFirstSeenVersion:t.auto_first_seen_version??void 0,autoFirstSeenTag:t.auto_first_seen_tag??void 0,autoFirstSeenAt:t.auto_first_seen_at??void 0,autoLastAttemptVersion:t.auto_last_attempt_version??void 0,autoLastAttemptAt:t.auto_last_attempt_at??void 0,autoLastSuccessVersion:t.auto_last_success_version??void 0,autoLastSuccessAt:t.auto_last_success_at??void 0}),Number(t.updated_at_ms))}if(M(e,`voicewake_triggers`)){let t=e.prepare(`SELECT trigger, updated_at_ms FROM voicewake_triggers WHERE config_key = 'default' ORDER BY position`).all();t.length>0&&n.run(`voicewake.triggers`,JSON.stringify(t.map(e=>e.trigger)),Math.max(...t.map(e=>Number(e.updated_at_ms))))}if(M(e,`voicewake_routing_config`)){let t=e.prepare(`SELECT * FROM voicewake_routing_config WHERE config_key = 'default'`).get();if(t){let r=M(e,`voicewake_routing_routes`)?e.prepare(`SELECT trigger, target_mode, target_agent_id, target_session_key FROM voicewake_routing_routes WHERE config_key = 'default' ORDER BY position`).all():[],targetFromColumns=(e,t,n)=>e===`agent`&&typeof t==`string`&&t?{agentId:t}:e===`session`&&typeof n==`string`&&n?{sessionKey:n}:{mode:`current`};n.run(`voicewake.routing`,JSON.stringify({version:1,defaultTarget:targetFromColumns(t.default_target_mode,t.default_target_agent_id,t.default_target_session_key),routes:r.map(e=>({trigger:e.trigger,target:targetFromColumns(e.target_mode,e.target_agent_id,e.target_session_key)})),updatedAtMs:t.updated_at_ms}),Number(t.updated_at_ms))}}if(M(e,`onboarding_recommendations`)){let t=e.prepare(`SELECT * FROM onboarding_recommendations`).all();for(let e of t)n.run(`onboarding.recommendations.${String(e.config_key)}`,JSON.stringify({inventoryHash:e.inventory_hash,matches:JSON.parse(String(e.matches_json)),offeredAt:e.offered_at_ms,acceptedAt:e.accepted_at_ms,updatedAt:e.updated_at_ms}),Number(e.updated_at_ms))}if(M(e,`sidebar_sections`)){let t=e.prepare(`SELECT section_id FROM sidebar_sections ORDER BY position, section_id`).all();t.length>0&&n.run(`sidebar.sectionOrder`,JSON.stringify(t.map(e=>e.section_id)),Date.now())}if(M(e,`node_host_config`)){let t=e.prepare(`SELECT * FROM node_host_config WHERE config_key = 'current'`).get();if(t){let e={host:t.gateway_host??void 0,port:t.gateway_port??void 0,tls:t.gateway_tls==null?void 0:t.gateway_tls===1,tlsFingerprint:t.gateway_tls_fingerprint??void 0,contextPath:t.gateway_context_path??void 0,cloudflareAccess:t.gateway_cloudflare_access_json==null?void 0:JSON.parse(String(t.gateway_cloudflare_access_json))};n.run(`nodeHost.config`,JSON.stringify({version:t.version,nodeId:t.node_id,...t.display_name==null?{}:{displayName:t.display_name},gateway:Object.values(e).some(e=>e!==void 0)?e:void 0,installedAppsSharing:t.installed_apps_sharing===1}),Number(t.updated_at_ms))}}if(M(e,`web_push_vapid_keys`)){let t=e.prepare(`SELECT * FROM web_push_vapid_keys WHERE key_id = 'default'`).get();t&&n.run(`webPush.vapidKeys`,JSON.stringify({publicKey:t.public_key,privateKey:t.private_key,subject:t.subject}),Number(t.updated_at_ms))}let r=!1;for(let t of gd)M(e,t)&&(e.exec(`DROP TABLE IF EXISTS ${t};`),r=!0);return r}const _d=`explicit`,vd=`ambient-group`,yd=`provenance TEXT NOT NULL DEFAULT '${_d}' CHECK (provenance IN ('${_d}', '${vd}'))`;function getSessionWatchCursorKysely(e){return w(e)}function decodeLegacyAmbientWatchMarkerKey(e){let t=e.slice(20);if(t&&t.length%2==0&&/^[0-9a-f]+$/.test(t))try{return new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(Buffer.from(t,`hex`))}catch{return}}function migrateSessionWatchCursorProvenance(e){if(!M(e,`session_watch_cursors`))return{migratedAmbientWatches:0,removedLegacySentinels:0};k(e,`session_watch_cursors`,yd);let t=getSessionWatchCursorKysely(e),n=A(e,t.selectFrom(`session_watch_cursors`).select([`watcher_session_key`,`target_session_key`,`updated_at`]).where(`watcher_session_key`,`>=`,`ambient-group-watch:`).where(`watcher_session_key`,`<`,`ambient-group-watch;`)).rows,r=0;for(let i of n){let n=decodeLegacyAmbientWatchMarkerKey(i.watcher_session_key);if(n){let a=C(e,t.selectFrom(`session_watch_cursors`).select(`updated_at`).where(`watcher_session_key`,`=`,n).where(`target_session_key`,`=`,i.target_session_key));if(a){let o=A(e,t.updateTable(`session_watch_cursors`).set({provenance:vd,updated_at:Math.max(a.updated_at,i.updated_at)}).where(`watcher_session_key`,`=`,n).where(`target_session_key`,`=`,i.target_session_key));r+=Number(o.numAffectedRows??0n)}}A(e,t.deleteFrom(`session_watch_cursors`).where(`watcher_session_key`,`=`,i.watcher_session_key).where(`target_session_key`,`=`,i.target_session_key))}return{migratedAmbientWatches:r,removedLegacySentinels:n.length}}const bd=`
  id TEXT NOT NULL PRIMARY KEY,
  agent_id TEXT NOT NULL,
  session_key TEXT NOT NULL,
  channel TEXT NOT NULL,
  account_id TEXT,
  recipient_id TEXT,
  thread_id TEXT,
  sender_id TEXT,
  kind TEXT NOT NULL,
  sensitivity TEXT NOT NULL,
  source TEXT NOT NULL,
  status TEXT NOT NULL,
  reason TEXT NOT NULL,
  suggested_text TEXT NOT NULL,
  dedupe_key TEXT NOT NULL,
  confidence REAL NOT NULL,
  due_earliest_ms INTEGER NOT NULL,
  due_latest_ms INTEGER NOT NULL,
  due_timezone TEXT NOT NULL,
  source_message_id TEXT,
  source_run_id TEXT,
  created_at_ms INTEGER NOT NULL,
  updated_at_ms INTEGER NOT NULL,
  attempts INTEGER NOT NULL,
  last_attempt_at_ms INTEGER,
  sent_at_ms INTEGER,
  dismissed_at_ms INTEGER,
  snoozed_until_ms INTEGER,
  expired_at_ms INTEGER,
  record_json TEXT NOT NULL
`,xd=`CREATE INDEX idx_commitments_scope_due
  ON commitments(agent_id, session_key, status, due_earliest_ms, due_latest_ms);
CREATE INDEX idx_commitments_status_due
  ON commitments(status, due_earliest_ms, due_latest_ms);
CREATE INDEX idx_commitments_scope_dedupe
  ON commitments(agent_id, session_key, channel, dedupe_key, status);`,Sd=`
CREATE TABLE commitments (${bd.slice(1,-1)}
) STRICT;
${xd}
CREATE INDEX idx_commitments_agent_due
  ON commitments(agent_id, status, due_earliest_ms, due_latest_ms, session_key);
CREATE INDEX idx_commitments_agent_sent
  ON commitments(agent_id, status, sent_at_ms, session_key);
`,Cd=`
CREATE TABLE commitments (${bd.slice(1,-1)}
);
${xd}
`,wd=er(`state/db`),logRetiredStateTableMigration=e=>wd.info(e),Td=[`agent_model_catalogs`,`android_notification_recent_packages`,`command_log_entries`,`diagnostic_stability_bundles`,`media_blobs`,`model_capability_cache`],Ed=[`commitments.account_id`,`commitments.recipient_id`,`commitments.thread_id`,`commitments.sender_id`,`commitments.kind`,`commitments.sensitivity`,`commitments.source`,`commitments.reason`,`commitments.suggested_text`,`commitments.dedupe_key`,`commitments.confidence`,`commitments.due_timezone`,`commitments.source_message_id`,`commitments.source_run_id`,`commitments.created_at_ms`,`commitments.attempts`,`commitments.last_attempt_at_ms`,`commitments.sent_at_ms`,`commitments.dismissed_at_ms`,`commitments.snoozed_until_ms`,`commitments.expired_at_ms`];function deriveRetiredCommitmentsContract(){let e=new Map(getCanonicalSqliteNamedIndexContracts(Sd).map(({fingerprint:e,name:t})=>[t,JSON.stringify(e)]));return{indexFingerprints:e,compatibility:{allowedColumnDefinitions:{"commitments.attempts":[`attempts INTEGER NOT NULL DEFAULT 0`],"commitments.confidence":[`confidence REAL NOT NULL DEFAULT 0`],"commitments.created_at_ms":[`created_at_ms INTEGER NOT NULL DEFAULT 0`],"commitments.dedupe_key":[`dedupe_key TEXT NOT NULL DEFAULT ''`],"commitments.due_timezone":[`due_timezone TEXT NOT NULL DEFAULT 'UTC'`],"commitments.kind":[`kind TEXT NOT NULL DEFAULT 'followup'`],"commitments.reason":[`reason TEXT NOT NULL DEFAULT ''`],"commitments.sensitivity":[`sensitivity TEXT NOT NULL DEFAULT 'normal'`],"commitments.source":[`source TEXT NOT NULL DEFAULT 'unknown'`],"commitments.suggested_text":[`suggested_text TEXT NOT NULL DEFAULT ''`]},allowedMissingColumns:Ed,allowedMissingIndexes:[...e.keys()]}}}function hasSupportedRetiredCommitmentsSchema(e,t,{compatibility:n,indexFingerprints:r}){return collectSqliteSchemaIssues(e,t,n).length>0?!1:e.prepare(`SELECT type, name
           FROM sqlite_schema
          WHERE type IN ('index', 'trigger')
            AND tbl_name = 'commitments'
            AND sql IS NOT NULL
          ORDER BY type, name`).all().every(t=>t.type===`index`&&JSON.stringify(collectSqliteNamedIndexContract(e,t.name))===r.get(t.name))}function assertRecognizedRetiredCommitmentsSchema(e){if(!hasRecognizedRetiredCommitmentsSchema(e))throw assertSqliteSchemaContains(e,`retired OpenClaw commitments schema`,Sd,deriveRetiredCommitmentsContract().compatibility),Error(`Retired OpenClaw commitments schema has unsupported additional indexes; refusing destructive migration.`)}function hasRecognizedRetiredCommitmentsSchema(e){let t=deriveRetiredCommitmentsContract();return hasSupportedRetiredCommitmentsSchema(e,Sd,t)||hasSupportedRetiredCommitmentsSchema(e,Cd,t)}function assertNoRetiredCommitmentsForeignKeys(e){let t=e.prepare(`SELECT name
         FROM sqlite_schema
        WHERE type = 'table' AND name <> 'commitments'
        ORDER BY name`).all();for(let n of t)if(e.prepare(`PRAGMA foreign_key_list(${W(n.name)})`).all().some(e=>typeof e.table==`string`&&e.table.toLowerCase()===`commitments`))throw Error(`Retired OpenClaw commitments schema is referenced by table ${n.name}; refusing destructive migration.`)}function collectRetainedSchemaSql(e){return new Map(e.prepare(`SELECT type, name, sql
             FROM sqlite_schema
            WHERE type IN ('trigger', 'view')
              AND tbl_name <> 'commitments'
              AND sql IS NOT NULL
            ORDER BY type, name`).all().map(e=>[`${e.type}:${e.name}`,e.sql]))}function assertNoRetiredCommitmentsSchemaDependencies(e){let t=`__openclaw_retired_commitments_probe`;if(M(e,t))throw Error(`OpenClaw state database already contains ${t}; refusing destructive migration.`);let n=collectRetainedSchemaSql(e),r=`openclaw_probe_commitments_dependencies`;e.exec(`SAVEPOINT ${r};`);let i;try{e.exec(`ALTER TABLE commitments RENAME TO ${W(t)};`);let r=collectRetainedSchemaSql(e);i=[...n].find(([e,t])=>r.get(e)!==t)?.[0]}catch(t){throw e.exec(`ROLLBACK TO ${r}; RELEASE ${r};`),Error(`Could not prove retained SQLite views and triggers independent of commitments; refusing destructive migration.`,{cause:t})}if(e.exec(`ROLLBACK TO ${r}; RELEASE ${r};`),i){let[e,t]=i.split(`:`,2);throw Error(`Retired OpenClaw commitments schema is referenced by ${e} ${t}; refusing destructive migration.`)}}function assertVirtualTablesUsable(e,t){let n=e.prepare(`SELECT name
         FROM sqlite_schema
        WHERE type = 'table' AND lower(sql) LIKE 'create virtual table%'
        ORDER BY name`).all();for(let r of n)try{e.prepare(`SELECT * FROM ${W(r.name)} LIMIT 1`).all()}catch(e){throw Error(`SQLite virtual table ${r.name} is unusable ${t} commitments retirement.`,{cause:e})}}function migrateRetiredCommitmentsSchema(e,t){if(t>=7||!M(e,`commitments`))return!1;assertRecognizedRetiredCommitmentsSchema(e),assertNoRetiredCommitmentsForeignKeys(e),assertNoRetiredCommitmentsSchemaDependencies(e),assertVirtualTablesUsable(e,`before`);let n=`openclaw_retire_commitments_v7`;e.exec(`SAVEPOINT ${n};`);try{return e.exec(`DROP TABLE commitments;`),assertVirtualTablesUsable(e,`after`),e.exec(`RELEASE ${n};`),!0}catch(t){throw e.exec(`ROLLBACK TO ${n}; RELEASE ${n};`),t}}function migrateRetiredDeadStateTablesV10(e,t){if(t>=10)return!1;let n=!1;for(let t of Td)M(e,t)&&(e.exec(`DROP TABLE IF EXISTS ${t};`),n=!0);return n}const Dd=[`skill_lifecycle`,`skill_workshop_proposal_origin_runs`];function migrateRetiredSkillCuratorTablesV11(e,t){if(t>=11)return!1;let n=Dd.filter(t=>M(e,t));if(n.length===0)return!1;if(n.includes(`skill_lifecycle`)){let t=Number(e.prepare(`SELECT COUNT(*) AS archived_count FROM skill_lifecycle WHERE state = 'archived'`).get()?.archived_count);t>0&&wd.info(`${t} previously archived workshop skills are live again; archive any you no longer want`)}for(let t of n)e.exec(`DROP TABLE IF EXISTS ${t};`);return!0}function runRetiredStateTableMigrations(e,t){let n=[];return migrateRetiredCommitmentsSchema(e,t)&&n.push(`Discarded retired shared-state commitments rows, table, and indexes`),migrateRetiredDeadStateTablesV10(e,t)&&n.push(`Retired six dead shared-state tables (v10)`),migrateRetiredSkillCuratorTablesV11(e,t)&&n.push(`Retired legacy skill curator lifecycle and proposal origin-run tables`),n}[...gd],[...Ru],[...Ul.flat()],H.split(`
`).flatMap(e=>{let t=/^CREATE TABLE IF NOT EXISTS (\w+) \(/u.exec(e)?.[1];return t?[t]:[]});function dropLegacyStateTables(e){e.exec(`DROP TABLE IF EXISTS database_verifications;`),e.exec(`DROP TABLE IF EXISTS node_pairing_pending; DROP TABLE IF EXISTS node_pairing_paired;`)}function migrateWorkerPlacementExecutionModeSchema(e,t){if(t>=8||!M(e,`worker_session_placements`))return!1;for(let t of[`execution_mode TEXT`,`terminal_reason TEXT`,`terminal_at_ms INTEGER`])k(e,`worker_session_placements`,t);let n=B(H,`worker_session_placements`,{errorMessage:`Canonical worker placement schema block is missing`}),r=Ga(`:memory:`),i;try{r.exec(n),i=r.prepare(`PRAGMA table_xinfo(worker_session_placements)`).all().filter(e=>e.hidden===0).map(e=>e.name)}finally{r.close()}let a=e.prepare(`PRAGMA table_xinfo(worker_session_placements)`).all().filter(e=>e.hidden===0).map(e=>e.name),o=new Set(i);if(a.length!==i.length||a.some(e=>!o.has(e)))throw Error(`OpenClaw v7 worker placement columns are not canonical`);if(e.prepare(`SELECT type, name
         FROM sqlite_schema
        WHERE tbl_name = 'worker_session_placements'
          AND type IN ('index', 'trigger')
          AND sql IS NOT NULL
          AND name NOT IN (
            'idx_worker_session_placements_session_key',
            'idx_worker_session_placements_reconcile',
            'idx_worker_session_placements_environment'
          )`).all().length>0)throw Error(`OpenClaw v7 worker placement schema has unsupported attached objects`);let s=`worker_session_placements_migration_v8`;if(M(e,s))throw Error(`OpenClaw worker placement migration table already exists: ${s}`);let c=n.replace(`CREATE TABLE IF NOT EXISTS worker_session_placements`,`CREATE TABLE ${s}`),l=i.map(W).join(`, `);return e.exec(c),e.exec(`INSERT INTO ${s} (${l}) SELECT ${l} FROM worker_session_placements;`),e.exec(`DROP TABLE worker_session_placements;`),e.exec(`ALTER TABLE ${s} RENAME TO worker_session_placements;`),!0}function isDefaultAgentDatabasePath(e,t){let n=X.dirname(e),r=X.dirname(n);return X.basename(e)===`openclaw-agent.sqlite`&&X.basename(n)===`agent`&&X.basename(r)===t&&X.basename(X.dirname(r))===`agents`}function migrateAgentDatabaseRelativePaths(e,t,n){if(t>=9||!M(e,`agent_databases`))return{relativized:0,reanchored:[],deleted:[],preserved:0};let r=e.prepare(`SELECT agent_id, path FROM agent_databases`).all(),i=e.prepare(`UPDATE agent_databases SET path = ? WHERE agent_id = ? AND path = ?`),a=e.prepare(`DELETE FROM agent_databases WHERE agent_id = ? AND path = ?`),o=e.prepare(`SELECT 1 FROM agent_databases WHERE agent_id = ? AND path = ? LIMIT 1`),s=e.prepare(`
    UPDATE agent_databases AS canonical
       SET schema_version = source.schema_version,
           last_seen_at = source.last_seen_at,
           size_bytes = source.size_bytes
      FROM agent_databases AS source
     WHERE canonical.agent_id = ? AND canonical.path = ?
       AND source.agent_id = canonical.agent_id AND source.path = ?
       AND source.last_seen_at > canonical.last_seen_at
  `),c=0,l=[],u=[];for(let e of r){let t=e.agent_id,r=e.path;if(typeof t!=`string`||typeof r!=`string`)throw Error(`OpenClaw v8 agent database registry paths are not canonical`);if(!X.isAbsolute(r))continue;let l=Yo(n,r);X.isAbsolute(l)||(o.get(t,l)?(s.run(t,l,r),a.run(t,r),u.push(r)):(i.run(l,t,r),c+=1))}let d=is(n);for(let e of r){let t=e.agent_id,r=e.path;if(typeof t==`string`&&typeof r==`string`&&X.isAbsolute(r)&&X.isAbsolute(Yo(n,r))&&isDefaultAgentDatabasePath(X.resolve(r),t)){let e=X.join(d,`agents`,t,`agent`,`openclaw-agent.sqlite`),s=Yo(n,e);o.get(t,s)?(a.run(t,r),u.push(r)):Ks(e)&&(i.run(s,t,r),l.push(r))}}return{relativized:c,reanchored:l,deleted:u,preserved:r.length-c-l.length-u.length}}function assertCanonicalAgentDatabasesPrimaryKey(e,t){if(!M(e,`agent_databases`))return;let n=$e(e,`agent_databases`);if(n.length!==2||n[0]!==`agent_id`||n[1]!==`path`)throw new N(`OpenClaw state database ${t} has an unsupported agent database registry schema. Upgrades from pre-July-2026 state are no longer migrated; restore a backup produced by a July 2026 or newer release before retrying.`)}function repairLegacyGatewayRestartHandoffsForStrictMigration(e){M(e,`gateway_restart_handoff`)&&(e.prepare(`DELETE FROM gateway_restart_handoff WHERE expires_at <= ?`).run(Date.now()),e.exec(`
    UPDATE gateway_restart_handoff
    SET
      restart_trace_started_at = CASE
        WHEN typeof(restart_trace_started_at) = 'real'
          THEN CAST(restart_trace_started_at AS INTEGER)
        ELSE restart_trace_started_at
      END,
      restart_trace_last_at = CASE
        WHEN typeof(restart_trace_last_at) = 'real'
          THEN CAST(restart_trace_last_at AS INTEGER)
        ELSE restart_trace_last_at
      END
    WHERE typeof(restart_trace_started_at) = 'real'
       OR typeof(restart_trace_last_at) = 'real';
  `))}function assertCanonicalStateSchemaShape(e,t){if(assertCanonicalOperatorApprovalKinds(e,t),assertCanonicalAgentDatabasesPrimaryKey(e,t),!hasCanonicalAuditEventsSchema(e))throw canRepairLegacyAuditEventsSchema(e)?new Co(`audit-events-v2`,t):new N(`OpenClaw state database ${t} has a noncanonical audit event schema that cannot be repaired automatically; restore the canonical audit_events shape before retrying.`)}function assertCurrentStateRuntimeSchema(e,t,n=Pt(e)){let r=findMissingLazyStateStartupColumn(n);r&&je(t,[`missing column `+r.tableName+`.`+r.columnName]),assertCanonicalStateSchemaShape(e,t),assertOpenClawStateDatabaseForMaintenance(e,{pathname:t},n),assertSqliteSchemaContains(e,t,H,Xu,n)}function assertNoLegacyStateRuntimeRepair(e,t){if(hasLegacyCronRunLogs(e))throw new Co(`legacy-cron-run-logs`,t)}function isOpenClawStateSchemaFastPathEligible(e,t,n){let r=we(e);if(r)return r.startupReady;let i,a=ra(e,()=>Vt(e,()=>{let r=assertSupportedStateSchemaVersion(e,t);if(readStateSchemaContentVersion(e)!==40)return!1;let a=readSqliteSchemaCookie(e);if(typeof a!=`number`)throw Error(`Shared-state database ${t} schema version is unavailable.`);assertCurrentStateRuntimeSchema(e,t,Pt(e)),assertNoLegacyStateRuntimeRepair(e,t);let o=readGatewayOwnerLeaseFromDatabase(e);return o?.state===`live`&&o.pid!==process.pid&&o.stateDatabaseProvenance&&o.stateDatabaseProvenance===readAgentDatabaseLeaseProvenance(t)||(i=ut(e,t,{schemaVersion:a,userVersion:r},n)),!0},{operationLabel:`state.admission.fast-path`}));return i?.(),a&&at(e,!0),a}function assertExistingOpenClawStateRuntimeMetadata(e,n,r){if(we(e)){let n=t(e)?.userVersion;if(n!==void 0)return n}let i=assertSupportedStateSchemaVersion(e,n,void 0,void 0,r);if(readStateSchemaContentVersion(e)!==40)throw Error(`Existing shared-state database ${n} requires schema migration by its owning installation; run openclaw doctor --fix there before using it.`);let a;try{a=C(e,w(e).selectFrom(`schema_meta`).select([`role`,`schema_version`]).where(`meta_key`,`=`,`primary`).limit(1))}catch(t){throw pt(e,`schema_meta`,[`meta_key`,`role`,`schema_version`],t)}if(a?.role!==`global`||a.schema_version!==i)throw Error(`Existing shared-state database ${n} has inconsistent ownership or schema metadata.`);return i}function assertExistingOpenClawStateRuntimeSchema(e,t,n,r,i=`runtime`){let a=we(e)?K(e):void 0;if(a){ut(e,t,a,n,r)?.();return}let o;Ct(e,()=>{let a=assertExistingOpenClawStateRuntimeMetadata(e,t,i),s=readSqliteSchemaCookie(e);if(typeof s!=`number`)throw Error(`Existing shared-state database ${t} schema version is unavailable.`);o=ut(e,t,{schemaVersion:s,userVersion:a},n,r),assertCurrentStateRuntimeSchema(e,t,Pt(e)),assertNoLegacyStateRuntimeRepair(e,t)},{operationLabel:`state.admission.existing-schema`}),o?.(),at(e,!0)}function assertStateDatabaseSchemaAdmission(e){if(T(e.path,e.db)){let t=m(e.db)?.canonicalPath;if(!t)throw Error(`Existing shared-state schema admission requires a filesystem-backed database.`);if(!T(t,e.db))throw Error(`Existing shared-state schema admission requires its selected physical database.`);if(z(e.db)){assertSupportedStateSchemaVersion(e.db,e.path);return}assertExistingOpenClawStateRuntimeSchema(e.db,e.path)}}function chunkItems(e,t){if(t<=0)return[Array.from(e)];let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}const Od=Buffer.from(`302a300506032b6570032100`,`hex`),kd=Buffer.from(`302e020100300506032b657004220420`,`hex`);function pemEncode(e,t){return`-----BEGIN ${e}-----\n${t.toString(`base64`).match(/.{1,64}/g)?.join(`
`)??``}\n-----END ${e}-----\n`}function decodeCanonicalPem(e,t){let n=`-----BEGIN ${e}-----\n`,r=`\n-----END ${e}-----\n`;if(!t.startsWith(n)||!t.endsWith(r))throw Error(`${e} must use canonical PEM framing`);let i=t.slice(n.length,-r.length);if(!i||!/^[A-Za-z0-9+/=\n]+$/.test(i))throw Error(`${e} contains invalid PEM body bytes`);let a=Buffer.from(i.replaceAll(`
`,``),`base64`);if(pemEncode(e,a)!==t)throw Error(`${e} must use canonical PEM base64 encoding`);return a}function assertEd25519KeyType(e,t){if(e.asymmetricKeyType!==`ed25519`)throw Error(`${t} must be an Ed25519 key`)}function deriveRawKeyFromDer(e,t,n){let r=n.length+32;if(e.length!==r||!e.subarray(0,n.length).equals(n))throw Error(`${t} has a noncanonical Ed25519 encoding`);return e.subarray(n.length)}function deriveCanonicalEd25519PublicKeyRaw(e){let t=decodeCanonicalPem(`PUBLIC KEY`,e);return assertEd25519KeyType(tc.createPublicKey({key:t,type:`spki`,format:`der`}),`public key`),deriveRawKeyFromDer(t,`public key`,Od)}function deriveCanonicalEd25519PrivateKeyRaw(e){let t=decodeCanonicalPem(`PRIVATE KEY`,e);return assertEd25519KeyType(tc.createPrivateKey({key:t,type:`pkcs8`,format:`der`}),`private key`),deriveRawKeyFromDer(t,`private key`,kd)}var DeviceIdentityStorageError=class extends Error{constructor(e,t){super(e,t),this.name=`DeviceIdentityStorageError`}};function invalidStoredIdentityError(e,t){return new DeviceIdentityStorageError(`SQLite contains an invalid persisted device identity "${e}". Run "openclaw doctor --fix" before starting the gateway or connecting this client.`,t===void 0?void 0:{cause:t})}function fingerprintPublicKey(e){let t=deriveCanonicalEd25519PublicKeyRaw(e);return tc.createHash(`sha256`).update(t).digest(`hex`)}function keyPairMatches(e,t){try{return deriveCanonicalEd25519PublicKeyRaw(e),deriveCanonicalEd25519PrivateKeyRaw(t),tc.createPublicKey(t).export({type:`spki`,format:`pem`})===e}catch{return!1}}function parseCreatedAtMs(e){return Jn(e,{min:0})??null}function validateStoredDeviceIdentity(e,t=`primary`){try{if(!e.deviceId||!/^[a-f0-9]{64}$/.test(e.deviceId)||!e.publicKeyPem||!e.privateKeyPem||parseCreatedAtMs(e.createdAtMs)===null||!keyPairMatches(e.publicKeyPem,e.privateKeyPem)||fingerprintPublicKey(e.publicKeyPem)!==e.deviceId)throw invalidStoredIdentityError(t);return{deviceId:e.deviceId,publicKeyPem:e.publicKeyPem,privateKeyPem:e.privateKeyPem}}catch(e){throw e instanceof DeviceIdentityStorageError?e:invalidStoredIdentityError(t,e)}}function storedDeviceIdentityFromRow(e,t){if(e.identity_key!==t||typeof e.device_id!=`string`||typeof e.public_key_pem!=`string`||typeof e.private_key_pem!=`string`||parseCreatedAtMs(e.created_at_ms)===null||parseCreatedAtMs(e.updated_at_ms)===null)throw invalidStoredIdentityError(t);let n={deviceId:e.device_id,publicKeyPem:e.public_key_pem,privateKeyPem:e.private_key_pem,createdAtMs:e.created_at_ms};return validateStoredDeviceIdentity(n,t),n}function salvageStoredIdentityRow(e,t,n){if(e.identity_key!==t||typeof e.public_key_pem!=`string`||typeof e.private_key_pem!=`string`)return null;try{let r=tc.createPublicKey(e.public_key_pem),i=tc.createPrivateKey(e.private_key_pem);if(r.asymmetricKeyType!==`ed25519`||i.asymmetricKeyType!==`ed25519`)return null;let a=r.export({type:`spki`,format:`pem`}),o=i.export({type:`pkcs8`,format:`pem`});if(tc.createPublicKey(o).export({type:`spki`,format:`pem`})!==a)return null;let s=parseCreatedAtMs(e.created_at_ms)??parseCreatedAtMs(e.updated_at_ms)??n,c={deviceId:fingerprintPublicKey(a),publicKeyPem:a,privateKeyPem:o,createdAtMs:s};return validateStoredDeviceIdentity(c,t),c}catch{return null}}function storedDeviceIdentityToRow(e,t,n=t.createdAtMs){return{identity_key:e,device_id:t.deviceId,public_key_pem:t.publicKeyPem,private_key_pem:t.privateKeyPem,created_at_ms:t.createdAtMs,updated_at_ms:n}}const Ad=Se([`allowlist`,`full`,`deny`]),jd=Se([`always`,`off`,`on-miss`]),Md=Le({security:Ad.optional(),ask:jd.optional(),askFallback:Ad.optional(),autoAllowSkills:fe().optional()});function normalizePersistedAllowlistSource(e){return e===`allow-always`?e:void 0}const Nd=Le({pattern:S().refine(e=>e.trim().length>0),id:S().min(1),source:s(`allow-always`).optional(),commandText:re().optional(),argPattern:S().optional(),lastUsedAt:Pe().finite().optional(),lastUsedCommand:S().optional(),lastResolvedPath:S().optional()}),Pd=Lt([S().trim().min(1),Nd.extend({id:S().optional(),source:S().transform(normalizePersistedAllowlistSource).optional(),commandText:S().optional()})]).transform(e=>typeof e==`string`?{pattern:e}:e);function createExecApprovalsSchema(e,t){let n=Md.extend({allowlist:oe(e).optional(),mcpTools:oe(Le({server:S().refine(e=>e.trim().length>0),tool:S().refine(e=>e.trim().length>0),source:s(`allow-always`),addedAt:Pe().finite().nonnegative(),lastUsedAt:Pe().finite().nonnegative().optional()})).optional()}),r=ce().refine(e=>!I(e)||!Object.hasOwn(e,`__proto__`)).pipe(x(S(),n)).refine(e=>t||!Object.hasOwn(e,`default`));return Le({version:s(1),socket:Le({path:S().optional(),token:S().optional()}).optional(),defaults:Md.optional(),agents:r.optional()})}createExecApprovalsSchema(Nd,!1),createExecApprovalsSchema(Pd,!0);function stripExecApprovalsRawSocketCredentials(e){let t;try{t=JSON.parse(e)}catch{return e}if(!I(t)||!I(t.socket)||!Object.hasOwn(t.socket,`path`)&&!Object.hasOwn(t.socket,`token`))return e;let{path:n,token:r,...i}=t.socket;return Object.keys(i).length?t.socket=i:delete t.socket,`${JSON.stringify(t,null,2)}\n`}function resolveClientCredentialLegacyImportClaims(e,t){let n={};for(let e of t.identities)(e.identity_key===`primary`||e.identity_key===`node`||e.identity_key===`shareExtension`)&&(n[`identity:${e.identity_key}`]={sha256:null},t.authTablePresent&&(n[`auth:${e.identity_key}`]={sha256:null}));return!t.nativeBootstrap&&M(e,`migration_sources`)&&e.prepare(`SELECT 1 FROM migration_sources WHERE migration_kind = 'legacy-device-identity-json' LIMIT 1`).get()&&(n[`identity:primary`]={sha256:null}),n}function sourceRows(e,t){let n=w(e),r={identities:t&&!M(e,`device_identities`)?[]:A(e,n.selectFrom(`device_identities`).selectAll()).rows,tokens:t&&!M(e,`device_auth_tokens`)?[]:A(e,n.selectFrom(`device_auth_tokens`).selectAll()).rows,origins:t&&!M(e,`gateway_origin_device_tokens`)?[]:A(e,n.selectFrom(`gateway_origin_device_tokens`).selectAll()).rows,approvals:t&&!M(e,`exec_approvals_config`)?[]:A(e,n.selectFrom(`exec_approvals_config`).selectAll()).rows},compare=(e,t)=>Buffer.compare(Buffer.from(e),Buffer.from(t));return r.identities.sort((e,t)=>compare(e.identity_key,t.identity_key)),r.tokens.sort((e,t)=>compare(e.device_id,t.device_id)||compare(e.role,t.role)),r.origins.sort((e,t)=>compare(e.gateway_scope,t.gateway_scope)||compare(e.device_id,t.device_id)||compare(e.role,t.role)),r.approvals.sort((e,t)=>compare(e.config_key,t.config_key)),r}function validateSource(e,t=`require-valid`){if(t===`require-valid`){for(let t of e.identities)if(validateStoredDeviceIdentity({deviceId:t.device_id,publicKeyPem:t.public_key_pem,privateKeyPem:t.private_key_pem,createdAtMs:t.created_at_ms},t.identity_key),!Number.isSafeInteger(t.updated_at_ms)||t.updated_at_ms<0)throw Error(`Client credential migration found an invalid identity timestamp.`)}for(let t of[...e.tokens,...e.origins]){let e;try{e=JSON.parse(t.scopes_json)}catch{throw Error(`Client credential migration found invalid token scopes.`)}if(!Array.isArray(e)||!e.every(e=>typeof e==`string`)||!Number.isSafeInteger(t.updated_at_ms)||t.updated_at_ms<0)throw Error(`Client credential migration found an invalid token record.`)}if(e.approvals.some(e=>e.config_key!==`current`)||e.approvals.length>1)throw Error(`Client credential migration found a noncanonical approval singleton.`)}function hashClientCredentialRows(e,t){return nc(`sha256`).update(stableStringify(t?{authTablePresent:t.authTablePresent,identities:e.identities,tokens:e.tokens}:e)).digest(`hex`)}function extractSocket(e){if(!e)return{socket:void 0,policy:void 0};let invalid=()=>Object.assign(/* @__PURE__ */ Error(`Client credential migration found invalid socket credentials or projections.`),{code:`CLIENT_CREDENTIAL_SOCKET_INVALID`}),t;try{t=JSON.parse(e.raw_json)}catch{throw Error(`Client credential migration found invalid approval JSON.`)}let n=I(t)?t.socket:void 0;if(n!==void 0&&!I(n))throw invalid();let r=I(n)?n.path:void 0,i=I(n)?n.token:void 0;if(r!==void 0&&typeof r!=`string`||i!==void 0&&typeof i!=`string`)throw invalid();return r===void 0&&i===void 0?{socket:void 0,policy:e.raw_json}:{socket:{socket_key:`current`,socket_path:r??null,socket_token:i??null,updated_at_ms:e.updated_at_ms},policy:stripExecApprovalsRawSocketCredentials(e.raw_json)}}function resolveClientCredentialStorePath(e){return X.join(Cn(e),`client`,`credentials.sqlite`)}function resolveStateClientCredentialEnvironment(e){let t=wo({path:e.path}),n={...e.env,OPENCLAW_STATE_DIR:is(t)};return t===Do(n)?n:void 0}const Fd=[`identity:primary`,`identity:node`,`identity:shareExtension`,`auth:primary`,`auth:node`,`auth:shareExtension`];function readClientCredentialFileIdentity(e){let t=Y.statSync(e,{bigint:!0,throwIfNoEntry:!1});if(!t){if(h.some(t=>Y.existsSync(`${e}${t}`)))throw Error(`Client credential source is unavailable; restore the matching main database before using this client.`);return null}if(!t.isFile())throw Error(`Client credential source is not a regular file.`);return{path:Y.realpathSync.native(e),dev:String(t.dev),ino:String(t.ino)}}function emptyClientCredentialReceipt(e=null){return{format:1,source:null,sharedFile:e,legacyImports:{}}}function digest(e){return typeof e==`string`&&/^[a-f0-9]{64}$/u.test(e)}function parseClientCredentialReceipt(e,t){let invalid=()=>/* @__PURE__ */ Error(`Client credential migration receipt is invalid; run openclaw doctor --fix.`),n;try{n=JSON.parse(e)}catch{throw invalid()}if(!I(n)||n.format!==1||!I(n.legacyImports))throw invalid();let r=null;if(n.source!==null){let e=n.source;if(!I(e)||e.kind!==`canonical`&&e.kind!==`independent`||e.engine!==`sqlite`&&e.engine!==`postgres`&&e.engine!==`native-v0`||typeof e.identity!=`string`||e.identity.length===0||typeof e.generation!=`string`||e.generation.length===0||!digest(e.sha256)||e.destinationVersion!==1)throw invalid();r={kind:e.kind,engine:e.engine,identity:e.identity,generation:e.generation,sha256:e.sha256,destinationVersion:e.destinationVersion}}let i=null;if(n.sharedFile!==null){let e=n.sharedFile;if(!I(e)||typeof e.path!=`string`||typeof e.dev!=`string`||!/^-?\d+$/u.test(e.dev)||typeof e.ino!=`string`||!/^-?\d+$/u.test(e.ino))throw invalid();i={path:e.path,dev:e.dev,ino:e.ino}}if(r?.kind===`independent`&&(r.engine!==`native-v0`||!i))throw invalid();let a={};for(let[e,t]of Object.entries(n.legacyImports)){let n=Fd.find(t=>t===e);if(!n||!I(t)||t.sha256!==null&&!digest(t.sha256))throw invalid();a[n]={sha256:t.sha256}}return rebaseCanonicalReceipt({format:1,source:r,sharedFile:i,legacyImports:a},t,!1)}function rebaseCanonicalReceipt(e,t,n){let r=e.sharedFile;if(!r||e.source?.kind===`independent`)return e;let i=!X.isAbsolute(r.path);if(i&&(!t||!r.path.startsWith(`./`)||r.path.slice(2).split(`/`).some(e=>!e||e===`.`||e===`..`||e.includes(`\\`))))throw Error(`Client credential receipt has an invalid relative shared binding.`);if(!t)return e;let a=resolvePathViaExistingAncestorSync$1(t),o=X.resolve(a,r.path),s=X.relative(a,o),c=s&&!X.isAbsolute(s)&&s!==`..`&&!s.startsWith(`..${X.sep}`),l=n&&c?`./${s.split(X.sep).join(`/`)}`:o,u=e.source;if(u?.engine===`sqlite`){let e=`${r.path}:`;if(u.identity.startsWith(e))u={...u,identity:`${l}:${u.identity.slice(e.length)}`};else if(i)throw Error(`Client credential receipt has an invalid relative source identity.`)}return{...e,source:u,sharedFile:{...r,path:l}}}function serializeClientCredentialReceipt(e,t){return JSON.stringify(rebaseCanonicalReceipt(e,t,!0))}function isNativeClientCredentialBootstrap(e){fs(e);let t=K(e);if(t.userVersion!==0)return!1;let n=[...[...t.tables].map(e=>({type:`table`,name:e})),...[...t.indexes].map(e=>({type:`index`,name:e})),...[...t.views].map(e=>({type:`view`,name:e})),...[...t.triggers.keys()].map(e=>({type:`trigger`,name:e}))].filter(({name:e})=>!e.startsWith(`sqlite_`)),r=/* @__PURE__ */ new Set([`table:device_identities`,`index:idx_device_identities_device`,`table:device_auth_tokens`,`index:idx_device_auth_tokens_updated`,`table:macos_port_guardian_records`,`index:idx_macos_port_guardian_records_port`]);if(!n.length||n.some(e=>!r.has(`${e.type}:${e.name}`)))return!1;if(t.tables.has(`macos_port_guardian_records`)||t.indexes.has(`idx_macos_port_guardian_records_port`)){let t=readGeneratedSqliteCatalog(H)?.tables.filter(({name:e})=>e===`macos_port_guardian_records`);if(!t?.length)throw Error(`Native PortGuardian companion has no canonical schema catalog.`);assertSqliteSchemaContains(e,`Native PortGuardian companion`,{tables:t,views:[]})}return assertSqliteSchemaContains(e,`Native client credential bootstrap`,Au,{allowedMissingTables:[`device_identities`,`device_auth_tokens`,`gateway_origin_device_tokens`,`native_exec_socket_credentials`,`client_credential_migration`]}),!0}function readIndependentClientCredentialSource(e){try{var t=Ss();let n=readClientCredentialFileIdentity(e);if(!n)throw Error(`Independent client credential source is missing; restore its matching backup.`);let r=Y.openSync(e,Y.constants.O_RDONLY|Y.constants.O_NOFOLLOW);try{let e=Buffer.alloc(100);if(Y.readSync(r,e,0,e.length,0)!==e.length||e.subarray(0,16).toString(`binary`)!==`SQLite format 3\0`||e[18]!==1||e[19]!==1)throw Error(`Independent client credentials require DELETE journal mode; stop the old client and restore a compatible source.`)}finally{Y.closeSync(r)}let i=t.u(Ga(e,{readOnly:!0}));if(!isNativeClientCredentialBootstrap(i))throw Error(`Independent client credential source is not a native credential-only database.`);i.exec(`BEGIN`);try{let e=K(i).tables.has(`device_auth_tokens`),t=sourceRows(i,!0);validateSource(t);let r=hashClientCredentialRows(t,{authTablePresent:e});return{file:n,identity:`${n.dev}:${n.ino}`,sha256:r,rows:t,authTablePresent:e}}finally{i.exec(`ROLLBACK`)}}catch(e){t.e=e}finally{t.d()}}var ClientCredentialMigrationRequiredError=class extends as{constructor(e=`Client credential migration is incomplete or stale; run openclaw doctor --fix before using this client.`){super(`state-migrations`,e),this.name=`ClientCredentialMigrationRequiredError`}};function notReady(){return new ClientCredentialMigrationRequiredError}function assertSupportedVersion(e){if(e!==1)throw Error(`Client credentials have unsupported schema version ${String(e)}. Use a compatible OpenClaw version.`)}function readClientCredentialAdmission(e){let t;try{t=e.prepare(`
    SELECT header.user_version, receipt.source_store, receipt.phase
    FROM pragma_user_version AS header
    LEFT JOIN client_credential_migration AS receipt ON receipt.version = 1
  `).get()}catch(t){throw assertSupportedVersion(Lo(e)),t}if(!t||typeof t.user_version!=`number`)throw notReady();assertSupportedVersion(t.user_version);let n=e.location();return{stored:t.source_store===null?null:{phase:t.phase===`complete`?`complete`:`copied`,receipt:parseClientCredentialReceipt(String(t.source_store),n?X.dirname(X.dirname(n)):void 0)}}}function readClientCredentialReceipt(e,t){let n=w(e),r=C(e,n.selectFrom(`client_credential_migration`).selectAll().where(`version`,`=`,1)),i=e.location();return r?{phase:r.phase,receipt:parseClientCredentialReceipt(r.source_store,t??(i?X.dirname(X.dirname(i)):void 0))}:null}function writeClientCredentialReceipt(e,t,n,r=Date.now()){let i=w(e),a=e.location(),o={version:1,source_store:serializeClientCredentialReceipt(t,a?X.dirname(X.dirname(a)):void 0),phase:n,updated_at_ms:r};A(e,i.insertInto(`client_credential_migration`).values(o).onConflict(e=>e.column(`version`).doUpdateSet(o)))}function assertClientCredentialLegacyReady(e,t,n=!1,r){let i=!1,a=e?w(e):void 0,o=r??(e?readClientCredentialReceipt(e)?.receipt:void 0),s={primary:`device`,node:`node-device`,shareExtension:`share-device`};for(let r of[`primary`,`node`,`shareExtension`])for(let c of[`identity`,`auth`]){if(o?.legacyImports[`${c}:${r}`])continue;let l=`${s[r]}${c===`auth`?`-auth`:``}.json`,u=X.join(Cn(t),`identity`,l);if([u,`${u}.doctor-importing`,`${u}.native-importing`].some(e=>Y.existsSync(e))){if(c===`identity`&&e&&a&&C(e,a.selectFrom(`device_identities`).select(`identity_key`).where(`identity_key`,`=`,r)))continue;throw new ClientCredentialMigrationRequiredError(`Legacy client credentials require migration; run openclaw doctor --fix before using this client.`)}n&&o&&(o.legacyImports[`${c}:${r}`]={sha256:null},i=!0)}i&&o&&e&&writeClientCredentialReceipt(e,o,`complete`)}function assertMissingClientCredentialStoreReady(e){if(assertClientCredentialLegacyReady(null,e),readClientCredentialFileIdentity(Do(e)))throw notReady()}function prepareClientCredentialReceipt(e,t,n,r=!1,i=readClientCredentialReceipt(e)){let a=i,o=readClientCredentialFileIdentity(Do(t));if(!a&&n&&!o){assertClientCredentialLegacyReady(null,t);let n=emptyClientCredentialReceipt();for(let e of Fd)n.legacyImports[e]={sha256:null};writeClientCredentialReceipt(e,n,`complete`),a={phase:`complete`,receipt:n}}if(!a||a.phase!==`complete`)throw notReady();if(a.receipt.source?.kind===`independent`){let t=a.receipt.sharedFile,n=readIndependentClientCredentialSource(t.path);if(n.identity!==a.receipt.source.identity||n.file.path!==t.path||n.file.dev!==t.dev||n.file.ino!==t.ino||n.sha256!==a.receipt.source.sha256){if(r)throw Error(`Independent client credentials changed; open the client or run openclaw doctor --fix before read-only inspection.`);let t=w(e);A(e,t.deleteFrom(`device_auth_tokens`)),A(e,t.deleteFrom(`device_identities`)),A(e,t.deleteFrom(`gateway_origin_device_tokens`));for(let r of chunkItems(n.rows.identities,500))A(e,t.insertInto(`device_identities`).values(r));for(let r of chunkItems(n.rows.tokens,500))A(e,t.insertInto(`device_auth_tokens`).values(r));a.receipt.source={kind:`independent`,engine:`native-v0`,identity:n.identity,generation:`0`,sha256:n.sha256,destinationVersion:1},a.receipt.sharedFile=n.file,writeClientCredentialReceipt(e,a.receipt,`complete`)}}else{let e=a.receipt.sharedFile;if(e===null?o!==null:o===null||e.path!==o.path||e.dev!==o.dev||e.ino!==o.ino)throw notReady()}return a}function admitClientCredentialStore(e,t,n){let r=prepareClientCredentialReceipt(e,t,n.initialize,n.readOnly,n.stored);return assertClientCredentialLegacyReady(e,t,!n.readOnly,r.receipt),r.receipt}function encodeClientNativeTokenRole(e,t){return`v2.${Buffer.from(t).toString(`base64url`)}.${Buffer.from(e.trim()).toString(`base64url`)}`}function decodeRole(e){let t=e.split(`.`);if(t.length===3&&t[0]===`v2`&&t[1]!==void 0&&t[2]!==void 0)try{let decode=e=>{if(!/^[A-Za-z0-9_-]*$/u.test(e)||e.length%4==1)throw Error(`Invalid component`);return new TextDecoder(`utf-8`,{fatal:!0}).decode(Buffer.from(e,`base64url`))};return{gateway:decode(t[1]),role:decode(t[2])}}catch{}return{role:e,gateway:null}}function clearClientNativeTokens(e,t,n){let r=w(e);if(n.kind===`all`)return Number(A(e,r.deleteFrom(`device_auth_tokens`).where(`device_id`,`=`,t)).numAffectedRows);let i=A(e,r.selectFrom(`device_auth_tokens`).select(`role`).where(`device_id`,`=`,t)).rows.filter(({role:e})=>{let t=decodeRole(e);return n.kind===`role`?t.role===n.role.trim():n.kind===`gateway`?t.gateway===n.gateway:t.gateway===null}).map(({role:e})=>e);return i.length===0?0:(A(e,r.deleteFrom(`device_auth_tokens`).where(`device_id`,`=`,t).where(`role`,`in`,i)),i.length)}function claimClientNativeToken(e,t,n,r){let i=w(e),a=n.trim(),o=C(e,i.selectFrom(`device_auth_tokens`).selectAll().where(`device_id`,`=`,t).where(`role`,`=`,a));return o?(A(e,i.insertInto(`device_auth_tokens`).values({...o,role:encodeClientNativeTokenRole(n,r)}).onConflict(e=>e.columns([`device_id`,`role`]).doNothing())),A(e,i.deleteFrom(`device_auth_tokens`).where(`device_id`,`=`,t).where(`role`,`=`,a)),!0):!1}function performClientCredentialOperation(e,t,n){let r=w(e);switch(t.kind){case`identity.read`:case`identity.create`:case`identity.repair`:{let n=t.kind===`identity.read`?t.identity_key:t.identity.identity_key,i=C(e,r.selectFrom(`device_identities`).selectAll().where(`identity_key`,`=`,n));if(t.kind===`identity.repair`){if(i)try{return storedDeviceIdentityFromRow(i,n),{kind:`identityRepair`,identity:i,repaired:!1,rotated:!1}}catch{}let a=i?salvageStoredIdentityRow(i,n,t.identity.updated_at_ms):null,o=a?storedDeviceIdentityToRow(n,a,t.identity.updated_at_ms):t.identity;return storedDeviceIdentityFromRow(o,n),A(e,r.insertInto(`device_identities`).values(o).onConflict(e=>e.column(`identity_key`).doUpdateSet(o))),{kind:`identityRepair`,identity:o,repaired:!0,rotated:a===null}}return i?(storedDeviceIdentityFromRow(i,n),{kind:`identity`,identity:i}):t.kind===`identity.create`?(storedDeviceIdentityFromRow(t.identity,n),A(e,r.insertInto(`device_identities`).values(t.identity)),{kind:`identity`,identity:t.identity}):{kind:`identity`,identity:null}}case`native.tokens.clear`:return{kind:`cleared`,count:clearClientNativeTokens(e,t.device_id,t.selector)};case`native.token.claim`:return{kind:`changed`,changed:claimClientNativeToken(e,t.device_id,t.role,t.gateway)};case`token.list`:{let n=t.gateway_scope===void 0?`device_auth_tokens`:`gateway_origin_device_tokens`,i=r.selectFrom(n).selectAll().where(`device_id`,`=`,t.device_id);t.gateway_scope!==void 0&&(i=i.where(`gateway_scope`,`=`,t.gateway_scope)),t.afterRole!==void 0&&(i=i.where(`role`,`>`,t.afterRole));let a=Math.max(1,Math.min(32,Math.trunc(t.limit??32))),o=A(e,i.orderBy(`role`).limit(a+1)).rows,s=o.slice(0,a).map(({device_id:e,role:t,token:n,scopes_json:r,updated_at_ms:i})=>({device_id:e,role:t,token:n,scopes_json:r,updated_at_ms:i}));return{kind:`tokens`,tokens:s,nextRole:o.length>a?s.at(-1)?.role??null:null}}case`token.read`:case`token.replace`:case`token.remove`:{let{key:n}=t,i=n.gateway_scope===void 0?`device_auth_tokens`:`gateway_origin_device_tokens`,a=o(),s=a.and([a(`device_id`,`=`,n.device_id),a(`role`,`=`,n.role),...n.gateway_scope===void 0?[]:[a(`gateway_scope`,`=`,n.gateway_scope)]]),c=r.selectFrom(i).selectAll().where(s);if(t.kind===`token.read`){let t=C(e,c);return{kind:`token`,token:t?{device_id:t.device_id,role:t.role,token:t.token,scopes_json:t.scopes_json,updated_at_ms:t.updated_at_ms}:null}}let l=C(e,c),u=t.expectedToken===void 0?t.kind!==`token.remove`||t.observedToken===void 0:(l?.token??null)===t.expectedToken,d=t.kind===`token.remove`&&t.observedToken!==void 0&&l?.token===t.observedToken&&(t.expectedToken===void 0||typeof t.expectedToken==`string`&&t.observedToken.trim()===t.expectedToken);if(!(u||d))return{kind:`changed`,changed:!1};if(t.kind===`token.remove`){if(!l)return{kind:`changed`,changed:!1};A(e,r.deleteFrom(i).where(s))}else{let i={...t.token,device_id:n.device_id,role:n.role};n.gateway_scope===void 0?A(e,r.insertInto(`device_auth_tokens`).values(i).onConflict(e=>e.columns([`device_id`,`role`]).doUpdateSet(i))):A(e,r.insertInto(`gateway_origin_device_tokens`).values({...i,gateway_scope:n.gateway_scope}).onConflict(e=>e.columns([`gateway_scope`,`device_id`,`role`]).doUpdateSet(i)))}return{kind:`changed`,changed:!0}}case`socket.read`:case`socket.ensure`:{let i=C(e,r.selectFrom(`native_exec_socket_credentials`).selectAll().where(`socket_key`,`=`,`current`))??null;if(t.kind===`socket.read`)return{kind:`socket`,socket:i};let a=t.requested?.path?.trim(),o=i?.socket_path,s=!a&&o===X.join(n,`exec-approvals.sock`)&&o!==t.fallback.socket_path,c={socket_key:`current`,socket_path:a||(s?t.fallback.socket_path:o)||t.fallback.socket_path,socket_token:t.requested?.token?.trim()||i?.socket_token||t.fallback.socket_token,updated_at_ms:t.fallback.updated_at_ms};return i&&i.socket_path===c.socket_path&&i.socket_token===c.socket_token?{kind:`socket`,socket:i}:(A(e,r.insertInto(`native_exec_socket_credentials`).values(c).onConflict(e=>e.column(`socket_key`).doUpdateSet(c))),{kind:`socket`,socket:c})}default:throw Error(`Unsupported client credential operation.`)}}function createPrivateIfMissing(e){try{return e(),!0}catch(e){if(!(e instanceof Cc&&e.code===`already-exists`))throw e;return!1}}function createPrivateStoreDirectorySync(e){let t=X.dirname(e),n=process.platform===`linux`?Y.lstatSync(t,{bigint:!0}):void 0;try{bc(e,{private:!0})}catch(r){let i=r instanceof Cc?r.details?.publication:void 0;if(process.platform!==`linux`||typeof process.getuid!=`function`||!n||!(r instanceof Cc&&r.code===`helper-failed`)||!(r.cause instanceof Cc&&r.cause.code===`insecure-permissions`)||r.details?.path!==e||!i||typeof i!=`object`||!(`status`in i&&i.status===`published`))throw r;let a;try{yc(t,n),a=Y.openSync(e,Y.constants.O_RDONLY|Y.constants.O_DIRECTORY|Y.constants.O_NOFOLLOW);let i=Y.fstatSync(a,{bigint:!0}),o=Y.lstatSync(e,{bigint:!0});if(!i.isDirectory()||i.uid!==BigInt(process.getuid())||(i.mode&4095n)!=1472n||i.dev!==o.dev||i.ino!==o.ino)throw r;yc(t,n),Y.fchmodSync(a,448);let s=Y.fstatSync(a,{bigint:!0}),c=Y.lstatSync(e,{bigint:!0});if((s.mode&4095n)!=448n||s.dev!==c.dev||s.ino!==c.ino)throw r;yc(t,n)}catch{throw r}finally{a!==void 0&&Y.closeSync(a)}}}function preparePrivateStoreFileSync(e,t){let n=X.dirname(e);t||Y.mkdirSync(X.dirname(n),{recursive:!0,mode:448});let r=X.join(Y.realpathSync.native(X.dirname(n)),X.basename(n));return t||createPrivateIfMissing(()=>createPrivateStoreDirectorySync(r)),Me(n,448),!Y.existsSync(e)&&createPrivateIfMissing(()=>xc(X.join(r,X.basename(e)),{private:!0}).close())}const Id=R(Symbol.for(`openclaw.clientCredentialCustody`),()=>/* @__PURE__ */ new Set),Ld=R(Symbol.for(`openclaw.clientCredentialAdmittedFiles`),()=>/* @__PURE__ */ new Map,e=>e.clear());var ClientCredentialBusyError=class extends Error{constructor(){super(`Client credential owner is busy.`),this.name=`ClientCredentialBusyError`}};const Rd={name:`client.credentials.schema-v1`,schemaDependent:!0,read:e=>e===!0||void 0};function assertPrivateAcl(e){if(process.platform===`darwin`&&Ac(e).kind!==`none`)throw Error(`Client credentials require a private directory and file without ACL entries.`)}function openClientCredentialCustody(...e){let t=openClientCredentialCustodySteps(...e),n=t.next();for(;!n.done;)try{n.value.admit(),n=t.next()}catch(e){n=t.throw(e)}return n.value}async function openClientCredentialCustodyAsync(...e){us(Is())?.throwIfAborted();let t=openClientCredentialCustodySteps(...e),n=t.next();for(;!n.done;)try{let e=n.value;await runUpdateSqliteMigrationAsync(e.database,e.path,e.admit,{created:e.created,retainExclusive:!0}),n=t.next()}catch(e){n=t.throw(e)}return n.value}function*openClientCredentialCustodySteps(e,t={},n){let r=t.readOnly===!0||t.inspect===!0,i=(t.createIfMissing??!1)&&!r,a=resolveClientCredentialStorePath(e),o=t.inspect===!0&&!Y.existsSync(`${a}-journal`),s=X.dirname(a),c=mi(a);if(Id.has(c))throw new ClientCredentialBusyError;t.migration&&Ld.delete(c),!t.migration&&!Y.existsSync(a)&&assertMissingClientCredentialStoreReady(e);let l=Y.lstatSync(s,{throwIfNoEntry:!1});if(l&&(!l.isDirectory()||process.getuid&&l.uid!==process.getuid()||process.platform!==`win32`&&l.mode&63))throw Error(`Client credential directory is unsafe.`);if(!l&&!i)return;l&&assertPrivateAcl(s);let u=!1;i&&(u=preparePrivateStoreFileSync(a,!!l));let d=zn({absolutePath:a,rootPath:s,boundaryLabel:`client credential store`,rejectSymlinks:!0});if(!d.ok){if(cn(d.error,`ENOENT`)&&!i)return;throw Error(`Client credential store cannot be safely opened.`,{cause:d.error})}Id.add(c);let f,p=!1,physicalClose;try{let s=Y.fstatSync(d.fd,{bigint:!0});if(process.getuid&&s.uid!==BigInt(process.getuid())||process.platform!==`win32`&&(s.mode&63n)!=0n)throw Error(`Client credential store owner is unsafe.`);let l=`${s.dev}:${s.ino}:${Nr(s)}`;assertPrivateAcl(a),f=o?Ga(yo(a),{readOnly:!0,timeout:t.timeoutMs??5e3}):Ga(_o(a),{timeout:t.timeoutMs??5e3});let m=f;if(f.prepare(`PRAGMA journal_mode`).get()?.journal_mode!==`delete`)throw Error(`Client credentials require DELETE journal mode for exclusive owner custody.`);physicalClose=()=>{if(!p){p=!0;try{m.close()}finally{Y.closeSync(d.fd),Id.delete(c)}}};let transaction=e=>{if(p)throw Error(`Client credential custody is closed.`);return o?Vt(m,e):r?O(m,e):runUpdateSqliteMigration(m,a,()=>O(m,e),{retainExclusive:!0})},h=Ld.get(c),g=!1,_=!1;return yield{database:m,path:a,created:u,admit:()=>transaction(()=>{if(o||m.exec(`PRAGMA locking_mode=EXCLUSIVE`),t.migration||h?.identity!==l||h.version!==1){let e=Lo(m);if(e===0&&!m.prepare(`SELECT 1 FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%'`).get()){if(!i)throw Error(`Client credential store is empty; run openclaw doctor --fix.`);m.exec(Au),g=!0,Xo(m,1)}else{if(e!==1)throw Error(`Client credentials have unsupported schema version ${String(e)}. Use a compatible OpenClaw version.`);assertSqliteSchemaContains(m,`Client credentials`,Au),Qe(m,`Client credentials`)}fi(m,Rd,!0)}if(!t.migration){let t=readClientCredentialAdmission(m),n=admitClientCredentialStore(m,e,{initialize:g,readOnly:r,stored:t.stored});_=n.sharedFile!==null&&n.source===null}g||n?.(m)})},g&&n&&(yield{database:m,path:a,created:u,admit:()=>transaction(()=>n(m))}),t.migration||Ld.set(c,{identity:l,version:1}),{database:m,path:a,created:u,needsMetadataUpgrade:_,transaction,run(t,n){if(p)throw Error(`Client credential custody is closed.`);if(r&&isClientCredentialMutation(t))throw Error(`Client credential custody is read-only.`);return transaction(()=>{let r=performClientCredentialOperation(m,t,Cn(e));return n?.(),r})},close:physicalClose,[Symbol.dispose]:physicalClose}}catch(e){throw Ld.delete(c),physicalClose?physicalClose():(f?.close(),Y.closeSync(d.fd),Id.delete(c)),e}}function isClientCredentialMutation(e){return![`identity.read`,`token.read`,`token.list`,`socket.read`].includes(e.kind)}function postgresBootstrapProvenance(e){let t=z(e),n=readEngineAnchor(t?e.anchor:e,`identity`,t);if(!n)return;let r=n[0];if(n.length!==1||!r||r.engine!==`postgres`||typeof r.store_id!=`string`||!r.store_id.trim()||typeof r.schema!=`string`||!r.schema.trim())throw Error(`Invalid PostgreSQL anchor identity during client credential bootstrap.`);return{kind:`canonical`,engine:`postgres`,identity:r.store_id,generation:`bootstrap:${r.store_id}`,sha256:hashClientCredentialRows({identities:[],tokens:[],origins:[],approvals:[]}),destinationVersion:1}}function readClientCredentialBootstrapSource(e,t){let n=postgresBootstrapProvenance(e);if(n)return n;let r=e.prepare(`SELECT created_at FROM schema_meta WHERE meta_key = 'primary'`).get();if(!r)throw Error(`Shared credential source identity was not published.`);return{kind:`canonical`,engine:`sqlite`,identity:`${t}:${String(r.created_at)}`,generation:`bootstrap:${String(r.created_at)}`,sha256:hashClientCredentialRows({identities:[],tokens:[],origins:[],approvals:[]}),destinationVersion:1}}function isPristineSqliteBootstrap(e,t){let n=t?.receipt.source,r=t?.receipt.sharedFile;if(t?.phase!==`complete`||n?.kind!==`canonical`||n.engine!==`sqlite`||!r||!n.generation.startsWith(`bootstrap:`)||n.generation===`bootstrap:`||n.identity!==`${r.path}:${n.generation.slice(10)}`||n.sha256!==hashClientCredentialRows({identities:[],tokens:[],origins:[],approvals:[]})||Object.keys(t.receipt.legacyImports).length!==0)return!1;let i=w(e);return[`device_identities`,`device_auth_tokens`,`gateway_origin_device_tokens`,`native_exec_socket_credentials`].every(t=>!C(e,i.selectFrom(t).selectAll().limit(1)))}async function prepareClientCredentialMigrationCustody(e){let t=resolveStateClientCredentialEnvironment(e);return t?openClientCredentialCustodyAsync(t,{createIfMissing:e.fromVersion<29,migration:!0}):void 0}function bindFreshClientCredentialStore(e,t){if(!e.isTransaction||!$i(e))throw Error(`Client credential bootstrap has no source commit lifecycle.`);let n=resolveStateClientCredentialEnvironment(t);if(!n)return;let r=postgresBootstrapProvenance(e),i=t.custody===void 0?openClientCredentialCustody(n,{createIfMissing:!0,migration:!0}):t.custody;if(!i)throw Error(`Cannot acquire local credentials during shared bootstrap.`);let close=()=>{t.custody===void 0&&i.close()};try{let n=beginUpdateSqliteCompanion(i.database,i.path,i.created),a=readClientCredentialReceipt(i.database),o=w(i.database),s=C(i.database,o.selectFrom(`client_credential_migration`).selectAll().where(`version`,`=`,1)),c=readClientCredentialFileIdentity(t.path);if(!c)throw Error(`Shared credential source is missing during bootstrap.`);let l=a?.receipt.source,u=a?.receipt.sharedFile,d=u?.path===c.path&&u.dev===c.dev&&u.ino===c.ino,f=r&&l?.kind===r.kind&&l.engine===r.engine&&l.identity===r.identity&&l.generation===r.generation&&l.sha256===r.sha256&&l.destinationVersion===r.destinationVersion&&d,p=!r&&isPristineSqliteBootstrap(i.database,a);if(l&&!f&&!p||u&&!d&&!p)throw Error(`Existing client credentials belong to a previous shared database; run openclaw doctor --fix.`);let m={format:1,source:p&&!d?null:a?.receipt.source??null,sharedFile:c,legacyImports:a?.receipt.legacyImports??{}};if(O(i.database,()=>writeClientCredentialReceipt(i.database,m,`copied`)),!da(e,{stage(){},commit(){try{m.source=readClientCredentialBootstrapSource(e,c.path),O(i.database,()=>writeClientCredentialReceipt(i.database,m,`complete`)),n?.complete()}finally{close()}},rollback(){try{O(i.database,()=>{s?A(i.database,o.insertInto(`client_credential_migration`).values(s).onConflict(e=>e.column(`version`).doUpdateSet(s))):A(i.database,o.deleteFrom(`client_credential_migration`).where(`version`,`=`,1))}),n?.complete()}finally{close()}},invalidate:close}))throw Error(`Client credential bootstrap has no source commit lifecycle.`)}catch(e){throw close(),e}}function prepareClientCredentialMigration(e,t){if(t.fromVersion>=29||z(e)&&t.fromVersion!==28)return;if(!e.isTransaction)throw Error(`Client credential migration requires the shared owner's transaction.`);let n=t.fromVersion===0;if(n&&!ku.some(t=>M(e,t))){bindFreshClientCredentialStore(e,t);return}let r=resolveStateClientCredentialEnvironment(t),i=So(),a=t.capture??getUpdateDoctorMigrationSource(t.path)??(z(e)?void 0:getDoctorMigrationBackup(e,{path:t.path,env:r??t.env,tables:[...ku,`sqlite_stat1`,`sqlite_stat4`]})?.capture);if(!i?.ownsSchemaMaintenance||!a||a.path!==t.path||!a.generation)throw Error(`Client credentials require backed-up migration custody; stop the app and run openclaw doctor --fix.`);if(!r)throw Error(`Client credentials in an auxiliary shared database require explicit recovery; preserve the source database.`);Je(t.path),i.assertAdmission(),a.assertCurrent();let o=sourceRows(e,n||t.fromVersion<28),s=!n||M(e,`device_auth_tokens`);validateSource(o,n?`require-valid`:`preserve-for-doctor`);let c=extractSocket(o.approvals[0]),l=readClientCredentialFileIdentity(t.path);if(!l)throw Error(`Client credential source disappeared before migration.`);let u=M(e,`schema_meta`),d=t.fromVersion===1&&!u,f=(n||d)&&!u?void 0:e.prepare(`SELECT created_at FROM schema_meta WHERE meta_key = 'primary'`).get(),p=z(e)?readEngineAnchor(e.anchor,`identity`,!0)?.[0]:void 0,m={format:1,source:{kind:`canonical`,engine:z(e)?`postgres`:n?`native-v0`:`sqlite`,identity:p?String(p.store_id):`${l.path}:${String(f?.created_at??0)}`,generation:a.generation,sha256:hashClientCredentialRows(o,n?{authTablePresent:s}:void 0),destinationVersion:1},sharedFile:l,legacyImports:resolveClientCredentialLegacyImportClaims(e,{identities:o.identities,nativeBootstrap:n,authTablePresent:s})},h=t.custody===void 0?openClientCredentialCustody(r,{createIfMissing:!0,migration:!0}):t.custody;if(!h)throw Error(`Client credential migration could not acquire local custody.`);let close=()=>{t.custody===void 0&&h.close()};try{let t=beginUpdateSqliteCompanion(h.database,h.path,h.created);if(O(h.database,()=>{let e=h.database,t=readClientCredentialReceipt(e);if(t&&(m.legacyImports={...m.legacyImports,...t.receipt.legacyImports}),t?.phase===`complete`&&t.receipt.source?.kind===`independent`&&n&&t.receipt.source.identity===`${l.dev}:${l.ino}`&&t.receipt.source.sha256===m.source.sha256&&t.receipt.sharedFile?.path===l.path&&t.receipt.sharedFile.dev===l.dev&&t.receipt.sharedFile.ino===l.ino){writeClientCredentialReceipt(e,m,`copied`);return}let r=w(e);for(let t of[`device_identities`,`device_auth_tokens`,`gateway_origin_device_tokens`,`native_exec_socket_credentials`,`client_credential_migration`])A(e,r.deleteFrom(t));for(let t of chunkItems(o.identities,500))A(e,r.insertInto(`device_identities`).values(t));for(let t of chunkItems(o.tokens,500))A(e,r.insertInto(`device_auth_tokens`).values(t));for(let t of chunkItems(o.origins,500))A(e,r.insertInto(`gateway_origin_device_tokens`).values(t));c.socket&&A(e,r.insertInto(`native_exec_socket_credentials`).values(c.socket)),A(e,r.insertInto(`client_credential_migration`).values({version:1,source_store:serializeClientCredentialReceipt(m,X.dirname(X.dirname(h.path))),phase:`copied`,updated_at_ms:Date.now()}))}),!da(e,{stage(){},prepareCommit(){if(!d)return;let t=e.prepare(`SELECT created_at FROM schema_meta WHERE meta_key = 'primary'`).get();if(!t||!m.source)throw Error(`Historical client credential source identity was not published.`);m.source.identity=`${l.path}:${String(t.created_at)}`,O(h.database,()=>writeClientCredentialReceipt(h.database,m,`copied`))},commit(){try{if(n&&!z(e)&&M(e,`schema_meta`)){let t=e.prepare(`SELECT created_at FROM schema_meta WHERE meta_key = 'primary'`).get();m.source&&(m.source.engine=`sqlite`,m.source.identity=`${l.path}:${String(t?.created_at??0)}`)}O(h.database,()=>writeClientCredentialReceipt(h.database,m,`complete`)),t?.complete()}finally{close()}},rollback:close,invalidate:close}))throw Error(`Client credential migration has no source commit lifecycle.`);i.assertAdmission(),a.assertCurrent(),o.approvals[0]&&c.policy!==void 0&&A(e,w(e).updateTable(`exec_approvals_config`).set({raw_json:c.policy,socket_path:null,has_socket_token:0}).where(`config_key`,`=`,`current`)),e.exec(`DROP TABLE IF EXISTS device_auth_tokens; DROP TABLE IF EXISTS device_identities; DROP TABLE IF EXISTS gateway_origin_device_tokens;`)}catch(e){throw close(),e}}const zd=/* @__PURE__ */ new Set([.../* @__PURE__ */ new Set([26985,20859,4283649346,4266872130]),16914839]),Bd=1e3,Vd=/* @__PURE__ */ new Set([`cifs`,`smbfs`,`smb2`,`smb3`]),Hd=/* @__PURE__ */ new Set([`virtiofs`,`fuse.virtiofs`,`9p`,`9p2000.l`]),Ud=er(`infra/sqlite-wal`);let Wd=!1;function findExistingVolumePaths(e){let t=X.resolve(e);for(;;){let e;try{e=Y.statSync(t)}catch{let e=X.dirname(t);if(e===t)return null;t=e;continue}let n=Y.realpathSync(t);return{canonicalPath:e.isDirectory()?n:X.dirname(n),originalPath:e.isDirectory()?t:X.dirname(t)}}}function parseProcMountInfoEntries(e){let t=[];for(let n of e.split(`
`)){let e=n.indexOf(` - `);if(e===-1)continue;let r=n.slice(0,e).split(` `),i=n.slice(e+3).split(` `),a=r[4],o=i[0];a&&o&&t.push({mountPoint:decodeMountInfoPath(a),fsType:o,...i[1]?{source:decodeMountInfoPath(i[1])}:{}})}return t}function parseMountCommandEntries(e){let t=[];for(let n of e.split(`
`)){let e=/^(.+) on (.+) type ([^,\s)]+) \(/.exec(n)??/^(.+) on (.+) \(([^,\s)]+)/.exec(n);if(e){let[,n,r,i]=e;n&&r&&i&&t.push({source:n,mountPoint:r,fsType:i})}}return t}function readMountEntries(){try{return{ok:!0,value:parseProcMountInfoEntries(Y.readFileSync(`/proc/self/mountinfo`,`utf8`))}}catch{}try{return{ok:!0,value:parseMountCommandEntries(String(process.getBuiltinModule(`node:child_process`).execFileSync(`mount`,[],{killSignal:`SIGKILL`,timeout:Bd})))}}catch(e){return cn(e,`ETIMEDOUT`)?{ok:!1,error:`timeout`}:{ok:!0,value:[]}}}function isPathWithinMount(e,t){let n=X.resolve(e),r=X.resolve(t);return n===r||r===X.parse(r).root||n.startsWith(`${r}${X.sep}`)}function isSshfsMountSource(e){if(!e)return!1;let t=e.toLowerCase();return t===`sshfs`||t.startsWith(`sshfs#`)||t.startsWith(`sshfs@`)||/^(?:[^/\s:]+@)?[^/\s:]+:.*/u.test(e)}function resolveNetworkMountJournalPolicy(e){let t=e.fsType.toLowerCase();if(t.startsWith(`nfs`)||Vd.has(t))return`rollback`;if(t===`fuse.sshfs`||(t===`macfuse`||t===`osxfuse`)&&isSshfsMountSource(e.source))return`unsupported`}function resolveMountTypeJournalPolicy(e){let t=e.fsType.toLowerCase();return resolveNetworkMountJournalPolicy(e)??(Hd.has(t)||t.startsWith(`9p`)?`rollback`:`wal`)}function findMountEntry(e,t){return t.filter(t=>isPathWithinMount(e,t.mountPoint)).toSorted((e,t)=>t.mountPoint.length-e.mountPoint.length)[0]}function resolveMountEntryJournalPolicy(e,t){let n=findMountEntry(e,t);return n?resolveMountTypeJournalPolicy(n):`wal`}function isSqlitePathOnBtrfs(e){if(process.platform!==`linux`)return!1;let t=findExistingVolumePaths(e);if(!t)return!1;try{return Y.statfsSync(t.canonicalPath).type===2435016766}catch{let e=readMountEntries();return e.ok&&findMountEntry(t.canonicalPath,e.value)?.fsType.toLowerCase()===`btrfs`}}function setSqliteDirectoryNoCow(e){if(!Y.statSync(e).isDirectory())throw Error(`SQLite NOCOW target is not a directory: ${e}`);let t=process.getBuiltinModule(`node:child_process`).spawnSync(`chattr`,[`+C`,e],{encoding:`utf8`,killSignal:`SIGKILL`,timeout:Bd,maxBuffer:4096});if(t.error||t.status!==0)throw t.error??/* @__PURE__ */ Error(`chattr +C failed: ${t.stderr.trim()||t.signal||t.status}`)}function prepareSqliteDatabaseDirectory(e){if(!(process.platform!==`linux`||Y.existsSync(e)))try{isSqlitePathOnBtrfs(e)&&setSqliteDirectoryNoCow(X.dirname(e))}catch(t){Wd||(Wd=!0,Ud.warn(`Could not enable SQLite directory NOCOW; continuing with filesystem defaults`,{databasePath:e,error:t instanceof Error?t.message:String(t)}))}}function combineMountEntryJournalPolicies(e){let[t,n]=e;if(process.platform===`darwin`&&t===n)try{if(jc(n)===`apfs`)return`wal`}catch{}let r=readMountEntries();if(!r.ok)return`rollback`;let i=new Set(e.map(e=>resolveMountEntryJournalPolicy(e,r.value)));return i.has(`unsupported`)?`unsupported`:i.has(`rollback`)?`rollback`:`wal`}function isWindowsUncPath(e){return/^\\\\\?\\UNC\\[^\\]+\\[^\\]+/i.test(e)||/^\\\\(?![?.]\\)[^\\]+\\[^\\]+/.test(e)}function isWindowsDrivePath(e){return/^[A-Za-z]:[\\/]/.test(e)||/^\\\\\?\\[A-Za-z]:[\\/]/i.test(e)}function resolvePathJournalPolicy(e){if(process.platform===`win32`){let t=X.win32.normalize(e);if(isWindowsUncPath(t))return`rollback`;if(isWindowsDrivePath(t))try{return isWindowsUncPath(X.win32.normalize(Y.realpathSync.native(e)))?`rollback`:`wal`}catch{return`rollback`}}let t=findExistingVolumePaths(e);if(!t)return`wal`;let n=[t.originalPath,t.canonicalPath];try{if(zd.has(Y.statfsSync(t.canonicalPath).type))return`rollback`}catch{}return combineMountEntryJournalPolicies(n)}const Gd=/* @__PURE__ */ new WeakMap;function createSqliteWalReclamationResult(){return{checkpointCompleted:!1,freePagesBefore:null,remainingFreePages:null,checkpointCalls:0,checkpointIncomplete:0,checkpointMs:0,checkpointMaxMs:0,queryMs:0,vacuumMs:0,vacuumPasses:0,vacuumPagesRequested:0}}function readSqliteFreePageCount(e,t){let n=t?vc.now():0;try{return Number(e.prepare(`PRAGMA freelist_count`).get()?.freelist_count??0)}finally{t&&(t.queryMs+=vc.now()-n)}}function reclaimSqliteWalFreePages(e,t,n){let r=createSqliteWalReclamationResult(),checkpoint=()=>{n.beforeMutation?.();let e=vc.now();try{let e=n.checkpointMode??`TRUNCATE`,i=t(e);return r.checkpointCalls++,!i&&e===`TRUNCATE`&&(n.beforeMutation?.(),i=t(`PASSIVE`),r.checkpointCalls++),r.checkpointCompleted=i,r.checkpointIncomplete+=Number(!i),i}finally{let t=vc.now()-e;r.checkpointMs+=t,r.checkpointMaxMs=Math.max(r.checkpointMaxMs,t)}};return n.maxPages===0&&n.checkpointMode===`PASSIVE`?(checkpoint(),r):ps(e,0,()=>{if(!checkpoint()||n.maxPages===0)return r;let t=readSqliteFreePageCount(e,r);if(r.freePagesBefore=t,r.remainingFreePages=t,!Number.isSafeInteger(t)||t<=0)return r;let i=Math.min(Gd.get(e)??8,t,n.maxPages??512);if(!Number.isSafeInteger(i)||i<=0)throw Error(`SQLite page reclamation requires a positive integer page limit`);let a=vc.now(),o=!1,s=!1;try{O(e,()=>{o=!0,n.beforeMutation?.(),r.vacuumPasses++,r.vacuumPagesRequested+=i,e.exec(`PRAGMA incremental_vacuum(${i});`),n.onCommit?.()},{beginLockFailureReporting:`suppress`,busyTimeoutMs:0,operationLabel:`incremental-vacuum`}),s=!0}catch(e){if(o||!Oa(e))throw e;return r}finally{let t=vc.now()-a;r.vacuumMs+=t,s&&Gd.set(e,Math.max(1,Math.min(512,i*2,Math.floor(i*25/Math.max(t,.001)))))}return n.afterCommit?.(),checkpoint()&&(r.remainingFreePages=readSqliteFreePageCount(e,r)),r})}const Kd=R(Symbol.for(`openclaw.sessionControllerCleanupContext`),()=>({}));function runWithSessionControllerCleanup(e){return Kd.exit?Kd.exit(e):e()}const qd=er(`gateway/scheduler`),Jd={now:()=>Date.now(),monotonicNow:()=>performance.now(),arm:(e,t)=>{let n=setTimeout(()=>{An(`scheduler:wake`,()=>{e()})},t);return n.unref(),()=>clearTimeout(n)}};function nextMaintenanceSlot(e,t,n){return e+(Math.floor(Math.max(0,t-e)/n)+1)*n}var GatewayScheduler=class{constructor(e={}){this.jobs=/* @__PURE__ */ new Map,this.pending=/* @__PURE__ */ new Set,this.dispatching=!1,this.fenced=!1,this.controller=new AbortController,this.clock=e.clock??Jd}get signal(){return this.controller.signal}now(){return this.clock.now()}get nextWakeAtMs(){let e=this.now(),t=this.clock.monotonicNow(),n=null;for(let r of this.jobs.values()){if(r.running)continue;let i=e+this.remaining(r,e,t);n=n===null?i:Math.min(n,i)}return n}scope(){let e=new AbortController,t={signal:AbortSignal.any([this.signal,e.signal]),jobs:/* @__PURE__ */ new Set},beginClose=()=>{e.abort(),_s(e.signal.reason),_s(t.signal.reason);for(let e of t.jobs)this.cancel(e)},close=()=>{beginClose();let e=[...t.jobs].flatMap(e=>e.running??[]);return e.length>0?Promise.all(e).then(()=>void 0):void 0};return{signal:t.signal,now:()=>this.now(),schedule:e=>this.scheduleOwned(e,t),beginClose,close,stop:async()=>{await close()}}}schedule(e){return this.scheduleOwned(e)}scheduleOwned(e,t){let n=`delayMs`in e,r=this.now(),i=n?r+e.delayMs:e.atMs,a=e.phase===`maintenance`?Math.max(r,Math.floor(i/1e4)*1e4):i;if(!Number.isFinite(a)||e.everyMs!==void 0&&(!Number.isFinite(e.everyMs)||e.everyMs<=0))throw Error(`Invalid Gateway schedule: ${e.id}`);let o=this.fenced||t?.signal.aborted===!0,s=o?void 0:this.jobs.get(e.id),c={id:e.id,diagnosticName:`scheduler:${e.id.startsWith(`maintenance:`)?e.id.split(`:`).slice(0,3).join(`:`):e.id.split(/[:/]/u,1)[0]}`,run:e.run,everyMs:e.everyMs,phase:e.phase,atMs:a,elapsedAtMs:e.phase!==`maintenance`&&(n||e.everyMs!==void 0)?this.clock.monotonicNow()+Math.max(0,a-r):void 0,context:Fs(()=>runWithSessionControllerCleanup(()=>ec.snapshot())),cancelled:o,owner:t};e.mode===`earliest`&&s&&!s.running&&(c.atMs=Math.min(c.atMs,s.atMs),e.phase!==`maintenance`&&s.elapsedAtMs!==void 0&&(c.elapsedAtMs=c.elapsedAtMs===void 0?s.elapsedAtMs:Math.min(c.elapsedAtMs,s.elapsedAtMs)));let cancel=()=>this.cancel(c);return o||(t?.jobs.add(c),this.jobs.set(c.id,c),s&&this.cancel(s),this.arm()),{get atMs(){return c.atMs},cancel,stop:async()=>{cancel(),await c.running}}}cancel(e){e.cancelled=!0,e.running||e.owner?.jobs.delete(e),this.jobs.get(e.id)===e&&(this.jobs.delete(e.id),this.arm())}fence(){this.fenced=!0,this.cancelTimer?.(),this.cancelTimer=void 0;for(let e of this.jobs.values())this.cancel(e);this.jobs.clear()}beginClose(){this.fence(),this.controller.abort(),_s(this.controller.signal.reason)}async stop(){this.beginClose(),await Promise.all(this.pending)}remaining(e,t,n){let r=e.atMs-t;return e.elapsedAtMs===void 0?r:Math.min(r,e.elapsedAtMs-n)}arm(){if(this.fenced||this.dispatching)return;this.cancelTimer?.(),this.cancelTimer=void 0;let e=this.nextWakeAtMs;if(e!==null){let t=this.now(),n=Math.min(2147483647,Math.max(0,Math.ceil(e-t)));this.cancelTimer=gn(()=>this.clock.arm(()=>this.wake(t+n),n))}}wake(e){if(this.cancelTimer=void 0,this.fenced)return;let t=this.now(),n=this.clock.monotonicNow(),r=[...this.jobs.values()].filter(e=>!e.running&&this.remaining(e,t,n)<=0).toSorted((e,r)=>this.remaining(e,t,n)-this.remaining(r,t,n)),i;t-e>6e4&&qd.debug(`late wake by ${t-e}ms; coalescing ${r.length} due jobs`),this.dispatching=!0;try{for(let e of r){if(this.fenced||e.cancelled||e.owner?.signal.aborted||this.jobs.get(e.id)!==e)continue;e.everyMs===void 0&&this.jobs.delete(e.id);let t=this.run(e);t&&(i??=[]).push(t)}}finally{this.dispatching=!1,this.arm()}return i?Promise.all(i).then(()=>void 0):void 0}run(e){qd[e.everyMs===void 0?`debug`:`trace`](`running ${e.id}`);let t=vs(),n=new Ls;e.running=t.promise,this.pending.add(t.promise);let finish=()=>{e.running=void 0,this.pending.delete(t.promise),e.everyMs!==void 0&&!e.cancelled&&!this.fenced?e.phase===`maintenance`?(e.atMs=Math.floor(e.atMs/1e4)*1e4,e.atMs=nextMaintenanceSlot(e.atMs,this.now(),e.everyMs)):(e.atMs=this.now()+e.everyMs,e.elapsedAtMs=this.clock.monotonicNow()+e.everyMs):e.owner?.jobs.delete(e),t.resolve(),this.arm()},r;try{r=e.context(()=>An(e.diagnosticName,()=>n.run(e.run)))}catch(t){qd.error(`${e.id} failed: ${String(t)}`)}if(!r&&!n.hasPendingWork)finish();else return Promise.resolve(r).catch(t=>qd.error(`${e.id} failed: ${String(t)}`)).then(()=>Ls.runWhenAllIdle(()=>[n],()=>n.drain())).finally(finish),t.promise}};const Yd=R(Symbol.for(`openclaw.sqliteWalCheckpointListeners`),()=>/* @__PURE__ */ new Set);function observeSqliteWalCheckpointHealth(e,t){let{activeReaders:n,readerDiagnostics:r,...i}=t;if(t.state===`complete`)return i;let{activeReaders:a,...o}=_i(e);return{...i,activeReaders:[...(n??[]).filter(e=>e.threadId!==o.threadId),...a].toSorted((e,t)=>t.ageMs-e.ageMs).slice(0,8),readerDiagnostics:[...(r??[]).filter(e=>e.threadId!==o.threadId),o].slice(-8)}}function notifyCheckpoint(e,t){for(let n of Yd)try{n({databasePath:ji(e),health:structuredClone(t.health),observedAtNs:t.observedAtNs,lastCompletedAtNs:t.lastCompletedAtNs})}catch{}}function sqliteFileBytes(e){try{return Y.statSync(e).size}catch(e){if(cn(e,`ENOENT`))return 0;throw e}}function readCheckpointResult(e){let[t,n,r]=Object.values(e??{}).map(e=>normalizeSqliteNumber(typeof e==`number`||typeof e==`bigint`?e:null));if(t===void 0||n===void 0||r===void 0)throw Error(`SQLite returned an invalid WAL checkpoint result`);return{busy:t,logFrames:n,checkpointedFrames:r}}function checkpoint(e,t){return e.prepare(`PRAGMA wal_checkpoint(${t});`).get()}function createSqliteWalCheckpoint(e,t,n){let r,checkpointObservation=()=>({state:`error`,observedAtMs:Date.now(),walBytes:null,databaseBytes:null,logFrames:null,checkpointedFrames:null,lastCompletedAtMs:r?.health.lastCompletedAtMs??null,consecutiveBlocked:0,warning:!0}),recordCheckpointError=(e,n=checkpointObservation())=>{let i={...n,observedAtMs:Date.now(),state:`error`,consecutiveBlocked:0,warning:!0,error:Cs(e)};r={observedAtNs:process.hrtime.bigint(),lastCompletedAtNs:r?.lastCompletedAtNs,health:t.databasePath?observeSqliteWalCheckpointHealth(t.databasePath,i):i},t.databasePath&&notifyCheckpoint(t.databasePath,r),t.onCheckpointError?.(e)},recordCheckpoint=(e,i,a)=>{let o=process.hrtime.bigint(),s=checkpointObservation(),c,l;try{let{busy:e,logFrames:a,checkpointedFrames:u}=readCheckpointResult(i);if(c=e!==0,s.logFrames=a,s.checkpointedFrames=u,s.state=c||u<a?`blocked`:`complete`,s.state===`complete`?s.lastCompletedAtMs=s.observedAtMs:s.consecutiveBlocked=(r?.health.consecutiveBlocked??0)+1,t.databasePath)try{s.databaseBytes=sqliteFileBytes(t.databasePath),s.walBytes=sqliteFileBytes(`${t.databasePath}-wal`)}catch(e){l=e,s.error=Cs(e)}s.warning=s.state===`blocked`&&(s.consecutiveBlocked>=2||s.walBytes!==null&&s.databaseBytes!==null&&s.walBytes>Math.max(2*s.databaseBytes,n)),r={observedAtNs:o,lastCompletedAtNs:s.state===`complete`?o:r?.lastCompletedAtNs,health:t.databasePath?observeSqliteWalCheckpointHealth(t.databasePath,s):s},t.databasePath&&notifyCheckpoint(t.databasePath,r)}catch(e){return recordCheckpointError(e,s),!1}if(s.error!==void 0&&t.onCheckpointError?.(l),s.warning&&!a){let n=t.databaseLabel??`sqlite database`;t.onCheckpointError?.(/* @__PURE__ */ Error(`${n} WAL checkpoint ${e} ${c?`remained busy`:`blocked by a reader`}`))}return s.state===`complete`};return{adopt(e){if(r&&r.observedAtNs>=e.observedAtNs&&(r.lastCompletedAtNs??0n)>=(e.lastCompletedAtNs??0n))return;let n=(r?.lastCompletedAtNs??0n)>(e.lastCompletedAtNs??0n)?r:e;(!r||e.observedAtNs>r.observedAtNs)&&(r=structuredClone(e)),r.lastCompletedAtNs=n?.lastCompletedAtNs,r.health.lastCompletedAtMs=n?.health.lastCompletedAtMs??null,t.databasePath&&(r.health=observeSqliteWalCheckpointHealth(t.databasePath,r.health),notifyCheckpoint(t.databasePath,r))},checkpoint(t,n={}){try{return recordCheckpoint(t,checkpoint(e,t),n.quiet===!0)}catch(e){return recordCheckpointError(e),!1}},recordError:recordCheckpointError,inspectIdle(){let{busy:t,logFrames:n,checkpointedFrames:r}=readCheckpointResult(checkpoint(e,`PASSIVE`));return t===0&&n>=0&&r>=0&&r<=n},get health(){return r?structuredClone(r.health):void 0},get snapshot(){return r?structuredClone(r):void 0}}}const Xd=`/proc/self/fd`;async function readUnlessMissing(e,t=!1){try{return await e()}catch(e){if(t&&cn(e,`EBADF`)||cn(e,`ENOENT`))return;throw e}}function isSqliteWalSidecarSplitBrain(e,t){return e.nlink===0n||!t||e.dev!==t.dev||e.ino!==t.ino}async function detectSqliteWalSplitBrain(e){let t=await readUnlessMissing(()=>Y.promises.readdir(Xd)),n=[`${e}-wal`,`${e}-shm`];for(let r of t??[]){let t=X.join(Xd,r),i=await readUnlessMissing(()=>Y.promises.readlink(t));if(i===void 0)continue;let a=n.find(e=>i===e||i===`${e} (deleted)`);if(!a)continue;let o=await readUnlessMissing(()=>dc(Y.fstat)(Number(r),{bigint:!0}),!0);if(o===void 0||await readUnlessMissing(()=>Y.promises.readlink(t))!==i)continue;let s=await readUnlessMissing(()=>Y.promises.stat(a,{bigint:!0}));if(!isSqliteWalSidecarSplitBrain(o,s))continue;let c=await readUnlessMissing(()=>dc(Y.fstat)(Number(r),{bigint:!0}),!0);if(c&&c.dev===o.dev&&c.ino===o.ino&&await readUnlessMissing(()=>Y.promises.readlink(t))===i)return{event:`sqlite_wal_sidecar_identity_mismatch`,databasePath:e,descriptorDevice:o.dev.toString(),descriptorInode:o.ino.toString(),sidecarPath:a,...s?{targetDevice:s.dev.toString(),targetInode:s.ino.toString()}:{}}}}function terminateForSqliteWalSplitBrain(e,t){try{Y.writeSync(2,`${JSON.stringify({level:`fatal`,subsystem:`infra/sqlite-wal`,message:`SQLite WAL sidecar identity mismatch; terminating without SQLite cleanup`,...e,databaseLabel:t,pid:process.pid})}\n`)}catch{}try{process.kill(process.pid,`SIGKILL`)}finally{process.abort()}}const Zd=1e4,Qd=67108864,$d=new Int32Array(new SharedArrayBuffer(4)),ef=er(`infra/sqlite-wal`),tf=new GatewayScheduler;let nf=0;const rf={name:`sqlite-wal-completed-write-revision`,read:e=>e instanceof SharedArrayBuffer&&e.byteLength===Int32Array.BYTES_PER_ELEMENT?e:void 0};function sharedCompletedCheckpoint(e,t){let n=V(e,rf);return n||=(n=new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT),Atomics.store(new Int32Array(n),0,t-1|0),fi(e,rf,n),V(e,rf)),n?new Int32Array(n):void 0}function enableIncrementalAutoVacuumForFreshDatabase(e){let t=e.location(),n=t?xr(t,Ba):void 0;n&&(n.userVersion>0||n.tables.size>0||n.views.size>0)||e.prepare(`PRAGMA page_count`).get()?.page_count===0&&e.exec(`PRAGMA auto_vacuum = INCREMENTAL;`)}function configureSqlitePreSchemaPragmas(e,t={}){t.busyTimeoutMs!==void 0&&oo(e,t.busyTimeoutMs),enableIncrementalAutoVacuumForFreshDatabase(e)}function readJournalModeResult(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.journal_mode??Object.values(t)[0];return typeof n==`string`?n.toLowerCase():null}function hasInMemoryMainDatabase(e){return e.prepare(`PRAGMA database_list;`).all().find(e=>e.name===`main`)?.file===``}function requireRollbackJournalMode(e,t){let n=readJournalModeResult(e.prepare(`PRAGMA journal_mode = DELETE;`).get());if(n!==`delete`){let e=t.databaseLabel??`sqlite database`,r=t.databasePath?` at ${t.databasePath}`:``;throw Error(`${e}${r} is on a network-backed volume but SQLite kept journal_mode=${n??`unknown`}; refusing to continue with WAL on network storage.`)}}function enableSqliteWalJournalMode(e,t,n){let r=vc.now()+t,i=!1;try{for(;;)try{let t=readJournalModeResult(e.prepare(`PRAGMA journal_mode = WAL;`).get());if(t===`wal`)return!0;if(t===`memory`&&hasInMemoryMainDatabase(e))return!1;let r=n.databaseLabel??`sqlite database`,i=n.databasePath?` at ${n.databasePath}`:``;throw Error(`${r}${i} could not enable WAL; SQLite kept journal_mode=${t??`unknown`}.`)}catch(t){let n=Math.max(0,r-vc.now());if(!Oa(t)||n<=0)throw t;i||=(oo(e,0),!0),Atomics.wait($d,0,0,Math.min(10,n))}}finally{i&&oo(e,t)}}function enableMacosCheckpointFullfsync(e){if(process.platform===`darwin`)try{e.exec(`PRAGMA checkpoint_fullfsync = 1;`)}catch{}}function refuseUnsupportedFilesystem(e){let t=e.databaseLabel??`sqlite database`,n=e.databasePath?` at ${e.databasePath}`:``;throw Error(`${t}${n} is on SSHFS, which cannot safely coordinate SQLite writes across mounts; refusing to open the database.`)}function configureSqliteWalMaintenance(t,n={}){let r=n.busyTimeoutMs??0;n.busyTimeoutMs!==void 0&&oo(t,n.busyTimeoutMs);let i=ms(n.autoCheckpointPages??16384,`autoCheckpointPages`),a=ms(n.checkpointIntervalMs??18e5,`checkpointIntervalMs`),o=Math.min(a,Qn),s=a>Zd?Zd:0,c=n.checkpointMode??`TRUNCATE`,l=n.checkpointMode??`PASSIVE`,u=n.databasePath?resolvePathJournalPolicy(n.databasePath):`wal`;if(u===`unsupported`&&refuseUnsupportedFilesystem(n),u===`rollback`&&requireRollbackJournalMode(t,n),u===`rollback`||!enableSqliteWalJournalMode(t,r,n))return{checkpoint:()=>!0,reclaimFreePages:(e={})=>reclaimSqliteWalFreePages(t,()=>!0,e),stop:async()=>{},close:()=>!0};enableMacosCheckpointFullfsync(t),t.exec(`PRAGMA wal_autocheckpoint = ${Wt(t)?0:i};`),t.exec(`PRAGMA journal_size_limit = ${Qd};`);let d=process.platform===`linux`&&n.databasePath&&Y.existsSync(n.databasePath)?Y.realpathSync.native(n.databasePath):void 0,f=!1,p=!1,m=!!d,h=createSqliteWalCheckpoint(t,n,Qd),g=h.checkpoint,runMaintenance=e=>{if(f||p)return!1;try{return n.runMaintenance?n.runMaintenance(e):e()}catch(e){return h.recordError(e),!1}},checkpoint=()=>runMaintenance(()=>g(c)),reclaimFreePages=(e={})=>{let n,r;if(runMaintenance(()=>{try{return n=reclaimSqliteWalFreePages(t,g,e),n.checkpointCompleted}catch(e){throw r={error:e},e}}),r)throw r.error;if(!n)throw Error(`SQLite page reclamation owner is unavailable`);return{...n,checkpoint:h.snapshot}},_=tf.scope(),v=`sqlite-wal:${++nf}`,y=0,b,maintainPeriodic=(e,n,r)=>{if(f)return{reclaimedPages:0};e.checkpoint&&h.adopt(e.checkpoint);let i=0,a=e.maxPages===0,o=a&&e.checkpointMode===`PASSIVE`,s=o?Mi(t):void 0,c=s===void 0?void 0:sharedCompletedCheckpoint(t,s),l=c!==void 0&&Atomics.load(c,0)===s;if(s!==void 0&&(l||s===b&&h.health?.state===`complete`))return{reclaimedPages:0,checkpoint:h.health?.state===`complete`?h.snapshot:void 0};let runTickCheckpoint=e=>h.checkpoint(e,{quiet:a});return b=runMaintenance(()=>{let a;if(o)n?.(`transaction`),a=runTickCheckpoint(`PASSIVE`);else{let r=reclaimSqliteWalFreePages(t,runTickCheckpoint,{checkpointMode:e.checkpointMode,maxPages:e.maxPages,beforeMutation:()=>n?.(`transaction`),onCommit:()=>n?.(`commit`)});a=r.checkpointCompleted,a&&r.freePagesBefore!==null&&r.remainingFreePages!==null&&(i=Math.min(r.vacuumPagesRequested,r.freePagesBefore-r.remainingFreePages))}if(a&&e.checkpointMode===`PASSIVE`&&(h.health?.walBytes??0)>Qd&&(n?.(`transaction`),ps(t,0,()=>runTickCheckpoint(`TRUNCATE`))),a&&e.maxPages>0&&!e.continuation)try{r?.()}catch(e){if(!Oa(e))throw e}return a})&&h.health?.state===`complete`?s:void 0,c&&b!==void 0&&Atomics.store(c,0,b),{reclaimedPages:i,checkpoint:h.snapshot}},stopCheckpointTick,ee=ot(t,maintainPeriodic,e=>o>0&&!_.signal.aborted&&!f&&!p&&!n.isScheduledMaintenanceSuspended?.()?{maxPages:e,checkpointMode:l,checkpoint:h.snapshot}:void 0,h.adopt,e=>h.recordError(e),()=>{let e=y;return y=0,e},()=>stopCheckpointTick?.()),schedule=(e,t,r)=>gn(()=>_.schedule({id:`${v}:${e}`,delayMs:e===`periodic`&&n.checkpointIntervalMs===void 0?t+Math.floor(Math.random()*t):t,everyMs:t,run:r}));if(o>0&&schedule(`periodic`,o,async()=>{if(d&&m){p=!0;let e=Ro(t,()=>{throw Error(`SQLite WAL inspection is pending; await maintenance.stop() before close`)});try{let e;try{e=await detectSqliteWalSplitBrain(d)}catch(e){m=!1,ef.warn(`SQLite WAL split-brain detection disabled`,{databaseLabel:n.databaseLabel,databasePath:d,error:e instanceof Error?e.message:String(e)})}e&&(f=!0,_.beginClose(),terminateForSqliteWalSplitBrain(e,n.databaseLabel))}finally{e(),p=!1}if(_.signal.aborted)return}return y=512,ee()}),s>0&&!Wt(t)){let e=!1,n,cancelTick=()=>{n?.cancel(),n=void 0},armTick=()=>{e||n||_.signal.aborted||f||(n=gn(()=>_.schedule({id:`${v}:tick`,delayMs:s,run:runTick})))},runTick=async()=>{if(n=void 0,await ee(),e)return;let r=Mi(t),i=r===void 0?void 0:sharedCompletedCheckpoint(t,r);i&&Atomics.load(i,0)===r?cancelTick():armTick()},r=l===`PASSIVE`?ci(t,armTick):void 0;r?(stopCheckpointTick=()=>{e=!0,r(),cancelTick()},armTick()):stopCheckpointTick=schedule(`tick`,s,ee).cancel}let beginClose=()=>(stopCheckpointTick?.(),gn(()=>_.beginClose()),e(t));return{get health(){return h.health},checkpoint,maintainPeriodic,reclaimFreePages,inspectIdle:()=>runMaintenance(h.inspectIdle)?`healthy`:`retire`,stop:async()=>{try{await beginClose()}finally{await gn(()=>_.stop())}},close:e=>(beginClose(),f||Wt(t)?!1:runMaintenance(()=>g(e?.checkpointMode??c)))}}function configureSqliteConnectionPragmas(e,t={}){let{foreignKeys:n,synchronous:r,...i}=t,a=configureSqliteWalMaintenance(e,i);try{return r&&e.exec(`PRAGMA synchronous = ${r};`),n&&e.exec(`PRAGMA foreign_keys = ON;`),a}catch(e){try{a.close()}catch(t){throw Zr([e,t],`SQLite connection pragma configuration and WAL maintenance cleanup both failed.`,e)}throw e}}function hasExplicitModelPolicyAllow(e){return I(e)&&Object.hasOwn(e,`allow`)}const af={};let of=/* @__PURE__ */ new WeakSet,sf=0;function boundFrozenPlainData(e){sf>262144&&(of=new WeakSet([e]),sf=1)}function isPlainDataObject(e){if(lc(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype||Array.isArray(e)&&t===Array.prototype}function inspectPlainData(e,t,n=!0){if(!e||typeof e!=`object`)return typeof e!=`function`;if(of.has(e))return!0;if(!t&&n&&(lc(e)||!Object.isFrozen(e)))return!1;let r=!0,i=/* @__PURE__ */ new Set,a=[e];for(;a.length;){let e=a.pop();if(!i.has(e)){if(isPlainDataObject(e)){if(!t&&n&&!Object.isFrozen(e))return!1;i.add(e);for(let n of Reflect.ownKeys(e)){let i=Object.getOwnPropertyDescriptor(e,n),o=i.value;if(!(`value`in i)||typeof o==`function`){if(!t)return!1;r=!1}else o&&typeof o==`object`&&!of.has(o)&&a.push(o)}t&&Object.freeze(e)}else{if(!t)return!1;r=!1}}}if(r&&(t||n)){for(let e of i)of.add(e);sf+=i.size,boundFrozenPlainData(e)}return r}function isDeeplyFrozenPlainData(e){return inspectPlainData(e,!1)}function freezeJsonSnapshot(e){return inspectPlainData(e,!0),e}function memoizeFrozenPlainDataProjection(e){let t=/* @__PURE__ */ new WeakMap;return n=>{if(t.has(n))return t.get(n);if(!isDeeplyFrozenPlainData(n))return e(n);let r=freezeJsonSnapshot(e(n));return t.set(n,r),r}}new Set([{id:`openclaw`,kind:`system`},{id:`crestodian`,kind:`system`}].map(e=>q(e.id)));let cf;const lf=/* @__PURE__ */ new WeakMap;function readAgentRosterFacts(e){if(e===void 0)return cf.facts;let t=af.current,n=t?.config===e?t.revision:void 0;if(n===void 0&&!isDeeplyFrozenPlainData(e))return;let r=lf.get(e);return r&&r.publication===n||(r={publication:n,facts:{}},lf.set(e,r)),r.facts}function collectAgentEntries(e,t,n){let r=readAgentRosterProperty(e);if(r?.kind===`entries`&&I(r.value)){let e=[];for(let i in r.value){if(!Object.hasOwn(r.value,i))continue;let a=r.value[i];if(I(a)){let r={...a,id:i};if(e.push(t?{entry:r,source:{kind:`entries`,key:i}}:r),e.length===n)break}}return e}if(r?.kind!==`list`||!Array.isArray(r.value))return[];let i=[];return r.value.some((e,t)=>(typeof e==`object`&&e&&i.push({entry:e,source:{kind:`list`,index:t}}),i.length===n)),t?i:i.map(({entry:e})=>e)}function listAgentEntriesWithSource(e){return collectAgentEntries(e,!0)}function listAgentEntries(e){return collectAgentEntries(e,!1)}function readAgentRosterProperty(e){if(!I(e))return;let t=e.agents;if(I(t))for(let e of[`entries`,`list`]){let n=t[e];if(Object.hasOwn(t,e)&&n!==void 0)return{kind:e,value:n}}}function hasAgentRosterProperty(e){return readAgentRosterProperty(e)!==void 0}function listAgentIds(e){let t=readAgentRosterFacts(e);if(t?.agentIds)return t.agentIds;let n=listAgentEntries(e),r=n.length===0&&!hasAgentRosterProperty(e)?[`main`]:[...new Set(n.map(e=>q(e?.id)))];return t&&(Object.freeze(r),t.agentIds=r),r}function resolveConcreteSessionStorePath(e){let t=e?.trim();if(t&&t!==`(multiple)`&&!t.includes(`{agentId}`))return t}function resolveUnsuffixedSqliteTargetFromSessionStorePath(e){let t=resolveConcreteSessionStorePath(e);if(!t)throw Error(`Session storage requires a concrete store path`);let n=X.resolve(t);if(n.endsWith(`.sqlite`)){let e=resolveAgentIdFromSqliteDatabasePath(n);return{path:n,...e?{agentId:e}:{shared:!0}}}let r=X.dirname(n);if(X.basename(n)!==`sessions.json`){let e=X.basename(n,X.extname(n))||`openclaw-agent`;return{path:X.join(r,`${e}.sqlite`)}}if(X.basename(r)!==`sessions`)return{path:X.join(r,`openclaw-agent.sqlite`)};let i=X.dirname(r);return X.basename(X.dirname(i))===`agents`?{agentId:q(X.basename(i)),path:X.join(i,`agent`,`openclaw-agent.sqlite`)}:{path:X.join(r,`openclaw-agent.sqlite`)}}function listSqliteTargetCandidatePathsForSessionStorePath(e,t){let n=resolveUnsuffixedSqliteTargetFromSessionStorePath(e);if(n.agentId||n.shared)return[n.path];let r=X.dirname(n.path),i=X.basename(n.path,`.sqlite`),a=t?`${i}.${q(t)}`:void 0,o=/* @__PURE__ */ new Set([X.basename(n.path)]);try{for(let e of Y.readdirSync(r)){let t=e.replace(/-(?:wal|shm|journal)$/u,``);t.startsWith(`${i}.`)&&t.endsWith(`.sqlite`)&&(!a||parseSqliteTargetSuffixIndex(t,a)!==void 0)&&o.add(t)}}catch(e){Dn(e)}return[...o].map(e=>X.join(r,e))}function parseSqliteTargetSuffixIndex(e,t){if(e===`${t}.sqlite`)return 1;if(!e.startsWith(`${t}.`)||!e.endsWith(`.sqlite`))return;let n=e.slice(t.length+1,-7);if(!/^[1-9]\d*$/.test(n))return;let r=Number(n);return Number.isSafeInteger(r)&&r>=2&&String(r)===n?r:void 0}function resolveAgentIdFromSqliteDatabasePath(e){if(X.basename(e)!==`openclaw-agent.sqlite`)return;let t=X.dirname(e);if(X.basename(t)!==`agent`)return;let n=X.dirname(t);if(X.basename(X.dirname(n))===`agents`)return q(X.basename(n))}function resolveSessionTranscriptsDirForAgent(e,t=process.env,n=()=>dn(t,ic.homedir)){if(!e?.trim())throw Error(`Session storage path requires an explicit agent id.`);let r=Cn(t,n),i=q(e);return X.join(r,`agents`,i,`sessions`)}var SessionStoreAgentIdRequiredError=class extends Error{constructor(){super(`Session store path requires an explicit agent id.`),this.name=`SessionStoreAgentIdRequiredError`}};function resolveSessionStorePathCore(e,t){let n=t?.env??process.env,homedir=()=>dn(n,ic.homedir);if(!e){if(!t?.agentId?.trim())throw new SessionStoreAgentIdRequiredError;return`${resolveSessionTranscriptsDirForAgent(t.agentId,n,homedir)}${X.sep}sessions.json`}let r=e;if(r.includes(`{agentId}`)){if(!t?.agentId?.trim())throw new SessionStoreAgentIdRequiredError;let e=q(t.agentId);r=r.replaceAll(`{agentId}`,e)}return r.startsWith(`~`)&&(r=wn(r,{home:dn(n,homedir),env:n,homedir})),X.isAbsolute(r)?X.resolve(r):X.resolve(Cn(n,homedir),r)}function resolveDefaultAgentWorkspaceDir(e=process.env,t=ic.homedir){let n=e.OPENCLAW_WORKSPACE_DIR?.trim();if(n)return X.resolve(n);if(e.OPENCLAW_STATE_DIR?.trim())return X.join(Cn(e,t),`workspace`);let r=dn(e,t),i=e.OPENCLAW_PROFILE?.trim();return i&&Pn(i)!=="default"?X.join(rr(i,e,t),`workspace`):X.join(r,`.openclaw`,`workspace`)}resolveDefaultAgentWorkspaceDir();function resolveAgentEntry(e,t){let n=q(t),r=readAgentRosterFacts(e);if(r){let t=(r.entryByNormalizedId??=buildAgentEntryIndex(e)).get(n);return t?t.clone?{...t.entry}:t.entry:void 0}let i=readAgentRosterProperty(e);if(i?.kind===`entries`&&I(i.value)){let e=i.value;for(let t in e){if(!Object.hasOwn(e,t))continue;let r=e[t];if(I(r)&&q(t)===n)return{...r,id:t}}}else if(i?.kind===`list`&&Array.isArray(i.value))return i.value.find(e=>typeof e==`object`&&!!e&&q(e.id)===n)}function buildAgentEntryIndex(e){let t=/* @__PURE__ */ new Map;for(let{entry:n,source:r}of listAgentEntriesWithSource(e)){let e=q(n?.id);t.has(e)||t.set(e,{clone:r.kind===`entries`,entry:n})}return t}function resolveAgentConfig(e,t){let n=q(t),r=resolveAgentEntry(e,n)??(!hasAgentRosterProperty(e)&&n===`main`?{id:n}:void 0);if(!r)return;let i=e.agents?.defaults;return{name:r.name,workspace:r.workspace,workspaceFileMode:r.workspaceFileMode??i?.workspaceFileMode,agentDir:r.agentDir,model:r.model,...r.models?{models:r.models}:{},...r.params?{params:r.params}:{},...r.runtime?{runtime:r.runtime}:{},...hasExplicitModelPolicyAllow(r.modelPolicy)?{modelPolicy:r.modelPolicy}:{},utilityModel:r.utilityModel,decisionModel:r.decisionModel,thinkingDefault:r.thinkingDefault,verboseDefault:r.verboseDefault??i?.verboseDefault,toolProgressDetail:r.toolProgressDetail??i?.toolProgressDetail,reasoningDefault:r.reasoningDefault,fastModeDefault:r.fastModeDefault??i?.fastModeDefault,newSessionPermissionMode:r.newSessionPermissionMode,contextInjection:r.contextInjection,bootstrapMaxChars:r.bootstrapMaxChars,bootstrapTotalMaxChars:r.bootstrapTotalMaxChars,experimental:r.experimental?{...i?.experimental,...r.experimental}:i?.experimental,skills:r.skills,memory:r.memory,humanDelay:r.humanDelay,typingMode:r.typingMode??i?.typingMode,tts:r.tts,...r.compaction?{compaction:r.compaction}:{},contextLimits:r.contextLimits?{...i?.contextLimits,...r.contextLimits}:i?.contextLimits,heartbeat:r.heartbeat,identity:r.identity,groupChat:r.groupChat,subagents:r.subagents,embeddedAgent:r.embeddedAgent,sandbox:r.sandbox,tools:r.tools}}function resolveEffectiveAgentDir(e,t,n){let r=q(t),i=resolveAgentConfig(e,r)?.agentDir?.trim(),a=n?.env??process.env;return i?yn(i,a,n?.homedir):X.join(Cn(a,n?.homedir),`agents`,r,`agent`)}function readBackupEngine(e){return xo(e,void 0,hs(`shared`,e)?`backup-engine-preserving`:`backup-engine`)}const uf=er(`config`);function normalizeLegacyWorkboardDatabaseConfig(e,t){if(!I(e)||!I(e.database))return e;let n=e.database;if(_n(n.engine,t)!==`postgres`||n.families!==void 0)return e;let r=Cn(t),i=X.join(r,`state/openclaw.sqlite`),a=X.join(r,`plugins/workboard/workboard.sqlite`);return!Y.existsSync(i)||!Y.existsSync(a)||!xo(i,void 0,`state-sqlite-populated`)||readBackupEngine(a).engine!==`postgres`?e:(uf.warn(`Preserving the 2026.11.1 Workboard-only PostgreSQL setting: Workboard remains on PostgreSQL; shared state and other families remain on SQLite. The next config write records this explicitly.`),{...e,database:{...n,engine:`sqlite`,families:{workboard:{engine:`postgres`}}}})}const df=/* @__PURE__ */ new WeakMap;function createConfigResolutionFacts(e,t=/* @__PURE__ */ new Map,n=xn,r=/* @__PURE__ */ new Map){let i=new Set(e.map(({configPath:e})=>e)),a=n?.trim()||`default`;if(t.size>0||r.size>0){let e=/* @__PURE__ */ new Map;for(let[n,i]of[[`pending`,t],[`resolved`,r]])for(let[t,r]of i)e.set(t,{ref:{source:`env`,provider:a,id:r},state:n});df.set(i,e)}return i}function coerceConfig(e){return Vn(e)??{}}function normalizeConfigIoDeps(e={}){let t=e.env??process.env;return{fs:e.fs??Y,env:t,lowerPrecedenceEnv:e.lowerPrecedenceEnv??{},homedir:e.homedir??(()=>dn(t,ic.homedir)),configPath:e.configPath??``,mapIncludePath:e.mapIncludePath??(e=>e),logger:e.logger??console,measure:e.measure??(async(e,t)=>await t()),suppressFutureVersionWarning:e.suppressFutureVersionWarning??(sn(t.OPENCLAW_UPDATE_IN_PROGRESS)||sn(t.OPENCLAW_UPDATE_POST_CORE)),observe:e.observe??!0}}function parseConfigJson5(e){try{return{ok:!0,parsed:pn(e,kc)}}catch(e){return{ok:!1,error:String(e)}}}function resolveConfigIncludesForRead(e,t,n,r,i,a,o){let s=Yn(n.env,n.homedir),recordIncludeWatchPath=e=>{a?.add(X.normalize(e))},recordIncludeTarget=(e,n)=>{if(!i)return;let r=X.normalize(e);try{i[r]=X.normalize(n??Fn({configPath:t,includePath:e,allowedRoots:s}))}catch{}};return kn(e,t,{readFile:e=>n.fs.readFileSync(e,`utf-8`),mapPath:n.mapIncludePath,onLexicalPath:recordIncludeWatchPath,onIncludeResolved:o,readFileWithGuards:({includePath:e,resolvedPath:t,rootRealDir:i})=>{try{let a=In({includePath:e,resolvedPath:t,rootRealDir:i,ioFs:n.fs,onResolvedPath:e=>{recordIncludeWatchPath(e),recordIncludeTarget(t,e)}});return r&&(r[X.normalize(t)]=Un(a)),a}catch(e){let n=ir(e,e=>[e.cause]).some(e=>un(e)===`ENOENT`);throw r&&n&&(r[X.normalize(t)]=Un(null)),n&&recordIncludeTarget(t),e}},parseJson:e=>kc.parse(e)},{allowedRoots:s})}function resolveConfigForRead(e,t,n={}){e&&typeof e==`object`&&`env`in e&&We(e,t,{lowerPrecedenceEnv:n});let r=[],i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=_n(e,t,{onMissing:e=>r.push(e),onPendingEnvSecretRef:(e,t)=>i.set(t,e),onResolvedEnvSecretRef:(e,t)=>a.set(t,e)});return{resolvedConfigRaw:normalizeLegacyWorkboardDatabaseConfig(tt(o,t),t),envSnapshotForRestore:Ce(t),envWarnings:r,resolutionFacts:createConfigResolutionFacts(r,i,coerceConfig(o).secrets?.defaults?.env,a)}}function listConfiguredSessionStoreAgentIds(e){let t=new Set(listAgentIds(e).map(e=>q(e))),addAcpAgentId=e=>{let n=e?.trim()??``;n&&n!==`*`&&t.add(q(n))};addAcpAgentId(e.acp?.defaultAgent);for(let t of e.acp?.allowedAgents??[])addAcpAgentId(t);for(let t of listAgentEntries(e))t.runtime?.type===`acp`&&addAcpAgentId(t.runtime.acp?.agent??t.id);return[...t]}function readAgentStorePathsFromConfig(e,t){let n=Ce(e);n.OPENCLAW_STATE_DIR=t;let r=nr(n,t),i=`{}`;try{i=Y.readFileSync(r,`utf8`)}catch(e){Dn(e)}let a=parseConfigJson5(i);if(!a.ok)throw Error(`Cannot parse agent storage configuration at ${r}.`);let o=normalizeConfigIoDeps({env:n,configPath:r,observe:!1}),s=resolveConfigIncludesForRead(a.parsed,r,o);if(!I(s)||[`agents`,`session`].some(e=>s[e]!==void 0&&!I(s[e])))throw Error(`Invalid agent storage configuration at ${r}.`);let c=readAgentRosterProperty(s),hasValidStorageLocator=e=>I(e)&&(e.agentDir===void 0||typeof e.agentDir==`string`);if(c&&(c.kind===`entries`?!I(c.value)||Object.values(c.value).some(e=>!hasValidStorageLocator(e)):!Array.isArray(c.value)||c.value.some(e=>!hasValidStorageLocator(e)||typeof e.id!=`string`)))throw Error(`Invalid agent roster at ${r}.`);if(I(s.session)&&s.session.store!==void 0&&typeof s.session.store!=`string`)throw Error(`Invalid session storage configuration at ${r}.`);let l=resolveConfigForRead(s,n);if(l.envWarnings.some(e=>e.configPath===`session.store`||e.configPath.endsWith(`.agentDir`)||e.configPath.startsWith(`agents.list[`)&&e.configPath.endsWith(`.id`)||e.configPath===`acp.defaultAgent`||e.configPath.startsWith(`acp.allowedAgents`)||e.configPath.endsWith(`.runtime.type`)||e.configPath.endsWith(`.runtime.acp.agent`)))throw Error(`Unresolved environment reference in agent storage configuration at ${r}.`);let u=coerceConfig(l.resolvedConfigRaw),d=listAgentIds(u),f=new Set(d.map(e=>X.join(resolveEffectiveAgentDir(u,e,{env:n}),`openclaw-agent.sqlite`))),p=new Set(listConfiguredSessionStoreAgentIds(u).map(e=>resolveSessionStorePathCore(u.session?.store,{agentId:e,env:n})));for(let e of p)for(let t of listSqliteTargetCandidatePathsForSessionStorePath(e))f.add(t);for(let e of[n.OPENCLAW_AGENT_DIR,n.PI_CODING_AGENT_DIR])e?.trim()&&f.add(X.join(yn(e,n),`openclaw-agent.sqlite`));return[...f]}function resolveOpenClawAgentDatabaseDiscoveryPaths(e){return[Uo(e),Qo(e)].map(t=>X.join(e.agentDir,X.basename(t)))}function prepareStateDatabaseInitialization(e,t,n=[]){try{if(ve(Bo(t)).some(e=>Y.lstatSync(e,{throwIfNoEntry:!1})))return{kind:`existing`};let r=is(e),i=/* @__PURE__ */ new Set([...n,...readAgentStorePathsFromConfig(t,r)]),a=X.join(r,`agents`);if(Y.lstatSync(a,{throwIfNoEntry:!1})?.isSymbolicLink())return{kind:`unavailable`};let o=[];try{o=Y.readdirSync(a,{withFileTypes:!0})}catch(e){Dn(e)}for(let e of o){if(!e.isDirectory()&&!e.isSymbolicLink())continue;let n=X.join(a,e.name,`agent`);if(e.isSymbolicLink()||Y.lstatSync(n,{throwIfNoEntry:!1})?.isSymbolicLink())return{kind:`unavailable`};for(let r of resolveOpenClawAgentDatabaseDiscoveryPaths({agentDir:n,agentId:e.name,env:t}))i.add(r)}for(let e of i){let t=ve(e),n=Y.lstatSync(e,{throwIfNoEntry:!1});if(n&&(!n.isFile()||n.size>0)||t.slice(1).some(e=>Y.lstatSync(e,{throwIfNoEntry:!1})))return{kind:`existing`}}return ve(e).some(e=>Y.lstatSync(e,{throwIfNoEntry:!1}))?{kind:`existing`,nativeBootstrapEligible:!0}:{kind:`fresh`}}catch{return{kind:`unavailable`}}}function createDedupeCache(e){let t=Mn(e.ttlMs,0),n=Mn(e.maxSize,0),r=/* @__PURE__ */ new Map,i=1/0,a=-1/0,o=!0,prune=e=>{let a=t>0?e-t:void 0;if(a!==void 0&&a>=i){i=1/0;for(let[e,t]of r)if(t.recordedAt<=a)r.delete(e);else if(t.recordedAt<i&&(i=t.recordedAt,o))break}n<=0?(r.clear(),i=1/0):Hn(r,n)},hasUnexpired=(e,n,i)=>{let a=r.get(e);return a?t>0&&n-a.recordedAt>=t?(r.delete(e),!1):(i&&(a.recordedAt=n,r.delete(e),r.set(e,a)),!0):!1};return{check:(e,n,s)=>{if(!e)return!1;let c=n??Date.now();return t>0&&(c<i&&(i=c),o&&(o=c>=a,a=c)),hasUnexpired(e,c,!0)?!0:(r.set(e,{recordedAt:c,...s?{ownerToken:s}:{}}),prune(c),!1)},peek:(e,t=Date.now())=>e?hasUnexpired(e,t,!1):!1,delete:(e,t)=>{e&&(t&&r.get(e)?.ownerToken!==t||r.delete(e))},clear:()=>{r.clear(),i=1/0,a=-1/0,o=!0},size:()=>r.size}}const ff=er(`state/db`),pf=createDedupeCache({ttlMs:0,maxSize:4096});function bestEffortChmodSync(e,t){let n;try{n=Me(e,t)}catch(t){if(!cn(t,`EPERM`)||!process.getuid||Xs(e).uid===process.getuid())throw t;n={applied:!1,error:t}}n.applied||pf.check(e)||ff.warn(`skipped permission hardening for ${e}: ${String(n.error)}`)}Object.freeze([[`client`,`credentials.sqlite`],[`control`,`services.sqlite`]]);function ensureOpenClawStatePermissions(e,t,n={}){let r=X.dirname(e),i=Do(t),a=X.dirname(i),o=X.resolve(e)===X.resolve(i);if(o&&r!==a)throw Error(`OpenClaw state database path resolved outside its state dir: ${e}`);let s=Ks(r);n.createDirectory&&qs(r,{recursive:!0,mode:448}),(o||!s)&&bestEffortChmodSync(r,448);for(let t of ve(e))if(Ks(t))try{bestEffortChmodSync(t,384)}catch(n){if(t===e||!cn(n,`ENOENT`))throw n}}function hasVerifiedLiveSqliteOwner(e,t){if(Qt.get(X.resolve(e))?.accepting)return!0;let n=en(e),r;try{r=i(Y.readFileSync(n,`utf8`))}catch{return!1}if(!r||r.role&&r.role!==`gateway`&&r.role!==`agent-embedded`||u(r,n)===`dead`)return!1;let a=readStateLeaseProcessOwnerStatus({pid:r.pid,host:r.processNamespace?.host??ac(),startedAt:r.startTime??null,processNamespace:r.processNamespace,machineIdentity:r.machineIdentity});if(a===`unknown`&&t?.unknownOwner!==`return-false`)throw new g(r,n);return a===`live`}const mf=R(Symbol.for(`openclaw.pluginSharedStateAdmission`),()=>({}));function getPluginSharedStateResourceHost(){return mf.resolveHost?.()}function runPluginSharedStateWork(e){let t=getPluginSharedStateResourceHost();return t?t.trackSharedStateWork(e):e()}function assertStateReadSchemaForPolicy(e,t,n,r,i,a=`runtime`){z(e)?(r!==void 0&&Fa(`postgres`,`integrity`),assertSupportedStateSchemaVersion(e,t,void 0,i,a)):n?assertExistingOpenClawStateRuntimeSchema(e,t,be(),r,a):assertSupportedStateSchemaVersion(e,t,void 0,i,a)}const hf=R(Symbol.for(`openclaw.postgresStateReadSnapshot`),()=>new ec),gf=/* @__PURE__ */ new Map,_f=/* @__PURE__ */ new WeakSet;let vf;function retireReader(e){gf.get(e.identity.key)===e&&(clearTimeout(e.idleTimer),e.idleTimer=void 0,e.retiring=!0,e.connection.close(),e.quarantineAdmission?.release(),gf.delete(e.identity.key),gf.size||(vf?.(),vf=void 0))}function scheduleReaderRetirement(e){Xr().explicitSqliteCloseReleasesNativeResources&&gf.get(e.identity.key)===e&&(e.idleTimer??=gn(()=>setTimeout(()=>{try{retireReader(e)}catch(t){process.emitWarning(`Idle shared-state reader cleanup failed: ${String(t)}`),scheduleReaderRetirement(e)}},gt).unref()),e.idleTimer.refresh())}function closeRetainedOpenClawStateReadConnections(e){let t=[];for(let n of gf.values())if(e===void 0||n.identity.key===e)try{retireReader(n)}catch(e){t.push(e)}G(t,`Retained shared-state reader cleanup failed.`)}function borrowStateReadConnection(e,t,n){if(isStatePostgres())return openStateReadConnectionResult(e,e,t,void 0,!0);T(e);let r=jr(e);t!==void 0&&oi(e,t);for(let e of gf.values())e.identity.canonicalPath===r.canonicalPath&&e.identity.key!==r.key&&retireReader(e);if(!r.key.startsWith(`file:`))return openStateReadConnectionResult(e,e,t);let i=gf.get(r.key);if((i?.retiring||i&&!i.connection.database.db.isOpen)&&(retireReader(i),i=void 0),i?.borrowed)return openStateReadConnectionResult(e,e,r.key);if(!i){let t=openStateReadConnectionResult(e,e,r.key);if(t.status===`unavailable`)return t;i={connection:t.value,identity:r,retiring:!1,borrowed:!1},gf.set(r.key,i),vf??=Ln(closeRetainedOpenClawStateReadConnections)}let a=i;if(a.quarantineAdmission?.location!==n||!a.quarantineAdmission?.isCurrent()){a.quarantineAdmission?.release(),a.quarantineAdmission=void 0;try{a.quarantineAdmission=n?Ci(n):void 0}catch{}}return Eo(a),a.borrowed=!0,{status:`available`,value:{database:{db:a.connection.database.db,path:e},close(e){return a.borrowed=!1,e&&a.connection.database.db.isOpen&&!a.connection.database.db.isTransaction?scheduleReaderRetirement(a):retireReader(a),!0}}}}var SnapshotCleanupIncompleteError=class extends Error{};function assertStateReadSchema(e,t,n,r=`runtime`){assertStateReadSchemaForPolicy(e,t,T(t,e),n,void 0,r)}function withOpenClawStateReadOnlyLocation(e,t,n,r,i,a,o=!1,s,c){let l=readOpenClawStateReadOnlyLocation(e,t,n,r,i,a,o,s,c);if(l.status===`unavailable`)throw l.error;return l.value}function readOpenClawStateReadOnlyLocation(e,t,n,r,i,a,o=!1,s,c){let l=typeof n!=`string`&&`connection`in n?n.connection:void 0,u=typeof n!=`string`&&`connection`in n?n.location:n,d=l?{status:`available`,value:l}:o&&u===t&&!a?borrowStateReadConnection(t,i,c):openStateReadConnectionResult(t,u,i,a,!0);if(d.status===`unavailable`)return d;let f=d.value,p=[],m,h;try{r&&!z(f.database.db)&&(m=r(f.database.db));let n=T(t,f.database.db),i=r?`doctor-maintenance`:`runtime`;try{let r=!1,a=hf.getStore(),read=()=>Xa(f.database.db,()=>{admitStateSchemaFacts(f.database.db,t,i),assertStateReadSchemaForPolicy(f.database.db,t,n,void 0,s,i),r=!0;let a=e(f.database);if(u===t&&lr(a))throw new Ta(`SQLite source read must remain synchronous`);return a});h={status:`available`,value:withPostgresSchemaAdmissionRetry(f.database.db,()=>z(f.database.db)?f.database.db.runTransaction(()=>(a?.path===t&&f.database.db.exec(`SET TRANSACTION SNAPSHOT '${a.snapshot.replaceAll(`'`,`''`)}'`),read()),void 0,!0):l&&u===t?Ct(f.database.db,read):read(),()=>!r&&a?.path!==t)}}catch(e){!z(f.database.db)&&wi(e)&&(Jt(f.database.db),_f.add(f.database.db)),h={status:`unavailable`,error:e}}Xe(f.database.db)}catch(e){p.push(e)}try{m?.()}catch(e){p.push(e)}try{let e=typeof n!=`string`&&p.length===0&&h?.status===`available`&&!Xr().explicitSqliteCloseReleasesNativeResources;if(!l&&!f.close(p.length===0&&h?.status===`available`&&!_f.has(f.database.db))&&!e)throw new SnapshotCleanupIncompleteError(`Shared-state snapshot cleanup is incomplete.`)}catch(e){p.push(e)}return p.length&&(h?.status===`unavailable`&&!p.includes(h.error)&&p.unshift(h.error),G(p,`Shared-state read and reader cleanup failed.`)),h}function openOpenClawStateReadOnlyLocation(e,t){let n=openOpenClawStateReadConnection(e,t);try{Xa(n.database.db,()=>{admitStateSchemaFacts(n.database.db,e),assertStateReadSchema(n.database.db,e)})}catch(e){try{n.close()}catch(t){G([e,t],`Shared-state reader admission and cleanup failed.`)}throw e}return n}function openOpenClawStateReadConnection(e,t,n,r){let i=openStateReadConnectionResult(e,t,n,r);if(i.status===`unavailable`)throw i.error;return i.value}function openStateReadConnectionResult(e,t,n,r,i=!1){let a=typeof t==`string`?void 0:t,o=typeof t==`string`?t:t.location,s=ua(o),c={readOnly:!0,timeout:Wo},l,cleanupFailedOpen=e=>{let t=[e];try{l?.()}catch(e){t.push(e)}try{a&&!a.cleanup()&&t.push(new SnapshotCleanupIncompleteError(`Shared-state snapshot cleanup is incomplete.`))}catch(e){t.push(e)}if(t.length>1)throw Zr(t,`Shared-state reader open and cleanup failed.`,e)},u;try{if(isStatePostgres()){(t!==e||r)&&assertStateFileSnapshotAllowed(),i&&T(e);let a=openExistingStatePostgresConnection(e,n);if(a)return{status:`available`,value:a}}if(n!==void 0&&oi(s,n),l=r?Dt(r):void 0,i&&T(e),o===e)u=Ae(e,c);else try{u={status:`available`,database:Ga(o,c)}}catch(e){u={status:`unavailable`,error:e}}}catch(e){throw cleanupFailedOpen(e),e}if(u.status===`unavailable`)return cleanupFailedOpen(u.error),u;let d=u.database,f=!1,p=!1,m=0,h={db:d,path:e,afterClose:()=>{if(l?.(),a&&m===0&&!a.cleanup())throw new SnapshotCleanupIncompleteError(`Shared-state snapshot cleanup is incomplete.`)}},g={database:{db:d,path:e},snapshotSource:a?{retain(){if(p||f)throw Error(`Shared-state snapshot source is closing or closed`);let e=Za(a.cleanupRoot??X.dirname(a.location));m++;let t=!1;return{location:a.location,cleanupRoot:a.cleanupRoot,async release(){if(t||(t=!0,e(),m--),f&&m===0&&!await a.cleanupAsync())throw new SnapshotCleanupIncompleteError(`Shared-state snapshot cleanup is incomplete.`)}}}}:void 0,close(){if(f)return!1;p=!0;let e=j.closeOpenClawStateDatabaseHandle(h);return e.length===1&&e[0]instanceof SnapshotCleanupIncompleteError?!1:(G(e,`Shared-state reader cleanup failed.`),f=!0,!0)}};try{so(d),n!==void 0&&oi(s,n)}catch(e){try{if(!g.close())throw new SnapshotCleanupIncompleteError(`Shared-state snapshot cleanup is incomplete.`)}catch(t){throw Zr([e,t],`Shared-state reader identity and cleanup failed.`,e)}throw e}return{status:`available`,value:g}}function readOnlyStateDatabase(e,t){return{...e,walMaintenance:{checkpoint:()=>!1,stop:async()=>{},reclaimFreePages:createSqliteWalReclamationResult,close:t}}}const yf=R(Symbol.for(`openclaw.managedStateTransactions`),()=>/* @__PURE__ */ new WeakSet);function isManagedStateTransaction(e){return e.isTransaction&&yf.has(e)}function runManagedStateTransaction(e,t,n){if(e.isTransaction&&!yf.has(e))throw Error(`Cannot join an unmanaged shared-state transaction; enter through runOpenClawStateWriteTransaction before BEGIN.`);let transaction=()=>ra(e,()=>{let r=!e.isTransaction;r&&yf.add(e);try{return n.singleStatement?Kt(e,t):O(e,t,n)}finally{r&&yf.delete(e)}});return n.busyTimeoutMs===void 0||z(e)?transaction():ps(e,n.busyTimeoutMs,transaction)}const bf=/* @__PURE__ */ new WeakMap;function withMaintenanceOpenClawStateDatabaseReadOnly(e,t){let n=So();if(!n||!Po(n,t))return{reused:!1};n.assertReadAdmission();let r=bf.get(n);r||(r=/* @__PURE__ */ new Map,bf.set(n,r));let i=r.get(t);if(!i){let e=Rt(t);oi(t,e.identity.key,e.identity.birthtime);let a=openOpenClawStateReadOnlyLocation(t,t),o=!1,close=()=>{if(!o){if(!a.close())throw Error(`Maintenance authority reader cleanup is incomplete`);o=!0,r.delete(t),s()}},s=Nt(e,async()=>{close()});n.own(a,`shared-handles`,close),i={read(n){e.assertCurrent(),oi(t,e.identity.key,e.identity.birthtime);let r=Xa(a.database.db,()=>(assertStateReadSchema(a.database.db,t),n(a.database)));if(lr(r))throw new Ta(`SQLite maintenance authority read must remain synchronous`);return r}},r.set(t,i)}return{reused:!0,value:i.read(e)}}function withCachedOpenClawStateDatabaseReadOnly(e,t,n){return j.withCachedOpenClawStateDatabase(t,{readOnly:!0},r=>{if(!r.db.isOpen)return{reused:!1};let i=n&&isManagedStateTransaction(r.db);if(r.db.isTransaction&&!i)return{reused:!1};try{assertStateReadSchema(r.db,t),Eo(r.db);let n=e(r);if(i&&lr(n))throw new Ta(`SQLite current-authority read must remain synchronous`);return{reused:!0,value:n}}catch(e){throw j.evictOpenClawStateDatabaseAfterCorruption(r,e),e}})??{reused:!1}}function canReadWarmNativeSourceIndependently(e,t,n){let r=Tt(e);if(r.key!==n)return!1;try{return oi(t,r.key),!0}catch{return!1}}async function acquireWithWait(e){let t=e.now??performance.now.bind(performance),n=e.pollIntervalMs;for(;;)try{return await e.acquire()}catch(r){let i=e.shouldRetry(r);if(!i)throw r;let a=e.deadlineMs-t();if(a<=0)throw r;await(e.sleep??Oc)(Math.min(i===!0?n:i.delayMs,a)),n=Math.min(n*2,e.maxPollIntervalMs??e.pollIntervalMs)}}function isUpdateRunAdmissionReadCommand(e){return e.type===`updateRuns.recoveryAdmission`||e.type===`updateRuns.reconciliationCandidates`||e.type===`updateRuns.reconciliationCandidate`}const xf=R(Symbol.for(`openclaw.sqliteDatabaseAdmissionTurns`),()=>({pending:/* @__PURE__ */ new Map,discovery:Promise.resolve(),discovering:0})),Sf=new ar(Symbol.for(`openclaw.sqliteDatabaseAdmissionTurnContext`));function hasPublishedSchema(e){let t=Jr(e);return t!==void 0&&ii(t)}function reserveAdmissionTurn(e){if(e.size===0)return;let t=new Set([...e].flatMap(e=>xf.pending.get(e)??[])),{promise:n,resolve:r}=vs();for(let t of e)xf.pending.set(t,n);return{ready:Promise.all(t),release:()=>{for(let t of e)xf.pending.get(t)===n&&xf.pending.delete(t);r()}}}function prepareAdmissionTurn(e,t,n,r=()=>{}){xf.discovering++;let i=xf.discovery.then(async()=>{try{r();let i=typeof n==`function`?await n():n;r();let a=/* @__PURE__ */ new Set;for(let e of t){let t=i?.physicalFamilies?e:await Ms(e);r(),a.add(`family:${t}`)}let o=new Map(i?.readIdentities);for(let t of e){if((typeof n==`function`||!i?.readIdentities?.has(t))&&hasPublishedSchema(t))continue;let e;try{e=await fa({location:t,identity:i?.readIdentities?.get(t),assertCurrent:r})}catch(e){if(!En(e))throw e}let s=e?.canonicalPath??await Ms(t);r(),a.add(`path:${s}`),e&&(o.set(t,e),a.add(`${e.key}:${e.birthtime??``}`)),e&&ii(e)||a.add(`family:${X.dirname(s)}`)}return{turn:reserveAdmissionTurn(a),prepared:{readIdentities:o}}}finally{xf.discovering--}});return xf.discovery=i.then(()=>{},()=>{}),i}function acquireSqliteDatabaseAdmissionTurn(e,t=[],n,r){let i=typeof e==`string`?[e]:e;if(!Sf.getStore()?.active&&zi()&&(xf.discovering||n||t.length||!i.every(hasPublishedSchema)))return prepareAdmissionTurn(i,t,n,r).then(async({turn:e})=>(await e?.ready,e?.release??(()=>{})))}function runWithSqliteDatabaseAdmissionTurn(e,t,n=[],r,i,a){if(Sf.getStore()?.active||!zi())return typeof i==`function`?i().then(t):t(i);let run=(e,n)=>{let r={active:!0};return Sf.run(r,async()=>{try{return await t(n)}finally{r.active=!1,e?.release()}})};return!xf.discovering&&!i&&!n.length&&e.every(hasPublishedSchema)?run(void 0,void 0):prepareAdmissionTurn(e,n,i,()=>{r?.throwIfAborted(),a?.()}).then(({turn:e,prepared:t})=>e?xs(e.ready,r,e=>e.reason).then(()=>run(e,t),t=>{throw e.ready.then(e.release),t}):run(void 0,t))}function stateReadPools(e){return[e.pool,e.awaitedPool].filter(e=>e!==void 0)}function createStateReadPool(e,t){return Fr(),aa({workerUrl:e,workerOptions:{resourceLimits:{maxOldGenerationSizeMb:512}},maxWorkers:xa(),idleTimeoutMs:gt,burstIdleTimeoutMs:3e4,maxPendingTasks:128,maxPendingBytes:Bi},t?{retainedTransport:!0,nativeSource:t,databaseAccess:`read-only`}:{databaseAccess:`read-only`})}function closeReadResources(e,t){return Xr().explicitSqliteCloseReleasesNativeResources?e.closeResources(t):e.rotate()}const Cf=/["\\\u0000-\u001f\ud800-\udfff]/u;function quotedStringBytes(e){let t=Buffer.byteLength(e,`utf8`)+2;if(!Cf.test(e))return t;for(let n=0;n<e.length;n++){let r=e.codePointAt(n);r<32?t+=r===8||r===9||r===10||r===12||r===13?1:5:r===34||r===92?t++:r>=55296&&r<=57343?t+=3:r>65535&&n++}return t}function commandBytes(e,t=!1){if(typeof e==`string`)return t?Buffer.byteLength(e,`utf8`):quotedStringBytes(e);if(typeof e==`number`||typeof e==`bigint`)return 8;if(typeof e==`boolean`)return 1;if(e==null)return 0;if(Array.isArray(e))return e.reduce((e,n)=>e+(t?0:8)+commandBytes(n,t),0);let n=0,r=e;for(let e in r)Object.hasOwn(r,e)&&(n+=Buffer.byteLength(e,`utf8`)+(t?0:8)+commandBytes(r[e],t));return n}function requestBytes(e){return commandBytes(e.command)+commandBytes(e.context.databaseEngineSelection)+commandBytes(e.context.environment,!0)+commandBytes([e.context.existingSchemaPath,e.databasePath,e.location,e.expectedIdentity,e.snapshotRoot,e.postgresSnapshot],!0)}function decodeOpenClawStateReadReply(e){if(e.ok)return{value:e};let t=Error(e.message);return es(t,e.error),{error:Go(t,{includeOrdinary:!0}),sourceAdmitted:e.sourceAdmitted===!0}}async function closeReadPool(e){if(e.closing)return await e.closing;let t=stateReadPools(e);if(!t.length)return;let n=(async()=>{let n=await Promise.allSettled(t.map(async e=>{await closeReadResources(e),await e.close()}));G(n.flatMap(e=>e.status===`rejected`?[e.reason]:[]),`Shared-state reader pools cleanup failed`),e.pool=void 0,e.awaitedPool=void 0})();e.closing=n;try{await n}finally{e.closing=void 0}}function readRuntimes(){return R(Symbol.for(`openclaw.stateReadWorkers`),()=>{let e=/* @__PURE__ */ new Map;return nt({phase:`after-resources`,async close(t){let n=await Promise.allSettled([...e.values()].map(async e=>{if(t){let n=await Promise.allSettled(stateReadPools(e).map(e=>closeReadResources(e,t.key)));G(n.flatMap(e=>e.status===`rejected`?[e.reason]:[]),`Shared-state reader resources cleanup failed`)}else await closeReadPool(e)}));G(n.flatMap(e=>e.status===`rejected`?[e.reason]:[]),`Shared-state reader source cleanup failed`)}}),st(t=>{if(t.kind!==`opened`&&t.identity){let n=t.identity;for(let t of e.values())Promise.allSettled(stateReadPools(t).map(e=>closeReadResources(e,n.key))).then(e=>G(e.flatMap(e=>e.status===`rejected`?[e.reason]:[]),`Shared-state reader invalidation failed`)).catch(e=>{process.emitWarning(`Shared-state reader invalidation failed: ${String(e)}`)})}}),e})}function readPool(e,t,n){if(e.sealed&&!t||e.closing)throw new na(`Shared-state readers are closing`,`unavailable`);let r=ne(),i=r!==`cli-oneshot`&&(!n||e.pool!==void 0||r===`gateway`),a=i?`pool`:`awaitedPool`;return e[a]||(e[a]=createStateReadPool(e.workerUrl,i?e.nativeSource:void 0)),{pool:e[a],retained:i}}function captureOpenClawStateReadSource(){let e=vi(cr(`stateRead`)),t=Oi({runtimeGeneration:e.runtimeGeneration}),n=readRuntimes(),r=n.get(t);if(!r){let i={nativeSource:t,workerUrl:e.moduleUrl,operations:/* @__PURE__ */ new Set,sealed:!1};t.retain(i,()=>(i.sealed=!0,i.stopping||=Promise.resolve().then(async()=>{let e=await Promise.allSettled([...i.operations].map(e=>Promise.resolve().then(()=>e.close())));G(e.flatMap(e=>e.status===`rejected`?[e.reason]:[]),`Shared-state reader source cleanup failed`),await closeReadPool(i),n.delete(t)}).finally(()=>{i.stopping=void 0}),i.stopping)),n.set(t,i),r=i}return new StateReadSource(r)}var StateReadSource=class{constructor(e){this.state=e,this.admitted=/* @__PURE__ */ new Set}createTransport(e,t,n,r=!1){return new StateReadTransport(e,this,t,n,r)}ownsAdmission(){return this.admitted.size>0}own(e){let{state:t,admitted:n}=this;if(t.sealed||t.closing)throw new na(`Shared-state readers are closing`,`unavailable`);let r=ec.snapshot(),i={close:()=>r(e)};return t.operations.add(i),n.add(i),()=>{t.operations.delete(i),n.delete(i)}}},StateReadTransport=class{constructor(e,t,n,r,i=!1){this.source=t,this.onChunk=n,this.onChunkAsync=r,this.awaitedOnly=i,this.tasks=/* @__PURE__ */ new Map,this.closed=!1,this.pendingChunks=0,this.capturedCommand=isDeeplyFrozenPlainData(e)?e:structuredClone(e)}async closeTask(e){await e.close(this.tasks.get(e)?.retire?{retire:!0}:void 0),this.tasks.delete(e)}startRun(e,t,n,r,i,a,o,s){let{onChunk:c,onChunkAsync:l}=this,u,d={retire:!0};try{if(this.closed)throw new na(`Shared-state read transport is closed`,`unavailable`);e.databaseEngineSelection&&Object.values(e.databaseEngineSelection.effectiveEngines).includes(`postgres`)&&mr();let f={context:{databaseEngineSelection:e.databaseEngineSelection,environment:{...e.environment},existingSchemaPath:e.existingSchemaPath,stateIntegrity:e.stateIntegrity,liveStateReads:e.liveStateReads},databasePath:e.admission.databasePath,location:t,checkFreshAdmission:n,expectedIdentity:a,snapshotRoot:o,postgresSnapshot:s,command:r},p=readPool(this.source.state,this.source.ownsAdmission(),this.awaitedOnly);if(ne()===`gateway`&&!On()?.canUseInteractiveStateReadCapacity){let{pendingTasks:e,maxWorkers:t}=p.pool.getSnapshot();if(e>=128-2*t)throw new na(`worker task capacity reached (shared-state interactive reserve)`,`overloaded`)}let m=!p.retained&&!e.maintenanceScope&&r.type!==`admit`,h=m&&ne()===`cli-oneshot`,g=fo(),prepareDispatch=async()=>{let n=ua(t);g||await i.acquire(()=>void 0);try{let t=acquireSqliteDatabaseAdmissionTurn(n,[],void 0,()=>{i.signal.throwIfAborted(),e.admission.assertCurrent()});t&&(u=await t);let validateDispatch=async()=>(a!==void 0&&(fr(await $s(n,{bigint:!0}),{key:a}),i.assertCurrent()),f);return g?(i.assertCurrent(),await validateDispatch()):await i.acquire(validateDispatch)}catch(e){throw u?.(),u=void 0,e}},_=p.pool.runTask(g?async()=>await i.acquire(prepareDispatch):prepareDispatch,{signal:i.signal,inputBytes:requestBytes(f),diagnosticOperation:r.type,...l?{onRequest:async(e,{signal:t})=>{i.assertCurrent();let n=AbortSignal.any([i.signal,t]);n.throwIfAborted(),this.pendingChunks+=1;try{return await l(e,n),n.throwIfAborted(),i.assertCurrent(),{input:null,timeoutMs:3e5}}finally{--this.pendingChunks,this.pendingChunks===0&&this.chunksDrained?.()}}}:c?{onRequestSync(e){return i.assertCurrent(),c(e),{input:null,timeoutMs:3e5}}}:{}});return this.tasks.set(_,d),{task:_,result:(async()=>{let e;try{let t=await _.result;d.retire=m&&!h||!!t.nativeCleanupFailure,e=decodeOpenClawStateReadReply(t)}catch(t){e={error:t}}return u?.(),u=void 0,d.retire||=`error`in e,m&&!(`error`in e)&&(await this.closeTask(_),d.retire||await closeReadResources(p.pool)),e})()}}catch(e){throw u?.(),u=void 0,e}}async startValidateFresh(e,t){let n=this.startRun(e,e.admission.databasePath,!0,{type:`admit`},t),r=await n.result;if(`error`in r)throw r.error;t.assertCurrent(),await this.closeTask(n.task)}async startRead(e,t){return this.startRun(e.context,e.location,e.checkFreshAdmission,this.capturedCommand,t,e.expectedIdentity,e.snapshotRoot,e.postgresSnapshot).result}startClose(){return this.closed=!0,this.closing||=(async()=>{let e=await Promise.allSettled([...this.tasks.keys()].map(e=>this.closeTask(e)));this.pendingChunks>0&&await new Promise(e=>{this.chunksDrained=e}),G(e.flatMap(e=>e.status===`rejected`?[e.reason]:[]),`Shared-state reader task cleanup failed`)})().finally(()=>{this.chunksDrained=void 0,this.closing=void 0}),this.closing}};function isStateReadReply(e,t){return e.ok&&e.type===t}async function prepareOwnedStateReadImage(e,t,n,r,i){let a=n&&!e.isTransaction?it(t,n,{logicalReader:!0}):void 0;if(a)return a;let o=n?wt(t):void 0,s=await Ft(e,r.assertCurrent,i,`async`);return o?lt(t,o,s,()=>s.cleanupAsync(),{logicalOnly:!0}):s}function startOpenClawStateReadOperation(e,t){let{pathname:n,snapshot:r,scopes:i,context:a,preserveArtifacts:o,controller:s,signal:c,receipt:l}=t,u,d,f,p,m,h,g,_,startSnapshotCleanup,v,y,b,ee=!1,x,isPendingAdmission=e=>e instanceof Fi&&e.databasePath===n,te={signal:c,assertCurrent(){c.throwIfAborted(),a.maintenanceScope?.assertAdmission(),a.admission.assertCurrent(),j.assertOpenClawStateDatabaseOpenAllowed(n,`cached-read`,b)},async acquire(e){let acquire=()=>(te.assertCurrent(),e());try{return await acquire()}catch(e){if(!isPendingAdmission(e))throw e}return x??=performance.now()+Wo,acquireWithWait({acquire,shouldRetry:isPendingAdmission,deadlineMs:x,pollIntervalMs:10,sleep:e=>bs(e,c)})}},closeTransport=async()=>{if(u){h??=u.startClose();try{await h}catch(e){throw h=void 0,e}}},cleanup=()=>ee?Promise.resolve():y??=(async()=>{if(await closeTransport(),v?.(),v=void 0,p){if(_=startSnapshotCleanup?.(),!(_?await _.result:await p.cleanupAsync()))throw Error(`Shared-state read snapshot cleanup failed: ${p.cleanupRoot??n}`);p=void 0,_=void 0}if(m){g??=m.startClose();try{await g.result}catch(e){throw g=void 0,e}m=void 0,g=void 0}f?.release(),await r?.release?.(),ee=!0,re(),d?.();for(let e of i)e.resources.delete(ne)})().finally(()=>{y=void 0}),ne={async close(){s.abort(/* @__PURE__ */ Error(`Shared-state read admission closed`)),p||(g??=m?.startClose()),await closeTransport(),await ie.catch(()=>void 0),await cleanup()}},re=nt({async close(e){e&&e.key!==a.admission.identity.key&&e.canonicalPath!==a.admission.identity.canonicalPath||await ne.close()}});a.maintenanceScope?.own(ne,`shared-resources`,()=>ne.close());for(let e of i)e.resources.add(ne);function consume(e){let t=`error`in e?e.sourceAdmitted:e.value.type!==`admit`&&e.value.sourceAdmitted;if(t===!0?l.phase=`read`:t===!1&&l.phase!==`read`&&(l.phase=`before-read`),`error`in e)throw e.error;return t===!0&&f?.observe(),e.value}async function query(t){return p&&(v=Za(p.cleanupRoot??X.dirname(p.location))),l.phase=e.type===`admit`?`before-read`:`unobserved`,consume(await t.startRead({context:a,location:p?.location??r?.location??n,checkFreshAdmission:!f,expectedIdentity:!r&&!p||r?.location===n?a.admission.identity.key:void 0,snapshotRoot:p?.cleanupRoot??r?.cleanupRoot,postgresSnapshot:r?.postgresSnapshot},te))}async function run(){let i=captureOpenClawStateReadSource(),s=i.createTransport(e,t.onChunk,t.onChunkAsync,t.snapshotPreparation===`awaited`);if(u=s,d=i.own(()=>ne.close()),b=await et(a.admission),c.throwIfAborted(),a.maintenanceScope?.assertAdmission(),a.admission.assertCurrent(),e.type===`admit`)return query(s);let l=r?void 0:te.acquire(()=>{let e=o?Ot(n,`cached-read`,b):void 0;return{native:e,borrowed:e??(o?void 0:ft(n,`cached-read`,b))}}),h=l instanceof Promise?await l:l,g=h?.native;f=h?.borrowed;let _=g&&t.preferIndependentWarmRead&&canReadWarmNativeSourceIndependently(g.database,n,a.admission.identity.key);if(!r&&!f&&!await js(n))te.assertCurrent();else{if(!r&&!_){let t=(e.type===`plugins.metadata.read`||e.type===`config.health.read`||isUpdateRunAdmissionReadCommand(e))&&!a.existingSchemaPath&&!a.maintenanceScope&&!nn(n)&&(!g||!z(g.database.db)&&canReadWarmNativeSourceIndependently(g.database,n,a.admission.identity.key))&&(hasVerifiedLiveSqliteOwner(n)||Kr(n));if(o&&(!g||t)&&await s.startValidateFresh(a,te),t){te.assertCurrent();let t=await Ho(n,{type:`startupMetadata.readCurrent`,input:e},{source:`canonical`,expectedIdentity:a.admission.identity.key,env:a.environment,signal:c});if(te.assertCurrent(),t){let e=t.value;if(!e.ok){let t=/* @__PURE__ */ Error(`Startup metadata inspection failed`);return es(t,e.error),consume({error:Go(t,{includeOrdinary:!0}),sourceAdmitted:e.sourceAdmitted})}return consume({value:{ok:!0,sourceAdmitted:!0,...e.result}})}}}if(g&&!_)z(g.database.db)&&Fa(`postgres`,`file-snapshot`),p=await prepareOwnedStateReadImage(g.database.db,n,canReadWarmNativeSourceIndependently(g.database,n,a.admission.identity.key)?a.admission.identity:void 0,te,c);else if(!r&&o&&!_){let r={key:a.admission.identity.key};if(t.snapshotPreparation===`awaited`||qt())p=await _t(n,{signal:c,expectedSourceIdentity:r,reuse:!0,allowLiveOwner:t.snapshotPreparation===`awaited`&&e.type===`plugins.metadata.read`&&a.maintenanceScope?.ownsSchemaMaintenance!==!0&&!nn(n)});else{m=Mt(n,{preserveSourceArtifacts:!0,signal:c,expectedSourceIdentity:r,reuse:!0});let e=await m.result;p=e,startSnapshotCleanup=()=>e.startCleanup()}}return query(s)}}let ie=run();return(async()=>{let e,n=[];try{e=await ie}catch(e){n.push(e)}try{await cleanup()}catch(e){n.push(e)}return G(n,`Shared-state read and cleanup failed`),t.callerSignal?.throwIfAborted(),e})().catch(e=>{throw t.mapError?t.mapError(e,l.phase):e})}function configureSqliteSnapshotReadCache(e){e.exec(`PRAGMA cache_size = -16384; PRAGMA mmap_size = 268435456;`)}function readRetainedStateSnapshot(e,t,n){let{location:r}=t;if(isStatePostgres())return withOpenClawStateReadOnlyLocation(n,e.path,r);if(!e.reader){let t=openOpenClawStateReadOnlyLocation(e.path,r),n=!1;e.resources.add({async close(){if(!n){if(!t.close())throw Error(`Shared-state report reader cleanup is incomplete`);n=!0}}}),z(t.database.db)||configureSqliteSnapshotReadCache(t.database.db),e.reader=t}return withOpenClawStateReadOnlyLocation(n,e.path,{location:r,connection:e.reader})}function assertRetainedReadScopeAdmission(e,t){if(t.some(t=>t?.path===e&&(!t.active||t.work.isClosing)))throw new ja(`Shared-state read scope is closing or closed; retry the operation in a current scope.`)}function captureOpenClawStateReadWorkerContext(e={}){return d(e,Rt,j.getKnownOpenClawStateDatabaseIdentity)}er(`state/db`);const wf={reuse:!0},Tf=R(Symbol.for(`openclaw.disposableStateReads`),()=>new ec),Ef=R(Symbol.for(`openclaw.stateSnapshotReads`),()=>new ec);function exitStateReadSnapshot(e){return Ef.exit(()=>hf.exit(e))}function resolveStateReadCallerSignal(){let e=Is(),t=Ef.getStore();return t&&e===t.work.signal?t.callerSignal:e}function requiresArtifactPreservingSnapshot(e){if(isStatePostgres()||Pa())return!1;let t=So();if(t&&ls(t,e))return!1;let n=hs(`shared`,e)&&!Ht(e,process.env)&&!Tf.getStore()?.some(t=>t.active&&t.path===e)&&!hasVerifiedLiveSqliteOwner(e,{unknownOwner:`return-false`});return n&&assertStateFileSnapshotAllowed(),n}const Df=R(Symbol.for(`openclaw.synchronousStateReadSnapshots`),()=>({current:void 0}));function resolveOpenClawStateReadPath(e){let t=wo(e);return assertOpenClawStateReadPathCurrent(t),t}function assertOpenClawStateReadPathCurrent(e){let t=Ef.getStore(),n=Tf.getStore();(t||n?.length)&&assertRetainedReadScopeAdmission(e,[t,...n??[]]),T(e)}function withOpenClawStateDatabaseReadOnlyIfOpen(e,t,n=!1){let r=Ef.getStore();if(r?.active&&r.path===t){j.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(t,r.env);let n=r.readSource();if(n)return{reused:!0,value:readRetainedStateSnapshot(r,n,e)}}return hs(`agent`,t)&&(requiresArtifactPreservingSnapshot(t)||Ht(t,process.env))||isStatePostgres()&&!n?{reused:!1}:withCachedOpenClawStateDatabaseReadOnly(e,t,n||Df.currentAuthorityPath===t)}function withFreshOpenClawStateDatabaseReadOnly(e,t,n){let r=t.env??process.env;if(j.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(n,r),Df.currentAuthorityPath===n){let t=withMaintenanceOpenClawStateDatabaseReadOnly(e,n);if(t.reused)return t.value}let i=Df.current;if(i&&requiresArtifactPreservingSnapshot(n)){let t=i.get(n);t||(t=openOpenClawStateReadOnlyLocation(n,Ze(n,void 0,wf)),i.set(n,t)),assertStateReadSchema(t.database.db,n);let r=e(t.database);if(lr(r))throw new Ta(`SQLite metadata snapshot read must remain synchronous`);return r}return withOpenClawStateReadOnlyLocation(e,n,(requiresArtifactPreservingSnapshot(n)?Ze(n,void 0,wf):void 0)??n,void 0,void 0,void 0,!Vs&&!So())}function withExistingOpenClawStateDatabaseReadOnly(e,t={}){let n=resolveOpenClawStateReadPath(t);if(Df.current?.has(n))return withFreshOpenClawStateDatabaseReadOnly(e,t,n);let r=withOpenClawStateDatabaseReadOnlyIfOpen(e,n);if(r.reused)return r.value;let i=Io(n);return i===void 0?void 0:withFreshOpenClawStateDatabaseReadOnly(e,t,i)}function executeExistingOpenClawStateRead(e,t,n={}){let r=t.type,{context:i,current:a,live:o,mapError:s}=n,c={phase:`before-read`},l;try{i?.admission.assertCurrent();let execute=()=>startRetainedOpenClawStateRead(e,t,c,n),r=o?()=>ro.run(!1,()=>exitStateReadSnapshot(execute)):a?()=>exitStateReadSnapshot(execute):execute;l=runPluginSharedStateWork(()=>i?.runInCapturedSchemaScope?i.runInCapturedSchemaScope(r):r())}catch(e){throw s?s(e,c.phase):e}return l.then(e=>{if(!e||isStateReadReply(e,r))return e;throw Error(`Unexpected shared-state read reply for ${r}`)})}function startRetainedOpenClawStateRead(e,t,n,{context:r,signal:i,current:a,live:o,mapError:s,preferIndependentWarmRead:c,snapshotPreparation:l,onChunk:u,onChunkAsync:d}){let f=a||o,p=resolveOpenClawStateReadPath(e),m=Ef.getStore(),h=m?.active&&m.path===p?m:void 0,g=[...h?[h]:[],...(Tf.getStore()??[]).filter(e=>e.active&&e.path===p)],_=h?.env??e.env,v=r??captureOpenClawStateReadWorkerContext({path:p,env:_});if(r){if(v.admission.databasePath!==p)throw Error(`Shared-state read context does not match its selected source`);v.maintenanceScope?.assertAdmission(),v.admission.assertCurrent()}let y=requiresArtifactPreservingSnapshot(p),b=new AbortController,ee=i??(hs()?resolveStateReadCallerSignal():h?.callerSignal),x=ee?AbortSignal.any([ee,b.signal]):b.signal,te=g.reduceRight((e,t)=>()=>t.work.run(()=>{let n=e();return t.work.track(()=>n).catch(()=>void 0),n}),()=>{let e=f?void 0:Df.current?.get(p)?.snapshotSource?.retain(),start=()=>startOpenClawStateReadOperation(t,{pathname:p,snapshot:e??h?.readSource(),scopes:g,context:v,preserveArtifacts:y,preferIndependentWarmRead:c,snapshotPreparation:l,onChunk:u,onChunkAsync:d,controller:b,signal:x,callerSignal:ee,receipt:n,mapError:s});return h?.prepareSource&&!e?(x.throwIfAborted(),h.prepareSource().then(()=>{if(x.aborted)throw s?s(x.reason,n.phase):x.reason;return start()},e=>{throw s?s(e,n.phase):e})):start()}),ne=v.maintenanceScope,re;if(ne?ne.run(()=>{let e=te();return re=e,e}):re=te(),!re)throw Error(`Shared-state read maintenance scope did not start its operation`);return eo(re,()=>b.abort(/* @__PURE__ */ Error(`Shared-state read admission closed`))),re}const Of=er(`state/db`);function assertStateDatabaseIntegrityBeforeMutation(e,t){if(we(e))return;let n=readStateSchemaContentVersion(e);n!==40&&((n===0&&inspectStateSqlite(e).hasExistingData||n>0&&n<40)&&Of.info(`state database schema migration pending; verifying integrity first`,{fromVersion:n,path:t,toVersion:40}),Ke(e,t))}function openUnpublishedStateDatabase(e){return runStateOpenSteps(openUnpublishedStateDatabaseSteps(e))}function runStateOpenSteps(e){let t=e.next();for(;!t.done;)try{t=e.next(t.value.run())}catch(n){t=e.throw(n)}return t.value}async function openUnpublishedStateDatabaseAsync(e){return runStateOpenStepsAsync(openUnpublishedStateDatabaseSteps(e))}async function runStateOpenStepsAsync(e){us(Is())?.throwIfAborted();let t=Ne(()=>e.next());for(;!t.done;)try{let n=await t.value.runAsync();t=Ne(()=>e.next(n))}catch(n){t=Ne(()=>e.throw(n))}return t.value}function*openUnpublishedStateDatabaseSteps(e,t=!1){let n=he(e.pathname),r=e.existingSchema||n?Xs(e.pathname,{bigint:!0}):Xs(e.pathname,{bigint:!0,throwIfNoEntry:!1});if(n&&(!r||`file:${r.dev}:${r.ino}`!==n))throw Error(`SQLite database file identity changed before existing-only open`);if(!r&&!t){let t,n={databasePath:e.pathname,busyTimeoutMs:e.busyTimeoutMs};try{if(yield{run(){withStateDatabaseSchemaMaintenance(n,()=>{t=runStateOpenSteps(openUnpublishedStateDatabaseSteps(e,!0))})},async runAsync(){await withStateDatabaseSchemaMaintenanceAsync(n,async()=>{t=await runStateOpenStepsAsync(openUnpublishedStateDatabaseSteps(e,!0))})}},!t)throw Error(`Shared-state acquisition did not return its native handle.`);return t}catch(n){let r=t?j.closeUnpublishedOpenClawStateDatabaseHandle(t):[];throw r.length>0?Zr([n,...r],`Fresh shared-state acquisition and cleanup failed for ${e.pathname}.`,n):n}}if(r&&!r.isFile())throw Error(`Existing shared-state database must be a regular file: ${e.pathname}`);let i=prepareStateDatabaseInitialization(e.pathname,e.env,e.initializationAgentPaths);return r||(f(e.pathname),ensureOpenClawStatePermissions(e.pathname,e.env,{createDirectory:!0}),prepareSqliteDatabaseDirectory(e.pathname)),yield*openNativeStateDatabase(e,i,r)}function*openNativeStateDatabase(e,t,n){let{busyTimeoutMs:r,lockFailureReporting:i}=e,assertSameFile=()=>{if(n){let t=Xs(e.pathname,{bigint:!0});if(!t.isFile()||t.dev!==n.dev||t.ino!==n.ino||Nr(t)!==Nr(n))throw Error(`Existing shared-state database generation changed: ${e.pathname}`)}},a=Xt(e.pathname,{existingOnly:n!==void 0,expectedIdentity:n?`file:${n.dev}:${n.ino}`:void 0}),o,s=a,c;try{assertSameFile(),so(a),oo(a,r);let l=stateEngineInput(),u,initializeSqliteSchema=()=>{e.ensureSchema(a,t,u),ensureOpenClawStatePermissions(e.pathname,e.env),assertSameFile()},openSelected=(n=!1)=>{if(c)return ps(a,r,initializeSqliteSchema,{lockFailureReporting:i}),a;if(admitStateSchemaFacts(a,e.pathname),l&&isNativeClientCredentialBootstrap(a))throw Error(`Native credential bootstrap cannot become a PostgreSQL anchor. Start the Gateway once on SQLite and run openclaw doctor --fix, then use openclaw database port before selecting PostgreSQL.`);return openEngineStore({anchor:a,schema:ou,input:l,existingOnly:e.existingSchema,inspectSqlite:()=>inspectStateSqlite(a),prepareAnchor:()=>{},onFreshAnchor:t=>bindFreshClientCredentialStore(t,{path:e.pathname,env:e.env,custody:u}),admitPostgres:(t,n)=>{admitStatePostgres(t,n),n&&(_e(t,{previousVersion:0,legacyDefaultStoreKey:bt(e.env),fresh:!0}),bindFreshClientCredentialStore(t,{path:e.pathname,env:e.env,custody:u}))},beforeMigrate:(t,n,r)=>{prepareClientCredentialMigration(t,{path:e.pathname,env:e.env,fromVersion:n,custody:u}),n===28&&advanceStateSchemaContentVersion(t,{fromVersion:n,toVersion:29}),n===33&&_e(t,{previousVersion:n,legacyDefaultStoreKey:bt(e.env),sourceTables:r})},closeOnFailure:(e,t)=>{throw s=e,t},openSqlite:()=>{if(assertOpenClawStateWriteAllowed({database:a,databasePath:e.pathname,env:e.env}),e.existingSchema){assertSameFile(),e.ensureSchema(a,t,u),assertSameFile(),c={db:a,path:e.pathname,walMaintenance:{checkpoint:()=>!1,stop:async()=>{},close:()=>!0,reclaimFreePages:createSqliteWalReclamationResult}};return}ensureOpenClawStatePermissions(e.pathname,e.env);let s=ps(a,r,()=>(assertSupportedStateSchemaVersion(a,e.pathname),assertStateDatabaseIntegrityBeforeMutation(a,e.pathname),configureSqlitePreSchemaPragmas(a,{busyTimeoutMs:r}),o=configureSqliteConnectionPragmas(a,{busyTimeoutMs:r,databaseLabel:`openclaw-state`,databasePath:e.pathname,onCheckpointError:t=>Of.warn(`Shared-state WAL maintenance failed`,{error:Cs(t),path:e.pathname,checkpoint:o?.health}),runMaintenance:t=>{try{Je(e.pathname)}catch(t){if(!(t instanceof Fi)&&!(t instanceof ia))throw t;return Of.debug(`Shared-state WAL maintenance deferred during offline maintenance`,{path:e.pathname}),!1}return t()},isScheduledMaintenanceSuspended:pe(),foreignKeys:!0,synchronous:`NORMAL`}),n||initializeSqliteSchema(),o),{lockFailureReporting:i});c={db:a,path:e.pathname,walMaintenance:s}}})},d=e.existingSchema?void 0:()=>{assertSameFile(),openSelected(!0)};return yield{run(){s=l?openSelected():runUpdateSqliteMigration(a,e.pathname,openSelected,{beforeExclusive:d,created:n===void 0})},async runAsync(){let t=e.clientCredentialMigrationFromVersion;if(t===void 0){if(l&&inspectStateSqlite(a).hasEngineAnchor){let n=await executeExistingOpenClawStateRead({path:e.pathname,env:e.env},{type:`stateBootstrap.inspect`,input:{pathname:e.pathname,supportedVersion:40,purpose:`maintenance`,scope:`state`}},{signal:us(Is()),current:!0});if(!n||n.inspection.schemas.indeterminate.length>0||n.inspection.schemas.incompatible.length>0)throw Error(`Cannot prepare PostgreSQL credentials without its supported state schema. Restore the matching state schema and anchor before retrying Doctor.`);t=n.inspection.schemas.pendingMigrations?.[0]?.foundVersion??40}else t=l||!n?0:readStateSchemaContentVersion(a)}let r=await prepareClientCredentialMigrationCustody({path:e.pathname,env:e.env,fromVersion:t});u=r??null;try{if(l){let open=()=>(s=Ne(openSelected),s);s=r?await runUpdateSqliteMigrationAsync(r.database,r.path,open,{created:r.created,retainExclusive:!0}):open()}else s=await runUpdateSqliteMigrationAsync(a,e.pathname,()=>(assertSameFile(),openSelected()),{beforeExclusive:d,created:n===void 0,companions:r?[{database:r.database,path:r.path,created:r.created}]:[]})}finally{u=void 0,r?.close()}}},c||(assertOpenClawStateWriteAllowed({database:s,databasePath:e.pathname,env:e.env}),{db:s,path:e.pathname,walMaintenance:{checkpoint:()=>!1,stop:async()=>{},close:()=>!0,reclaimFreePages:createSqliteWalReclamationResult}})}catch(t){let n=j.closeUnpublishedOpenClawStateDatabaseHandle({db:s,path:e.pathname,walMaintenance:o});throw t instanceof Error&&(ns(t)||De(t))&&e.recordOpenFailure(e.pathname,t),n.length>0?Zr([t,...n],`OpenClaw state database acquisition and cleanup failed for ${e.pathname}.`,t):t}}const kf=/^[A-Za-z_][A-Za-z0-9_]*$/u;function foreignKeyMismatch(e){if(!(e instanceof Error)||e.name!==`SqliteIntegrityError`||!e.message.startsWith(`SQLite foreign_key_check failed for `)||!(e.cause instanceof Error)||!(`code`in e.cause)||e.cause.code!==`ERR_SQLITE_ERROR`)return;let t=/^foreign key mismatch - "[A-Za-z_][A-Za-z0-9_]*" referencing "([A-Za-z_][A-Za-z0-9_]*)"$/u.exec(e.cause.message);return t?.[1]?{error:e,parentTable:t[1]}:void 0}function repairCanonicalSqliteIndexes(e,t,n,r={}){let i=/* @__PURE__ */ new Set,a=r.deferredForeignKeyMismatch;if(Ya(e,()=>{let o=Pt(e);if(!hasCanonicalSqliteSchemaFingerprint(n,o)){let e=getCanonicalSqliteNamedIndexContracts(n),a=/* @__PURE__ */ new Map;for(let t of e){assertSqliteIdentifier(t.name),assertSqliteIdentifier(t.tableName);let e=a.get(t.tableName)??[];e.push(t),a.set(t.tableName,e)}for(let e of getCanonicalSqliteTableNames(n)){assertSqliteIdentifier(e);let n=o(e);if(!n)continue;let s=a.get(e)??[],c=new Set(s.map(e=>e.name)),l=n.indexes,u=l.find(e=>e.unique===1&&e.origin===`c`&&e.name!==null&&!c.has(e.name));if(u)throw new N(`SQLite schema is incomplete or noncanonical for ${t}: unexpected unique index ${u.name}`);for(let e of s){let t=l.find(t=>t.name===e.name);if(JSON.stringify(t)!==JSON.stringify(e.fingerprint)){if(r.nonUniqueOnly&&(e.unique||t?.unique===1))throw new N(`Canonical unique index ${e.name} requires full admission`);i.add(e)}}}}if(r.verifyPhysicalIntegrity!==!1)try{Qe(e,t,r.integrity)}catch(e){if(a=foreignKeyMismatch(e),!a)throw e}if(a&&![...i].some(e=>e.unique&&e.tableName===a?.parentTable))throw a.error;i.size===0&&r.validateUnchanged?.(o)}),i.size===0)return[];let o=`repair_canonical_indexes`,s;e.exec(`SAVEPOINT ${o};`);try{for(let t of i){s=t,e.exec(`SAVEPOINT repair_canonical_index;`);try{e.exec(`DROP INDEX IF EXISTS main.${t.name};`);let n=t.unique?`CREATE UNIQUE INDEX`:`CREATE INDEX`;e.exec(`${n} main.${t.name} ${t.definition};`)}catch(n){if(e.exec(`ROLLBACK TO SAVEPOINT repair_canonical_index;`),r.allowMissingColumns&&isMissingColumnError(n)){i.delete(t);continue}throw n}finally{e.exec(`RELEASE SAVEPOINT repair_canonical_index;`)}}if(i.size===0){if(a)throw a.error;return r.validateUnchanged?.(),e.exec(`RELEASE SAVEPOINT ${o};`),[]}for(let n of new Set([...i].map(e=>e.tableName)))$t(e,t,n);r.validateAfterRepair?.(),a&&Qe(e,t,{...r.integrity,schemaOnly:void 0}),e.exec(`RELEASE SAVEPOINT ${o};`)}catch(n){try{e.exec(`ROLLBACK TO SAVEPOINT ${o};`)}finally{e.exec(`RELEASE SAVEPOINT ${o};`)}if(l(n)||n instanceof Error&&De(n))throw n;let i=n instanceof Error?n.message:String(n);throw r.nonUniqueOnly&&isMissingColumnError(n)?new N(i,{cause:n}):Error(`SQLite canonical index ${s?.name??`repair`} failed for ${t}: ${i}`,{cause:n})}return[...i].map(e=>e.name).toSorted()}function assertSqliteIdentifier(e){if(!kf.test(e))throw Error(`invalid SQLite identifier: ${e}`)}function isMissingColumnError(e){return e instanceof Error&&e.code===`ERR_SQLITE_ERROR`&&/^no such column:/iu.test(e.message)}const Af=[`_rowid_`,`rowid`,`oid`];function readMainTableList(e,t={}){return e.prepare(`PRAGMA table_list`).all().filter(e=>e.schema===`main`&&typeof e.name==`string`&&(t.includeInternal===!0||!e.name.startsWith(`sqlite_`)))}function hasNonStrictSqliteTables(e){return readMainTableList(e).some(e=>e.type===`table`&&Number(e.strict)!==1)}function readTableColumns(e,t){return e.prepare(`PRAGMA table_xinfo(${W(t)})`).all()}function readVisibleColumns(e,t){return readTableColumns(e,t).filter(e=>Number(e.hidden??0)===0).map(e=>{if(typeof e.name!=`string`||e.name.length===0)throw Error(`SQLite table ${t} has an invalid column name`);return e.name})}function readTableRowidModel(e,t,n){return Number(n.wr??0)===1?{alias:null,storage:`without-rowid`}:resolveTableRowidModel(t,readTableColumns(e,t),!!e.prepare(`SELECT 1 AS found FROM pragma_index_list(?) WHERE origin = 'pk' LIMIT 1`).get(t))}function resolveTableRowidModel(e,t,n){let r=t.filter(e=>Number(e.pk??0)>0),i=r[0]?.type;if(r.length===1&&typeof i==`string`&&i.toUpperCase()===`INTEGER`&&!n)return{alias:null,storage:`integer-primary-key`};let a=new Set(t.flatMap(e=>typeof e.name==`string`?[e.name.toLowerCase()]:[])),o=Af.find(e=>!a.has(e))??null;if(!o)throw Error(`SQLite table ${e} shadows every rowid alias; its implicit rowids cannot be migrated safely`);return{alias:o,storage:`implicit`}}function canonicalStrictTablesFromCatalog(e){return e.tables.map(e=>{if(e.sql===null)throw Error(`Canonical SQLite table ${e.name} has no CREATE statement`);let t=e.withoutRowid===1?{alias:null,storage:`without-rowid`}:resolveTableRowidModel(e.name,e.columns,e.indexes.some(e=>e.origin===`pk`));return{columns:e.columns.filter(e=>e.hidden===0).map(e=>e.name),createSql:e.sql,name:e.name,rowidAlias:t.alias,rowidStorage:t.storage,usesAutoincrement:/\bAUTOINCREMENT\b/iu.test(e.sql)}}).toSorted((e,t)=>e.name.localeCompare(t.name))}function readCanonicalStrictTables(e){let t=Ga(`:memory:`);try{t.exec(e);let n=readMainTableList(t).filter(e=>e.type===`table`),r=n.filter(e=>Number(e.strict??0)!==1).map(e=>e.name);if(r.length>0)throw Error(`Canonical SQLite schema contains non-STRICT tables: ${r.toSorted().join(`, `)}`);return n.map(e=>{let n=t.prepare(`SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = ?`).get(e.name);if(typeof n?.sql!=`string`)throw Error(`Canonical SQLite table ${e.name} has no CREATE statement`);let r=readTableRowidModel(t,e.name,e);return{columns:readVisibleColumns(t,e.name),createSql:n.sql,name:e.name,rowidAlias:r.alias,rowidStorage:r.storage,usesAutoincrement:/\bAUTOINCREMENT\b/iu.test(n.sql)}}).toSorted((e,t)=>e.name.localeCompare(t.name))}finally{t.close()}}function rewriteCreateTableName(e,t){let n=e.indexOf(`(`);if(n===-1)throw Error(`Canonical SQLite table CREATE statement has no column list`);return`CREATE TABLE ${W(t)} ${e.slice(n)}`}function readPreservedSchemaObjects(e,t){return e.prepare(`SELECT type, name, tbl_name, sql FROM sqlite_schema WHERE type IN ('index', 'trigger', 'view')`).all().flatMap(e=>e.type!==`index`&&e.type!==`trigger`&&e.type!==`view`||typeof e.name!=`string`||typeof e.tbl_name!=`string`||typeof e.sql!=`string`||e.type===`index`&&!t.has(e.tbl_name)?[]:[{name:e.name,sql:e.sql,type:e.type}]).toSorted((e,t)=>{let n={view:0,index:1,trigger:2};return n[e.type]-n[t.type]||e.name.localeCompare(t.name)})}function readAutoincrementHighWater(e,t){if(!e.prepare(`SELECT 1 AS found FROM sqlite_schema WHERE type = 'table' AND name = 'sqlite_sequence'`).get())return null;let n=e.prepare(`SELECT CAST(seq AS TEXT) AS seq FROM sqlite_sequence WHERE name = ?`).get(t);if(n===void 0)return null;let r=typeof n.seq==`string`?/^(\d+)(?:\.0+)?$/u.exec(n.seq)?.[1]:null;if(!r)throw Error(`SQLite table ${t} has an invalid AUTOINCREMENT high-water mark (${typeof n.seq}: ${String(n.seq)})`);return r}function restoreAutoincrementHighWater(e,t,n){if(n===null)return;let r=readAutoincrementHighWater(e,t),i=r===null||BigInt(n)>BigInt(r)?n:r;e.prepare(`DELETE FROM sqlite_sequence WHERE name = ?`).run(t),e.prepare(`INSERT INTO sqlite_sequence (name, seq) VALUES (?, CAST(? AS INTEGER))`).run(t,i)}function assertMatchingColumns(e,t,n){let r=new Set(t),i=new Set(n),a=n.filter(e=>!r.has(e)),o=t.filter(e=>!i.has(e));if(a.length===0&&o.length===0)return;let s=[a.length>0?`missing ${a.join(`, `)}`:``,o.length>0?`extra ${o.join(`, `)}`:``].filter(Boolean).join(`; `);throw Error(`SQLite table ${e} does not match its canonical columns (${s})`)}function readForeignKeysEnabled(e){let t=e.prepare(`PRAGMA foreign_keys`).get();return Number(t?.foreign_keys??0)===1}function migrateSqliteSchemaToStrictInTransaction(e,t,n={}){if(!e.isTransaction)throw Error(`SQLite STRICT schema migration requires an active transaction`);let r=n.expectedSchema??t,i=typeof r==`string`?readGeneratedSqliteFingerprint(r):void 0,a=i?.tableNames??(typeof r==`string`?void 0:r.tables.map(e=>e.name)),readCurrentTables=()=>new Map(readMainTableList(e).filter(e=>e.type===`table`).map(e=>[e.name,e])),o=n.expectedSchema!==void 0&&a?readCurrentTables():/* @__PURE__ */ new Map;if(n.expectedSchema!==void 0&&a?.every(e=>Number(o.get(e)?.strict??0)===1))return{migratedTables:[]};let s=typeof r==`string`?i&&readGeneratedSqliteCatalog(r):r,c=s?.tables.every(e=>e.strict===1),l=s&&c?canonicalStrictTablesFromCatalog(s):readCanonicalStrictTables(t);(n.expectedSchema===void 0||!c||l.some(e=>!o.has(e.name)))&&(e.exec(t),o=readCurrentTables());let u=l.filter(e=>Number(o.get(e.name)?.strict??0)!==1);if(u.length===0)return{migratedTables:[]};if(readForeignKeysEnabled(e))throw Error(`SQLite STRICT schema migration requires foreign_keys=OFF before BEGIN`);let d=readPreservedSchemaObjects(e,new Set(u.map(e=>e.name)));for(let t of[`trigger`,`view`])for(let n of d)n.type===t&&e.exec(`DROP ${t.toUpperCase()} ${W(n.name)};`);for(let[t,n]of u.entries()){let r=`__openclaw_strict_migration_${t}_${n.name}`;if(o.has(r))throw Error(`SQLite STRICT migration table already exists: ${r}`);let i=readVisibleColumns(e,n.name);assertMatchingColumns(n.name,i,n.columns);let a=o.get(n.name);if(!a)throw Error(`SQLite table ${n.name} disappeared during STRICT migration`);let s=readTableRowidModel(e,n.name,a);if(s.storage!==n.rowidStorage)throw Error(`SQLite table ${n.name} changes rowid storage from ${s.storage} to ${n.rowidStorage}; refusing an identity-changing STRICT migration`);let c=n.usesAutoincrement?readAutoincrementHighWater(e,n.name):null;e.exec(rewriteCreateTableName(n.createSql,r));let l=n.columns.map(W);n.rowidAlias&&l.unshift(W(n.rowidAlias));let u=l.join(`, `);try{e.exec(`INSERT INTO ${W(r)} (${u}) SELECT ${u} FROM ${W(n.name)};`)}catch(e){throw Error(`Failed migrating SQLite table ${n.name} to STRICT`,{cause:e})}e.exec(`DROP TABLE ${W(n.name)};`),e.exec(`ALTER TABLE ${W(r)} RENAME TO ${W(n.name)};`),restoreAutoincrementHighWater(e,n.name,c)}e.exec(t);let f=e.prepare(`SELECT 1 AS found FROM sqlite_schema WHERE type = ? AND name = ? LIMIT 1`);for(let t of d)f.get(t.type,t.name)||e.exec(t.sql);return Qe(e,n.databaseLabel??`SQLite STRICT schema migration`,{check:n.integrityCheck??`quick`,tables:u.map(e=>e.name)}),{migratedTables:u.map(e=>e.name)}}const jf=[`auth`,`auth_permanent`,`format`,`rate_limit`,`overloaded`,`billing`,`server_error`,`route_unavailable`,`timeout`,`tls_certificate`,`context_overflow`,`model_not_found`,`session_expired`,`empty_response`,`no_error_details`,`unclassified`,`unknown`];function closedObject(e){let t=Nc.Object(e,{additionalProperties:!1});return Object.defineProperty(t,"~openclawClosedObjectIdentity",{value:Symbol(`closedObject`)}),t}const Mf=Nc.Integer({minimum:0,maximum:864e13});function stringLiteralUnion(e){let t=e.map(e=>Nc.Literal(e));return Nc.Union(t)}const Nf=stringLiteralUnion([`progress`,`done`,`blocked`,`needs_attention`]);Nc.Union([Nc.Literal(`no_change`),Nf]);const Pf=Nc.String({minLength:1,maxLength:2e3,pattern:`\\S`}),Ff=closedObject({outcome:Nf,summary:Pf}),If=Nc.Union([closedObject({outcome:Nc.Literal(`no_change`),summary:Nc.Optional(Pf)}),Ff]);closedObject({...Ff.properties,atMs:Mf});function parseAutomationResult(e){if(!I(e))return;let t=typeof e.summary==`string`?{...e,summary:e.summary.trim()}:{...e};return Mc.Check(If,t)?t:void 0}function resolveCronCompletionStatus(e){return e.status===`error`||e.status===`skipped`?`failed`:e.status===`ok`?e.requiredDelivery===void 0?e.delivered===!0||e.deliveryStatus===`delivered`||e.deliveryStatus===`not-requested`?`succeeded`:`unknown`:!e.requiredDelivery||e.deliveryStatus===`delivered`||e.deliveryStatus===`not-delivered`&&e.deliverySuppressionReason!==void 0?`succeeded`:e.deliveryStatus===`not-delivered`?`failed`:`unknown`:`unknown`}const Lf=[`cron: job execution timed out`,`cron: isolated agent setup timed out before runner start`,`cron: isolated agent run stalled before execution start`];function isCronTimeoutErrorText(e){return typeof e==`string`&&Lf.some(t=>e===t||e.startsWith(`${t} `))}function normalizeSeverity(e){return e===`info`||e===`warn`||e===`error`?e:`error`}function normalizeSource(e){switch(e){case`cron-preflight`:case`cron-setup`:case`model-preflight`:case`agent-run`:case`tool`:case`exec`:case`delivery`:return e;default:return`agent-run`}}function normalizeTimestamp$1(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t()}function normalizeDiagnosticMessage(e,t){if(typeof e!=`string`)return{};let n=Xn(e);if(!n)return{};let r=t(n);return r.length<=1e3?{message:r}:{message:`${tr(r,999)}…`,truncated:!0}}function normalizeCronRunDiagnosticSummary(e){let t=Xn(e);if(t)return t.length<=2e3?t:`${tr(t,1999)}…`}function normalizeCronRunDiagnosticsCore(e,t){if(!e||typeof e!=`object`)return;let n=e,r=t?.nowMs??Date.now,i=t?.redactText??(e=>e),a=Array.isArray(n.entries)?n.entries:[],o=[];for(let e of a){if(!e||typeof e!=`object`)continue;let t=e,n=normalizeDiagnosticMessage(t.message,i);n.message&&(o.push({ts:normalizeTimestamp$1(t.ts,r),source:normalizeSource(t.source),severity:normalizeSeverity(t.severity),message:n.message,...typeof t.toolName==`string`&&t.toolName.trim()?{toolName:t.toolName.trim()}:{},...typeof t.exitCode==`number`&&Number.isFinite(t.exitCode)?{exitCode:t.exitCode}:t.exitCode===null?{exitCode:null}:{},...t.truncated===!0||n.truncated?{truncated:!0}:{}}),o.length>10&&o.shift())}let s=normalizeCronRunDiagnosticSummary(typeof n.summary==`string`?i(n.summary):void 0);if(o.length!==0||s)return{...s?{summary:s}:{},entries:o}}const Rf=`cron-run`,zf=Se([`ok`,`error`,`skipped`]),Bf=Se([`succeeded`,`failed`,`unknown`]),Vf=Se([`delivered`,`not-delivered`,`unknown`,`not-requested`]),Hf=S().optional().catch(void 0),Uf=S().refine(e=>e.trim().length>0).optional().catch(void 0),Wf=ce().optional().transform(e=>normalizeTimestamp(e)),Gf=ce().optional().transform(e=>Jn(e,{min:0})),Kf=D({input_tokens:Gf,output_tokens:Gf,total_tokens:Gf,cache_read_tokens:Gf,cache_write_tokens:Gf}).transform(e=>Object.values(e).some(e=>e!==void 0)?e:void 0).optional().catch(void 0),qf=Le({status:Vf,delivered:fe().optional().catch(void 0),error:Hf}).transform(({status:e,delivered:t,error:n})=>({status:e,...t===void 0?{}:{delivered:t},...n===void 0?{}:{error:n}})).optional().catch(void 0),Jf=Le({action:s(`finished`),jobId:S().refine(e=>e.trim().length>0),ts:ce().transform(e=>normalizeTimestamp(e)).pipe(Pe()),status:zf.optional().catch(void 0),completionStatus:Bf.optional().catch(void 0),error:Hf,errorReason:Se(jf).optional().catch(void 0),summary:Hf,result:ce().optional().transform(parseAutomationResult),runId:Uf,diagnostics:ce().optional(),runAtMs:Wf,durationMs:Gf,nextRunAtMs:Wf,triggerFired:fe().optional().catch(void 0),model:Uf,provider:Uf,usage:Kf,delivered:fe().optional().catch(void 0),deliveryStatus:Vf.optional().catch(void 0),deliveryError:Hf,deliverySuppressionReason:Se([`empty`,`silent`,`heartbeat`,`channel_transform`]).optional().catch(void 0),failureNotificationDelivery:qf,delivery:Ee(isJsonObject).optional().catch(void 0),sessionId:Uf,sessionKey:Uf});function parseCronRunDetailJson(e){return safeParseJson(e)}function toJsonValue(e){let t=JSON.stringify(e);return t===void 0?void 0:parseCronRunDetailJson(t)}function isJsonObject(e){return I(e)}function normalizeTimestamp(e){return Jn(e,{min:0,max:Kn})}function parseCronRunLogEntryObject(e,t){let n=Xn(t?.jobId),r=Jf.safeParse(e);if(!r.success)return null;let i=r.data;return n&&i.jobId!==n?null:{ts:i.ts,jobId:i.jobId,action:`finished`,status:i.status,completionStatus:i.completionStatus??resolveCronCompletionStatus({status:i.status,delivered:i.delivered,deliveryStatus:i.deliveryStatus}),error:i.error,errorReason:i.errorReason,summary:i.summary,result:i.result,runId:i.runId,diagnostics:normalizeCronRunDiagnosticsCore(i.diagnostics),runAtMs:i.runAtMs,durationMs:i.durationMs,nextRunAtMs:i.nextRunAtMs,triggerFired:i.triggerFired,model:i.model,provider:i.provider,usage:i.usage,delivered:i.delivered,deliveryStatus:i.deliveryStatus,deliveryError:i.deliveryError,deliverySuppressionReason:i.deliverySuppressionReason,failureNotificationDelivery:i.failureNotificationDelivery,delivery:i.delivery,sessionId:i.sessionId,sessionKey:i.sessionKey}}function cronRunLogEntryToDetail(e,t){return toJsonValue({kind:Rf,status:e.status,completionStatus:e.completionStatus,error:e.error??null,summary:e.summary??null,result:e.result,storeKey:t.storeKey,errorReason:e.errorReason,diagnostics:e.diagnostics,delivered:e.delivered,deliveryStatus:e.deliveryStatus,deliveryError:e.deliveryError,deliverySuppressionReason:e.deliverySuppressionReason,failureNotificationDelivery:e.failureNotificationDelivery,delivery:e.delivery,sessionId:e.sessionId,runId:e.runId,runAtMs:e.runAtMs,durationMs:e.durationMs,nextRunAtMs:e.nextRunAtMs,triggerFired:e.triggerFired,triggerStateChanged:t.triggerEval?.fired===!0?t.triggerEval.stateChanged:void 0,triggerState:t.triggerEval?.fired===!0&&t.triggerEval.stateChanged?t.triggerEval.state:void 0,scriptStateChanged:t.scriptResult?.scriptStateChanged===!0||void 0,scriptState:t.scriptResult?.scriptStateChanged===!0?t.scriptResult.scriptState:void 0,model:e.model,provider:e.provider,usage:e.usage})??{kind:Rf}}function cronRunStorageStatus(e){return e.status===`ok`?(e.completionStatus??resolveCronCompletionStatus({status:e.status,delivered:e.delivered,deliveryStatus:e.deliveryStatus}))===`succeeded`?`succeeded`:`failed`:e.status===`error`&&isCronTimeoutErrorText(e.error)?`timed_out`:`failed`}function collectMirroredTasks(e){let t=e.prepare(`SELECT source_id, ended_at, detail_json
       FROM task_runs
       WHERE runtime = 'cron' AND source_id IS NOT NULL AND detail_json IS NOT NULL`).all(),n=/* @__PURE__ */ new Map;for(let e of t){let t=e.detail_json?safeParseJsonRecord(e.detail_json):void 0;if(!e.source_id||t?.kind!==`cron-run`)continue;let r=n.get(e.source_id)??[];r.push({endedAt:normalizeSqliteNumber(e.ended_at)??null,...typeof t.runId==`string`&&t.runId?{runId:t.runId}:{}}),n.set(e.source_id,r)}return n}function hasMirroredIdentity(e,t,n){return e.some(e=>t&&e.runId?e.runId===t:e.endedAt===n)}function integerToBoolean(e){return e==null?void 0:coerceRequiredSqliteNumber(e)!==0}function parseLegacyRow(e){let t=parseCronRunLogEntryObject(safeParseJson(e.entry_json??``),{jobId:e.job_id});return t?{...t,ts:normalizeSqliteNumber(e.ts)??t.ts,jobId:e.job_id,status:e.status??t.status,error:e.error??t.error,summary:e.summary??t.summary,delivered:integerToBoolean(e.delivered)??t.delivered,deliveryStatus:e.delivery_status??t.deliveryStatus,deliveryError:e.delivery_error??t.deliveryError,sessionId:e.session_id??t.sessionId,sessionKey:e.session_key??t.sessionKey,runId:e.run_id??t.runId,runAtMs:normalizeSqliteNumber(e.run_at_ms??null)??t.runAtMs,durationMs:normalizeSqliteNumber(e.duration_ms??null)??t.durationMs,nextRunAtMs:normalizeSqliteNumber(e.next_run_at_ms??null)??t.nextRunAtMs,model:e.model??t.model,provider:e.provider??t.provider}:null}function migrateLegacyCronRunLogsToTaskRuns(e){if(!hasLegacyCronRunLogs(e))return{imported:0,alreadyMirrored:0,malformed:0,skipped:!0};let t=collectMirroredTasks(e),n=/* @__PURE__ */ new Map,r=e.prepare(`
    INSERT INTO task_runs (
      task_id, runtime, task_kind, source_id, requester_session_key, owner_key, scope_kind,
      child_session_key, parent_flow_id, parent_task_id, agent_id, requester_agent_id, run_id,
      label, task, status, delivery_status, notify_policy, created_at, started_at, ended_at,
      last_event_at, cleanup_after, error, progress_summary, terminal_summary, terminal_outcome,
      detail_json
    ) VALUES (
      @task_id, 'cron', NULL, @source_id, '', '', 'system', @child_session_key, NULL, NULL,
      NULL, NULL, @run_id, NULL, @task, @status, 'not_applicable', 'silent', @created_at,
      @started_at, @ended_at, @ended_at, NULL, @error, NULL, @terminal_summary,
      @terminal_outcome, @detail_json
    )
  `),i=0,a=0,o=0,s=0;for(;;){let c=e.prepare(`SELECT * FROM cron_run_logs
         ORDER BY job_id, ts, store_key, seq
         LIMIT ? OFFSET ?`).all(500,s);if(c.length===0)break;s+=c.length;for(let e of c){let s=parseLegacyRow(e);if(!s){o++;continue}let c=`${s.jobId}\0${s.ts}`,l=(n.get(c)??0)+1;if(n.set(c,l),hasMirroredIdentity(t.get(s.jobId)??[],s.runId,s.ts)){a++;continue}let u=`cron-runlog-import:${s.jobId}:${s.ts}:${l}`,d=cronRunStorageStatus(s);r.run({task_id:u,source_id:s.jobId,child_session_key:s.sessionKey?.trim()||null,run_id:u,task:s.jobId,status:d,created_at:s.runAtMs??s.ts,started_at:s.runAtMs??null,ended_at:s.ts,error:s.error??null,terminal_summary:s.summary??null,terminal_outcome:d===`succeeded`?`succeeded`:null,detail_json:JSON.stringify(cronRunLogEntryToDetail(s,{storeKey:e.store_key}))}),i++}}e.exec(`
    DROP INDEX IF EXISTS idx_cron_run_logs_store_ts;
    DROP INDEX IF EXISTS idx_cron_run_logs_job_status;
    DROP INDEX IF EXISTS idx_cron_run_logs_delivery;
    DROP TABLE cron_run_logs;
  `);let c={imported:i,alreadyMirrored:a,malformed:o,skipped:!1},l=Date.now();return e.prepare(`INSERT INTO migration_runs (id, started_at, finished_at, status, report_json)
     VALUES (?, ?, ?, 'completed', ?)
     ON CONFLICT(id) DO UPDATE SET
       finished_at = excluded.finished_at,
       status = excluded.status,
       report_json = excluded.report_json`).run(`state:cron-run-logs-to-task-runs:v1`,l,l,JSON.stringify(c)),c}function hasPreJournalStateSchema(e){if(z(e)||readStateSchemaContentVersion(e)!==1||M(e,`config_machine_state`)||M(e,`agent_database_leases`)||!M(e,`agent_databases`)||!M(e,`migration_sources`))return!1;let t=w(e),n=C(e,t.selectFrom(`schema_meta`).selectAll().where(`meta_key`,`=`,`primary`));return n?.role===`global`&&n.schema_version===1&&n.agent_id===null&&!C(e,t.selectFrom(`migration_sources`).select(`source_key`).where(`target_table`,`=`,`agent_deletion_journal`).limit(1))}const Yf=/* @__PURE__ */ new Set([`table:device_auth_tokens`,`index:idx_device_auth_tokens_updated`,`table:device_identities`,`index:idx_device_identities_device`,`table:exec_approvals_config`,`table:macos_port_guardian_records`,`index:idx_macos_port_guardian_records_port`,`table:schema_meta`,`table:state_leases`,`index:idx_state_leases_expiry`,`index:idx_state_leases_owner`]);Ge(`state.startup-checkpoint`,e=>e===!0||void 0);function isUninitializedNativeStartupDatabase(e,n){let r=K(e);if((n??t(e)?.userVersion??r?.userVersion??Lo(e))!==0)return!1;let i=r?[...[...r.tables].map(e=>({type:`table`,name:e})),...[...r.indexes].map(e=>({type:`index`,name:e})),...[...r.views].map(e=>({type:`view`,name:e})),...[...r.triggers.keys()].map(e=>({type:`trigger`,name:e}))].filter(({name:e})=>!e.startsWith(`sqlite_`)):e.prepare(`SELECT type, name FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%'`).all();if(i.some(({type:e,name:t})=>typeof e!=`string`||typeof t!=`string`||!Yf.has(`${e}:${t}`)))return!1;let a=new Set(i.filter(({type:e})=>e===`table`).map(({name:e})=>e));return a.has(`schema_meta`)&&e.prepare(`SELECT 1 FROM schema_meta LIMIT 1`).get()?!1:!(a.has(`state_leases`)&&e.prepare(`SELECT 1 FROM state_leases LIMIT 1`).get())}function assertGatewayServiceSchemaMigrationAllowed(e,t,n){let r=Be();if(r&&t>0&&t<n&&r.databasePath===Ns(e))throw new as(`state-migrations`,`Refusing a forward database schema migration: this CLI is ${r.cliVersion} but the Gateway service runs ${r.version} from ${r.root}; run openclaw update (or the CLI from ${r.root}).`)}function resolveSchemaMigrationIntegrityCheck(e,t=`quick`){return t===`full`?{check:`full`}:{check:t,tables:resolveSchemaMigrationIntegrityTables(e),...e.kind===`agent`&&e.foundVersion>=38&&e.foundVersion<e.supportedVersion&&e.supportedVersion<=42?{schemaOnly:!0}:{}}}const Xf=er(`state/db`);function ensureOpenClawStateRuntimeSchema(e,t,n,r,i=Wo,a=!1,o,s){let c=be()??(Vs?ht(t):void 0);if(T(t,e))return assertExistingOpenClawStateRuntimeSchema(e,t,c),assertOpenClawStateWriteAllowed({database:e,databasePath:t,env:n}),[];try{if(isOpenClawStateSchemaFastPathEligible(e,t,c))return assertOpenClawStateWriteAllowed({database:e,databasePath:t,env:n}),[]}catch(t){if(!e.isOpen||t instanceof as)throw t}return withStateDatabaseSchemaMaintenance({databasePath:t,busyTimeoutMs:i},()=>{let c=Date.now(),l=[],u=!1,d=runStateSchemaMigrationTransaction(e,t,()=>{if(assertOpenClawStateWriteAllowed({database:e,databasePath:t,env:n}),assertSupportedStateSchemaVersion(e,t),a&&!isUninitializedNativeStartupDatabase(e))return[];let i=readStateSchemaContentVersion(e);if(So()?.ownsSchemaMaintenance||assertGatewayServiceSchemaMigrationAllowed(t,i,40),i===0&&!isUninitializedNativeStartupDatabase(e))throw Error(`Unrecognized native bootstrap database; preserve it and run openclaw doctor --fix.`);i>0&&assertCanonicalStateSchemaShape(e,t),prepareClientCredentialMigration(e,{path:t,env:n,fromVersion:i,custody:s});let d=K(e);if(i===0&&d?.tables.size===0&&d.views.size===0)return createStateConfigMachineTable(e),executeCanonicalStateSchema(e,{includeVersionLazyAdditiveTables:!0,includeAgentDeletionJournal:r.kind===`fresh`||r.nativeBootstrapEligible===!0}),_e(e,{previousVersion:i,legacyDefaultStoreKey:o??bt(n),fresh:!0,nowMs:c}),writeCurrentStateSchemaMetadata(e,c),u=!0,[];if(i===40){assertNoLegacyStateRuntimeRepair(e,t),Ke(e,t);let n=repairCanonicalSqliteIndexes(e,t,H,{verifyPhysicalIntegrity:!1,allowMissingColumns:!0,validateAfterRepair:()=>{assertCanonicalStateSchemaShape(e,t),assertOpenClawStateDatabaseForMaintenance(e,{pathname:t})}});return ensureAdditiveStateColumns(e,`runtime`),assertCurrentStateRuntimeSchema(e,t),writeCurrentStateSchemaMetadata(e,c),u=!0,n.length>0?[`Rebuilt canonical shared-state SQLite indexes (${n.length})`]:[]}rd.get(i)?.(e,{pathname:t});let f=resolveSchemaMigrationIntegrityCheck({kind:`state`,foundVersion:i,supportedVersion:40});f.check===`quick`?Qe(e,t,f):Ke(e,t);let p=migrateBoundedStateSchema(e,i,{env:n,legacyCronDefaultStoreKey:o});if(p)return writeCurrentStateSchemaMetadata(e,c),assertCurrentStateRuntimeSchema(e,t),assertMigratedStateTableIntegrity(e,t,i),u=!0,p;let m=migrateHistoricalStateImports(e,i),h=M(e,`agent_deletion_journal`)||hasPreJournalStateSchema(e)||(r.kind===`fresh`||r.nativeBootstrapEligible===!0)&&isUninitializedNativeStartupDatabase(e);dropLegacyStateTables(e);let g=runRetiredStateTableMigrations(e,i);l.push(...g),migrateSingletonStateFoldInV12(e,i)&&g.push(`Folded singleton state tables into config_machine_state (v12)`),migrateWorkerPlacementExecutionModeSchema(e,i)&&g.push(`Migrated cloud worker placements to execution modes`);let _=migrateAgentDatabaseRelativePaths(e,i,t);g.push(...ts(_)),migratePredicateColumnsV21(e,i)&&g.push(`Derived meeting transcript selectors and bounded delivery retention columns (v21)`),ensureAdditiveStateColumns(e,i<20?`repair`:`runtime`);for(let t of fd)t.migrate(e,i,{env:n,legacyCronDefaultStoreKey:o})&&g.push(t.applied);if(migrateSessionWatchCursorProvenance(e),assertCanonicalStateSchemaShape(e,t),executeCanonicalStateSchema(e,{includeVersionLazyAdditiveTables:!0,includeAgentDeletionJournal:h}),migrateLegacyCronRunLogsToTaskRuns(e),i<3&&hasNonStrictSqliteTables(e)){repairLegacyGatewayRestartHandoffsForStrictMigration(e),ensureFirstUseAdditiveStateColumnsForStrictMigration(e);let n=migrateSqliteSchemaToStrictInTransaction(e,getOpenClawStateRuntimeSchema({includeVersionLazyAdditiveTables:!0,includeAgentDeletionJournal:h}),{databaseLabel:t});n.migratedTables.length>0&&g.push(`Migrated shared state tables to SQLite STRICT typing (${n.migratedTables.length})`)}return repairCanonicalSqliteIndexes(e,t,H,{verifyPhysicalIntegrity:!1}),writeCurrentStateSchemaMetadata(e,c),assertOpenClawStateDatabaseForMaintenance(e,{pathname:t}),assertMigratedStateTableIntegrity(e,t,i,!0),u=!0,ss(Xf,_,t),[...m,...g]},{busyTimeoutMs:i,databaseLabel:t,operationLabel:`state.schema.ensure`});return u&&at(e,!0),l.forEach(logRetiredStateTableMigration),d})}const Zf=`NOT EXISTS (SELECT 1 FROM task_runs WHERE task_runs.task_id = task_delivery_state.task_id)`;function orphanRows(e){let t=e.prepare(`SELECT rowid, * FROM task_delivery_state
    WHERE ${Zf} ORDER BY rowid`);return t.setReadBigInts(!0),t.iterate()}function encodeOrphanRow(e){if(typeof e.rowid!=`bigint`||typeof e.task_id!=`string`||e.requester_origin_json!==null&&typeof e.requester_origin_json!=`string`||e.last_notified_event_at!==null&&typeof e.last_notified_event_at!=`bigint`)throw Error(`Orphan task delivery values do not match the supported recovery contract.`);return`${JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t)}\n`}function assertOrphanTaskDeliveryRecoveryShape(e){let t=e.prepare(`PRAGMA table_xinfo(task_delivery_state)`).all(),n=[{cid:0,name:`task_id`,type:`TEXT`,notnull:1,dflt_value:null,pk:1,hidden:0},{cid:1,name:`requester_origin_json`,type:`TEXT`,notnull:0,dflt_value:null,pk:0,hidden:0},{cid:2,name:`last_notified_event_at`,type:`INTEGER`,notnull:0,dflt_value:null,pk:0,hidden:0}],r=e.prepare(`PRAGMA foreign_key_list(task_delivery_state)`).all(),i=[{id:0,seq:0,table:`task_runs`,from:`task_id`,to:`task_id`,on_update:`NO ACTION`,on_delete:`CASCADE`,match:`NONE`}],a=e.prepare(`SELECT 1 FROM sqlite_schema WHERE type = 'trigger' AND tbl_name = 'task_delivery_state'`).get();if(JSON.stringify(t)!==JSON.stringify(n)||JSON.stringify(r)!==JSON.stringify(i)||a)throw Error(`Orphan task delivery recovery refused an unrecognized table, foreign key, or trigger.`)}function assertKnownOrphanTaskDeliveryIntegrity(e){try{return Qe(e,`task delivery recovery database`),0}catch(e){if(e instanceof tn)return e.repair.orphanCount;throw e}}function hasOrphanTaskDeliveryRows(e){return M(e,`task_delivery_state`)&&M(e,`task_runs`)&&!!e.prepare(`SELECT 1 FROM task_delivery_state WHERE ${Zf} LIMIT 1`).get()}function hashOrphanRows(e){let t=nc(`sha256`),n=0;for(let r of orphanRows(e))t.update(encodeOrphanRow(r)),n+=1;return{count:n,payloadSha256:t.digest(`hex`)}}function applyOrphanTaskDeliveryRecovery(e,t,n,r){if(!e.isTransaction)throw Error(`Orphan task delivery recovery requires the Doctor write transaction.`);assertOrphanTaskDeliveryRecoveryShape(e);let i=hashOrphanRows(e);if(i.count!==n.count||i.payloadSha256!==n.payloadSha256)throw Error(`Orphan task delivery snapshot does not preserve the current payload.`);let a=e.prepare(`DELETE FROM task_delivery_state WHERE ${Zf}`).run();if(Number(a.changes)!==n.count)throw Error(`Orphan task delivery recovery removed an unexpected number of rows.`);return Qe(e,t),[`Preserved and recovered ${n.count} orphan task delivery rows; backup and row export: ${r}`]}function preserveOrphanTaskDeliveryRecoveryInProcess(e,t,n){let r=Ga(e);try{r.exec(`PRAGMA journal_mode = DELETE;`),assertOrphanTaskDeliveryRecoveryShape(r);let i=assertKnownOrphanTaskDeliveryIntegrity(r);if(i===0)throw Error(`Orphan task delivery snapshot no longer contains orphan rows.`);let a=X.join(n,`database.sqlite`),o=Va(e);if(Y.copyFileSync(e,a,Y.constants.COPYFILE_EXCL),Y.chmodSync(a,384),JSON.stringify(Va(a))!==JSON.stringify(o))throw Error(`Orphan task delivery backup verification failed.`);let s=X.join(n,`orphan-rows.jsonl`),c=Y.openSync(s,`wx+`,384),l=nc(`sha256`),u=0,d;try{for(let e of orphanRows(r)){let t=encodeOrphanRow(e);Y.writeFileSync(c,t),l.update(t),u+=1}if(Y.fsyncSync(c),d=l.digest(`hex`),qa(c).sha256!==d)throw Error(`Orphan task delivery export verification failed.`)}finally{Y.closeSync(c)}if(u!==i)throw Error(`Orphan task delivery export did not account for every foreign-key violation.`);return Y.writeFileSync(X.join(n,`manifest.json`),JSON.stringify({format:`openclaw.task-delivery-recovery.v1`,state:`preserved-before-repair`,sourcePath:t,backup:{file:`database.sqlite`,...o,integrity:`structural-ok-known-orphans`},export:{file:`orphan-rows.jsonl`,...Va(s),count:i,integerEncoding:`decimal-string`},relation:`task_delivery_state.task_id -> task_runs.task_id`,createdAt:(/* @__PURE__ */ new Date()).toISOString()},null,2),{flag:`wx`,mode:384,flush:!0}),lo(mo(n),`Task delivery recovery directory`),lo(mo(X.dirname(n)),`Task delivery recovery parent`),{count:i,payloadSha256:d}}finally{r.close()}}function recoveryFailure(e,t){return Error(`Task delivery recovery failed without committing row removal${t?`; retained artifacts: ${t}`:``}: ${String(e)}`,{cause:e})}function recoverOrphanTaskDeliveryRows(e,t){if(!hasOrphanTaskDeliveryRows(e))return[];assertOpenClawStateDatabaseOwner(e,{pathname:t}),assertOrphanTaskDeliveryRecoveryShape(e);let n=assertKnownOrphanTaskDeliveryIntegrity(e);if(!e.isTransaction)throw Error(`Orphan task delivery recovery requires the Doctor write transaction.`);let r=Ze(t),i;try{i=mt(X.dirname(t),`openclaw-task-delivery-recovery-`);let a=preserveOrphanTaskDeliveryRecoveryInProcess(r.location,t,i);if(a.count!==n)throw Error(`Orphan task delivery snapshot changed before preservation.`);return assertOpenClawStateDatabaseOwner(e,{pathname:t}),applyOrphanTaskDeliveryRecovery(e,t,a,i)}catch(e){throw recoveryFailure(e,i)}finally{r.cleanup()}}const Qf=/* @__PURE__ */ new WeakSet;function openOpenClawStateDatabaseWithBusyTimeout(...e){return runStateOpenSteps(openStateDatabaseSteps(...e))}function*openStateDatabaseSteps(e={},n=Wo,r=`report`,i){So()?.assertAdmission();let a=e.env??process.env,o=e.database?.path??wo(e);if(hs(`agent`,o)){assertStateFileSnapshotAllowed(),j.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(o,a);let e=Bt(o,{timeout:n});return assertSupportedStateSchemaVersion(e,o),readOnlyStateDatabase({db:e,path:o},()=>(e.close(),!0))}let s=!e.database&&T(o),c=e.database??j.getCachedOpenClawStateDatabase(o);if(c&&(e.database||c.db.isOpen))return e.database||j.assertOpenClawStateDatabaseOpenAllowed(o),assertStateDatabaseSchemaAdmission(c),assertOpenClawStateWriteAllowed({database:c.db,databasePath:o,env:a,schemaReady:j.isOpenClawStateDatabaseSchemaReady(c)}),Eo(c.db),e.database?j.touchStateDatabase(c):!s&&Qf.has(c.db)&&(reconcileOpenClawStateSchemaPublication(e),t(c.db)?.userVersion===40&&Qf.delete(c.db)),c;let l;try{let open=(t,n)=>(So()?.assertAdmission(),j.assertOpenClawStateDatabaseOpenAllowed(o),j.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(o,a),c&&j.closeStaleCachedOpenClawStateDatabase(c),n({pathname:o,env:a,busyTimeoutMs:t(),lockFailureReporting:r,existingSchema:s,initializationAgentPaths:e.initializationAgentPaths,clientCredentialMigrationFromVersion:e.clientCredentialMigrationFromVersion,ensureSchema:(e,n,r)=>ensureOpenClawStateRuntimeSchema(e,o,a,n,t(),!1,void 0,r),recordOpenFailure:Gt})),acquire=e=>i?open(i,e):ke({databasePath:o,busyTimeoutMs:n},t=>open(t,e));l=yield{run(){return acquire(openUnpublishedStateDatabase)},runAsync(){return acquire(openUnpublishedStateDatabaseAsync)}},us(Is())?.throwIfAborted(),So()?.assertAdmission(),z(l.db)||oo(l.db,n)}catch(e){if(r!==`report`&&isOpenClawStateWriteContentionError(e)||j.recordOpenClawStateDatabaseLifecycleOpenError(o,e),l){let t=j.closeUnpublishedOpenClawStateDatabaseHandle(l);if(t.length>0)throw Zr([e,...t],`Fresh OpenClaw state database open failed releasing access and closing its unpublished handle for ${o}.`,e)}throw e}s&&rn(l.db,o);let u=j.publishOpenClawStateDatabase(l,a);try{return!s&&kt(u.db)<40&&(Qf.add(u.db),reconcileOpenClawStateSchemaPublication(e)),u}catch(e){throw u.db.isOpen&&!z(u.db)&&oo(u.db,Wo),e}}function reconcileOpenClawStateSchemaPublication(e={}){if(T(e.database?.path??wo(e)))return;let t=withExistingOpenClawStateDatabaseReadOnly(({db:e})=>{if(!(kt(e)>=40||readStateSchemaContentVersion(e)<40))return z(e)&&Fa(`postgres`,`repair`),{blocker:readStateSchemaPublicationBlocker(e)}},e);if(!t||t.blocker)return t?.blocker;let n=wo(e);try{return withStateDatabaseSchemaMaintenance({databasePath:n},()=>runOpenClawStateWriteTransaction(({db:e})=>{z(e)&&Fa(`postgres`,`repair`);let t=readStateSchemaPublicationBlocker(e);if(t)return t;assertOpenClawStateDatabaseForMaintenance(e,{pathname:n}),markCurrentStateSchemaVersion(e)},e,{operationLabel:`state.schema.publish`}))}catch(e){if(e instanceof fu)return;throw e}}function runOpenClawStateWriteTransaction(e,t={},n={}){if(hs(`agent`,t.database?.path??wo(t)))throw Error(`Programming error: shared-state write during artifact-preserving inspection.`);So()?.assertAdmission();let r=t.database??getOpenClawStateDatabaseIfOpen(t);r&&(T(r.path,r.db),t.database&&Je(r.path));let i=r,a=!1,o,execute=r=>{let o=i??openOpenClawStateDatabaseWithBusyTimeout(t,5e3,`report`,r);i=o;let write=()=>runManagedStateTransaction(o.db,()=>(z(o.db)&&admitStateSchemaFacts(o.db,o.path),assertStateDatabaseSchemaAdmission(o),t.database||getOpenClawStateDatabaseIfOpen(t),assertOpenClawStateWriteAllowed({database:o.db,databasePath:o.path,env:t.env??process.env,schemaReady:j.isOpenClawStateDatabaseSchemaReady(o)}),Eo(o.db),t.database&&j.touchStateDatabase(o),a=!0,e(o)),{databaseLabel:o.path,...n,...r?{busyTimeoutMs:r()}:{},operationLabel:n.operationLabel??Ar()?.operation??`state.write`});return{database:o,value:z(o.db)?withPostgresSchemaAdmissionRetry(o.db,write,()=>!a):write()}};try{o=r?execute():ke({databasePath:wo(t),busyTimeoutMs:n.busyTimeoutMs??5e3,canRetry(){return a||i&&(!i.db.isOpen||i.db.isTransaction)?!1:(i&&=(Xe(i.db),z(i.db)||$a(i.db),j.closeOpenClawStateDatabaseByPath(i.path),void 0),!0)}},execute)}catch(e){throw i&&j.evictOpenClawStateDatabaseAfterCorruption(i,e),e}try{T(o.database.path,o.database.db)||ensureOpenClawStatePermissions(o.database.path,t.env??process.env)}catch{}return o.value}function getOpenClawStateDatabaseIfOpen(e={}){let t=wo(e);T(t);let n=j.getCachedOpenClawStateDatabase(t);return n?.db.isOpen&&T(n.path,n.db),n?.db.isOpen?n:void 0}function statusKey(e){return{name:`agent.deletion-status:${q(e)}`,read:e=>e===`absent`||e===`pending`||e===`complete`?e:void 0}}function prepareAgentDeletionJournalStatus(e,t){let n=statusKey(t),r=kr(e,n);return e=>(e?V(e,n):r())??void 0}R(Symbol.for(`openclaw.agentDeletionJournalStatusLoads`),()=>/* @__PURE__ */ new Map);const $f=R(Symbol.for(`openclaw.agentDatabaseIdentities`),()=>/* @__PURE__ */ new WeakMap);function registerOpenClawAgentDatabaseIdentity(e,t){let n=hr(e),r=ui(n.location()??``),i=r?Jr(r):void 0,a=i?{...i,canonicalPath:mi(r)}:r?jr(r):void 0;if(!a||!a.key.startsWith(`file:`))throw Error(`OpenClaw agent database requires a physical file for identity registration`);let o=a.key.slice(5);$f.set(n,{identity:o,birthtime:a.birthtime,incarnation:rc(),filename:r,canonicalPath:a.canonicalPath,ownerDatabasePath:t?mi(t):void 0})}function readOpenClawAgentDatabaseIdentity(e){let t=findOpenClawAgentDatabaseIdentity(e);if(t===void 0)throw Error(`OpenClaw agent database identity was not prepared at open`);return t}function findOpenClawAgentDatabaseIdentity(e){return $f.get(hr(e.db))}R(Symbol.for(`openclaw.agentDatabaseRegistryMemo`),()=>({pending:/* @__PURE__ */ new Map,publications:/* @__PURE__ */ new WeakSet}));function parseAgentDeletionDatabasePaths(e){let t=JSON.parse(e);if(Bn(t))return t;throw Error(`Invalid agent deletion database path journal.`)}const ep=1e4;function waitForSqliteOpen(e,t){return xs(e,t,e=>e.reason)}function createSqliteWorkerAdmissionWarning(){let e=0;return(t,n)=>{let r=Date.now();r>=e&&(e=r+ep,Gn({subsystem:`infra/sqlite-worker`}).warn(`SQLite worker admission delayed`,{queueDepth:t,waitMs:n}))}}function validateSqliteWorkerDatabaseLocator(e){let t=X.basename(e);if(!e||e.startsWith(`file:`)||t===`:memory:`||t===`incognito-openclaw-agent.sqlite`)throw Error(`SQLite worker stores require a file-backed filesystem path; in-memory and incognito databases are not supported`)}function reserveSqliteWorkerClient(e,t,n,r){let i=e.size<n;if(!i&&![...t].some(e=>e.retireIdle))throw new U(`SQLite worker store capacity reached`,`overloaded`);return i&&e.add(r),i}function findReusableSqliteWorkerClient(e,t){for(let n of e)if(!n.sealed&&n.isAvailable()&&n.actor.pathReferences.has(t))return n}async function reclaimSqliteWorkerClient(e,t,n,r){let assertCurrent=()=>{if(e.signal?.throwIfAborted(),e.assertCurrent?.(),r())throw new U(`SQLite worker host is closing`,`closed`)};assertCurrent();for(let r of t){if(n())return;r.actor.runtimeGeneration===e.runtimeGeneration&&await r.retireIdle?.(),assertCurrent()}if(!n())throw new U(`SQLite worker store capacity reached`,`overloaded`)}function captureSqliteWorkerOpen(e,t,n,r={}){let{createAdmission:i,preparation:a,retireIdle:o,...s}=r,c=ec.snapshot(),l=e.admission,u=l?()=>{n?.(),l.assertCurrent()}:n,d=u?()=>c(u):void 0,f=X.resolve(e.databasePath);if(e.admission&&(!e.existingOnly||!e.admission.identity.startsWith(`file:`)))throw Error(`Owned SQLite Worker admission requires an existing physical identity`);d?.();let p=cr(`sqliteStore`),m=wa(p,e.runtimeGeneration);return{...s,carrierClass:r.carrierClass??e.isolation,retireIdle:o?()=>c(o):void 0,maintenanceScope:r.cleanupAccess?void 0:r.maintenanceScope??So(),...a===void 0?{}:{preparation:gc(a)},runtimeGeneration:e.runtimeGeneration,carrierUrl:m,createAdmission:i?e=>c(i,e):void 0,assertCurrent:d,...e.admission?{expectedIdentity:e.admission.identity,expectedBirthtime:e.admission.birthtime,createOpenAdmission:()=>{let e=!1;return{nativeLocations:[f],admission:Hi((t,n)=>{if(e||t.stage!==`open`)throw Error(`SQLite Worker open admission requested out of order`);if(d(),!n())throw Error(`SQLite Worker open admission expired`);e=!0})}}}:{},moduleUrl:new URL(e.moduleUrl),databasePath:f,input:gc(e.input),existingOnly:e.existingOnly===!0,...t?{stateContext:vt(t)}:{}}}function validateSqliteWorkerModuleUrl(e){if(e.protocol!==`file:`||e.search||e.hash)throw Error(`SQLite worker backend must be a static local module URL`)}async function prepareSqliteWorkerDatabaseAdmission(e){validateSqliteWorkerModuleUrl(e.moduleUrl);let t=X.resolve(e.databasePath),n=nc(`sha256`).update(e.input).digest(`hex`),r=await fa({location:t,...e.expectedIdentity?{expectedIdentity:{key:e.expectedIdentity,birthtime:e.expectedBirthtime}}:{},assertCurrent:()=>{e.signal?.throwIfAborted(),e.assertCurrent?.()}});if(!r)throw Error(`SQLite worker database path must identify a regular file`);if(e.assertCurrent?.(),e.expectedIdentity&&(r.key!==e.expectedIdentity||e.expectedBirthtime!==void 0&&r.birthtime!==e.expectedBirthtime))throw Error(`SQLite Worker path no longer matches its borrowed native owner`);return{databasePath:t,inputHash:n,identity:r,key:r.key}}function captureSqliteWorkerAdmissionPaths(e,t,n){let r=/* @__PURE__ */ new Set([e,t.canonicalPath]);if([...n].some(e=>e.key!==t.key&&[...r].some(t=>e.pathReferences.has(t))))throw Error(`SQLite database pathname changed while its worker owner is active; close the existing store first`);return r}function retainSqliteWorkerAdmissionCleanup(e,t,n){t?.({get pending(){return e.references===0&&e.cleanupState===`pending`},close:()=>e.references===0?n():Promise.resolve()})}function retainSqliteWorkerAdmissionPathReferences(e,t){for(let n of t)e.pathReferences.set(n,(e.pathReferences.get(n)??0)+1);return()=>{for(let n of t){let t=e.pathReferences.get(n)??0;t>1?e.pathReferences.set(n,t-1):e.pathReferences.delete(n)}}}function suspendSqliteWorkerScheduledMaintenance(e,t){if(!e.stateContext)return;let n=e.stateContext.scheduledMaintenanceSuspension??=new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT);if(!t)return;let r=new Int32Array(n);return Atomics.add(r,0,1),()=>{Atomics.sub(r,0,1)}}async function resolveOpenedSqliteWorkerIdentity(e,t,n){let r=await ma(e),i=r.key;if(r.canonicalPath!==t.canonicalPath)throw Error(`SQLite database canonical pathname changed during open`);if(!i.startsWith(`file:`))throw Error(`SQLite worker backend did not establish its database file`);if(n(i))throw Error(`SQLite database identity collided with an existing worker owner during open`);if(t.key.startsWith(`file:`)&&i!==t.key)throw Error(`SQLite database file identity changed during open`);return r}function findUnclaimedSharedStateActors(e,t){let n=X.resolve(t);return[...e].filter(e=>e.stateContext!==void 0&&e.references===0&&e.cleanupState===`pending`&&e.databasePath===n)}async function closeUnclaimedSharedStateActors(e,t,n){let r=(await Promise.allSettled(findUnclaimedSharedStateActors(e,t).map(n))).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(r.length)throw AggregateError(r,`SQLite worker unclaimed cleanup failed`,{cause:r[0]})}async function resolveSqliteWorkerModuleUrl(e){let t=await Qs(oc(e)),n=sc(t).href;if(!/\.[cm]?[jt]s$/.test(t)||!(await $s(t)).isFile())throw Error(`SQLite worker backend must identify a JavaScript or TypeScript file`);return{modulePath:t,moduleUrl:n}}function assertSqliteWorkerActorStateContext(e,t){let n=t?.gatewayServiceInstallation;if(e.stateContext?.existingSchemaPath!==t?.existingSchemaPath||n!==void 0&&!uc(e.stateContext?.gatewayServiceInstallation,n))throw Error(`Shared-state worker schema policy changed; close its actor first`)}function assertSqliteWorkerActorReusable(e,t,n,r){if(e.moduleUrl!==t||e.inputHash!==n)throw Error(`SQLite database already belongs to another worker backend`);assertSqliteWorkerActorStateContext(e,r)}function prepareSqliteWorkerActorContext(e,t){let{request:n}=t,r=n.stateContext??e?.stateContext;if(e&&r){assertSqliteWorkerActorStateContext(e,r),n.stateDatabasePath=e.stateDatabasePath??e.databasePath;let t={...r,gatewayServiceInstallation:e.stateContext?.gatewayServiceInstallation,...e.stateContext?.scheduledMaintenanceSuspension?{scheduledMaintenanceSuspension:e.stateContext.scheduledMaintenanceSuspension}:{}};if(n.type!==`open`){let r=e.deliveredStateContext;n.stateContext={...t,...t.scheduledMaintenanceSuspension&&t.scheduledMaintenanceSuspension===r?.scheduledMaintenanceSuspension?{scheduledMaintenanceSuspension:void 0}:{},...Object.hasOwn(t,`stateIntegrity`)&&t.stateIntegrity===r?.stateIntegrity?{stateIntegrity:void 0}:{}}}else n.stateContext=t;return t}}function captureSqliteWorkerCreationPaths(e){let select=(t,n)=>{let r=new Set(e.opening?.map(e=>t.get(e)));if(e.companions){let n=t.get(e.companions.primary);for(let i of e.companions.paths){let e=t.get(i);e!==n&&r.add(e)}}if(!r.has(t.get(n)))throw new U(`SQLite creation target differs from its captured database`,`closed`)},locations=t=>/* @__PURE__ */ new Set([...e.opening??[],...e.companions?[e.companions.primary,...e.companions.paths]:[],t]);return{assertCreate(e){select(new Map([...locations(e)].map(e=>[e,Ns(e)])),e)},async prepareCreate(e){let t=await Promise.all([...locations(e)].map(async e=>[e,await Ms(e)]));select(new Map(t),e)}}}function ownedWorkerBytes(e){if(e.buffer instanceof ArrayBuffer&&e.byteOffset===0&&e.byteLength===e.buffer.byteLength&&!Hs(e.buffer))return new Uint8Array(e.buffer);let t=new Uint8Array(e.byteLength);return t.set(e),t}var SqliteWorkerInputAdmission=class{constructor(e){this.owner=e,this.bytes=0,this.opens=/* @__PURE__ */ new Set,this.inputPreparations=/* @__PURE__ */ new Set,this.openQueue=/* @__PURE__ */ new Map}get retainedBytes(){return this.bytes}retain(e){this.bytes+=e;let t=!1;return()=>{t||(t=!0,this.bytes-=e)}}async open(e,t,n,r,i,a,o){if(this.opens.size>=this.owner.maxPendingOpens||e>this.owner.maxMessageBytes||this.owner.queuedBytes()+this.bytes+e>this.owner.maxQueuedBytes)throw new U(`SQLite worker open input capacity reached`,`overloaded`);let s=vs();this.opens.add(s.promise);let c=this.retain(e),enqueue=()=>runWithSqliteDatabaseAdmissionTurn([t],()=>ga({queues:this.openQueue,storePath:a??`generic`,label:`SQLite worker open`,fn:n,signal:r}),[],r,o);try{return await(i?Promise.resolve().then(i).then(e=>e===void 0?enqueue():e):enqueue())}finally{this.opens.delete(s.promise),c(),s.resolve()}}async joinOpens(){for(;this.opens.size>0;)await Promise.allSettled(this.opens)}async joinPreparations(){await Promise.allSettled(this.inputPreparations)}reserveInputPreparation(e,t=`stream`){if(!Number.isSafeInteger(e)||e<0)throw RangeError(`SQLite worker input bytes must be a non-negative safe integer`);if(this.owner.isClosing())throw new U(`SQLite worker host is closing`,`closed`);let n=t===`stream`&&e>this.owner.maxQueuedInputBytes?this.owner.maxMessageBytes:e;if(this.owner.queuedBytes()+this.bytes+n>this.owner.maxQueuedBytes)throw new U(`SQLite worker input preparation capacity reached`,`overloaded`);this.bytes+=n;let r=vs();this.inputPreparations.add(r.promise);let i=!1,release=()=>{this.inputPreparations.delete(r.promise)&&(this.bytes-=n,r.resolve())};return{assertCurrent:()=>{if(!i&&(!this.inputPreparations.has(r.promise)||this.owner.isClosing()))throw new U(`SQLite worker input preparation is closed`,`closed`)},handoff:e=>{if(!this.inputPreparations.has(r.promise)||this.owner.isClosing())throw release(),new U(`SQLite worker input preparation is closed`,`closed`);return i=!0,release(),e()},release}}};function prepareSqliteWorkerRequest(e){if(e.request.type!==`execute`||e.request.input.byteLength<=33554432)return`input`in e.request&&(e.request.input=ownedWorkerBytes(e.request.input)),e.request.type===`open`&&e.request.preparation&&(e.request.preparation=ownedWorkerBytes(e.request.preparation)),e.request;let{input:t,...n}=e.request,r=ao(),i=r.start([{kind:`command`,serialized:t}].values(),{kinds:[`command`]});return e.inputTransfer={id:i.id,producer:r},e.request.input=/* @__PURE__ */ new Uint8Array,{...n,type:`execute-start`,transfer:i}}async function dispatchSqliteWorkerJob(e,t,n){let r=[...e.actors].find(e=>e.id===t.request.actor),assertCurrentJob=()=>{if(!Ti(t.custody.descriptor))throw e.failed??new U(`SQLite worker job is no longer current`,`closed`)},assertDispatchable=()=>{t.custody.dispatched||t.signal?.throwIfAborted(),t.assertCurrent?.(),assertCurrentJob()};try{t.signal?.throwIfAborted(),assertCurrentJob();let n=prepareSqliteWorkerActorContext(r,t),i=r?.stateAccess,a=i?.canonicalPath,o;if(i&&t.request.type!==`close`){let prepareAccess=async()=>{t.signal?.throwIfAborted(),assertCurrentJob();let e=await i.prepareAccess({maintenanceScope:t.maintenanceScope,schemaLease:t.cleanupAccess});return t.signal?.throwIfAborted(),assertCurrentJob(),e(),e},isPending=e=>e instanceof Fi&&e.databasePath===a;try{o=await prepareAccess()}catch(e){if(!isPending(e))throw e;o=await acquireWithWait({acquire:prepareAccess,shouldRetry:isPending,deadlineMs:performance.now()+Wo,pollIntervalMs:10,sleep:e=>bs(e,t.signal)})}}if(t.createAdmission||a){let n=vs();t.settleNative=n.resolve;let i=t.createAdmission?t.createAdmission({settled:n.promise,nativeStopped:r?.nativeStopped??e.exit}):{admission:Hi(()=>{throw new U(`SQLite domain operation requires its own admission`,`closed`)}),nativeLocations:a?[a]:[]};try{if(i.admission.requestClass=t.observation.requestClass,i.databaseIdentity){let e=t.request.databaseIdentity;if(e&&(e.databasePath!==i.databaseIdentity.databasePath||e.key!==i.databaseIdentity.key||e.birthtime!==i.databaseIdentity.birthtime))throw new U(`SQLite request physical identities differ`,`closed`);t.request.databaseIdentity=i.databaseIdentity}if(ai(i.admission,e.databaseAdmissionCursor,()=>e.databaseAdmissionCursor=Qr()),a){let e=captureSqliteWorkerCreationPaths({...t.request.type===`open`&&!t.request.existingIdentity?{opening:[t.request.databasePath,a]}:{},...r?.stateContext?{companions:{primary:r.databasePath,paths:[...r.stateDatabasePath?[r.stateDatabasePath]:[],Bo(r.stateContext.environment)]}}:{}}),n,assertAccess=()=>{assertCurrentJob(),t.maintenanceScope?.assertAdmission();let e={maintenanceScope:t.maintenanceScope,schemaLease:n??t.cleanupAccess};o?o(e):r?.stateAccess.assertReadAllowed(e)},s=t.request.type===`open`&&!t.request.existingIdentity&&await Ms(t.request.databasePath)===await Ms(a)?a:void 0;assertDispatchable(),i.admission.bindDatabaseAuthority({databasePath:a,databaseIdentity:t.request.databaseIdentity,...s?{coldOpenPath:s}:{},assertRequest:assertDispatchable,assertAccess,...t.request.type===`close`?{}:e,acquireSchema(){assertAccess();let acquire=()=>dt(a),e=t.maintenanceScope?t.maintenanceScope.run(acquire):acquire();return n=e,t.maintenanceScope?.own(e,`shared-resources`,()=>e.release()),e}})}for(let e of/* @__PURE__ */ new Set([...i.nativeLocations,...a?[a]:[]])){let n=ua(e),r=t.request.databaseIdentity,i=Jr(n),a=r?.databasePath===n?r:i;a&&Wi(n,a)||(await fa({location:n,assertCurrent:assertDispatchable,...r?.databasePath===n?{expectedIdentity:r}:{}}),assertDispatchable())}}catch(e){throw await i.admission.finish(`not-entered`),e}t.operationAdmission={admission:i.admission,releaseService:jt([...i.nativeLocations,...a?[a]:[],...r?.pathReferences.keys()??[]],()=>i.admission.service())},t.request.executionAuthority=xi(i.admission),t.request.operationAttachment=i.admission.attachment,t.request.operationAdmission=i.admission.port}else t.request.operationAdmission=void 0;let s=bi(e.databaseAdmissionCursor);s.length>0&&(t.request.databaseAdmissions=s),t.request.timing=t.observation.timing,t.request.requestCustody=t.custody.descriptor;let c=prepareSqliteWorkerRequest(t);assertDispatchable();let l=c.stateContext?.databaseEngineSelection;!e.postgresPoolSent&&l&&(c.postgresPool=_r(l)),o?.(),t.custody.accept(),t.detach(),r&&c.type!==`close`&&(r.openDispatch.openRefused=!1),t.custody.post(),c.timing&&(c.timing.posted=performance.now()),e.worker.postMessage(c,[...Hr(c.postgresPool),...c.operationAdmission?[c.operationAdmission]:[],...`input`in c?[c.input.buffer]:[],...new Set(Object.values(c.transferredInput??{}).map(e=>e.buffer)),...c.type===`open`&&c.preparation?[c.preparation.buffer]:[]]),c.postgresPool&&(e.postgresPoolSent=!0),r&&n&&(r.deliveredStateContext=n),c.timing&&(c.timing.postFinished=performance.now())}catch(r){e.databaseAdmissionCursor=Qr(),n(r,t.custody.postAttempted)}}function decodeSqliteWorkerReplyError(e){if(e.name===`SqliteWorkerAdmissionTimeoutError`&&e.code===`admission-timeout`)return new Mr;if(e.name===`SqliteWorkerError`&&e.code===`outcome-unknown`)return new U(e.message,`outcome-unknown`);let t=Object.assign(Error(e.message),{name:e.name,...e.code===void 0?{}:{code:e.code}});return e.sharedState?(es(t,e.sharedState),Go(t,{includeOrdinary:!0})):t}function decodeSqliteWorkerCleanupError(e){let t=/* @__PURE__ */ Error(`SQLite worker native cleanup failed`);return es(t,e),Go(t,{includeOrdinary:!0})}function receiveSqliteWorkerReply(e,t,n){let r=e.current;if(!r||t.id!==r.request.id){n.fail(/* @__PURE__ */ Error(`SQLite worker returned an unexpected response`));return}let finishReply=(t,i,a,o)=>{let s=n.finish(r,t,i,a),release=()=>{e.current===r&&(e.current=void 0),o?.(),n.dispatch()};s?s.then(release,e=>n.fail(e)):release()};if(t.transactionCount!==void 0&&r.observation.recordTransactions?.(t.transactionCount),r.observation.timing&&t.timing&&Object.assign(r.observation.timing,t.timing,{replyReceived:performance.now()}),!t.ok){let i=r.operationAdmission?.admission;if(t.cleanupFailure&&r.custody.dispatched&&!t.retire){let e=(i?.failureSource===`domain`&&!t.admissionRefused?void 0:i?.failure)??decodeSqliteWorkerReplyError(t.error);n.fail(decodeSqliteWorkerCleanupError(t.cleanupFailure),void 0,void 0,{error:e});return}t.openNotEntered&&r.request.type===`open`&&r.dispatchState&&(r.dispatchState.openNotEntered=!0);let a=decodeSqliteWorkerReplyError(t.error),o=t.openOutcome===`refused-before-agent-open`;if(!t.retire&&(o||r.request.type===`open`&&t.openNotEntered)){let n=i?.failure??a;finishReply(n,void 0,t.openNotEntered?{kind:`not-entered`,error:n}:{kind:`completed`},()=>{if(o){let t=[...e.actors].find(e=>e.id===r.request.actor);t&&(t.openDispatch.openRefused=!i?.cleanupFailures.length)}});return}if(r.request.type!==`execute`||t.retire){let e=r.request.type===`open`&&o,s=e||t.admissionRefused?Tn(i?.failure??a,a.message):a;n.fail(s,r.request.type!==`execute`||t.admissionRefused?s:void 0,e?`refused-before-agent-open`:void 0);return}finishReply(i?.failure??a);return}let i;try{let n=An(`worker:sqlite`,()=>{if(t.input===`next`){let e=r.inputTransfer;if(!e||t.transfer)throw Error(`SQLite worker requested unexpected command input`);let n=e.producer.next(e.id),i=ownedWorkerBytes(gc(n));if(i.byteLength>33554432)throw Error(`SQLite worker input frame exceeds the transport byte limit`);return n.done&&(e.producer.end(e.id),r.inputTransfer=void 0),{type:`execute-frame`,id:r.request.id,actor:r.request.actor,input:i}}if(r.inputTransfer)throw Error(`SQLite worker completed before receiving its command input`);if(t.transfer===`start`){let e=pc(t.value);if(r.request.type!==`execute`||r.transfer||e.kinds.length!==1||e.kinds[0]!==`result`)throw Error(`SQLite worker returned an unexpected result transfer`);let n={id:e.id,value:void 0,receiver:Ia(e,e=>{n.value=e.value})};r.transfer=n}else if(t.transfer===`frame`){let e=r.transfer;if(!e)throw Error(`SQLite worker returned an unexpected result frame`);let n=pc(t.value),a=e.receiver.accept(n);if(a){if(a.length!==1||a[0]?.[1]!==1)throw Error(`SQLite worker returned an incomplete result transfer`);i=e.value,r.transfer=void 0}}else{if(r.transfer)throw Error(`SQLite worker ended its result transfer without completion`);i=pc(t.value)}if(r.transfer)return{type:`result-next`,id:r.request.id,actor:r.request.actor,transferId:r.transfer.id}},`reply-decode`);if(n){e.worker.postMessage(n,n.type===`execute-frame`?[n.input.buffer]:[]);return}}catch(e){n.fail(e);return}if(t.cleanupFailure){let e=r.operationAdmission?.admission,a=e?.failureSource===`domain`?void 0:e?.failure;n.fail(decodeSqliteWorkerCleanupError(t.cleanupFailure),void 0,void 0,a===void 0?{value:i}:{error:a})}else if(t.nativeRuntimeAdmission!==void 0&&Vr(t.nativeRuntimeAdmission),r.request.type===`close`){if(t.closeReceipt){let n=[...e.actors].find(e=>e.id===r.request.actor);n&&(n.closeReceipt=t.closeReceipt)}finishReply(void 0,i)}else{let e=r.operationAdmission?.admission;finishReply(e?.failureSource===`domain`?void 0:e?.failure,i)}}function withSqliteWorkerCleanupFailure(e,t){if(t===void 0)return e;let n=AggregateError([e,t],`SQLite worker failure and cleanup failed`,{cause:e});return ea(n,e)}function failSqliteWorkerSlot(e,t,n){if(e.failed)return;let r=Tn(t,`SQLite worker failed`);e.custody.retire(),e.failed=new U(r.message,`unavailable`),e.failed.cause=r;for(let t of e.actors)t.backendClosed||Ur(t.nativeLostObservers??[],e.failed);for(let t of n.waiters??[])t(e.failed);let i=e.current;i?.custody.retire(),e.current=void 0,i&&(i.inputTransfer?.producer.cancel(),i.inputTransfer=void 0,i.transfer=void 0);let{currentError:a,completed:o,openOutcome:s,retire:c,finish:l}=n,u=e.failed,d=e.queue.splice(0),f=c(),finishFailed=(e,t)=>{if(i&&o)process.emitWarning(Error(`SQLite worker operation completed before native cleanup failed`,{cause:withSqliteWorkerCleanupFailure(r,t)})),l(i,`error`in o?o.error:void 0,`value`in o?o.value:void 0,e?{kind:`completed`}:{kind:`unknown`,error:t??r});else if(i){let n=a??new U(`SQLite worker stopped before its result was received: ${r.message}`,i.request.type===`execute`&&i.custody.dispatched?`outcome-unknown`:`unavailable`);a||(n.cause=r),l(i,withSqliteWorkerCleanupFailure(n,t),void 0,i.custody.dispatched?e&&s===`refused-before-agent-open`?{kind:`completed`}:{kind:`unknown`,error:a??r,...e?{nativeStopped:!0}:{}}:{kind:`not-entered`,error:r})}for(let e of d)l(e,withSqliteWorkerCleanupFailure(u,t))};f.then(()=>finishFailed(!i?.operationAdmission?.admission.cleanupFailures.length),e=>finishFailed(!1,e))}function settleSqliteWorkerJob(e,t,n,r,i){e.custody.retire();let a=r??(e.custody.dispatched?{kind:`completed`}:{kind:`not-entered`,error:t}),o=e.operationAdmission?.admission.finish(a.kind===`not-entered`?`not-entered`:void 0),complete=(r=t)=>{e.settleNative?.(a),e.operationAdmission?.releaseService();let o=e.operationAdmission?.admission,s=r??(o?.failureSource===`domain`?void 0:o?.failure),c=e.operationAdmission?.admission.cleanupFailures??[];if(c.length>0){e.dispatchState&&(e.dispatchState.openRefused=!1);let t=AggregateError(c,`SQLite worker admission cleanup failed`);s===void 0&&e.request.type===`execute`?process.emitWarning(t):s=s===void 0?t:withSqliteWorkerCleanupFailure(Tn(s,`SQLite worker failed`),t)}e.inputTransfer?.producer.cancel(),e.inputTransfer=void 0,e.transfer=void 0,e.detach(),s===void 0?e.resolve(n):e.reject(s),i?.()};if(o)return o.then(complete,e=>complete(t===void 0?e:withSqliteWorkerCleanupFailure(Tn(t,`SQLite worker failed`),e)));complete()}function cleanupFailures(e){return e.flatMap(e=>e.status===`rejected`?[e.reason]:[])}function createSqliteWorkerLifecycle({explicitSqliteCloseReleasesNativeResources:e,actors:t,slots:n,stores:r,enqueueClose:i,fail:a}){function sealClients(e,t=!1){for(let t of e)for(let e of t)e(new U(`SQLite worker host is closing`,`overloaded`));for(let e of r.values())t&&e.actor.stateContext||(e.sealed=!0)}async function closeHost({inputAdmission:e,operations:i,waiters:a}){sealClients(a);let o=[];try{await e.joinOpens(),await Promise.allSettled(i);let n=await Promise.allSettled([...t.values()].map(e=>closeActor(e)));o.push(...cleanupFailures(n)),await e.joinPreparations()}catch(e){o.push(e)}if(o.push(...cleanupFailures(await Promise.allSettled([...n].map(retireEmpty)))),o.length)throw AggregateError(o,`SQLite worker host cleanup failed`);r.clear()}async function acquireSlot(t,r,i){t.signal?.throwIfAborted(),t.assertCurrent?.(),t.signal?.throwIfAborted();let a=e,o=[...n].filter(e=>e.carrierClass===t.carrierClass),s=t.carrierClass&&t.carrierClass!==`agent`?1:r.maxWorkers,c=o.filter(e=>!e.custody.retired&&e.runtimeGeneration===t.runtimeGeneration),l=a&&t.runtimeGeneration!==void 0&&c.length===0&&o.length>=s&&!o.some(e=>e.borrowedGenerationSlot);if(!l&&(a?o.length>=s:n.size>=r.maxStores)){if(!c.length||!a){let e=(a?o:[...n]).filter(e=>e.custody.retired);if(e.length>0)return await xs(Promise.race(e.map(({exit:e})=>e)),t.signal,e=>e.reason),acquireSlot(t,r,i);throw new U(`SQLite worker ${a?`runtime`:`store`} capacity reached`,`overloaded`)}let e=c.filter(e=>!e.current),s;if(e.length===0){if(s=await ys(Promise.race(c.map(e=>e.current.result.then(()=>e,()=>e))),ep,()=>{throw new U(`SQLite worker queue capacity reached`,`overloaded`)},{signal:t.signal,onAbort:e=>{throw e.reason}}),t.signal?.throwIfAborted(),t.assertCurrent?.(),t.signal?.throwIfAborted(),s.custody.retired)return acquireSlot(t,r,i)}else s=e.reduce((e,t)=>e.actors.size<=t.actors.size?e:t);return s.pendingOpens+=1,s}return createSlot(t,l,i)}function createSlot(e,t,r){e.signal?.throwIfAborted(),Fr(),e.assertCurrent?.(),e.signal?.throwIfAborted();let{carrierUrl:i}=e,o=Qr();bi(o);let s=_r(),{worker:c,exited:l}=gn(()=>({worker:Ki(i,{resourceLimits:{maxOldGenerationSizeMb:512,maxYoungGenerationSizeMb:16},env:Li(),execArgv:Os(i),workerData:{postgresPool:s},transferList:Hr(s)},()=>u.current?.observation.requestClass),exited:vs()}));c.stderr.prependListener(`data`,on),Ii(c);let u={carrierClass:e.carrierClass,postgresPoolSent:s!==void 0,custody:new va,databaseAdmissionCursor:o,runtimeGeneration:e.runtimeGeneration,...t?{borrowedGenerationSlot:!0}:{},worker:c,receiveReply:e=>receiveSqliteWorkerReply(u,e,d),actors:/* @__PURE__ */ new Set,queue:[],exit:l.promise,exited:!1,pendingOpens:1},d=r(u);return n.add(u),c.on(`message`,e=>{Gr(c,e)||u.receiveReply(e)}),c.on(`error`,e=>a(u,e)),c.on(`messageerror`,e=>a(u,e)),c.once(`exit`,e=>{u.exited=!0,a(u,/* @__PURE__ */ Error(`SQLite worker exited with code ${e}`));for(let e of u.actors)e.backendClosed=!0,e.markNativeStopped(),e.cleanupState===`pending`&&!e.closing&&forget(e);n.delete(u),l.resolve()}),c.unref(),u}async function settleGeneration(e){let r=[...t.values()].filter(t=>t.runtimeGeneration===e),i=Promise.allSettled(r.map(e=>retireActor(e)));return await Promise.all(r.map(async e=>await e.settlement)),async()=>{let t=cleanupFailures(await i);G(t,`Retained SQLite worker cleanup failed`),await Promise.all([...n].filter(t=>t.runtimeGeneration===e).map(e=>retireEmpty(e)))}}function releaseActorReference(e){--e.references,e.references||e.onReferencesDrained?.()}function bindClientRelease({actor:e,client:t,clientReservations:n,releasePaths:i,maintenanceScope:a,resumeScheduledMaintenance:o,readDraining:s}){let c=!1;return async(l,u)=>{c||(c=!0,o?.(),releaseActorReference(e),r.delete(l),n.delete(t),i());let d=s();d&&!u&&!e.stateContext?await d:e.slot.failed&&await e.slot.exit,e.references||await closeActor(e,a)}}async function rejectSlotAdmission(e,t){--e.pendingOpens;try{await retireEmpty(e)}catch(e){throw Zr([t,e],`SQLite slot admission and cleanup failed`,t)}throw t}async function rejectActorAdmission(e,t,n){if(releaseActorReference(e),!e.references){let r=[t];try{if(e.initialized)await closeActor(e,n);else{let n=e.openDispatch.custody.postAttempted&&!e.openDispatch.openNotEntered&&!e.openDispatch.openRefused;!n&&!e.slot.failed&&(e.backendClosed=!0,e.markNativeStopped(),e.cleanupState=`pending`),n&&(a(e.slot,t),await e.slot.exit),forget(e),await retireEmpty(e.slot)}}catch(e){r.push(e)}if(r.length>1)throw AggregateError(r,`SQLite worker admission and cleanup failed`,{cause:t})}throw t}function retireActor(e){let n=[...t.values()].find(t=>t===e);if(!n)return Promise.resolve();if(n.retirement)return n.retirement;n.retirementRequested=!0;let i=vs();n.onReferencesDrained=i.resolve,n.references||i.resolve(),n.settlement=i.promise;let a=[...r.values()].filter(e=>e.actor===n);return n.retirement=(async()=>{let e=await Promise.allSettled(a.map(e=>e.close()));await n.settlement;let t=cleanupFailures(e);if(!t.length)try{await closeActor(n)}catch(e){t.push(e)}if(t.length)throw AggregateError(t,`SQLite actor retirement failed`,{cause:t[0]})})().finally(()=>{n.retirement=void 0,n.onReferencesDrained=void 0}),n.retirement}function closeActor(t,n){return t.cleanupState===`complete`?Promise.resolve():(t.closing||=(t.cleanupState=`pending`,(async()=>{let r=[];if(!t.backendClosed)try{await i(t,n),t.backendClosed=!0,e&&t.markNativeStopped()}catch(e){e!==t.slot.failed&&r.push(e),a(t.slot,e instanceof Error?e:Error(String(e))),await t.slot.exit}try{(!e||t.slot.failed||!t.slot.pendingOpens&&[...t.slot.actors].every(e=>e.backendClosed))&&await retire(t.slot)}catch(e){r.push(e)}G(r,`SQLite worker actor cleanup failed`)})().finally(()=>{t.closing=void 0,(!t.slot.custody.retired||t.slot.exited)&&forget(t)})),t.closing)}function forget(e){t.get(e.key)===e&&t.delete(e.key),e.slot.actors.delete(e),e.cleanupState=`complete`}async function retireEmpty(e){!e.actors.size&&!e.pendingOpens&&await retire(e)}function retire(e){return e.custody.retire(),e.retiring??=(async()=>{e.exited||await e.worker.terminate(),await e.exit})().finally(()=>{e.retiring=void 0}),e.retiring}return{sealClients,closeHost,acquireSlot,createSlot,settleGeneration,releaseActorReference,bindClientRelease,rejectSlotAdmission,rejectActorAdmission,retireActor,closeActor,async retireFailedSlot(e){try{await retire(e)}finally{await e.exit}}}}function runSqliteWorkerClientOperation(e,t,n,r,i,a){if(!e||e.sealed)return Promise.reject(new U(`SQLite worker store is closed`,`closed`));let o={maintenanceScope:So(),createAdmission:a,assertCurrent:i,active:!0,pending:/* @__PURE__ */ new Set,...n?{stateContext:vt(n)}:{}},s=vs();e.scopes.add(s.promise);let c=r(s.promise);return(async()=>{try{let n=t({execute:(t,n={})=>e.execute(t,n,o)});return cc(n)?await n:n}finally{o.active=!1,await Promise.allSettled(o.pending),e.scopes.delete(s.promise),c(),s.resolve()}})()}function createSqliteWorkerClient(e){let t,n=!1,r=/* @__PURE__ */ new Set,i={actor:e.actor,close:()=>a.close(),retireIdle:e.retireIdle?()=>{if(!(i.sealed||i.scopes.size||r.size)){n=!0;try{return e.retireIdle?.()}finally{n=!1}}}:void 0,sealed:e.isDraining(),isAvailable:e.isAvailable,scopes:/* @__PURE__ */ new Set,execute:(t,n,a)=>{if(a?!a.active:i.sealed||e.isDraining())return Promise.reject(new U(`SQLite worker store is closed`,`closed`));if(n.signal?.aborted)return Promise.reject(Tn(n.signal.reason,`SQLite worker operation canceled`));let o,s,c=0,l,u,d=a?.assertCurrent,f=a?.createAdmission,p=d||f?ec.snapshot():void 0;try{let e=t.type;if(l=li(e,t.input),u=d&&p?()=>p(d,e):void 0,u?.(),o=fc.serialize({type:e,input:t.input}),n.transferredInput){let e=[...new Set(Object.values(n.transferredInput).map(e=>e.buffer))];c=e.reduce((e,t)=>e+t.byteLength,0),s=structuredClone(n.transferredInput,{transfer:e})}}catch(e){return Promise.reject(Tn(e,`SQLite worker command could not be serialized`))}let m=e.dispatch({type:`execute`,actor:e.actor.id,databaseIdentity:e.databaseIdentity,input:o,transferredInput:s,...a?.stateContext?{stateContext:a.stateContext}:{}},_(o,a?.stateContext)+c,{signal:n.signal,requestClass:l,scope:a,assertCurrent:u,createAdmission:f&&p?e=>p(f,e):void 0,cleanupAccess:e.cleanupAccess,maintenanceScope:e.cleanupAccess?void 0:a?a.maintenanceScope:So()});r.add(m),a?.pending.add(m);let settled=()=>{r.delete(m),a?.pending.delete(m)};return m.then(settled,settled),m}},a={execute:(e,t={})=>i.execute(e,t),close:()=>{if(!t){i.sealed=!0;let a=n;t=(async()=>{await Promise.allSettled(i.scopes),await Promise.allSettled(r),await e.release(a)})().catch(e=>{throw t=void 0,e})}return t}};return{store:a,client:i}}const tp=67108864,np=268435456;function captureSqliteWorkerRetirementReaders(e){return[()=>e.closeReceipt,()=>e.openDispatch.openRefused===!0]}var SqliteWorkerBroker=class{constructor(){this.explicitSqliteCloseReleasesNativeResources=Or(),this.maxWorkers=Qi(),this.waiters=/* @__PURE__ */ new Map,this.resuming=/* @__PURE__ */ new Set,this.warnAdmission=createSqliteWorkerAdmissionWarning(),this.actors=/* @__PURE__ */ new Map,this.slots=/* @__PURE__ */ new Set,this.clients=/* @__PURE__ */ new Set,this.stores=/* @__PURE__ */ new Map,this.operations=/* @__PURE__ */ new Set,this.lifecycle=createSqliteWorkerLifecycle({explicitSqliteCloseReleasesNativeResources:this.explicitSqliteCloseReleasesNativeResources,actors:this.actors,slots:this.slots,stores:this.stores,enqueueClose:(e,t)=>this.enqueue(e.slot,{type:`close`,actor:e.id},0,{maintenanceScope:t}),fail:(e,t)=>this.fail(e,t)}),this.nextActor=0,this.nextRequest=0,this.requests=/* @__PURE__ */ new WeakMap,this.bytes=0,this.inputAdmission=new SqliteWorkerInputAdmission({queuedBytes:()=>this.bytes,isClosing:()=>this.draining!==void 0,maxQueuedBytes:np,maxQueuedInputBytes:tp,maxMessageBytes:Sr,maxPendingOpens:64})}reserveInputPreparation(e,t=`stream`){return this.inputAdmission.reserveInputPreparation(e,t)}open(e,t,n,r={}){try{validateSqliteWorkerDatabaseLocator(e.databasePath)}catch(e){return Promise.reject(Tn(e,`SQLite worker database locator is invalid`))}if(this.draining)return Promise.reject(new U(`SQLite worker host is closing`,`closed`));let i={},a,o;try{a=reserveSqliteWorkerClient(this.clients,this.stores.values(),64,i),o=captureSqliteWorkerOpen(e,t,n,r);let s=e.runtimeGeneration;s?.retain(this,async()=>(await this.inputAdmission.joinOpens(),await this.lifecycle.settleGeneration(s)))}catch(e){return this.clients.delete(i),Promise.reject(Tn(e,`SQLite worker input could not be serialized`))}let s=a?findReusableSqliteWorkerClient(this.stores.values(),o.databasePath):void 0,c;return this.inputAdmission.open(_(o.input,o.stateContext,o.preparation),o.databasePath,async()=>(a||await reclaimSqliteWorkerClient(o,this.stores.values(),()=>reserveSqliteWorkerClient(this.clients,this.stores.values(),64,i),()=>this.draining!==void 0),this.openAdmitted(o,i,void 0,c)),o.signal,s?()=>this.openAdmitted(o,i,s):void 0,o.carrierClass,async()=>(c=await prepareSqliteWorkerDatabaseAdmission(o),{readIdentities:/* @__PURE__ */ new Map([[o.databasePath,c.identity]])})).catch(e=>{throw this.clients.delete(i),e})}async openAdmitted(e,t,n,r){let{maintenanceScope:i,cleanupAccess:a}=e,o=e.expectedIdentity?{databasePath:e.databasePath,key:e.expectedIdentity,birthtime:e.expectedBirthtime}:void 0;e.signal?.throwIfAborted(),e.assertCurrent?.();let{databasePath:s,inputHash:c,identity:l,key:u}=r?.identity.key.startsWith(`file:`)?r:await prepareSqliteWorkerDatabaseAdmission(e);if(e.assertCurrent?.(),n&&this.actors.get(u)!==n.actor)return;let d=await Yt(e.stateDatabasePath??l.canonicalPath),f=await d.prepareAccess({maintenanceScope:e.maintenanceScope,schemaLease:e.cleanupAccess});e.signal?.throwIfAborted(),e.assertCurrent?.(),f();let p=e.input,m=captureSqliteWorkerAdmissionPaths(s,l,this.actors.values());if(e.existingOnly&&!u.startsWith(`file:`)){this.clients.delete(t);return}let{modulePath:h,moduleUrl:g}=await resolveSqliteWorkerModuleUrl(e.moduleUrl);e.signal?.throwIfAborted(),e.assertCurrent?.();let v=this.actors.get(u);if(n&&(v!==n.actor||n.sealed||!n.isAvailable()))return;if(v?.slot.failed)return await waitForSqliteOpen(this.lifecycle.retireActor(v),e.signal),this.openAdmitted(e,t);let y;if(v?.retirementRequested||v?.cleanupState===`pending`){let n=v.retirementRequested?v.retirement:v.closing;if(n)return await waitForSqliteOpen(n,e.signal),this.openAdmitted(e,t);throw new U(v.retirementRequested?`SQLite actor retirement must finish before reopening`:`SQLite worker cleanup is pending; retry close before reopening`,`closed`)}if(v)assertSqliteWorkerActorReusable(v,g,c,e.stateContext),e.onNativeLost&&(v.nativeLostObservers??=/* @__PURE__ */ new Set).add(e.onNativeLost),v.references+=1,y=suspendSqliteWorkerScheduledMaintenance(v,i);else{let t=await this.lifecycle.acquireSlot(e,{maxWorkers:this.maxWorkers,maxStores:64},e=>this.createReplyOwner(e));try{if(e.assertCurrent?.(),e.signal?.throwIfAborted(),this.actors.has(u))throw new U(`SQLite database owner was admitted while acquiring a worker; retry open`,`overloaded`)}catch(e){return this.lifecycle.rejectSlotAdmission(t,e)}let n=vs();v={...e.onNativeLost?{nativeLostObservers:/* @__PURE__ */ new Set([e.onNativeLost])}:{},runtimeGeneration:e.runtimeGeneration,nativeStopped:n.promise,markNativeStopped:n.resolve,id:++this.nextActor,key:u,identity:l,pathReferences:new Map([...m].map(e=>[e,1])),moduleUrl:g,inputHash:c,slot:t,references:1,opened:Promise.resolve(),openDispatch:{custody:t.custody.createRequest()},initialized:!1,backendClosed:!1,databasePath:s,stateAccess:d,stateContext:e.stateContext,stateDatabasePath:e.stateDatabasePath},this.actors.set(u,v),y=suspendSqliteWorkerScheduledMaintenance(v,i),t.actors.add(v),--t.pendingOpens;let r=v;r.opened=this.enqueue(t,{type:`open`,actor:v.id,databaseIdentity:o,moduleUrl:g,databasePath:s,...e.createAdmission?{openAdmission:`input`}:e.createOpenAdmission?{openAdmission:`identity`}:{},...e.existingOnly?{existingIdentity:u}:{},input:p,...e.preparation?{preparation:e.preparation}:{},...Ds(h)?{sourceLoaderUrl:import.meta.resolve(`tsx/esm/api`)}:{}},_(p,e.stateContext,e.preparation),{dispatchState:r.openDispatch,signal:e.signal,assertCurrent:e.assertCurrent,maintenanceScope:e.maintenanceScope,cleanupAccess:e.cleanupAccess,createAdmission:e.createAdmission??e.createOpenAdmission}).then(async()=>{r.initialized=!0;let e=await resolveOpenedSqliteWorkerIdentity(s,l,e=>{let t=this.actors.get(e);return t!==void 0&&t!==r});r.identity=e,e.key!==u&&(this.actors.delete(u),r.key=e.key,this.actors.set(e.key,r))})}let b=v;try{if(retainSqliteWorkerAdmissionCleanup(b,e.retainCleanup,this.lifecycle.closeActor.bind(this.lifecycle,b,i)),e.onNativeStopped){let[t,n]=captureSqliteWorkerRetirementReaders(b);e.onNativeStopped(b.nativeStopped,t,n)}if(await v.opened,e.assertCurrent?.(),v.retirementRequested)throw new U(`SQLite actor retired during client admission`,`closed`);if(v.slot.failed)throw v.slot.failed}catch(t){return y?.(),this.lifecycle.rejectActorAdmission(v,t,e.maintenanceScope)}return this.bindClient(b,t,{releasePaths:retainSqliteWorkerAdmissionPathReferences(b,m),databaseIdentity:o,maintenanceScope:i,cleanupAccess:a,resumeScheduledMaintenance:y,retireIdle:e.retireIdle})}bindClient(e,t,n){let r=this.lifecycle.bindClientRelease({actor:e,client:t,clientReservations:this.clients,releasePaths:n.releasePaths,maintenanceScope:n.maintenanceScope,resumeScheduledMaintenance:n.resumeScheduledMaintenance,readDraining:()=>this.draining}),{store:i,client:a}=createSqliteWorkerClient({actor:e,isDraining:()=>this.draining!==void 0,isAvailable:()=>!e.slot.failed&&!e.cleanupState&&!e.retirementRequested,retireIdle:n.retireIdle,databaseIdentity:n.databaseIdentity,cleanupAccess:n.cleanupAccess,dispatch:(t,n,r)=>this.enqueue(e.slot,t,n,r),release:e=>r(i,e)});return this.stores.set(i,a),i}runOperation(e,t,n,r,i){return runSqliteWorkerClientOperation(this.draining?void 0:this.stores.get(e),t,n,e=>(this.operations.add(e),()=>this.operations.delete(e)),r,i)}isAvailable(e){return this.stores.get(e)?.isAvailable()??!1}retireActor(e){return this.lifecycle.retireActor(e)}getActorIdentity(e){let t=this.stores.get(e);if(!t||t.sealed||!t.actor.stateContext)throw new U(`SQLite shared actor binding is unavailable`,`closed`);return t.actor}hasUnclaimedSharedStateCleanup(e){return findUnclaimedSharedStateActors(this.actors.values(),e).length>0}async closeUnclaimedSharedState(e){await this.inputAdmission.joinOpens(),await closeUnclaimedSharedStateActors(this.actors.values(),e,e=>this.lifecycle.closeActor(e))}createReplyOwner(e){return{fail:(t,n,r,i)=>this.fail(e,t,n,r,i),finish:(t,n,r,i)=>this.finish(e,t,n,r,i),dispatch:()=>this.dispatch(e)}}enqueue(e,t,n,r,i=!1,a=Ni(`sqlite_writer`,r.requestClass??t.type)){let{signal:o,dispatchState:s,scope:c,assertCurrent:l,createAdmission:u,maintenanceScope:d,cleanupAccess:f}=r,reject=e=>(a.completed(),Promise.reject(e));if(this.draining&&t.type!==`close`&&!c?.active)return reject(new U(`SQLite worker host is closing`,`closed`));if(e.failed)return reject(e.failed);let p=t.type===`execute`&&n>tp,m=p?Sr:n;if(t.type!==`close`&&(t.type!==`execute`&&n>33554432||p&&(e.current||e.queue.length>0||e.pendingOpens>0)||this.bytes+this.inputAdmission.retainedBytes+m>np))return reject(new U(`SQLite worker queue capacity reached`,`overloaded`));if(t.type!==`close`&&((this.requests.get(e)??0)>=128||!i&&this.waiters.has(e)))return p||this.draining?reject(new U(`SQLite worker queue capacity reached`,`overloaded`)):this.waitForCapacity(e,t,n,r,a);let h=vs(),g={custody:s?.custody??e.custody.createRequest(),observation:a,signal:o,maintenanceScope:d,cleanupAccess:f,createAdmission:u,assertCurrent:l,dispatchState:s,request:{...t,id:++this.nextRequest,databaseAdmissionDeadlineAtMs:_a()},bytes:m,result:h.promise,resolve:h.resolve,reject:h.reject,detach:()=>o?.removeEventListener(`abort`,abort)},abort=()=>{g.custody.cancel();let t=e.queue.indexOf(g);t>=0&&(e.queue.splice(t,1),this.finish(e,g,o?.reason??/* @__PURE__ */ Error(`SQLite worker operation canceled`)))};return this.requests.set(e,(this.requests.get(e)??0)+1),this.bytes+=m,p?(o?.addEventListener(`abort`,abort,{once:!0}),o?.aborted?this.finish(e,g,o.reason??/* @__PURE__ */ Error(`SQLite worker operation canceled`)):this.dispatchJob(e,g),h.promise):(e.queue.push(g),o?.addEventListener(`abort`,abort,{once:!0}),o?.aborted&&abort(),this.dispatch(e),h.promise)}waitForCapacity(e,t,n,r,i){return new Promise((a,o)=>{let s=Date.now(),c=r.signal,l=this.waiters.get(e)??/* @__PURE__ */ new Set,resume=f=>{if(!l.delete(resume))return;l.size||this.waiters.delete(e),clearTimeout(u),c?.removeEventListener(`abort`,abort),d();let p=f;p===void 0&&Date.now()-s>=1e4&&(this.warnAdmission(this.waiters.get(e)?.size??0,Date.now()-s),p=new U(`SQLite worker queue capacity reached`,`overloaded`)),p===void 0?a(this.enqueue(e,t,n,r,!0,i)):(i.completed(),o(Tn(p,`SQLite worker admission failed`)))},abort=()=>resume(c?.reason??/* @__PURE__ */ Error(`SQLite worker operation canceled`)),u=setTimeout(()=>{this.warnAdmission(this.waiters.get(e)?.size??0,Date.now()-s),resume(new U(`SQLite worker queue capacity reached`,`overloaded`))},ep),d=this.inputAdmission.retain(n);l.add(resume),this.waiters.set(e,l),c?.addEventListener(`abort`,abort,{once:!0}),c?.aborted?abort():l.size>=128&&this.warnAdmission(l.size,0)})}dispatch(e){if(e.current||e.failed)return;let t=e.queue.shift();t?this.dispatchJob(e,t):e.worker.unref()}dispatchJob(e,t){t.custody.activate(),e.current=t,e.worker.ref(),t.observation.started(e.worker.threadId,e.worker.performance),dispatchSqliteWorkerJob(e,t,(n,r)=>{if(e.current===t){if(r)this.fail(e,n,Tn(n,`SQLite worker transfer failed`));else{let r=this.finish(e,t,n),release=()=>{e.current===t&&(e.current=void 0),this.dispatch(e)};r?r.then(release,t=>this.fail(e,t)):release()}}})}finish(e,t,n,r,i){if(t.finishing){let settled=()=>{};return t.result.then(settled,settled)}return t.finishing=!0,settleSqliteWorkerJob(t,n,r,i,()=>{if(t.observation.completed(),this.requests.set(e,(this.requests.get(e)??0)-1),this.bytes-=t.bytes,!this.resuming.has(e)){for(this.resuming.add(e);(this.requests.get(e)??0)<128;){let t=this.waiters.get(e)?.values().next().value;if(!t)break;t()}this.resuming.delete(e)}})}fail(e,t,n,r,i){failSqliteWorkerSlot(e,t,{currentError:n,openOutcome:r,completed:i,waiters:this.waiters.get(e),retire:()=>this.lifecycle.retireFailedSlot(e),finish:(t,n,r,i)=>this.finish(e,t,n,r,i)})}close(e){return e?(this.lifecycle.sealClients(this.waiters.values(),!0),e().then(()=>this.close())):(this.draining??=this.lifecycle.closeHost({inputAdmission:this.inputAdmission,operations:this.operations,waiters:this.waiters.values()}).then(()=>this.clients.clear()).finally(()=>{this.draining=void 0}),this.draining)}};function withCallerErrors(e){return e.catch(e=>{throw e instanceof Error?Go(e):e})}function bindCallerExecute(e){return{execute:(t,n)=>{let r=withCallerErrors(e.execute(t,n));return r.catch(()=>void 0),r}}}function runSqliteWorkerStoreOperation(e,t,n,r,i){return withCallerErrors(resolveSqliteWorkerBroker().runOperation(e,e=>t(bindCallerExecute(e)),n,r,i))}const rp=Zn(()=>import(`./session-transcript-reconcile.worker-openclaw-state-db-cache-BwXc4xzw.mjs`).then(e=>e.c));function resolveSqliteWorkerBroker(){return R(Symbol.for(`openclaw.sqliteWorkerBroker`),()=>new SqliteWorkerBroker,e=>withCallerErrors(e.close(async()=>{let{closeOpenClawStateDatabaseAsync:e}=await rp();await e()})),`shared-state`)}function isSqliteWorkerStoreAvailable(e){return resolveSqliteWorkerBroker().isAvailable(e)}function getSqliteWorkerActorIdentity(e){return resolveSqliteWorkerBroker().getActorIdentity(e)}function retireSqliteWorkerActor(e){return withCallerErrors(resolveSqliteWorkerBroker().retireActor(e))}function hasUnclaimedSharedStateSqliteCleanup(e){return resolveSqliteWorkerBroker().hasUnclaimedSharedStateCleanup(e)}function closeUnclaimedSharedStateSqliteWorkers(e){return withCallerErrors(resolveSqliteWorkerBroker().closeUnclaimedSharedState(e))}function openSharedStateSqliteWorkerStore(e,t,n,r){return Vs?withCallerErrors(resolveSqliteWorkerBroker().open({...e,input:void 0},t,n,{...r,carrierClass:`shared-state`})).then(e=>{if(e){let t=e.execute.bind(e),n=e.close.bind(e);e.execute=bindCallerExecute({execute:t}).execute,e.close=()=>withCallerErrors(n())}return e}):Promise.reject(new U(`Shared-state admission requires the host broker`,`unavailable`))}var AgentDatabaseDeletionRefusedError=class extends Error{};function assertAgentDeletionIdentityClaimAllowed(e,t){if(t&&q(e)===q(t))throw new AgentDatabaseDeletionRefusedError(`OpenClaw agent database is unavailable while agent ${q(t)} is deleted.`)}function readAgentDeletionPathFenceRows(e,t=`runtime`,n){t===`maintenance`&&assertAgentDeletionJournalAvailable(e);try{let r=w(e),i=!0,a=r.selectFrom(`agent_deletion_journal`).selectAll();n!==void 0&&(a=a.where(`agent_id`,`=`,q(n)));let o=A(e,a).rows.map(e=>{let n=[],r=[];try{n=parseAgentDeletionDatabasePaths(e.database_paths_json),r=parseCleanupPaths(e.cleanup_paths_json)}catch(e){if(t===`maintenance`)throw e;i=!1}return Object.assign(e,{databasePaths:n,cleanupPaths:r})});return{known:i,rows:o}}catch(e){if(t===`maintenance`||wi(e))throw e;return{known:!1,rows:[]}}}function prepareAgentDeletionPathFence(e,t={},n=e.fenceAgentId?`maintenance`:`runtime`){let r=t.env??process.env;return{env:r,purpose:n,claimAgentId:q(e.agentId),claimPath:X.resolve(e.path),...e.fenceAgentId?{fenceAgentId:q(e.fenceAgentId)}:{},targetPaths:ve(e.path).map(e=>normalizeAgentDirRegistryPath(e,r))}}function assertAgentDeletionPathFence(e,t){let n=e.db,{rows:r,known:i}=readAgentDeletionPathFenceRows(n,t.purpose);if(!i&&r.length===0)return;let a=t.fenceAgentId?void 0:os({agentId:t.claimAgentId,path:t.claimPath,statePath:e.path});a?.assertCurrent();let o=a?.assertJournal(e.path,r.map(e=>({agentId:e.agent_id,operationId:e.operation_id,cleanupCompleted:e.cleanup_completed===1}))),s=t.fenceAgentId?void 0:Ko(t.claimAgentId,e.path);for(let e of r){if(t.fenceAgentId&&t.fenceAgentId!==e.agent_id||e.agent_id===o||e.cleanup_completed===1&&e.agent_id===s||e.phase===`draining`&&e.cleanup_completed!==1&&e.agent_id===t.claimAgentId&&!t.fenceAgentId||(assertAgentDeletionIdentityClaimAllowed(t.claimAgentId,e.agent_id),e.cleanup_completed===1))continue;let n=[...[e.agent_dir,e.workspace_dir,e.sessions_dir,...e.databasePaths].map(e=>({path:e,canonicalPath:normalizeAgentDirRegistryPath(e,t.env)})),...e.cleanupPaths.map(e=>({path:e.path,canonicalPath:normalizeAgentDirRegistryPath(e.canonicalPath,t.env)}))];for(let r of n){let n=t.targetPaths.find(e=>e===r.canonicalPath||hn(r.canonicalPath,e));if(n)throw new AgentDatabaseDeletionRefusedError(`OpenClaw agent database ${n} is unavailable while agent ${e.agent_id} deletion owns ${r.path}.`)}}}function parseCleanupPaths(e){let t=JSON.parse(e);if(!Array.isArray(t)||!t.every(e=>I(e)&&typeof e.path==`string`&&typeof e.canonicalPath==`string`&&typeof e.parentPath==`string`&&(e.kind===`target`||e.kind===`symlink`)&&(e.dev===null||typeof e.dev==`number`&&Number.isInteger(e.dev)||typeof e.dev==`string`&&/^(0|-?[1-9][0-9]*)$/u.test(e.dev))&&(e.ino===null||typeof e.ino==`number`&&Number.isInteger(e.ino)||typeof e.ino==`string`&&/^(0|-?[1-9][0-9]*)$/u.test(e.ino))&&typeof e.coversDescendants==`boolean`&&typeof e.done==`boolean`&&(e.note===void 0||typeof e.note==`string`)&&Bn(e.sourcePaths)))throw Error(`Invalid agent deletion cleanup path journal.`);return t}function assertExistingOpenClawStateSchemaMetadata(e,t,n){let r=assertOpenClawStateDatabaseOwner(e,{pathname:t});if(n>=1&&r?.schema_version===n)return n;if(n>=1&&Ve(e,r))return 40;throw Error(`Existing-state schema metadata is inconsistent.`)}function assertExistingOpenClawStateSchema(e,t,n,r,i=`full`){let a=assertExistingOpenClawStateSchemaMetadata(e,t,assertSupportedStateSchemaVersion(e,t));return i===`quick`?Qe(e,t,{check:`quick`,tables:n===void 0?void 0:getCanonicalSqliteTableNames(n)}):Ke(e,t),n!==void 0&&assertSqliteSchemaContains(e,t,n,r),a}function runExistingOpenClawStateWriteTransaction(e,t,n){let r=prepareExistingOpenClawStateWriter(t,n),write=()=>{let i=createExistingOpenClawStateWriter(r,n);try{return i.run(e,t)}finally{i.close()}};return n.recoverTaskDeliveryOrphans?withStateDatabaseSchemaMaintenance({databasePath:r.pathname},write):write()}function prepareExistingOpenClawStateWriter(e,t){if(e.database||e.readOnly)throw Error(`Existing-state writes require their own tracked writable connection.`);let n=e.env??process.env,r=wo({path:e.path,env:n});T(r),t.recoverTaskDeliveryOrphans&&ie(r);let i=Y.lstatSync(r);if(!i.isFile())throw Error(`Existing-state write requires a regular database file.`);return{env:n,pathname:r,original:i}}function createExistingOpenClawStateWriter({env:e,pathname:t,original:n},r){let assertSameFile=()=>{let e=Y.lstatSync(t);if(!e.isFile()||e.dev!==n.dev||e.ino!==n.ino)throw Error(`Existing-state database generation changed.`)};if(assertSameFile(),j.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(t,e),isStatePostgres())return createExistingPostgresStateWriter(t,r,assertSameFile);let i=Xt(t,{existingOnly:!0,...r.recoverTaskDeliveryOrphans?{enableForeignKeyConstraints:!1}:{}}),a=Ge(`state.subset:${nc(`sha256`).update(JSON.stringify([r.schemaSql,r.schemaCompatibility,r.integrityCheck])).digest(`hex`)}`,e=>typeof e==`number`?e:void 0,r.integrityCheck===void 0?`process`:void 0),o=r.initializeAdditiveSchema?createSqliteSchemaEnsurer(()=>r.schemaSql,{tables:getCanonicalSqliteTableNames(r.schemaSql),indexes:getCanonicalSqliteNamedIndexNames(r.schemaSql)}):void 0,s=!1,close=()=>{s=!0,La(i),c(i)};return{run(e,n){if(s||!i.isOpen)throw Error(`Existing-state writer is closed.`);if(n.database||n.readOnly)throw Error(`Existing-state writes require their own tracked writable connection.`);let c=n.env??process.env;if(wo({path:n.path,env:c})!==t)throw Error(`Existing-state writer cannot change its database path.`);assertSameFile();let l=T(t),u=n.busyTimeoutMs??r.busyTimeoutMs??5e3;oo(i,u),admitStateSchemaFacts(i,t),!r.recoverTaskDeliveryOrphans&&r.integrityCheck===void 0&&Ke(i,t);let write=()=>runManagedStateTransaction(i,()=>{assertSameFile(),assertOpenClawStateWriteAllowed({database:i,databasePath:t,env:c});let n=a.get(i),s=n===void 0;l&&assertExistingOpenClawStateRuntimeSchema(i,t);let validate=()=>assertExistingOpenClawStateSchema(i,t,s&&r.initializeAdditiveSchema?void 0:r.schemaSql,r.schemaCompatibility,r.integrityCheck),u,d=[];if(r.recoverTaskDeliveryOrphans){try{validate()}catch(e){if(!(e instanceof tn))throw e}d=recoverOrphanTaskDeliveryRows(i,t),u=validate()}else u=n??validate();s&&r.initializeAdditiveSchema&&(assertSqliteSchemaContains(i,t,r.schemaSql,{...r.schemaCompatibility,allowedMissingTables:getCanonicalSqliteTableNames(r.schemaSql)}),fs(i),o?.(i),assertSqliteSchemaContains(i,t,r.schemaSql,r.schemaCompatibility)),s&&(fs(i),a.publish(i,u));let f=e({db:i,path:t,recoveryChanges:d});return assertSameFile(),r.recoverTaskDeliveryOrphans&&Qe(i,t),f},{beginLockFailureReporting:r.beginLockFailureReporting,busyTimeoutMs:u,databaseLabel:t,operationLabel:r.operationLabel});return r.attributeUpdateWrite?runUpdateSqliteMigration(i,t,write,{close}):write()},assertSettled(){if(assertSameFile(),Xe(i),i.isOpen&&i.isTransaction)throw Error(`Existing-state writer retained an unsettled transaction`);i.isOpen&&pa(i,`Existing-state writer`)},close}}function createExistingPostgresStateWriter(e,t,n){let r=Ne(()=>openExistingStatePostgresConnection(e));if(!r)throw Error(`Existing PostgreSQL state writer requires its selected engine`);let{db:i}=r.database,a=getCanonicalSqliteTableNames(t.schemaSql);return{run(r,o){if(!i.isOpen)throw Error(`Existing-state writer is closed.`);if(o.database||o.readOnly)throw Error(`Existing-state writes require their own tracked writable connection.`);let s=o.env??process.env;if(wo({path:o.path,env:s})!==e)throw Error(`Existing-state writer cannot change its database path.`);let c=!1;return Ne(()=>withPostgresSchemaAdmissionRetry(i,()=>runManagedStateTransaction(i,()=>{n(),assertOpenClawStateWriteAllowed({database:i,databasePath:e,env:s});let o=requireStatePostgresPhysicalFacts(i).catalog;for(let e of a)if(t.initializeAdditiveSchema)ensureStatePostgresFragment(i,e);else if(!o.some(t=>t.kind===`table`&&t.table===e))throw Error(`Existing PostgreSQL state schema is missing ${e}`);c=!0;let l=r({db:i,path:e,recoveryChanges:[]});return n(),l},{databaseLabel:e,operationLabel:t.operationLabel,beginLockFailureReporting:t.beginLockFailureReporting}),()=>!c))},assertSettled(){if(n(),Xe(i),!i.isOpen)throw Error(`Existing-state writer retained a closed PostgreSQL connection`);if(i.isTransaction)throw Error(`Existing-state writer retained an unsettled transaction`)},close(){r.close()}}}const ip=[`schema_meta`,`state_leases`,`agent_database_leases`].map(e=>B(H,e,{endMarker:`) STRICT;`,errorMessage:`Existing agent lease schema is unavailable.`})).join(`
`);function withExistingAgentLeaseWrite(e,t,n){return runExistingOpenClawStateWriteTransaction(({db:t})=>{e.assertOwnedInTransaction(t);let r=n(t);return e.assertOwnedInTransaction(t),r},t,{operationLabel:`agent.database.maintenance.admission`,schemaSql:ip,integrityCheck:So()?.sqliteIntegrityCheck,schemaCompatibility:{allowedMissingColumns:[`agent_database_leases.provenance`]}})}const ap=new ec;var AgentDatabaseMaintenanceRequiredError=class extends Error{constructor(...e){super(...e),this.name=`AgentDatabaseMaintenanceRequiredError`}};function assertAgentDatabaseMaintenanceAuthority(e){let t=ap.getStore()?.authority;if(!t||e&&t!==e)throw new(t?Error:AgentDatabaseMaintenanceRequiredError)(`Agent database migration requires stopped-writer maintenance; stop active agents and run openclaw doctor --fix.`);t.assertOwned(),ap.getStore()?.assertScopeCurrent?.()}[`insert`,`update`,`delete`].map(e=>({name:`memory_index_chunks_revision_after_${e}`,sql:`CREATE TRIGGER IF NOT EXISTS memory_index_chunks_revision_after_${e}
    AFTER ${e.toUpperCase()} ON memory_index_chunks
    BEGIN UPDATE memory_index_state SET revision = revision + 1 WHERE id = 1; END;`}));const op=B(Rr,`session_transcript_active_event_facts`,{endMarker:`-- END ACTIVE EVENT FACTS`,includeEndMarker:!1});function withoutAgentActiveEventFacts(e){return e.replace(`${op}-- END ACTIVE EVENT FACTS\n\n`,``)}const sp=/CREATE TABLE "session_transcript_active_event_facts" \([\s\S]*?\n\);|ALTER TABLE "session_transcript_active_event_facts"[^;]+;/gu;function withoutAgentPostgresActiveEventFacts(e){return e.replace(RegExp(`(?:${sp.source})\\n\\n`,`gu`),``)}function agentActiveEventFactsPostgresMigration(e){let t=e.match(sp);if(t?.length!==2)throw Error(`Active event facts table or foreign key is missing`);return t.join(`

`)}const cp=B(Rr,`session_transcript_cold_archive_chunks`);function withoutAgentColdArchiveChunks(e){return e.replace(`${cp}\n\n`,``)}function withoutAgentPostgresColdArchiveChunks(e){return e.replace(/CREATE TABLE "session_transcript_cold_archive_chunks" \([\s\S]*?\n\);\n\n/gu,``).replace(/ALTER TABLE "session_transcript_cold_archive_chunks" [^\n]+\n\n/gu,``)}function agentColdArchiveChunksPostgresMigration(e){return(e.match(/CREATE TABLE "session_transcript_cold_archive_chunks" \([\s\S]*?\n\);|ALTER TABLE "session_transcript_cold_archive_chunks" [^\n]+/gu)??[]).join(`

`)}function withoutAgentPostgresColdNavigation(e){return e.replace(` OR ("event_json" IS NULL AND "event_zstd" IS NULL AND "event_utf8_bytes" IS NOT NULL AND ("event_utf8_bytes" BETWEEN 1 AND 4194304) AND "navigation_json" IS NOT NULL)`,``)}function agentColdNavigationPostgresMigration(e){let t=e.match(/ {2}CHECK \([^\n]*"event_zstd" IS NOT NULL[^\n]+/u)?.[0];if(!t)throw Error(`Cold navigation payload constraint is missing`);return`ALTER TABLE "transcript_events" DROP CONSTRAINT "transcript_events_check";
    ALTER TABLE "transcript_events" ADD CONSTRAINT "transcript_events_check" ${t.trim().replace(/,$/u,``)};`}const lp=B(Rr,`session_creation_operations`,{endMarker:`-- END SESSION CREATION OPERATIONS`,includeEndMarker:!1});function withoutAgentCreationOperations(e){return e.replace(`${lp}-- END SESSION CREATION OPERATIONS\n\n`,``)}const up=/CREATE TABLE "session_creation_operations" \([\s\S]*?\n\);|CREATE INDEX "idx_agent_(?:session_creation_operations_expiry|session_input_completions_session_key|conversation_deliveries_source_session)"[^;]+;/gu;function withoutAgentPostgresCreationOperations(e){return e.replace(RegExp(`(?:${up.source})\\n\\n`,`gu`),``)}function agentCreationOperationsPostgresMigration(e){let t=e.match(up);if(t?.length!==4)throw Error(`Session creation receipt table or schema-40 index is missing`);return t.join(`

`)}function withLegacyAgentIndexes(e){return e.replace(`CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_label`,`CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_last_interaction_at
  ON session_nodes(last_interaction_at DESC, session_key);

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_label`).replace(`CREATE TABLE IF NOT EXISTS board_tabs (`,`CREATE INDEX IF NOT EXISTS idx_agent_session_reactions_message
  ON session_reactions(session_key, session_id, message_id);

CREATE TABLE IF NOT EXISTS board_tabs (`)}function withLegacyAgentPostgresIndexes(e){return`${e}
    ALTER FUNCTION openclaw_transcript_navigation_check(text)
      CALLED ON NULL INPUT RESET search_path;
    CREATE INDEX "idx_agent_session_nodes_last_interaction_at"
      ON "session_nodes" (("last_interaction_at") DESC NULLS LAST,
        ("session_key") ASC NULLS FIRST);
    CREATE INDEX "idx_agent_session_reactions_message"
      ON "session_reactions" (("session_key") ASC NULLS FIRST,
        ("session_id") ASC NULLS FIRST, ("message_id") ASC NULLS FIRST);
  `}const dp=[`memory_index_sources`,`memory_index_chunks`],fp=[`insert`,`update`,`delete`],pp=dp.flatMap(e=>fp.map(t=>({name:`${e}_revision_after_${t}`,table:e,sql:`CREATE TRIGGER IF NOT EXISTS ${e}_revision_after_${t}
AFTER ${t.toUpperCase()} ON ${e}
BEGIN
  UPDATE memory_index_state SET revision = revision + 1 WHERE id = 1;
END;`})));pp.map(e=>e.name);function withLegacyAgentMemoryRevisionTriggers(e){let t=pp.map(e=>e.sql).join(`

`);return e.replace(`CREATE INDEX IF NOT EXISTS idx_memory_embedding_cache_updated_at`,`${t}\n\nCREATE INDEX IF NOT EXISTS idx_memory_embedding_cache_updated_at`)}function withLegacyAgentPostgresMemoryRevisionTriggers(e){return`${e}\n${dp.map(e=>`CREATE FUNCTION "openclaw_${e}_trigger"() RETURNS trigger LANGUAGE plpgsql SET search_path FROM CURRENT AS $trigger$
BEGIN
  UPDATE memory_index_state SET revision = revision + 1 WHERE id = 1;
  RETURN NULL;
END;
$trigger$;
${fp.map(t=>`CREATE TRIGGER "${e}_revision_after_${t}" AFTER ${t.toUpperCase()} ON "${e}" FOR EACH ROW EXECUTE FUNCTION "openclaw_${e}_trigger"();`).join(`
`)}`).join(`

`)}`}dp.flatMap(e=>fp.map(t=>`DROP TRIGGER IF EXISTS ${e}_revision_after_${t};`)).join(`
`);const mp=dp.map(e=>`${fp.map(t=>`DROP TRIGGER IF EXISTS ${e}_revision_after_${t} ON ${e};`).join(`
`)}
DROP FUNCTION IF EXISTS openclaw_${e}_trigger();`).join(`
`);function sessionEntrySnapshotsSchemaSql(e){return B(e,`session_entry_snapshots`,{endMarker:`CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_updated_at`,includeEndMarker:!1})}function withoutSessionEntrySnapshotsSchema(e){return e.includes(`CREATE TABLE IF NOT EXISTS session_entry_snapshots (`)?e.replace(`  snapshot_revision INTEGER NOT NULL DEFAULT 0,
`,``).replace(sessionEntrySnapshotsSchemaSql(e),``):e}function withDeployedTranscriptFtsRowSchema(e){let t=B(e,`session_transcript_index_state`);return e.replace(t,t.replace(`  updated_at INTEGER NOT NULL,`,`  fts_row_count INTEGER,
  updated_at INTEGER NOT NULL,`)).replace(`CREATE VIRTUAL TABLE IF NOT EXISTS session_transcript_fts USING fts5(`,`CREATE TABLE IF NOT EXISTS session_transcript_fts_rows (
  session_id TEXT NOT NULL,
  fts_rowid INTEGER NOT NULL PRIMARY KEY
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_transcript_fts_rows_session
  ON session_transcript_fts_rows(session_id);

CREATE VIRTUAL TABLE IF NOT EXISTS session_transcript_fts USING fts5(`)}const hp={transcript_events:`CREATE TABLE IF NOT EXISTS transcript_events (
  session_id TEXT NOT NULL,
  seq INTEGER NOT NULL,
  event_json TEXT NOT NULL,
  created_at INTEGER NOT NULL,
  PRIMARY KEY (session_id, seq),
  FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE
) STRICT;`,memory_index_chunks:`CREATE TABLE IF NOT EXISTS memory_index_chunks (
  id TEXT PRIMARY KEY,
  path TEXT NOT NULL,
  source TEXT NOT NULL DEFAULT 'memory',
  start_line INTEGER NOT NULL,
  end_line INTEGER NOT NULL,
  hash TEXT NOT NULL,
  model TEXT NOT NULL,
  text TEXT NOT NULL,
  embedding TEXT NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;`,memory_embedding_cache:`CREATE TABLE IF NOT EXISTS memory_embedding_cache (
  provider TEXT NOT NULL,
  model TEXT NOT NULL,
  provider_key TEXT NOT NULL,
  hash TEXT NOT NULL,
  embedding TEXT NOT NULL,
  dims INTEGER,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (provider, model, provider_key, hash)
) STRICT;`};function withLegacyAgentStorageSchema(e,t=21){let n=withoutSessionEntrySnapshotsSchema(e);for(let[e,t]of Object.entries(hp))n=n.replace(B(n,e),t);return n.includes(`CREATE TABLE IF NOT EXISTS session_transcript_fts_rows (`)&&(n=n.replace(B(n,`session_transcript_fts_rows`,{endMarker:`INSERT OR IGNORE INTO memory_index_state`,includeEndMarker:!1}),``)),t===22?withDeployedTranscriptFtsRowSchema(n):n}const gp=B(Rr,`agent_tool_usage`,{endMarker:`-- END AGENT TOOL USAGE`,includeEndMarker:!1});function withoutAgentToolUsage(e){return e.replace(`${gp}-- END AGENT TOOL USAGE\n\n`,``)}const _p=/CREATE TABLE "agent_tool_usage" \([\s\S]*?\n\);/u;function withoutAgentPostgresToolUsage(e){return e.replace(RegExp(`${_p.source}\\n\\n`,`u`),``)}function agentToolUsagePostgresMigration(e){let t=e.match(_p)?.[0];if(!t)throw Error(`Agent tool usage table is missing`);return t}function withoutTrajectoryPayloadColumns(e){return e.replace(`  event_utf8_bytes INTEGER,
  event_payload BLOB,
  event_codec TEXT,
`,``).replace(`COALESCE(event_utf8_bytes, octet_length(event_json))`,`octet_length(event_json)`)}function withLegacyAgentPostgresTrajectoryStorage(e){return e.replace(`  "event_utf8_bytes" bigint,
  "event_payload" bytea,
  "event_codec" text COLLATE "C",
`,``).replaceAll(`coalesce("event_utf8_bytes", octet_length("event_json"))`,`octet_length("event_json")`)}const vp=`
CREATE TRIGGER IF NOT EXISTS session_nodes_entry_valid_after_insert
AFTER INSERT ON session_nodes
BEGIN
  UPDATE session_nodes SET entry_valid = 0 WHERE session_key = NEW.session_key;
END;

CREATE TRIGGER IF NOT EXISTS session_nodes_entry_valid_after_entry_update
AFTER UPDATE OF entry_json ON session_nodes
BEGIN
  UPDATE session_nodes SET entry_valid = 0 WHERE session_key = NEW.session_key;
END;

CREATE TRIGGER IF NOT EXISTS session_nodes_entry_valid_after_identity_update
AFTER UPDATE OF current_session_id, updated_at ON session_nodes
BEGIN
  UPDATE session_nodes SET entry_valid = 0 WHERE session_key = NEW.session_key;
END;
`,yp=`
-- Avoid trigger-local conflict clauses: SQLite inherits the outer writer's
-- conflict policy, including writers that predate this validation projection.
CREATE TRIGGER IF NOT EXISTS session_nodes_canonical_pending_after_insert
AFTER INSERT ON session_nodes
BEGIN
  INSERT INTO session_canonical_validation_pending (session_key)
  SELECT NEW.session_key
  WHERE NOT EXISTS (
    SELECT 1 FROM session_canonical_validation_pending WHERE session_key = NEW.session_key
  );
END;

CREATE TRIGGER IF NOT EXISTS session_nodes_canonical_pending_after_update
AFTER UPDATE OF session_key, current_session_id, entry_json, entry_valid,
  parent_session_key, spawned_by, fork_source_session_key ON session_nodes
WHEN OLD.session_key IS NOT NEW.session_key
  OR OLD.current_session_id IS NOT NEW.current_session_id
  OR OLD.entry_json IS NOT NEW.entry_json
  OR OLD.entry_valid IS NOT NEW.entry_valid
  OR OLD.parent_session_key IS NOT NEW.parent_session_key
  OR OLD.spawned_by IS NOT NEW.spawned_by
  OR OLD.fork_source_session_key IS NOT NEW.fork_source_session_key
BEGIN
  DELETE FROM session_canonical_validation_pending
  WHERE session_key = OLD.session_key AND OLD.session_key IS NOT NEW.session_key;
  INSERT INTO session_canonical_validation_pending (session_key)
  SELECT NEW.session_key
  WHERE NOT EXISTS (
    SELECT 1 FROM session_canonical_validation_pending WHERE session_key = NEW.session_key
  );
END;

CREATE TRIGGER IF NOT EXISTS session_nodes_canonical_pending_after_delete
AFTER DELETE ON session_nodes
BEGIN
  DELETE FROM session_canonical_validation_pending WHERE session_key = OLD.session_key;
END;

CREATE TRIGGER IF NOT EXISTS session_windows_canonical_pending_after_insert
AFTER INSERT ON session_windows
BEGIN
  INSERT INTO session_canonical_validation_pending (session_key)
  SELECT node.session_key FROM session_nodes AS node
  WHERE node.current_session_id = NEW.session_id
    AND NOT EXISTS (
      SELECT 1 FROM session_canonical_validation_pending AS pending
      WHERE pending.session_key = node.session_key
    );
END;

CREATE TRIGGER IF NOT EXISTS session_windows_canonical_pending_after_update
AFTER UPDATE OF session_id, session_key ON session_windows
WHEN OLD.session_id IS NOT NEW.session_id OR OLD.session_key IS NOT NEW.session_key
BEGIN
  INSERT INTO session_canonical_validation_pending (session_key)
  SELECT node.session_key FROM session_nodes AS node
  WHERE node.current_session_id IN (OLD.session_id, NEW.session_id)
    AND NOT EXISTS (
      SELECT 1 FROM session_canonical_validation_pending AS pending
      WHERE pending.session_key = node.session_key
    );
END;

CREATE TRIGGER IF NOT EXISTS session_windows_canonical_pending_after_delete
AFTER DELETE ON session_windows
BEGIN
  INSERT INTO session_canonical_validation_pending (session_key)
  SELECT node.session_key FROM session_nodes AS node
  WHERE node.current_session_id = OLD.session_id
    AND NOT EXISTS (
      SELECT 1 FROM session_canonical_validation_pending AS pending
      WHERE pending.session_key = node.session_key
    );
END;

CREATE TRIGGER IF NOT EXISTS session_key_contract_canonical_pending_after_insert
AFTER INSERT ON session_key_contract
BEGIN
  INSERT INTO session_canonical_validation_pending (session_key)
  SELECT node.session_key FROM session_nodes AS node
  WHERE NOT EXISTS (
    SELECT 1 FROM session_canonical_validation_pending AS pending
    WHERE pending.session_key = node.session_key
  );
END;

CREATE TRIGGER IF NOT EXISTS session_key_contract_canonical_pending_after_update
AFTER UPDATE OF main_key ON session_key_contract
WHEN OLD.main_key IS NOT NEW.main_key
BEGIN
  INSERT INTO session_canonical_validation_pending (session_key)
  SELECT node.session_key FROM session_nodes AS node
  WHERE NOT EXISTS (
    SELECT 1 FROM session_canonical_validation_pending AS pending
    WHERE pending.session_key = node.session_key
  );
END;

CREATE TRIGGER IF NOT EXISTS session_key_contract_canonical_pending_after_delete
AFTER DELETE ON session_key_contract
BEGIN
  INSERT INTO session_canonical_validation_pending (session_key)
  SELECT node.session_key FROM session_nodes AS node
  WHERE NOT EXISTS (
    SELECT 1 FROM session_canonical_validation_pending AS pending
    WHERE pending.session_key = node.session_key
  );
END;
`;function withLegacyCanonicalSessionValidationTriggers(e){return e.replace(`CREATE TABLE IF NOT EXISTS session_windows (`,`${vp}\nCREATE TABLE IF NOT EXISTS session_windows (`).replace(`CREATE TABLE IF NOT EXISTS conversations (`,`${yp}\nCREATE TABLE IF NOT EXISTS conversations (`)}Object.freeze([...`${vp}\n${yp}`.matchAll(/CREATE TRIGGER IF NOT EXISTS (\w+)/gu)].map(e=>e[1]));function canonicalSessionValidationSchemaSql(e=Rr){return B(e,`session_canonical_validation_pending`,{endMarker:`CREATE TABLE IF NOT EXISTS conversations (`,includeEndMarker:!1})}function withoutCanonicalSessionValidationSchema(e){return e.includes(`CREATE TABLE IF NOT EXISTS session_canonical_validation_pending (`)?e.replace(canonicalSessionValidationSchemaSql(e),``):e}const bp={session_started_at:`INTEGER`,has_optional_references:`INTEGER NOT NULL DEFAULT 0`,payload_state:`TEXT`,navigation_type:`TEXT`,navigation_custom_type:`TEXT`,navigation_display:`INTEGER NOT NULL DEFAULT 0`,message_role:`TEXT`,navigation_last_type:`TEXT`,navigation_last_custom_type:`TEXT`,navigation_valid:`INTEGER NOT NULL DEFAULT 1`};function withoutAgentJsonPredicateColumns(e){let t=e;for(let[e,n]of Object.entries(bp))t=t.replace(`  ${e} ${n},\n`,``);return t}function sessionParticipantsSchemaSql(){return B(Rr,Qu,{endMarker:`CREATE TABLE IF NOT EXISTS session_key_contract (`,includeEndMarker:!1,errorMessage:`OpenClaw session participant schema markers are missing.`})}function withLegacySessionParticipantsSchema(e){return withoutCanonicalSessionValidationSchema(e).replace(sessionParticipantsSchemaSql().trim(),`CREATE TABLE IF NOT EXISTS session_participants (
  session_key TEXT NOT NULL,
  actor_type TEXT NOT NULL,
  actor_id TEXT NOT NULL,
  actor_source TEXT,
  contribution_count INTEGER,
  first_prompted_at INTEGER NOT NULL,
  last_prompted_at INTEGER NOT NULL,
  PRIMARY KEY (session_key, actor_type, actor_id),
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;`)}function withoutOutboxEnqueueSequence(e){return e.replace(`  enqueue_sequence INTEGER PRIMARY KEY,
  advancement_key TEXT NOT NULL UNIQUE,`,`  advancement_key TEXT NOT NULL PRIMARY KEY,`)}function withLegacyAgentWriteLayout(e){return e.replace(/(CREATE TABLE IF NOT EXISTS memory_entry_origins \([\s\S]*?\n\) STRICT), WITHOUT ROWID;/u,`$1;`).replace(`ON session_windows(primary_conversation_id)`,`ON session_windows(primary_conversation_id, updated_at DESC, session_id)`).replace(`CREATE INDEX IF NOT EXISTS idx_agent_transcript_event_sequence`,`CREATE INDEX IF NOT EXISTS idx_agent_transcript_event_parent
  ON transcript_event_identities(session_id, parent_id)
  WHERE parent_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_agent_transcript_event_sequence`)}const xp=withoutAgentCreationOperations(withoutAgentActiveEventFacts(withoutAgentToolUsage(Rr))).replace(/\nCREATE INDEX IF NOT EXISTS idx_agent_(?:session_input_completions_session_key|conversation_deliveries_source_session)\b[^;]*;\n/gu,``),Sp=B(Rr,`board_tabs`,{endMarker:`CREATE TABLE IF NOT EXISTS session_progress_cards (`,includeEndMarker:!1,errorMessage:`OpenClaw agent board schema markers are missing from the canonical schema.`}),Cp=withLegacyAgentIndexes(withoutTrajectoryPayloadColumns(withLegacyAgentMemoryRevisionTriggers(withoutAgentColdArchiveChunks(xp)))).replace(Sp,``),wp=`session_progress_cards`,Tp=B(Cp,wp,{endMarker:`CREATE TABLE IF NOT EXISTS heartbeat_outcomes (`,includeEndMarker:!1,errorMessage:`OpenClaw agent progress-card schema markers are missing.`}),Ep=Cp.replace(Tp,``),Dp=B(Ep,`session_members`,{endMarker:`CREATE TABLE IF NOT EXISTS heartbeat_outcomes (`,includeEndMarker:!1,errorMessage:`OpenClaw agent session-sharing schema markers are missing.`}),Op=Dp.indexOf(`CREATE TABLE IF NOT EXISTS session_suggestions (`);if(Op===-1)throw Error(`OpenClaw agent session-suggestions schema marker is missing.`);Dp.slice(0,Op),Dp.slice(Op),withLegacySessionParticipantsSchema(withLegacyAgentStorageSchema(withLegacyCanonicalSessionValidationTriggers(withoutAgentJsonPredicateColumns(withoutOutboxEnqueueSequence(withLegacyAgentWriteLayout(Ep.replace(Dp,``)))))));const kp={allowCompatibleAdditiveColumns:!0,allowedMissingTables:[`session_reactions`,`memory_entry_origins`,`memory_session_tombstones`,`memory_index_chunk_provenance`,`memory_index_chunk_recall_metadata`,`context_engine_turn_outbox`,`message_tool_run_outcomes`,`session_goal_operations`,`session_pending_inputs`,`session_input_completions`,Qu,wp,`session_transcript_archives`,`standing_intents`,`standing_intents_fts`,`standing_intents_fts_config`,`standing_intents_fts_data`,`standing_intents_fts_docsize`,`standing_intents_fts_idx`],allowedMissingColumns:[...ri.map(({columnName:e,tableName:t})=>`${t}.${e}`),`standing_intents.creator_sender`,...Er.map(({columnName:e,tableName:t})=>`${t}.${e}`)],allowedColumnDefinitions:{"session_pending_inputs.recovery_intent_json":[`recovery_intent_json TEXT`],"conversations.delivery_target":[`delivery_target TEXT NOT NULL DEFAULT ''`]},allowedMissingIndexes:[`idx_agent_transcript_context_pending`,`idx_agent_session_nodes_label`,`idx_agent_session_nodes_entry_not_valid`,`idx_agent_session_input_completions_session_key`,`idx_agent_conversation_deliveries_source_session`],optionalCanonicalTriggerGroups:[{tableName:`memory_index_chunks`,triggers:Dl},{tableName:Cl,triggers:El}]},Ap=R(Symbol.for(`openclaw.agentDatabaseSettledReadOpenFailures`),()=>/* @__PURE__ */ new WeakSet);function recordOpenClawAgentDatabaseReadOpenFailure(e){typeof e==`object`&&e&&Zi(e)!==void 0&&Ap.add(e)}function classifyOpenClawAgentDatabaseReadError(e,t){if(z(e))return t;try{let n=collectSqliteSchemaIssues(e,Rr,kp).filter(e=>e.code===`missing-table`).map(e=>e.objectName);return n.length>0?new Fo(`table-missing`,{cause:t},n):t}catch{return t}}const jp=/* @__PURE__ */ new Set([`session_nodes`,`session_windows`,`session_key_contract`,`session_canonical_validation_pending`]),Mp=R(Symbol.for(`openclaw.agentCanonicalValidationSchemas`),()=>/* @__PURE__ */ new WeakMap),Np=/* @__PURE__ */ new Map([[`session_canonical_validation_pending`,qr(B(Rr,`session_canonical_validation_pending`))]]);function readDefinitions(e,t){let n=/* @__PURE__ */ new Map,r=`session_canonical_validation_pending`,i=t?[...t.tableSql.has(r)?[{name:r,sql:t.tableSql.get(r)}]:[],...Array.from(t.triggers).flatMap(([e,t])=>e===r||jp.has(t.table)?[{name:e,sql:t.sql}]:[])]:e.prepare(`SELECT name, sql FROM main.sqlite_schema
  WHERE name = 'session_canonical_validation_pending'
    OR (type = 'trigger' AND tbl_name IN (
      'session_nodes', 'session_windows', 'session_key_contract', 'session_canonical_validation_pending'
    ))`).all();for(let e of i){if(typeof e.name!=`string`||typeof e.sql!=`string`)throw Error(`Session canonical validation schema has an unreadable definition`);n.set(e.name,qr(e.sql))}return n}function assertCanonicalSessionValidationSchema(e){if(z(e)){let t=gs(e);if(t?.store!==`agent`||t.version<21)throw Error(`Session canonical validation requires current PostgreSQL agent admission`);return}let t=K(e),n=t?.schemaVersion??readSqliteSchemaCookie(e);if(typeof n!=`number`)throw Error(`Session canonical validation schema version is unavailable`);let r=Mp.get(e);if(r&&(t?r.schema===t:!r.schema&&r.cookie===n))return;Mp.delete(e);let i=readDefinitions(e,t);for(let t of/* @__PURE__ */ new Set([...Np.keys(),...i.keys()]))if(Np.get(t)!==i.get(t))throw classifyOpenClawAgentDatabaseReadError(e,/* @__PURE__ */ Error(`Session canonical validation schema is missing or drifted: ${t}; run openclaw doctor --fix with the compatible build.`));(t||!e.isTransaction)&&Mp.set(e,{cookie:n,schema:t})}function adoptCanonicalSessionValidationSchema(e){if(z(e)){assertCanonicalSessionValidationSchema(e);return}let t=K(e);if(!t)throw Error(`Canonical schema handoff requires admitted schema facts`);Mp.set(e,{cookie:t.schemaVersion,schema:t})}const Pp={name:`agent.canonical-validation-receipt`,lifetime:`process`,schemaDependent:!0,read:e=>e===null||typeof e==`string`?e:void 0};function hasOpenClawAgentCanonicalValidationReceiptColumn(e){let{tableName:t,columnName:n}=si;return P(e,t,n)}function physicalReceipt(e){let t=findOpenClawAgentDatabaseIdentity(e);if(t&&typeof t.identity==`string`)return JSON.stringify([1,e.agentId,t.identity,t.birthtime])}function hasPersistedOpenClawAgentCanonicalValidation(e){let t=physicalReceipt(e);return t!==void 0&&V(e.db,Pp)===t}function loadOpenClawAgentCanonicalValidationReceipt(e,t){let n=physicalReceipt(e);if(!n)return!1;let r=V(e.db,Pp);if(r===void 0){if(!hasOpenClawAgentCanonicalValidationReceiptColumn(e.db))return!1;assertCanonicalSessionValidationSchema(e.db),r=t?t.canonicalReady:C(e.db,w(e.db).selectFrom(`session_key_contract`).select(`canonical_ready`).where(`id`,`=`,1))?.canonical_ready??null,fi(e.db,Pp,r)}return r===n}const Fp={name:`agent.schema-metadata`,lifetime:`process`,schemaDependent:!0,read(e){if(!(typeof e!=`object`||!e||!(`agentId`in e)||e.agentId!==null&&typeof e.agentId!=`string`||!(`role`in e)||e.role!==null&&typeof e.role!=`string`||!(`schemaVersion`in e)||e.schemaVersion!==null&&typeof e.schemaVersion!=`number`))return{agentId:e.agentId,role:e.role,schemaVersion:e.schemaVersion}}};function schemaMetadataKey(e){return{name:`agent.schema-metadata:${e}`,read:Fp.read}}function publishAgentSchemaMetadata(e,t){fi(e,Fp,t);let n=K(e);n&&fi(e,schemaMetadataKey(n.admissionId),t)}function readExistingAgentSchemaMeta(e){let t=K(e),n=t&&V(e,schemaMetadataKey(t.admissionId));if(n)return n;let r=!t||V(e,Ba)?.admissionId===t.admissionId?V(e,Fp):void 0;if(r)return t&&fi(e,schemaMetadataKey(t.admissionId),r),r;if(!M(e,`schema_meta`))return null;let i;try{i=e.prepare(`SELECT role, schema_version, agent_id FROM schema_meta WHERE meta_key = 'primary'`).get()}catch(t){throw pt(e,`schema_meta`,[`meta_key`,`role`,`schema_version`,`agent_id`],t)}if(!i)return null;let a={agentId:Nn(i.agent_id),role:typeof i.role==`string`?i.role:null,schemaVersion:typeof i.schema_version==`number`?i.schema_version:null},o=t&&K(e)===t;return z(e)||o&&V(e,Ba)?.admissionId===t.admissionId?publishAgentSchemaMetadata(e,a):o&&fi(e,schemaMetadataKey(t.admissionId),a),a}function readAgentDatabaseSchemaVersion(e){if(z(e)){let t=gs(e);if(!t)throw Error(`Agent database has no PostgreSQL schema admission`);return t.version}return K(e)?.userVersion??Lo(e)}function assertSupportedAgentSchemaVersion(e,t,n=readAgentDatabaseSchemaVersion(e)){if(n>42)throw qo(`OpenClaw agent database`,t,n,42,To(e));return n}function hasAgentDatabaseApplicationSchema(e){if(z(e))return!!gs(e)?.catalog.some(e=>e.kind===`table`);let t=K(e);if(t){for(let e of[t.tables,t.views,t.indexes,t.triggers.keys()])for(let t of e)if(!t.startsWith(`sqlite_`))return!0;return!1}return!!e.prepare(`SELECT 1 FROM sqlite_master WHERE substr(name, 1, 7) <> 'sqlite_' LIMIT 1`).get()}function assertCanonicalAgentPersistenceVersion(e,t,n=readAgentDatabaseSchemaVersion(e)){if(K(e)?.tables.has(`openclaw_engine_anchor`))throw Error(`This agent store lives in PostgreSQL; set database.engine to postgres and configure database.postgres.connection.`);assertSupportedAgentSchemaVersion(e,t,n);let r=n===0&&!hasAgentDatabaseApplicationSchema(e);if(n<17&&!r)throw new rs(t,n);if(n<42&&!r)throw new as(`state-migrations`,`OpenClaw agent database ${t} uses schema version ${n}; stop active agents and run openclaw doctor --fix to upgrade it to schema version 42 before using it.`)}function assertExistingAgentSchemaOwner(e,t,n){if(e){if(e.role!==`agent`)throw new N(`OpenClaw agent database ${n} has schema role ${e.role??`unknown`}; expected agent. Run openclaw doctor --fix to inspect and repair its ownership.`);if(!e.agentId)throw new N(`OpenClaw agent database ${n} has no agent owner. Run openclaw doctor --fix to inspect and repair its ownership.`);if(q(e.agentId)!==t)throw new N(`OpenClaw agent database ${n} belongs to agent ${e.agentId}; requested agent ${t}.`)}}function assertCurrentAgentSchemaMetadata(e,t,n,r=42){if(!e)throw new N(`OpenClaw agent database ${n} has no schema ownership metadata. Run openclaw doctor --fix to inspect and repair its ownership.`);if(assertExistingAgentSchemaOwner(e,t,n),e.schemaVersion!==r)throw new N(`OpenClaw agent database ${n} metadata schema version ${e.schemaVersion??`invalid`} does not match ${r}; run openclaw doctor --fix before using it.`)}const Ip={name:`agent.completed-validation`,lifetime:`process`,read(e){return I(e)?e:void 0}};function matchesAgentDatabaseValidation(e,t){let n=findOpenClawAgentDatabaseIdentity(e);return t.agentId===e.agentId&&t.identity===n?.identity&&t.birthtime===n?.birthtime&&Atomics.load(new Int32Array(t.valid),0)===1}function createOpenClawAgentDatabaseValidationReceipt(e,t){let{identity:n,birthtime:r}=readOpenClawAgentDatabaseIdentity(e);if(typeof n!=`string`||r===void 0)throw Error(`Only persistent agent databases retain integrity validation`);let i={agentId:e.agentId,identity:n,birthtime:r,receiptId:rc(),integrityVerifiedAt:z(e.db)?void 0:or(e.db)?.verifiedAt,valid:new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT),canonicalReady:new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)};return t&&Atomics.store(new Int32Array(i.canonicalReady),0,1),Atomics.store(new Int32Array(i.valid),0,1),i}const Lp=R(Symbol.for(`openclaw.agentDatabaseValidationObservations`),()=>/* @__PURE__ */ new Map);function createAgentValidationObservation(e,t){function releaseValidationObservation(e){Lp.get(e)?.close()}function observeValidationPath(n,r){let i=Lp.get(n);if(i)return r?i.revalidate():i.ready;let revalidate=async()=>{let r=e(n);if(r&&Atomics.load(new Int32Array(r.valid),0)===1)try{fr(await $s(n,{bigint:!0}),{key:`file:${r.identity}`,birthtime:r.birthtime})}catch{e(n)===r&&t(n,r.identity)}},a=observeOwnedDirectory(X.dirname(n),(e,t)=>{(t!==`change`||e===void 0)&&(e===void 0||(process.platform===`win32`?e.toLowerCase()===X.basename(n).toLowerCase():e===X.basename(n)))&&revalidate()}),o=revalidate();return Lp.set(n,{revalidate,ready:o,close(){a.close(),Lp.delete(n)}}),o.finally(()=>{let e=Lp.get(n);e?.ready===o&&delete e.ready})}return{observe:observeValidationPath,release:releaseValidationObservation}}function adoptAgentValidationSchema(e,t,n,r){let i=t?.schema,a=n&&i&&!e.db.isTransaction?K(e.db):void 0,o=n&&i?.postgres&&!e.db.isTransaction?gs(e.db):void 0,s=!!(n&&i&&Atomics.load(new Int32Array(i.valid),0)===1&&(i.postgres?o?.storeId===i.postgres.storeId&&o.namespace===i.postgres.namespace&&o.version===i.postgres.version:!z(e.db)&&(a?.schemaVersion===i.facts.schemaVersion&&a.userVersion===i.facts.userVersion||co(e.db,i.facts)))&&Atomics.load(new Int32Array(i.valid),0)===1);if(r&&!s)throw Error(`Agent schema admission changed before handle adoption; retry the operation`);return s&&(adoptCanonicalSessionValidationSchema(e.db),t?.integrityVerifiedAt!==void 0&&!z(e.db)&&(or(e.db)===void 0&&ca(e.db,t.integrityVerifiedAt),V(e.db,Ip)?.receiptId!==t.receiptId&&fi(e.db,Ip,t))),s}const $=R(Symbol.for(`openclaw.agentDatabaseValidatedPaths`),()=>/* @__PURE__ */ new Map,()=>clearOpenClawAgentDatabaseValidationCache()),Rp=createAgentValidationObservation(e=>$.get(e)?.validation,invalidatePathValidation),zp=R(Symbol.for(`openclaw.agentDatabaseValidationBindings`),()=>/* @__PURE__ */ new WeakMap);function bindValidationLifetime(e,t){let n=zp.get(e.db);if(!e.db.isOpen||n?.validation===t)return;n?.unregister();let r=readOpenClawAgentDatabaseIdentity(e).canonicalPath,i=hr(e.db),a=zo(i,e=>{let revoke=t=>{t&&(!e||t.postgres||t.facts.schemaVersion!==e.schemaVersion||t.facts.userVersion!==e.userVersion)&&Atomics.store(new Int32Array(t.valid),0,0)};revoke(t.schema);let n=$.get(r)?.validation;n?.schema&&n.agentId===t.agentId&&n.identity===t.identity&&revoke(n.schema)}),o=Na(i,n=>{n===`replace`&&Atomics.store(new Int32Array(t.valid),0,0),zp.delete(e.db),a(),o()});zp.set(e.db,{validation:t,unregister:()=>{a(),o()}})}function adoptOpenClawAgentDatabaseSchema(e,t=!0,n=!1){return adoptAgentValidationSchema(e,getOpenClawAgentDatabaseValidation(e),t,n)}function hasRevokedOpenClawAgentDatabaseValidation(e,t){let n=$.get(typeof e==`string`?mi(e):e.canonicalPath);return t!==void 0&&Atomics.load(new Int32Array(t.valid),0)!==1||n?.revoked===!0||n?.validation!==void 0&&Atomics.load(new Int32Array(n.validation.valid),0)!==1}function getOpenClawAgentDatabaseValidation(e){let t=readOpenClawAgentDatabaseIdentity(e).canonicalPath,n=$.get(t);if(!n?.revoked){if(!n?.integrityVerified||!n.validation||n.validation.schema&&Atomics.load(new Int32Array(n.validation.schema.valid),0)!==1||!matchesAgentDatabaseValidation(e,n.validation)){let r=V(e.db,Ip);r&&matchesAgentDatabaseValidation(e,r)&&(n&&(n.agentId===void 0||n.agentId===e.agentId)&&(!n.validation||matchesAgentDatabaseValidation(e,n.validation))?(n.agentId=e.agentId,n.validation&&n.validation.receiptId===r.receiptId?n.validation.schema=r.schema:n.validation=r,n.integrityVerified=!0):(n={agentId:e.agentId,validation:r,integrityVerified:!0},$.set(t,n)))}if(n?.integrityVerified&&n.validation&&matchesAgentDatabaseValidation(e,n.validation))return bindValidationLifetime(e,n.validation),n.validation}}function canonicalValidationReceipt(e){let t=findOpenClawAgentDatabaseIdentity(e)?.canonicalPath;if(!e.db.isOpen||!t)return;let n=$.get(t)?.validation;if(n&&matchesAgentDatabaseValidation(e,n))return bindValidationLifetime({...e,path:t},n),n}function hasOpenClawAgentCanonicalValidation(e){let t=canonicalValidationReceipt(e);if(t)return Atomics.load(new Int32Array(t.canonicalReady),0)===1&&Atomics.load(new Int32Array(t.valid),0)===1;let n=findOpenClawAgentDatabaseIdentity(e)?.canonicalPath;if(!n||e.db.isTransaction||$.get(n)?.validation!==void 0||hasRevokedOpenClawAgentDatabaseValidation(n)||!hasPersistedOpenClawAgentCanonicalValidation(e))return!1;let r=createOpenClawAgentDatabaseValidationReceipt(e,!0),i=$.get(n)??{integrityVerified:!1};return i.validation=r,$.set(n,i),bindValidationLifetime({...e,path:n},r),!0}function invalidateOpenClawAgentDatabaseValidation(e,t){invalidatePathValidation(typeof e==`string`?mi(e):e.canonicalPath,t)}function invalidatePathValidation(e,t=$.get(e)?.validation?.identity){let n=/* @__PURE__ */ new Set([e]);if(t)for(let[e,r]of $)r.validation?.identity===t&&n.add(e);for(let e of n){Rp.release(e);let t=$.get(e),n=t?.validation;n&&Atomics.store(new Int32Array(n.valid),0,0),$.set(e,{agentId:t?.agentId,validation:n,integrityVerified:!1,revoked:!0})}}function clearOpenClawAgentDatabaseValidationCache(e){let t=e===void 0?void 0:mi(e);for(let e of $.keys())(t===void 0||hn(t,e))&&(invalidateOpenClawAgentDatabaseValidation(e),$.delete(e))}const Bp=er(`state/agent-db`),Vp=R(Symbol.for(`openclaw.agentDatabaseCloseReceipts`),()=>new ln(128),e=>e.clear()),Hp={scope:`core:agent-database-maintenance`,key:`global`};function readAgentDatabaseLeases(e,t){let n=w(e).selectFrom(`agent_database_leases`).selectAll();return A(e,t===void 0?n:n.where(`lease_id`,`=`,t)).rows}function claimOpenClawAgentDatabaseLease(e,t=rc(),n){let r=q(e.agentId),i=prepareAgentDeletionPathFence({agentId:r,path:e.path},{env:e.env}),a=ws(process.pid);return runOpenClawStateWriteTransaction(o=>claimAgentDatabaseLeaseInDatabase(o,{leaseId:t,agentId:r,path:e.path,ownerPid:process.pid,ownerStartTime:a,provenance:readAgentDatabaseLeaseProvenance(e.path)},i,n),{env:e.env,initializationAgentPaths:[e.path]}),t}function claimAgentDatabaseLeaseInDatabase(e,t,n,r){ensureAgentDatabaseLeaseSchema(e.db);let i=w(e.db),a=C(e.db,i.selectFrom(`state_leases`).select(`owner`).where(`scope`,`=`,Hp.scope).where(`lease_key`,`=`,Hp.key).where(`expires_at`,`>`,Date.now())),o=ap.getStore();if(a||o)throw Error(`Agent database maintenance is in progress; retry after openclaw doctor --fix completes.`);assertAgentDeletionPathFence(e,n);let s=!1,c,l=createAgentDatabaseLeaseStaleReasonReader();for(let n of readAgentDatabaseLeases(e.db)){let r=mayShareAgentDatabaseFile(n.path,t.path),a=r?l(n):void 0;a?(Bp.info(`agent database stale lease: ${a}; previous release not observed`,{agentId:n.agent_id,leaseId:n.lease_id,path:n.path,staleReason:a,ownerPid:n.owner_pid,ownerStartTime:n.owner_start_time}),A(e.db,i.deleteFrom(`agent_database_leases`).where(`lease_id`,`=`,n.lease_id)),reportPriorBootLeaseRelease(e.db,n.lease_id,a)):r&&n.lease_id!==t.leaseId&&(t.ownerStartTime===null||n.owner_pid!==t.ownerPid||n.owner_start_time===null||n.owner_start_time!==t.ownerStartTime)&&(s=!0,n.path===t.path&&n.provenance!==null&&n.provenance===t.provenance&&n.opened_at>0&&n.owner_start_time!==null&&ws(n.owner_pid)===n.owner_start_time&&(c=n.provenance))}r?.(!s,c),A(e.db,i.insertInto(`agent_database_leases`).values({lease_id:t.leaseId,provenance:t.provenance,agent_id:t.agentId,path:t.path,owner_pid:t.ownerPid,owner_start_time:t.ownerStartTime,opened_at:0}))}function releaseOpenClawAgentDatabaseLease(e,t={},n,r){let i=performance.now(),release=t=>{let a=w(t),o=C(t,n===void 0?a.selectFrom(`agent_database_leases`).select([`path`,`agent_id`]).where(`lease_id`,`=`,e):a.deleteFrom(`agent_database_leases`).where(`lease_id`,`=`,e).returning([`path`,`agent_id`]));n===void 0&&(o&&clearAgentDatabaseLeaseVerifications(t,o.path),A(t,a.deleteFrom(`agent_database_leases`).where(`lease_id`,`=`,e)));let s,c;o?typeof n==`object`?o.path===n.path?(c=findAgentDatabasePathLease(t,n.path),s=c?`active-leases`:n.publishSeal()?`written`:`verification-missing`):s=`path-mismatch`:s=n===`uncheckpointed`?`checkpoint-incomplete`:n??`close-unconfirmed`:s=`lease-not-held`;let publish=()=>{let t=r?performance.now()-r.startedAt:0,n=t>=500,a=n?{totalMs:Math.round(t),walStopMs:Math.round(r?.walStopMs??0),checkpointMs:Math.round(r?.checkpointMs??0),nativeCloseMs:Math.round(r?.nativeCloseMs??0),leaseReleaseMs:Math.round(performance.now()-i)}:void 0,l=a?nc(`sha256`).update(o?.path??`unknown`).digest(`hex`).slice(0,16):void 0;if(o){let e=Vp.get(o.path);if(!n&&e?.agentId===o.agent_id&&e.receipt===s&&e.blockingLeaseId===c?.lease_id)return;Vp.set(o.path,{agentId:o.agent_id,receipt:s,blockingLeaseId:c?.lease_id})}Bp.info(`agent database clean-close receipt: ${s}; agent=${o?.agent_id??`unknown`}${c?`; blockingLeaseId=${c.lease_id}; ownerPid=${c.owner_pid}`:``}${a?`; db=${l}; thread=${Gs}; close=${JSON.stringify(a)}`:``}`,{agentId:o?.agent_id,path:o?.path,leaseId:e,receipt:s,pid:process.pid,threadId:Gs,...a?{close:a}:{},...s===`checkpoint-incomplete`&&r?.checkpoint?{checkpoint:r.checkpoint}:{},blockingLease:c&&{leaseId:c.lease_id,ownerPid:c.owner_pid,ownerStartTime:c.owner_start_time,path:c.path,openedAt:c.opened_at}})};ya(t,publish)||publish()},a=ap.getStore(),o=X.resolve(t.database?.path??t.path??Do(t.env));if(a?.databasePath===o)return withExistingAgentLeaseWrite(a.authority,t,release);Ne(()=>runOpenClawStateWriteTransaction(e=>{ensureAgentDatabaseLeaseSchema(e.db),release(e.db)},typeof n==`object`?{...t,initializationAgentPaths:[...t.initializationAgentPaths??[],n.path]}:t))}function agentDatabaseLeasePaths(e){let t=w(e);return A(e,t.selectFrom(`agent_database_leases`).select(`path`).distinct()).rows.map(e=>e.path)}function findAgentDatabasePathLease(e,t){return readAgentDatabaseLeases(e).find(e=>mayShareAgentDatabaseFile(e.path,t))}function clearAgentDatabaseLeaseVerifications(e,t){for(let n of/* @__PURE__ */ new Set([t,...agentDatabaseLeasePaths(e)]))mayShareAgentDatabaseFile(n,t)&&(invalidateOpenClawAgentDatabaseValidation(n),ta(n))}function reportPriorBootLeaseRelease(e,t,n){if(n!==`owner-prior-boot`)return;let publish=()=>Bp.warn(`Released legacy agent database lease ${t} from a prior boot.`);ya(e,publish)||publish()}function memoryPathPostgresExpressions(e){let t=`pg_catalog.lower(pg_catalog.normalize(pg_catalog.regexp_replace(pg_catalog.replace(pg_catalog.btrim(${e}), E'\\\\', '/'), '^\\./', ''), 'NFC'))`,n=`pg_catalog.regexp_replace(${t}, '^.*/', '')`,r=`pg_catalog.regexp_replace(${n}, '^(.+)\\.[^.]*$', '\\1')`;return{normalized:t,basename:n,stem:r,keys:[t,n,r].map(e=>`pg_catalog.md5(${e})`)}}const Up=[`exact_path`,`basename`,`stem`].map((e,t)=>{let n=`idx_memory_index_sources_${e}`;return{name:n,sql:`CREATE INDEX "${n}" ON "memory_index_sources" ((${memoryPathPostgresExpressions(`path`).keys[t]}));`}}).map(e=>e.sql).join(`

`);function withLegacyAgentPostgresMemoryPaths(e){return e.replace(`${Up}\n\n`,``)}const Wp={text:{transcript:{table:`session_transcript_fts`,fields:[`text`],postgres:{identity:`rowid`}}}},template=e=>e.replaceAll(`%`,`%%`).replaceAll(`__TABLE__`,`%1$s`).replaceAll(`__FIELD__`,`%2$s`).replaceAll(`__SYNC__`,`%3$s`).replaceAll(`__CONFIG__`,`%4$L`).replaceAll(`'`,`''`),Gp=`DO $migration$
DECLARE text_index jsonb; tbl text; fld text; sync text;
  config text := format('%I.%I', current_schema(), 'openclaw_simple_unaccent');
BEGIN
  FOR text_index IN
    SELECT jsonb_build_object('table', 'session_transcript_fts', 'fields', jsonb_build_array('text'))
    UNION ALL
    SELECT indexes.value FROM openclaw_schema_meta meta,
      jsonb_each(coalesce((to_jsonb(meta)->>'search_extensions')::jsonb, '{}'::jsonb)) extensions,
      jsonb_each(coalesce(extensions.value->'text', '{}'::jsonb)) indexes
    WHERE meta.store = 'agent'
  LOOP
    IF to_regclass(format('%I', text_index->>'table')) IS NULL THEN CONTINUE; END IF;
    tbl := '"' || replace(text_index->>'table', '"', '""') || '"';
    fld := '"' || replace(text_index->'fields'->>0, '"', '""') || '"';
    sync := '"' || replace((text_index->>'table') || '_search_sync', '"', '""') || '"';
    EXECUTE format('ALTER TABLE %s ALTER COLUMN openclaw_search DROP EXPRESSION', tbl);
    EXECUTE format('${template(bo({table:`__TABLE__`,field:`__FIELD__`,sync:`__SYNC__`}))}', tbl, fld, sync);
    EXECUTE format('${template(`UPDATE __TABLE__ SET openclaw_search = ${no(`__CONFIG__`,`__FIELD__`,2)}`)}', tbl, fld, sync, config);
  END LOOP;
END $migration$;`,Kp=`DO $migration$
DECLARE extension_schema text;
BEGIN
  SELECT n.nspname INTO extension_schema
  FROM pg_catalog.pg_proc p
  JOIN pg_catalog.pg_type t ON t.oid = p.prorettype
  JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
  WHERE p.oid = to_regprocedure(format('%I.openclaw_vector(bytea,integer)', current_schema()));
  IF FOUND THEN
    EXECUTE replace($decoder$${Ma(`__vector_extension__`,2,!0)}$decoder$,
      '__vector_extension__', replace(extension_schema, '"', '""'));
  END IF;
END $migration$;`;function withLegacyAgentPostgresWriteLayout(e){return`${e}
    DROP INDEX "idx_agent_session_windows_conversation";
    CREATE INDEX "idx_agent_session_windows_conversation"
      ON "session_windows" (("primary_conversation_id") ASC NULLS FIRST,
        ("updated_at") DESC NULLS LAST, ("session_id") ASC NULLS FIRST)
      WHERE "primary_conversation_id" IS NOT NULL;
    CREATE INDEX "idx_agent_transcript_event_parent"
      ON "transcript_event_identities" (("session_id") ASC NULLS FIRST,
        ("parent_id") ASC NULLS FIRST)
      WHERE "parent_id" IS NOT NULL;
  `}const qp={get sql(){let e=`-- Generated runtime DDL; the owner supplies search_path and the transaction.

CREATE FUNCTION "openclaw_transcript_navigation_check"(navigation_json text) RETURNS boolean LANGUAGE sql IMMUTABLE STRICT SET search_path = pg_catalog AS $navigation$
WITH input AS (SELECT CASE WHEN navigation_json IS JSON THEN navigation_json::json END AS document),
members AS (SELECT (SELECT member.value FROM json_each(CASE WHEN json_typeof(document) = 'object' THEN document ELSE '{}'::json END) WITH ORDINALITY AS member(key, value, position) WHERE member.key = 'version' ORDER BY member.position LIMIT 1) AS "j_version",
(SELECT member.value FROM json_each(CASE WHEN json_typeof(document) = 'object' THEN document ELSE '{}'::json END) WITH ORDINALITY AS member(key, value, position) WHERE member.key = 'modelBytes' ORDER BY member.position LIMIT 1) AS "j_modelBytes",
(SELECT member.value FROM json_each(CASE WHEN json_typeof(document) = 'object' THEN document ELSE '{}'::json END) WITH ORDINALITY AS member(key, value, position) WHERE member.key = 'modelWithoutCheckpointBytes' ORDER BY member.position LIMIT 1) AS "j_modelWithoutCheckpointBytes",
(SELECT member.value FROM json_each(CASE WHEN json_typeof(document) = 'object' THEN document ELSE '{}'::json END) WITH ORDINALITY AS member(key, value, position) WHERE member.key = 'withoutCustomDataBytes' ORDER BY member.position LIMIT 1) AS "j_withoutCustomDataBytes",
(SELECT member.value FROM json_each(CASE WHEN json_typeof(document) = 'object' THEN document ELSE '{}'::json END) WITH ORDINALITY AS member(key, value, position) WHERE member.key = 'report' ORDER BY member.position LIMIT 1) AS "j_report",
(SELECT member.value FROM json_each(CASE WHEN json_typeof((SELECT member.value FROM json_each(CASE WHEN json_typeof(document) = 'object' THEN document ELSE '{}'::json END) WITH ORDINALITY AS member(key, value, position) WHERE member.key = 'report' ORDER BY member.position LIMIT 1)) = 'object' THEN (SELECT member.value FROM json_each(CASE WHEN json_typeof(document) = 'object' THEN document ELSE '{}'::json END) WITH ORDINALITY AS member(key, value, position) WHERE member.key = 'report' ORDER BY member.position LIMIT 1) ELSE '{}'::json END) WITH ORDINALITY AS member(key, value, position) WHERE member.key = 'kind' ORDER BY member.position LIMIT 1) AS "j_report.kind",
(SELECT member.value FROM json_each(CASE WHEN json_typeof(document) = 'object' THEN document ELSE '{}'::json END) WITH ORDINALITY AS member(key, value, position) WHERE member.key = 'navigation' ORDER BY member.position LIMIT 1) AS "j_navigation",
(SELECT member.value FROM json_each(CASE WHEN json_typeof(document) = 'object' THEN document ELSE '{}'::json END) WITH ORDINALITY AS member(key, value, position) WHERE member.key = 'reset' ORDER BY member.position LIMIT 1) AS "j_reset",
(SELECT member.value FROM json_each(CASE WHEN json_typeof(document) = 'object' THEN document ELSE '{}'::json END) WITH ORDINALITY AS member(key, value, position) WHERE member.key = 'model' ORDER BY member.position LIMIT 1) AS "j_model" FROM input)
SELECT "navigation_json" IS NULL OR CASE WHEN ("navigation_json" IS JSON) THEN coalesce((octet_length("navigation_json") <= 16384) AND (CASE WHEN json_typeof("j_version") = 'number' AND ("j_version" #>> '{}') ~ '^-?[0-9]+$' THEN 'integer' WHEN json_typeof("j_version") = 'number' THEN 'real' ELSE json_typeof("j_version") END = 'integer') AND (CASE WHEN json_typeof("j_version") = 'number' AND ("j_version" #>> '{}') ~ '^-?[0-9]+$' AND char_length(("j_version" #>> '{}')) <= 20 THEN ("j_version" #>> '{}')::numeric END = 1) AND (CASE WHEN json_typeof("j_report") = 'number' AND ("j_report" #>> '{}') ~ '^-?[0-9]+$' THEN 'integer' WHEN json_typeof("j_report") = 'number' THEN 'real' ELSE json_typeof("j_report") END = 'object') AND (CASE WHEN json_typeof("j_report.kind") = 'string' THEN ("j_report.kind" #>> '{}') END IN ('canonical', 'leaf', 'link', 'ignored')) AND (CASE WHEN json_typeof("j_navigation") = 'number' AND ("j_navigation" #>> '{}') ~ '^-?[0-9]+$' THEN 'integer' WHEN json_typeof("j_navigation") = 'number' THEN 'real' ELSE json_typeof("j_navigation") END = 'object') AND (CASE WHEN json_typeof("j_reset") = 'number' AND ("j_reset" #>> '{}') ~ '^-?[0-9]+$' THEN 'integer' WHEN json_typeof("j_reset") = 'number' THEN 'real' ELSE json_typeof("j_reset") END = 'object') AND (CASE WHEN json_typeof("j_model") = 'number' AND ("j_model" #>> '{}') ~ '^-?[0-9]+$' THEN 'integer' WHEN json_typeof("j_model") = 'number' THEN 'real' ELSE json_typeof("j_model") END = 'object') AND (CASE WHEN json_typeof("j_modelBytes") = 'number' AND ("j_modelBytes" #>> '{}') ~ '^-?[0-9]+$' THEN 'integer' WHEN json_typeof("j_modelBytes") = 'number' THEN 'real' ELSE json_typeof("j_modelBytes") END = 'integer') AND (CASE WHEN json_typeof("j_modelBytes") = 'number' AND ("j_modelBytes" #>> '{}') ~ '^-?[0-9]+$' AND char_length(("j_modelBytes" #>> '{}')) <= 20 THEN ("j_modelBytes" #>> '{}')::numeric END BETWEEN 0 AND 4194304) AND (CASE WHEN json_typeof("j_modelWithoutCheckpointBytes") = 'number' AND ("j_modelWithoutCheckpointBytes" #>> '{}') ~ '^-?[0-9]+$' THEN 'integer' WHEN json_typeof("j_modelWithoutCheckpointBytes") = 'number' THEN 'real' ELSE json_typeof("j_modelWithoutCheckpointBytes") END = 'integer') AND (CASE WHEN json_typeof("j_modelWithoutCheckpointBytes") = 'number' AND ("j_modelWithoutCheckpointBytes" #>> '{}') ~ '^-?[0-9]+$' AND char_length(("j_modelWithoutCheckpointBytes" #>> '{}')) <= 20 THEN ("j_modelWithoutCheckpointBytes" #>> '{}')::numeric END BETWEEN 0 AND 4194304) AND (CASE WHEN json_typeof("j_withoutCustomDataBytes") = 'number' AND ("j_withoutCustomDataBytes" #>> '{}') ~ '^-?[0-9]+$' THEN 'integer' WHEN json_typeof("j_withoutCustomDataBytes") = 'number' THEN 'real' ELSE json_typeof("j_withoutCustomDataBytes") END = 'integer') AND (CASE WHEN json_typeof("j_withoutCustomDataBytes") = 'number' AND ("j_withoutCustomDataBytes" #>> '{}') ~ '^-?[0-9]+$' AND char_length(("j_withoutCustomDataBytes" #>> '{}')) <= 20 THEN ("j_withoutCustomDataBytes" #>> '{}')::numeric END BETWEEN 0 AND 4194304), FALSE) ELSE FALSE END FROM members;
$navigation$;

CREATE TABLE "acp_parent_stream_events" (
  "session_id" text COLLATE "C" NOT NULL,
  "run_id" text COLLATE "C" NOT NULL,
  "seq" bigint NOT NULL,
  "event_json" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  PRIMARY KEY ("session_id", "run_id", "seq")
);

CREATE TABLE "agent_tool_usage" (
  "tool_id" text COLLATE "C" NOT NULL,
  "score" double precision NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("tool_id"),
  CHECK (("score" >= 0))
);

CREATE TABLE "auth_profile_state" (
  "state_key" text COLLATE "C" NOT NULL,
  "state_json" text COLLATE "C" NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("state_key")
);

CREATE TABLE "auth_profile_store" (
  "store_key" text COLLATE "C" NOT NULL,
  "store_json" text COLLATE "C" NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("store_key")
);

CREATE TABLE "board_tabs" (
  "session_key" text COLLATE "C" NOT NULL,
  "tab_id" text COLLATE "C" NOT NULL,
  "title" text COLLATE "C" NOT NULL,
  "position" bigint NOT NULL,
  "chat_dock" text COLLATE "C" NOT NULL DEFAULT 'right',
  "created_by" text COLLATE "C" NOT NULL,
  "revision" bigint NOT NULL,
  PRIMARY KEY ("session_key", "tab_id"),
  CHECK (("position" >= 0)),
  CHECK (("chat_dock" IN ('left', 'right', 'bottom', 'hidden'))),
  CHECK (("created_by" IN ('user', 'agent'))),
  CHECK (("revision" >= 0))
);

CREATE TABLE "board_widgets" (
  "session_key" text COLLATE "C" NOT NULL,
  "name" text COLLATE "C" NOT NULL,
  "tab_id" text COLLATE "C" NOT NULL,
  "title" text COLLATE "C",
  "content_kind" text COLLATE "C" NOT NULL,
  "html" bytea,
  "descriptor_json" text COLLATE "C",
  "sha256" text COLLATE "C" NOT NULL,
  "view_generation" text COLLATE "C",
  "revision" bigint NOT NULL,
  "size_w" bigint NOT NULL,
  "size_h" bigint NOT NULL,
  "position" bigint NOT NULL,
  "manifest" text COLLATE "C" NOT NULL DEFAULT '{}',
  "grant_state" text COLLATE "C" NOT NULL DEFAULT 'none',
  "granted_sha" text COLLATE "C",
  "created_by" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("session_key", "name"),
  CHECK (("content_kind" IN ('html', 'mcp-app', 'plugin'))),
  CHECK (("revision" >= 1)),
  CHECK (("size_w" BETWEEN 1 AND 12)),
  CHECK (("size_h" BETWEEN 1 AND 20)),
  CHECK (("position" >= 0)),
  CHECK (("grant_state" IN ('none', 'pending', 'granted', 'rejected'))),
  CHECK (("created_by" IN ('user', 'agent'))),
  CHECK ((("content_kind" = 'html') AND "html" IS NOT NULL AND "descriptor_json" IS NULL AND "view_generation" IS NOT NULL) OR (("content_kind" = 'mcp-app') AND "html" IS NULL AND "descriptor_json" IS NOT NULL AND "view_generation" IS NULL) OR (("content_kind" = 'plugin') AND "html" IS NULL AND "descriptor_json" IS NOT NULL AND "view_generation" IS NULL))
);

CREATE TABLE "cache_entries" (
  "scope" text COLLATE "C" NOT NULL,
  "key" text COLLATE "C" NOT NULL,
  "value_json" text COLLATE "C",
  "blob" bytea,
  "expires_at" bigint,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("scope", "key")
);

CREATE TABLE "context_engine_turn_outbox" (
  "enqueue_sequence" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "advancement_key" text COLLATE "C" NOT NULL,
  "engine_id" text COLLATE "C" NOT NULL,
  "owner_plugin_id" text COLLATE "C",
  "session_id" text COLLATE "C" NOT NULL,
  "payload_json" text COLLATE "C" NOT NULL,
  "payload_state" text COLLATE "C",
  "attempt_count" bigint NOT NULL DEFAULT 0,
  "last_attempt_at" bigint,
  "last_error" text COLLATE "C",
  "created_at" bigint NOT NULL,
  PRIMARY KEY ("enqueue_sequence"),
  UNIQUE ("advancement_key")
);

CREATE TABLE "conversation_deliveries" (
  "operation_id" text COLLATE "C" NOT NULL,
  "operation_kind" text COLLATE "C" NOT NULL,
  "conversation_id" text COLLATE "C" NOT NULL,
  "source_session_key" text COLLATE "C",
  "message_hash" text COLLATE "C" NOT NULL,
  "status" text COLLATE "C" NOT NULL,
  "prepared_message_id" text COLLATE "C",
  "platform_message_id" text COLLATE "C",
  "queue_id" text COLLATE "C",
  "rejection_error" text COLLATE "C",
  "reply_message_id" text COLLATE "C",
  "reply_to_id" text COLLATE "C",
  "reply_thread_id" text COLLATE "C",
  "reply_text" text COLLATE "C",
  "reply_timestamp" bigint,
  "created_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("operation_id"),
  CHECK (("operation_kind" IN ('send', 'turn'))),
  CHECK (("status" IN ('created', 'queued', 'sent', 'suppressed', 'rejected', 'unknown', 'replied'))),
  CHECK ((("status" = 'rejected') AND "rejection_error" IS NOT NULL) OR (("status" != 'rejected') AND "rejection_error" IS NULL))
);

CREATE TABLE "conversations" (
  "conversation_id" text COLLATE "C" NOT NULL,
  "channel" text COLLATE "C" NOT NULL,
  "account_id" text COLLATE "C" NOT NULL,
  "kind" text COLLATE "C" NOT NULL,
  "peer_id" text COLLATE "C" NOT NULL,
  "delivery_target" text COLLATE "C" NOT NULL,
  "parent_conversation_id" text COLLATE "C",
  "thread_id" text COLLATE "C",
  "native_channel_id" text COLLATE "C",
  "native_direct_user_id" text COLLATE "C",
  "label" text COLLATE "C",
  "metadata_json" text COLLATE "C",
  "created_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("conversation_id"),
  CHECK (("kind" IN ('direct', 'group', 'channel')))
);

CREATE TABLE "heartbeat_outcomes" (
  "session_key" text COLLATE "C" NOT NULL,
  "run_session_key" text COLLATE "C" NOT NULL,
  "outcome" text COLLATE "C" NOT NULL,
  "summary" text COLLATE "C" NOT NULL,
  "response_reason" text COLLATE "C",
  "priority" text COLLATE "C",
  "next_check" text COLLATE "C",
  "task_names_json" text COLLATE "C",
  "wake_source" text COLLATE "C",
  "wake_reason" text COLLATE "C",
  "occurred_at" bigint NOT NULL,
  "context_run_id" text COLLATE "C",
  "context_claimed_at" bigint,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("session_key"),
  CHECK (("outcome" IN ('progress', 'done', 'blocked', 'needs_attention'))),
  CHECK ("priority" IS NULL OR ("priority" IN ('low', 'normal', 'high')))
);

CREATE TABLE "memory_embedding_cache" (
  "provider" text COLLATE "C" NOT NULL,
  "model" text COLLATE "C" NOT NULL,
  "provider_key" text COLLATE "C" NOT NULL,
  "hash" text COLLATE "C" NOT NULL,
  "embedding" bytea NOT NULL,
  "dims" bigint,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("provider", "model", "provider_key", "hash")
);

CREATE TABLE "memory_entry_origins" (
  "entry_key" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C",
  "origin_class" text COLLATE "C" NOT NULL,
  "observed_at" bigint NOT NULL,
  PRIMARY KEY ("entry_key", "agent_id", "session_id"),
  CHECK (("origin_class" IN ('owner', 'agent', 'untrusted', 'system')))
);

CREATE TABLE "memory_index_chunk_provenance" (
  "chunk_id" text COLLATE "C" NOT NULL,
  "origin_class" text COLLATE "C" NOT NULL,
  "session_kind" text COLLATE "C" NOT NULL,
  "observed_at" bigint NOT NULL,
  "supersedes_key" text COLLATE "C",
  PRIMARY KEY ("chunk_id"),
  CHECK (("origin_class" IN ('owner', 'agent', 'untrusted', 'system'))),
  CHECK (("session_kind" IN ('interactive', 'cron', 'heartbeat', 'subagent', 'unknown')))
);

CREATE TABLE "memory_index_chunk_recall_metadata" (
  "chunk_id" text COLLATE "C" NOT NULL,
  "importance" bigint,
  "triggers" text COLLATE "C",
  "project_key" text COLLATE "C",
  PRIMARY KEY ("chunk_id"),
  CHECK ("importance" IS NULL OR ("importance" BETWEEN 1 AND 10))
);

CREATE TABLE "memory_index_chunks" (
  "chunk_rowid" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "id" text COLLATE "C" NOT NULL,
  "path" text COLLATE "C" NOT NULL,
  "source" text COLLATE "C" NOT NULL DEFAULT 'memory',
  "start_line" bigint NOT NULL,
  "end_line" bigint NOT NULL,
  "hash" text COLLATE "C" NOT NULL,
  "model" text COLLATE "C" NOT NULL,
  "text" text COLLATE "C" NOT NULL,
  "embedding" bytea NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("chunk_rowid"),
  UNIQUE ("id")
);

CREATE TABLE "memory_index_meta" (
  "key" text COLLATE "C" NOT NULL,
  "value" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("key")
);

CREATE TABLE "memory_index_sources" (
  "id" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "path" text COLLATE "C" NOT NULL,
  "source" text COLLATE "C" NOT NULL DEFAULT 'memory',
  "hash" text COLLATE "C" NOT NULL,
  "mtime" double precision NOT NULL,
  "size" bigint NOT NULL,
  PRIMARY KEY ("id"),
  UNIQUE ("path", "source")
);

CREATE TABLE "memory_index_state" (
  "id" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "revision" bigint NOT NULL,
  PRIMARY KEY ("id"),
  CHECK (("id" = 1))
);

CREATE TABLE "memory_session_tombstones" (
  "session_id" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "reason" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  PRIMARY KEY ("session_id")
);

CREATE TABLE "message_tool_run_outcomes" (
  "id" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "run_id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "agent_id" text COLLATE "C" NOT NULL,
  "provider" text COLLATE "C" NOT NULL,
  "model" text COLLATE "C" NOT NULL,
  "outcome" text COLLATE "C" NOT NULL,
  "run_status" text COLLATE "C" NOT NULL,
  "occurred_at" bigint NOT NULL,
  PRIMARY KEY ("id"),
  CHECK (("outcome" IN ('tool_delivered', 'mute'))),
  CHECK (("run_status" IN ('completed', 'errored', 'aborted')))
);

CREATE TABLE "schema_meta" (
  "meta_key" text COLLATE "C" NOT NULL,
  "role" text COLLATE "C" NOT NULL,
  "schema_version" bigint NOT NULL,
  "agent_id" text COLLATE "C",
  "app_version" text COLLATE "C",
  "created_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("meta_key")
);

CREATE TABLE "session_canonical_validation_pending" (
  "session_key" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("session_key")
);

CREATE TABLE "session_conversations" (
  "session_id" text COLLATE "C" NOT NULL,
  "conversation_id" text COLLATE "C" NOT NULL,
  "role" text COLLATE "C" NOT NULL DEFAULT 'primary',
  "route_context_json" text COLLATE "C",
  "first_seen_at" bigint NOT NULL,
  "last_seen_at" bigint NOT NULL,
  PRIMARY KEY ("session_id", "conversation_id", "role"),
  CHECK (("role" IN ('primary', 'participant', 'related')))
);

CREATE TABLE "session_creation_operations" (
  "operation_digest" text COLLATE "C" NOT NULL,
  "request_fingerprint" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "lifecycle_revision" text COLLATE "C",
  "role" text COLLATE "C",
  "scopes_json" text COLLATE "C" NOT NULL,
  "expires_at" bigint NOT NULL,
  PRIMARY KEY ("operation_digest")
);

CREATE TABLE "session_entry_snapshots" (
  "session_key" text COLLATE "C" NOT NULL,
  "field" text COLLATE "C" NOT NULL,
  "value_json" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("session_key", "field"),
  CHECK (("field" IN ('sessionDiffBaseline', 'skillsSnapshot', 'systemPromptReport')))
);

CREATE TABLE "session_goal_operations" (
  "session_key" text COLLATE "C" NOT NULL,
  "operation_id" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "request_fingerprint" text COLLATE "C" NOT NULL,
  "result_json" text COLLATE "C" NOT NULL,
  "expires_at" bigint NOT NULL,
  PRIMARY KEY ("session_key", "operation_id")
);

CREATE TABLE "session_input_completions" (
  "session_key" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "idempotency_key" text COLLATE "C" NOT NULL,
  "run_id" text COLLATE "C" NOT NULL,
  "request_hash" text COLLATE "C" NOT NULL,
  "outcome_json" text COLLATE "C" NOT NULL,
  "succeeded" bigint NOT NULL,
  "completed_at" bigint NOT NULL,
  PRIMARY KEY ("session_id", "idempotency_key"),
  CHECK (("succeeded" IN (0, 1)))
);

CREATE TABLE "session_key_contract" (
  "id" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "main_key" text COLLATE "C" NOT NULL,
  "canonical_ready" text COLLATE "C",
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("id"),
  CHECK (("id" = 1))
);

CREATE TABLE "session_members" (
  "session_key" text COLLATE "C" NOT NULL,
  "identity_id" text COLLATE "C" NOT NULL,
  "added_by" text COLLATE "C" NOT NULL,
  "added_at" bigint NOT NULL,
  PRIMARY KEY ("session_key", "identity_id")
);

CREATE TABLE "session_nodes" (
  "session_key" text COLLATE "C" NOT NULL,
  "current_session_id" text COLLATE "C" NOT NULL,
  "entry_json" text COLLATE "C" NOT NULL,
  "session_started_at" bigint,
  "has_optional_references" bigint NOT NULL DEFAULT 0,
  "snapshot_revision" bigint NOT NULL DEFAULT 0,
  "legacy_acp_migration_json" text COLLATE "C",
  "entry_valid" bigint NOT NULL DEFAULT 0,
  "updated_at" bigint NOT NULL,
  "status" text COLLATE "C",
  "created_at" bigint,
  "created_via" text COLLATE "C",
  "created_actor_type" text COLLATE "C",
  "created_actor_id" text COLLATE "C",
  "owner_actor_type" text COLLATE "C",
  "owner_actor_id" text COLLATE "C",
  "owner_assigned_by_type" text COLLATE "C",
  "owner_assigned_by_id" text COLLATE "C",
  "owner_assigned_at" bigint,
  "project_id" text COLLATE "C",
  "parent_session_key" text COLLATE "C",
  "spawned_by" text COLLATE "C",
  "fork_source_session_key" text COLLATE "C",
  "fork_source_session_id" text COLLATE "C",
  "fork_source_entry_id" text COLLATE "C",
  "label" text COLLATE "C",
  "display_name" text COLLATE "C",
  "category" text COLLATE "C",
  "icon" text COLLATE "C",
  "pinned_at" bigint,
  "archived_at" bigint,
  "last_read_at" bigint,
  "last_interaction_at" bigint,
  "last_activity_at" bigint,
  PRIMARY KEY ("session_key"),
  CHECK (("entry_valid" IN (-1, 0, 1))),
  CHECK ("status" IS NULL OR ("status" IN ('running', 'done', 'failed', 'killed', 'timeout'))),
  CHECK ("created_via" IS NULL OR ("created_via" IN ('operator', 'spawn', 'channel', 'cron', 'talk', 'run', 'plugin', 'internal'))),
  CHECK ("created_actor_type" IS NULL OR ("created_actor_type" IN ('human', 'agent', 'system')))
);

CREATE TABLE "session_participants" (
  "session_key" text COLLATE "C" NOT NULL,
  "identity_namespace" text COLLATE "C" NOT NULL,
  "actor_id" text COLLATE "C" NOT NULL,
  "contribution_count" bigint NOT NULL,
  "first_prompted_at" bigint,
  "last_prompted_at" bigint,
  PRIMARY KEY ("session_key", "identity_namespace", "actor_id")
);

CREATE TABLE "session_pending_inputs" (
  "seq" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "input_id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "idempotency_key" text COLLATE "C" NOT NULL,
  "run_id" text COLLATE "C" NOT NULL,
  "request_hash" text COLLATE "C" NOT NULL,
  "message_json" text COLLATE "C" NOT NULL,
  "lifecycle_generation" text COLLATE "C" NOT NULL,
  "state" text COLLATE "C" NOT NULL,
  "accepted_at" bigint NOT NULL,
  "consumed_event_id" text COLLATE "C",
  PRIMARY KEY ("seq"),
  CHECK (("state" IN ('queued', 'interrupted', 'cancelled'))),
  UNIQUE ("input_id"),
  UNIQUE ("session_id", "idempotency_key")
);

CREATE TABLE "session_progress_cards" (
  "session_key" text COLLATE "C" NOT NULL,
  "markdown" text COLLATE "C",
  "steps_json" text COLLATE "C",
  "revision" bigint NOT NULL,
  "created_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("session_key")
);

CREATE TABLE "session_reactions" (
  "session_key" text COLLATE "C" NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "message_id" text COLLATE "C" NOT NULL,
  "emoji" text COLLATE "C" NOT NULL,
  "identity_id" text COLLATE "C" NOT NULL,
  "identity_label" text COLLATE "C",
  "created_at" bigint NOT NULL,
  PRIMARY KEY ("session_key", "session_id", "message_id", "emoji", "identity_id")
);

CREATE TABLE "session_suggestions" (
  "id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "author_id" text COLLATE "C" NOT NULL,
  "author_label" text COLLATE "C",
  "text" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  "state" text COLLATE "C" NOT NULL,
  "dispatch_token" text COLLATE "C",
  "dispatch_started_at" bigint,
  "dispatch_resolution" text COLLATE "C",
  PRIMARY KEY ("id"),
  CHECK (("state" IN ('pending', 'accepted', 'dismissed'))),
  CHECK (("dispatch_resolution" IN ('send', 'queue', 'edit', 'dismiss'))),
  CHECK (("dispatch_token" IS NULL AND "dispatch_started_at" IS NULL AND "dispatch_resolution" IS NULL) OR ("dispatch_token" IS NOT NULL AND "dispatch_started_at" IS NOT NULL AND "dispatch_resolution" IS NOT NULL))
);

CREATE TABLE "session_transcript_active_event_facts" (
  "session_id" text COLLATE "C" NOT NULL,
  "seq" bigint NOT NULL,
  "serialized_bytes" bigint NOT NULL,
  "dependency_navigation_json" text COLLATE "C" NOT NULL,
  PRIMARY KEY ("session_id", "seq"),
  CHECK (("serialized_bytes" >= 1))
);

CREATE TABLE "session_transcript_active_events" (
  "session_id" text COLLATE "C" NOT NULL,
  "active_position" bigint NOT NULL,
  "event_seq" bigint NOT NULL,
  "message_position" bigint,
  "context_eligible" bigint,
  PRIMARY KEY ("session_id", "active_position"),
  CHECK (("active_position" >= 0)),
  CHECK ("message_position" IS NULL OR ("message_position" >= 0))
);

CREATE TABLE "session_transcript_archives" (
  "session_id" text COLLATE "C" NOT NULL,
  "generation" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "reason" text COLLATE "C" NOT NULL,
  "encoding" text COLLATE "C" NOT NULL,
  "archive_blob" bytea NOT NULL,
  "archive_sha256" text COLLATE "C" NOT NULL,
  "archive_name" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  "published_at" bigint,
  "publish_attempts" bigint NOT NULL DEFAULT 0,
  "last_publish_attempt_at" bigint,
  "last_publish_error" text COLLATE "C",
  PRIMARY KEY ("session_id", "generation"),
  CHECK (("reason" IN ('deleted', 'reset'))),
  CHECK (("encoding" IN ('identity', 'zstd'))),
  CHECK ((char_length("archive_sha256") = 64)),
  CHECK (("publish_attempts" >= 0)),
  CHECK ((strpos("archive_name", '/') = 0) AND (strpos("archive_name", '\\') = 0)),
  UNIQUE ("archive_name")
);

CREATE TABLE "session_transcript_cold_archive_chunks" (
  "session_id" text COLLATE "C" NOT NULL,
  "chunk_index" bigint NOT NULL,
  "archive_name" text COLLATE "C" NOT NULL,
  "archive_sha256" text COLLATE "C" NOT NULL,
  "first_seq" bigint NOT NULL,
  "last_seq" bigint NOT NULL,
  "event_count" bigint NOT NULL,
  "raw_bytes" bigint NOT NULL,
  "archive_bytes" bigint NOT NULL,
  "archive_blob" bytea,
  PRIMARY KEY ("session_id", "chunk_index"),
  CHECK (("chunk_index" >= 0)),
  CHECK ((char_length("archive_sha256") = 64)),
  CHECK (("last_seq" >= "first_seq")),
  CHECK (("event_count" >= 1)),
  CHECK (("raw_bytes" >= 0)),
  CHECK (("archive_bytes" >= 0)),
  CHECK ((char_length("archive_name") > 0) AND ("archive_name" NOT IN ('.', '..')) AND (strpos("archive_name", '/') = 0) AND (strpos("archive_name", '\\') = 0)),
  UNIQUE ("archive_name")
);

CREATE TABLE "session_transcript_cold_archives" (
  "session_id" text COLLATE "C" NOT NULL,
  "generation" text COLLATE "C" NOT NULL,
  "archive_name" text COLLATE "C" NOT NULL,
  "archive_sha256" text COLLATE "C" NOT NULL,
  "event_count" bigint NOT NULL,
  "raw_bytes" bigint NOT NULL,
  "archive_bytes" bigint NOT NULL,
  "last_seq" bigint NOT NULL,
  "archived_at" bigint NOT NULL,
  "storage" text COLLATE "C" NOT NULL,
  "archive_blob" bytea,
  PRIMARY KEY ("session_id"),
  CHECK ((char_length("archive_sha256") = 64)),
  CHECK (("event_count" >= 1)),
  CHECK (("raw_bytes" >= 0)),
  CHECK (("archive_bytes" >= 0)),
  CHECK (("storage" IN ('file', 'sqlite'))),
  CHECK ((char_length("archive_name") > 0) AND ("archive_name" NOT IN ('.', '..')) AND (strpos("archive_name", '/') = 0) AND (strpos("archive_name", '\\') = 0)),
  CHECK ((("storage" = 'file') AND "archive_blob" IS NULL) OR (("storage" = 'sqlite') AND "archive_blob" IS NOT NULL)),
  UNIQUE ("archive_name")
);

CREATE TABLE "session_transcript_fts_rows" (
  "id" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "session_id" text COLLATE "C" NOT NULL,
  "message_id" text COLLATE "C",
  PRIMARY KEY ("id")
);

CREATE TABLE "session_transcript_index_state" (
  "session_id" text COLLATE "C" NOT NULL,
  "indexed_seq" bigint NOT NULL,
  "leaf_event_id" text COLLATE "C",
  "needs_rebuild" bigint NOT NULL DEFAULT 0,
  "active_event_count" bigint NOT NULL DEFAULT 0,
  "active_message_count" bigint NOT NULL DEFAULT 0,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("session_id")
);

CREATE TABLE "session_windows" (
  "session_id" text COLLATE "C" NOT NULL,
  "session_key" text COLLATE "C" NOT NULL,
  "previous_session_id" text COLLATE "C",
  "reason" text COLLATE "C",
  "session_scope" text COLLATE "C" NOT NULL DEFAULT 'conversation',
  "created_at" bigint NOT NULL,
  "updated_at" bigint NOT NULL,
  "transcript_updated_at" bigint DEFAULT NULL,
  "row_transcript_json" text COLLATE "C",
  "row_transcript_updated_at" bigint,
  "transcript_observed_at" bigint DEFAULT NULL,
  "session_entry_provenance" bigint NOT NULL DEFAULT 0,
  "acp_owned" bigint NOT NULL DEFAULT 0,
  "plugin_owner_id" text COLLATE "C",
  "hook_external_content_source" text COLLATE "C",
  "started_at" bigint,
  "ended_at" bigint,
  "status" text COLLATE "C",
  "chat_type" text COLLATE "C",
  "channel" text COLLATE "C",
  "account_id" text COLLATE "C",
  "primary_conversation_id" text COLLATE "C",
  "model_provider" text COLLATE "C",
  "model" text COLLATE "C",
  "agent_harness_id" text COLLATE "C",
  "parent_session_key" text COLLATE "C",
  "spawned_by" text COLLATE "C",
  "display_name" text COLLATE "C",
  PRIMARY KEY ("session_id"),
  CHECK ("reason" IS NULL OR ("reason" IN ('initial', 'reset', 'rollover', 'fork', 'rewind', 'switch', 'recovery', 'compaction'))),
  CHECK (("session_scope" IN ('conversation', 'shared-main', 'group', 'channel'))),
  CHECK (("session_entry_provenance" IN (0, 1))),
  CHECK (("acp_owned" IN (0, 1))),
  CHECK ("hook_external_content_source" IS NULL OR ("hook_external_content_source" IN ('gmail', 'webhook'))),
  CHECK ("status" IS NULL OR ("status" IN ('running', 'done', 'failed', 'killed', 'timeout'))),
  CHECK ("chat_type" IS NULL OR ("chat_type" IN ('direct', 'group', 'channel')))
);

CREATE TABLE "standing_intents" (
  "intent_key" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
  "id" text COLLATE "C" NOT NULL,
  "description" text COLLATE "C" NOT NULL,
  "trigger_keywords" text COLLATE "C" NOT NULL,
  "trigger_embedding" text COLLATE "C",
  "channel_scope" text COLLATE "C",
  "sender_scope" text COLLATE "C",
  "creator_sender" text COLLATE "C",
  "status" text COLLATE "C" NOT NULL,
  "expires_at" bigint NOT NULL,
  "max_fires" bigint NOT NULL,
  "fire_count" bigint NOT NULL DEFAULT 0,
  "cooldown_seconds" bigint NOT NULL DEFAULT 86400,
  "last_fired_at" bigint,
  "created_at" bigint NOT NULL,
  "source_session_id" text COLLATE "C",
  PRIMARY KEY ("intent_key"),
  CHECK ("creator_sender" IS NULL OR (char_length(btrim("creator_sender")) > 0)),
  CHECK (("status" IN ('pending', 'armed', 'fired', 'done', 'cancelled', 'expired'))),
  CHECK (("max_fires" > 0)),
  CHECK (("fire_count" >= 0)),
  CHECK (("cooldown_seconds" >= 0)),
  UNIQUE ("id")
);

CREATE TABLE "trajectory_runtime_events" (
  "session_id" text COLLATE "C" NOT NULL,
  "seq" bigint NOT NULL,
  "run_id" text COLLATE "C",
  "event_json" text COLLATE "C" NOT NULL,
  "created_at" bigint NOT NULL,
  "event_utf8_bytes" bigint,
  "event_payload" bytea,
  "event_codec" text COLLATE "C",
  PRIMARY KEY ("session_id", "seq")
);

CREATE TABLE "transcript_event_identities" (
  "session_id" text COLLATE "C" NOT NULL,
  "event_id" text COLLATE "C" NOT NULL,
  "seq" bigint NOT NULL,
  "event_type" text COLLATE "C",
  "parent_id" text COLLATE "C",
  "message_idempotency_key" text COLLATE "C",
  "created_at" bigint NOT NULL,
  PRIMARY KEY ("session_id", "event_id")
);

CREATE TABLE "transcript_events" (
  "session_id" text COLLATE "C" NOT NULL,
  "seq" bigint NOT NULL,
  "event_json" text COLLATE "C",
  "created_at" bigint NOT NULL,
  "event_zstd" bytea,
  "event_utf8_bytes" bigint,
  "navigation_json" text COLLATE "C",
  "navigation_type" text COLLATE "C",
  "navigation_custom_type" text COLLATE "C",
  "navigation_display" bigint NOT NULL DEFAULT 0,
  "message_role" text COLLATE "C",
  "navigation_last_type" text COLLATE "C",
  "navigation_last_custom_type" text COLLATE "C",
  "navigation_valid" bigint NOT NULL DEFAULT 1,
  PRIMARY KEY ("session_id", "seq"),
  CHECK ("event_utf8_bytes" IS NULL OR ("event_utf8_bytes" >= 0)),
  CHECK (("event_json" IS NOT NULL AND "event_zstd" IS NULL) OR ("event_json" IS NULL AND "event_zstd" IS NOT NULL AND "event_utf8_bytes" IS NOT NULL AND ("event_utf8_bytes" BETWEEN 1 AND 4194304) AND (octet_length("event_zstd") BETWEEN 1 AND 4194304) AND "navigation_json" IS NOT NULL) OR ("event_json" IS NULL AND "event_zstd" IS NULL AND "event_utf8_bytes" IS NOT NULL AND ("event_utf8_bytes" BETWEEN 1 AND 4194304) AND "navigation_json" IS NOT NULL)),
  CHECK ("openclaw_transcript_navigation_check"("navigation_json"))
);

CREATE TABLE "transcript_rewrite_watermarks" (
  "session_id" text COLLATE "C" NOT NULL,
  "generation" text COLLATE "C" NOT NULL,
  "updated_at" bigint NOT NULL,
  PRIMARY KEY ("session_id")
);

CREATE INDEX "idx_agent_acp_parent_stream_run" ON "acp_parent_stream_events" (("run_id") ASC, ("seq") ASC);

CREATE INDEX "idx_agent_board_widgets_tab_position" ON "board_widgets" (("session_key") ASC, ("tab_id") ASC, ("position") ASC);

CREATE INDEX "idx_agent_cache_expiry" ON "cache_entries" (("scope") ASC, ("expires_at") ASC, ("key") ASC) WHERE "expires_at" IS NOT NULL;

CREATE INDEX "idx_agent_cache_updated" ON "cache_entries" (("scope") ASC, ("updated_at") DESC, ("key") ASC);

CREATE INDEX "idx_agent_voice_session_open_scope" ON "cache_entries" ((CASE WHEN ("value_json" IS JSON) THEN CASE WHEN json_typeof(("value_json"::json -> 'agentId')) = 'string' THEN (("value_json"::json -> 'agentId') #>> '{}') END ELSE NULL END) ASC NULLS FIRST, (CASE WHEN ("value_json" IS JSON) THEN CASE WHEN json_typeof(("value_json"::json -> 'sessionKey')) = 'string' THEN (("value_json"::json -> 'sessionKey') #>> '{}') END ELSE NULL END) ASC NULLS FIRST, (CASE WHEN ("value_json" IS JSON) THEN CASE WHEN json_typeof(("value_json"::json -> 'origin')) = 'string' THEN (("value_json"::json -> 'origin') #>> '{}') END ELSE NULL END) ASC NULLS FIRST) WHERE ("scope" = 'talk-client-voice-sessions') AND (CASE WHEN ("value_json" IS JSON) THEN CASE WHEN json_typeof(("value_json"::json -> 'status')) = 'string' THEN (("value_json"::json -> 'status') #>> '{}') END ELSE NULL END = 'open');

CREATE INDEX "idx_agent_voice_session_open_updated" ON "cache_entries" (("scope") ASC, ("updated_at") ASC) WHERE ("scope" = 'talk-client-voice-sessions') AND (CASE WHEN ("value_json" IS JSON) THEN CASE WHEN json_typeof(("value_json"::json -> 'status')) = 'string' THEN (("value_json"::json -> 'status') #>> '{}') END ELSE NULL END = 'open');

CREATE INDEX "idx_agent_context_engine_turn_outbox_engine" ON "context_engine_turn_outbox" (("engine_id") ASC, ("created_at") ASC);

CREATE INDEX "idx_agent_conversation_deliveries_reply" ON "conversation_deliveries" (("conversation_id") ASC, ("platform_message_id") ASC NULLS FIRST, ("prepared_message_id") ASC NULLS FIRST) WHERE ("status" IN ('queued', 'sent', 'replied'));

CREATE INDEX "idx_agent_conversation_deliveries_source_session" ON "conversation_deliveries" (("source_session_key") ASC NULLS FIRST, ("operation_id") ASC);

CREATE INDEX "idx_agent_conversation_deliveries_updated" ON "conversation_deliveries" (("updated_at") DESC, ("operation_id") ASC);

CREATE UNIQUE INDEX "idx_agent_conversations_identity" ON "conversations" (("channel") ASC, ("account_id") ASC, ("kind") ASC, ("peer_id") ASC, (coalesce("parent_conversation_id", '')) ASC NULLS FIRST, (coalesce("thread_id", '')) ASC NULLS FIRST);

CREATE INDEX "idx_agent_conversations_lookup" ON "conversations" (("channel") ASC, ("account_id") ASC, ("kind") ASC, ("peer_id") ASC, ("thread_id") ASC NULLS FIRST);

CREATE INDEX "idx_agent_conversations_updated" ON "conversations" (("updated_at") DESC, ("conversation_id") ASC);

CREATE INDEX "idx_memory_embedding_cache_updated_at" ON "memory_embedding_cache" (("updated_at") ASC);

CREATE INDEX "idx_memory_index_chunks_path_source" ON "memory_index_chunks" (("path") ASC, ("source") ASC);

CREATE INDEX "idx_memory_index_chunks_source" ON "memory_index_chunks" (("source") ASC);

CREATE INDEX "idx_memory_index_sources_source" ON "memory_index_sources" (("source") ASC);

CREATE INDEX "idx_agent_message_tool_run_outcomes_occurred" ON "message_tool_run_outcomes" (("occurred_at") DESC, ("id") DESC);

CREATE INDEX "idx_agent_session_conversations_conversation" ON "session_conversations" (("conversation_id") ASC, ("last_seen_at") DESC, ("session_id") ASC);

CREATE UNIQUE INDEX "idx_agent_session_conversations_primary" ON "session_conversations" (("session_id") ASC) WHERE ("role" = 'primary');

CREATE INDEX "idx_agent_session_creation_operations_expiry" ON "session_creation_operations" (("expires_at") ASC);

CREATE INDEX "idx_agent_session_goal_operations_expiry" ON "session_goal_operations" (("expires_at") ASC);

CREATE INDEX "idx_agent_session_input_completions_session_key" ON "session_input_completions" (("session_key") ASC);

CREATE INDEX "idx_agent_session_members_identity" ON "session_members" (("identity_id") ASC, ("session_key") ASC);

CREATE INDEX "idx_agent_session_nodes_active" ON "session_nodes" (("session_key") ASC) WHERE "archived_at" IS NULL;

CREATE INDEX "idx_agent_session_nodes_archived_at" ON "session_nodes" (("archived_at") ASC, ("session_key") ASC) WHERE "archived_at" IS NOT NULL;

CREATE INDEX "idx_agent_session_nodes_current_session_id" ON "session_nodes" (("current_session_id") ASC);

CREATE INDEX "idx_agent_session_nodes_entry_not_valid" ON "session_nodes" (("session_key") ASC) WHERE ("entry_valid" != 1);

CREATE INDEX "idx_agent_session_nodes_entry_valid_pending" ON "session_nodes" (("session_key") ASC) WHERE ("entry_valid" = 0);

CREATE INDEX "idx_agent_session_nodes_label" ON "session_nodes" (("label") ASC, ("session_key") ASC) WHERE "label" IS NOT NULL;

CREATE INDEX "idx_agent_session_nodes_parent_session_key" ON "session_nodes" (("parent_session_key") ASC NULLS FIRST, ("session_key") ASC);

CREATE INDEX "idx_agent_session_nodes_spawned_by" ON "session_nodes" (("spawned_by") ASC NULLS FIRST, ("session_key") ASC);

CREATE INDEX "idx_agent_session_nodes_status" ON "session_nodes" (("status") ASC, ("session_key") ASC) WHERE "status" IS NOT NULL;

CREATE INDEX "idx_agent_session_nodes_updated_at" ON "session_nodes" (("updated_at") DESC, ("session_key") ASC);

CREATE INDEX "idx_agent_session_pending_inputs_session" ON "session_pending_inputs" (("session_key") ASC, ("session_id") ASC, ("seq") DESC);

CREATE INDEX "idx_agent_session_suggestions_author_created" ON "session_suggestions" (("author_id") ASC, ("created_at") ASC, ("id") ASC);

CREATE INDEX "idx_agent_session_suggestions_session_state_created" ON "session_suggestions" (("session_key") ASC, ("state") ASC, ("created_at") ASC, ("id") ASC);

CREATE UNIQUE INDEX "idx_agent_transcript_active_event_seq" ON "session_transcript_active_events" (("session_id") ASC, ("event_seq") ASC);

CREATE UNIQUE INDEX "idx_agent_transcript_active_messages" ON "session_transcript_active_events" (("session_id") ASC, ("message_position") ASC) WHERE "message_position" IS NOT NULL;

CREATE INDEX "idx_agent_transcript_context_pending" ON "session_transcript_active_events" (("session_id") ASC) WHERE "context_eligible" IS NULL;

CREATE INDEX "idx_agent_session_transcript_archives_pending" ON "session_transcript_archives" (("created_at") ASC, ("session_id") ASC, ("generation") ASC) WHERE "published_at" IS NULL;

CREATE INDEX "idx_agent_session_transcript_archives_retention" ON "session_transcript_archives" (("created_at") ASC, ("session_id") ASC, ("generation") ASC);

CREATE INDEX "idx_session_transcript_fts_rows_session_message" ON "session_transcript_fts_rows" (("session_id") ASC, ("message_id") ASC NULLS FIRST);

CREATE INDEX "idx_agent_session_windows_conversation" ON "session_windows" (("primary_conversation_id") ASC) WHERE "primary_conversation_id" IS NOT NULL;

CREATE INDEX "idx_agent_session_windows_created_at" ON "session_windows" (("created_at") DESC, ("session_id") ASC);

CREATE INDEX "idx_agent_session_windows_session_key" ON "session_windows" (("session_key") ASC, ("updated_at") DESC, ("session_id") ASC);

CREATE INDEX "idx_agent_session_windows_updated_at" ON "session_windows" (("updated_at") DESC, ("session_id") ASC);

CREATE INDEX "idx_standing_intents_lifecycle" ON "standing_intents" (("status") ASC, ("expires_at") ASC, ("last_fired_at") ASC NULLS FIRST);

CREATE INDEX "idx_standing_intents_scope" ON "standing_intents" (("status") ASC, ("channel_scope") ASC NULLS FIRST, ("sender_scope") ASC NULLS FIRST);

CREATE INDEX "idx_agent_trajectory_runtime_run" ON "trajectory_runtime_events" (("session_id") ASC, ("run_id") ASC NULLS FIRST, ("created_at") ASC, (coalesce("event_utf8_bytes", octet_length("event_json"))) ASC NULLS FIRST);

CREATE INDEX "idx_agent_transcript_event_identity_sequence" ON "transcript_event_identities" (("session_id") ASC, ("seq") ASC);

CREATE INDEX "idx_agent_transcript_event_sequence" ON "transcript_event_identities" (("session_id") ASC, ("event_type") ASC NULLS FIRST, ("seq") DESC);

CREATE UNIQUE INDEX "idx_agent_transcript_message_idempotency" ON "transcript_event_identities" (("session_id") ASC, ("message_idempotency_key") ASC) WHERE "message_idempotency_key" IS NOT NULL;

CREATE INDEX "idx_memory_index_sources_exact_path" ON "memory_index_sources" ((pg_catalog.md5(pg_catalog.lower(pg_catalog.normalize(pg_catalog.regexp_replace(pg_catalog.replace(pg_catalog.btrim(path), E'\\\\', '/'), '^\\./', ''), 'NFC')))));

CREATE INDEX "idx_memory_index_sources_basename" ON "memory_index_sources" ((pg_catalog.md5(pg_catalog.regexp_replace(pg_catalog.lower(pg_catalog.normalize(pg_catalog.regexp_replace(pg_catalog.replace(pg_catalog.btrim(path), E'\\\\', '/'), '^\\./', ''), 'NFC')), '^.*/', ''))));

CREATE INDEX "idx_memory_index_sources_stem" ON "memory_index_sources" ((pg_catalog.md5(pg_catalog.regexp_replace(pg_catalog.regexp_replace(pg_catalog.lower(pg_catalog.normalize(pg_catalog.regexp_replace(pg_catalog.replace(pg_catalog.btrim(path), E'\\\\', '/'), '^\\./', ''), 'NFC')), '^.*/', ''), '^(.+)\\.[^.]*$', '\\1'))));

ALTER TABLE "acp_parent_stream_events" ADD FOREIGN KEY ("session_id") REFERENCES "session_windows" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "board_tabs" ADD FOREIGN KEY ("session_key") REFERENCES "session_nodes" ("session_key") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "board_widgets" ADD FOREIGN KEY ("session_key", "tab_id") REFERENCES "board_tabs" ("session_key", "tab_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "conversation_deliveries" ADD FOREIGN KEY ("conversation_id") REFERENCES "conversations" ("conversation_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "heartbeat_outcomes" ADD FOREIGN KEY ("session_key") REFERENCES "session_nodes" ("session_key") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "memory_index_chunk_provenance" ADD FOREIGN KEY ("chunk_id") REFERENCES "memory_index_chunks" ("id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "memory_index_chunk_recall_metadata" ADD FOREIGN KEY ("chunk_id") REFERENCES "memory_index_chunks" ("id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "session_conversations" ADD FOREIGN KEY ("conversation_id") REFERENCES "conversations" ("conversation_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "session_conversations" ADD FOREIGN KEY ("session_id") REFERENCES "session_windows" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "session_entry_snapshots" ADD FOREIGN KEY ("session_key") REFERENCES "session_nodes" ("session_key") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "session_input_completions" ADD FOREIGN KEY ("session_id") REFERENCES "session_windows" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "session_input_completions" ADD FOREIGN KEY ("session_key") REFERENCES "session_nodes" ("session_key") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "session_members" ADD FOREIGN KEY ("session_key") REFERENCES "session_nodes" ("session_key") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "session_participants" ADD FOREIGN KEY ("session_key") REFERENCES "session_nodes" ("session_key") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "session_pending_inputs" ADD FOREIGN KEY ("session_id") REFERENCES "session_windows" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "session_pending_inputs" ADD FOREIGN KEY ("session_key") REFERENCES "session_nodes" ("session_key") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "session_progress_cards" ADD FOREIGN KEY ("session_key") REFERENCES "session_nodes" ("session_key") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "session_reactions" ADD FOREIGN KEY ("session_key") REFERENCES "session_nodes" ("session_key") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "session_suggestions" ADD FOREIGN KEY ("session_key") REFERENCES "session_nodes" ("session_key") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "session_transcript_active_event_facts" ADD FOREIGN KEY ("session_id", "seq") REFERENCES "session_transcript_active_events" ("session_id", "event_seq") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "session_transcript_active_events" ADD FOREIGN KEY ("session_id", "event_seq") REFERENCES "transcript_events" ("session_id", "seq") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "session_transcript_cold_archive_chunks" ADD FOREIGN KEY ("session_id") REFERENCES "session_transcript_cold_archives" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "session_transcript_cold_archives" ADD FOREIGN KEY ("session_id") REFERENCES "session_windows" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "session_transcript_index_state" ADD FOREIGN KEY ("session_id") REFERENCES "session_windows" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "session_windows" ADD FOREIGN KEY ("primary_conversation_id") REFERENCES "conversations" ("conversation_id") ON UPDATE NO ACTION ON DELETE SET NULL NOT DEFERRABLE;

ALTER TABLE "session_windows" ADD FOREIGN KEY ("session_key") REFERENCES "session_nodes" ("session_key") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "trajectory_runtime_events" ADD FOREIGN KEY ("session_id") REFERENCES "session_windows" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "transcript_event_identities" ADD FOREIGN KEY ("session_id", "seq") REFERENCES "transcript_events" ("session_id", "seq") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "transcript_events" ADD FOREIGN KEY ("session_id") REFERENCES "session_windows" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

ALTER TABLE "transcript_rewrite_watermarks" ADD FOREIGN KEY ("session_id") REFERENCES "session_windows" ("session_id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE;

CREATE FUNCTION "openclaw_session_conversations_trigger"() RETURNS trigger LANGUAGE plpgsql SET search_path FROM CURRENT AS $trigger$
BEGIN
  UPDATE session_conversations SET route_context_json = NULL WHERE session_id = NEW.session_id AND conversation_id = NEW.conversation_id AND role = NEW.role;
  RETURN NULL;
END;
$trigger$;

CREATE FUNCTION "openclaw_session_entry_snapshots_trigger"() RETURNS trigger LANGUAGE plpgsql SET search_path FROM CURRENT AS $trigger$
BEGIN
  IF TG_OP = 'DELETE' THEN
    UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1 WHERE session_key = OLD.session_key;
  ELSIF TG_OP = 'INSERT' THEN
    UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1 WHERE session_key = NEW.session_key;
  ELSIF TG_OP = 'UPDATE' THEN
    UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1 WHERE session_key IN (OLD.session_key, NEW.session_key);
  END IF;
  RETURN NULL;
END;
$trigger$;

CREATE TRIGGER "session_conversations_route_context_invalidate_after_update" AFTER UPDATE OF "role", "last_seen_at" ON "session_conversations" FOR EACH ROW WHEN (NEW.route_context_json IS NOT DISTINCT FROM OLD.route_context_json) EXECUTE FUNCTION "openclaw_session_conversations_trigger"();

CREATE TRIGGER "session_entry_snapshots_after_delete" AFTER DELETE ON "session_entry_snapshots" FOR EACH ROW EXECUTE FUNCTION "openclaw_session_entry_snapshots_trigger"();

CREATE TRIGGER "session_entry_snapshots_after_insert" AFTER INSERT ON "session_entry_snapshots" FOR EACH ROW EXECUTE FUNCTION "openclaw_session_entry_snapshots_trigger"();

CREATE TRIGGER "session_entry_snapshots_after_update" AFTER UPDATE OF "session_key", "field", "value_json" ON "session_entry_snapshots" FOR EACH ROW WHEN (NEW.session_key IS DISTINCT FROM OLD.session_key OR NEW.field IS DISTINCT FROM OLD.field OR NEW.value_json IS DISTINCT FROM OLD.value_json) EXECUTE FUNCTION "openclaw_session_entry_snapshots_trigger"();
`;return Object.defineProperty(this,"sql",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},get expectedCatalog(){let e=[{table:`acp_parent_stream_events`,kind:`table`,value:null},{table:`acp_parent_stream_events`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`acp_parent_stream_events`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`acp_parent_stream_events`,kind:`column`,value:{name:`seq`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`acp_parent_stream_events`,kind:`column`,value:{name:`event_json`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`acp_parent_stream_events`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`acp_parent_stream_events`,kind:`primaryKey`,value:[`session_id`,`run_id`,`seq`]},{table:`acp_parent_stream_events`,kind:`foreignKey`,value:{columns:[`session_id`],target:`session_windows`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`acp_parent_stream_events`,kind:`indexes`,value:2},{table:`acp_parent_stream_events`,kind:`checks`,value:0},{table:`agent_tool_usage`,kind:`table`,value:null},{table:`agent_tool_usage`,kind:`column`,value:{name:`tool_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`agent_tool_usage`,kind:`column`,value:{name:`score`,type:`double precision`,nullable:!1,identity:!1,default:null,position:2}},{table:`agent_tool_usage`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`agent_tool_usage`,kind:`primaryKey`,value:[`tool_id`]},{table:`agent_tool_usage`,kind:`indexes`,value:1},{table:`agent_tool_usage`,kind:`checks`,value:1},{table:`auth_profile_state`,kind:`table`,value:null},{table:`auth_profile_state`,kind:`column`,value:{name:`state_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`auth_profile_state`,kind:`column`,value:{name:`state_json`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`auth_profile_state`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`auth_profile_state`,kind:`primaryKey`,value:[`state_key`]},{table:`auth_profile_state`,kind:`indexes`,value:1},{table:`auth_profile_state`,kind:`checks`,value:0},{table:`auth_profile_store`,kind:`table`,value:null},{table:`auth_profile_store`,kind:`column`,value:{name:`store_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`auth_profile_store`,kind:`column`,value:{name:`store_json`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`auth_profile_store`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`auth_profile_store`,kind:`primaryKey`,value:[`store_key`]},{table:`auth_profile_store`,kind:`indexes`,value:1},{table:`auth_profile_store`,kind:`checks`,value:0},{table:`board_tabs`,kind:`table`,value:null},{table:`board_tabs`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`board_tabs`,kind:`column`,value:{name:`tab_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`board_tabs`,kind:`column`,value:{name:`title`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`board_tabs`,kind:`column`,value:{name:`position`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`board_tabs`,kind:`column`,value:{name:`chat_dock`,type:`text`,nullable:!1,identity:!1,default:`'right'`,position:5}},{table:`board_tabs`,kind:`column`,value:{name:`created_by`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`board_tabs`,kind:`column`,value:{name:`revision`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`board_tabs`,kind:`primaryKey`,value:[`session_key`,`tab_id`]},{table:`board_tabs`,kind:`foreignKey`,value:{columns:[`session_key`],target:`session_nodes`,targetColumns:[`session_key`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`board_tabs`,kind:`indexes`,value:1},{table:`board_tabs`,kind:`checks`,value:4},{table:`board_widgets`,kind:`table`,value:null},{table:`board_widgets`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`board_widgets`,kind:`column`,value:{name:`name`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`board_widgets`,kind:`column`,value:{name:`tab_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`board_widgets`,kind:`column`,value:{name:`title`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`board_widgets`,kind:`column`,value:{name:`content_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`board_widgets`,kind:`column`,value:{name:`html`,type:`bytea`,nullable:!0,identity:!1,default:null,position:6}},{table:`board_widgets`,kind:`column`,value:{name:`descriptor_json`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`board_widgets`,kind:`column`,value:{name:`sha256`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`board_widgets`,kind:`column`,value:{name:`view_generation`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`board_widgets`,kind:`column`,value:{name:`revision`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`board_widgets`,kind:`column`,value:{name:`size_w`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`board_widgets`,kind:`column`,value:{name:`size_h`,type:`bigint`,nullable:!1,identity:!1,default:null,position:12}},{table:`board_widgets`,kind:`column`,value:{name:`position`,type:`bigint`,nullable:!1,identity:!1,default:null,position:13}},{table:`board_widgets`,kind:`column`,value:{name:`manifest`,type:`text`,nullable:!1,identity:!1,default:`'{}'`,position:14}},{table:`board_widgets`,kind:`column`,value:{name:`grant_state`,type:`text`,nullable:!1,identity:!1,default:`'none'`,position:15}},{table:`board_widgets`,kind:`column`,value:{name:`granted_sha`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`board_widgets`,kind:`column`,value:{name:`created_by`,type:`text`,nullable:!1,identity:!1,default:null,position:17}},{table:`board_widgets`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:18}},{table:`board_widgets`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:19}},{table:`board_widgets`,kind:`primaryKey`,value:[`session_key`,`name`]},{table:`board_widgets`,kind:`foreignKey`,value:{columns:[`session_key`,`tab_id`],target:`board_tabs`,targetColumns:[`session_key`,`tab_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`board_widgets`,kind:`indexes`,value:2},{table:`board_widgets`,kind:`checks`,value:8},{table:`cache_entries`,kind:`table`,value:null},{table:`cache_entries`,kind:`column`,value:{name:`scope`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`cache_entries`,kind:`column`,value:{name:`key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`cache_entries`,kind:`column`,value:{name:`value_json`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`cache_entries`,kind:`column`,value:{name:`blob`,type:`bytea`,nullable:!0,identity:!1,default:null,position:4}},{table:`cache_entries`,kind:`column`,value:{name:`expires_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:5}},{table:`cache_entries`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`cache_entries`,kind:`primaryKey`,value:[`scope`,`key`]},{table:`cache_entries`,kind:`indexes`,value:5},{table:`cache_entries`,kind:`checks`,value:0},{table:`context_engine_turn_outbox`,kind:`table`,value:null},{table:`context_engine_turn_outbox`,kind:`column`,value:{name:`enqueue_sequence`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`context_engine_turn_outbox`,kind:`column`,value:{name:`advancement_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`context_engine_turn_outbox`,kind:`column`,value:{name:`engine_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`context_engine_turn_outbox`,kind:`column`,value:{name:`owner_plugin_id`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`context_engine_turn_outbox`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`context_engine_turn_outbox`,kind:`column`,value:{name:`payload_json`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`context_engine_turn_outbox`,kind:`column`,value:{name:`payload_state`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`context_engine_turn_outbox`,kind:`column`,value:{name:`attempt_count`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:8}},{table:`context_engine_turn_outbox`,kind:`column`,value:{name:`last_attempt_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:9}},{table:`context_engine_turn_outbox`,kind:`column`,value:{name:`last_error`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`context_engine_turn_outbox`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`context_engine_turn_outbox`,kind:`primaryKey`,value:[`enqueue_sequence`]},{table:`context_engine_turn_outbox`,kind:`unique`,value:[`advancement_key`]},{table:`context_engine_turn_outbox`,kind:`indexes`,value:3},{table:`context_engine_turn_outbox`,kind:`checks`,value:0},{table:`conversation_deliveries`,kind:`table`,value:null},{table:`conversation_deliveries`,kind:`column`,value:{name:`operation_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`conversation_deliveries`,kind:`column`,value:{name:`operation_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`conversation_deliveries`,kind:`column`,value:{name:`conversation_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`conversation_deliveries`,kind:`column`,value:{name:`source_session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`conversation_deliveries`,kind:`column`,value:{name:`message_hash`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`conversation_deliveries`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`conversation_deliveries`,kind:`column`,value:{name:`prepared_message_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`conversation_deliveries`,kind:`column`,value:{name:`platform_message_id`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`conversation_deliveries`,kind:`column`,value:{name:`queue_id`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`conversation_deliveries`,kind:`column`,value:{name:`rejection_error`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`conversation_deliveries`,kind:`column`,value:{name:`reply_message_id`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`conversation_deliveries`,kind:`column`,value:{name:`reply_to_id`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`conversation_deliveries`,kind:`column`,value:{name:`reply_thread_id`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`conversation_deliveries`,kind:`column`,value:{name:`reply_text`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`conversation_deliveries`,kind:`column`,value:{name:`reply_timestamp`,type:`bigint`,nullable:!0,identity:!1,default:null,position:15}},{table:`conversation_deliveries`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:16}},{table:`conversation_deliveries`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:17}},{table:`conversation_deliveries`,kind:`primaryKey`,value:[`operation_id`]},{table:`conversation_deliveries`,kind:`foreignKey`,value:{columns:[`conversation_id`],target:`conversations`,targetColumns:[`conversation_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`conversation_deliveries`,kind:`indexes`,value:4},{table:`conversation_deliveries`,kind:`checks`,value:3},{table:`conversations`,kind:`table`,value:null},{table:`conversations`,kind:`column`,value:{name:`conversation_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`conversations`,kind:`column`,value:{name:`channel`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`conversations`,kind:`column`,value:{name:`account_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`conversations`,kind:`column`,value:{name:`kind`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`conversations`,kind:`column`,value:{name:`peer_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`conversations`,kind:`column`,value:{name:`delivery_target`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`conversations`,kind:`column`,value:{name:`parent_conversation_id`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`conversations`,kind:`column`,value:{name:`thread_id`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`conversations`,kind:`column`,value:{name:`native_channel_id`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`conversations`,kind:`column`,value:{name:`native_direct_user_id`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`conversations`,kind:`column`,value:{name:`label`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`conversations`,kind:`column`,value:{name:`metadata_json`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`conversations`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:13}},{table:`conversations`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:14}},{table:`conversations`,kind:`primaryKey`,value:[`conversation_id`]},{table:`conversations`,kind:`indexes`,value:4},{table:`conversations`,kind:`checks`,value:1},{table:`heartbeat_outcomes`,kind:`table`,value:null},{table:`heartbeat_outcomes`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`heartbeat_outcomes`,kind:`column`,value:{name:`run_session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`heartbeat_outcomes`,kind:`column`,value:{name:`outcome`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`heartbeat_outcomes`,kind:`column`,value:{name:`summary`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`heartbeat_outcomes`,kind:`column`,value:{name:`response_reason`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`heartbeat_outcomes`,kind:`column`,value:{name:`priority`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`heartbeat_outcomes`,kind:`column`,value:{name:`next_check`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`heartbeat_outcomes`,kind:`column`,value:{name:`task_names_json`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`heartbeat_outcomes`,kind:`column`,value:{name:`wake_source`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`heartbeat_outcomes`,kind:`column`,value:{name:`wake_reason`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`heartbeat_outcomes`,kind:`column`,value:{name:`occurred_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`heartbeat_outcomes`,kind:`column`,value:{name:`context_run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`heartbeat_outcomes`,kind:`column`,value:{name:`context_claimed_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:13}},{table:`heartbeat_outcomes`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:14}},{table:`heartbeat_outcomes`,kind:`primaryKey`,value:[`session_key`]},{table:`heartbeat_outcomes`,kind:`foreignKey`,value:{columns:[`session_key`],target:`session_nodes`,targetColumns:[`session_key`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`heartbeat_outcomes`,kind:`indexes`,value:1},{table:`heartbeat_outcomes`,kind:`checks`,value:2},{table:`memory_embedding_cache`,kind:`table`,value:null},{table:`memory_embedding_cache`,kind:`column`,value:{name:`provider`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`memory_embedding_cache`,kind:`column`,value:{name:`model`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`memory_embedding_cache`,kind:`column`,value:{name:`provider_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`memory_embedding_cache`,kind:`column`,value:{name:`hash`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`memory_embedding_cache`,kind:`column`,value:{name:`embedding`,type:`bytea`,nullable:!1,identity:!1,default:null,position:5}},{table:`memory_embedding_cache`,kind:`column`,value:{name:`dims`,type:`bigint`,nullable:!0,identity:!1,default:null,position:6}},{table:`memory_embedding_cache`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`memory_embedding_cache`,kind:`primaryKey`,value:[`provider`,`model`,`provider_key`,`hash`]},{table:`memory_embedding_cache`,kind:`indexes`,value:2},{table:`memory_embedding_cache`,kind:`checks`,value:0},{table:`memory_entry_origins`,kind:`table`,value:null},{table:`memory_entry_origins`,kind:`column`,value:{name:`entry_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`memory_entry_origins`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`memory_entry_origins`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`memory_entry_origins`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`memory_entry_origins`,kind:`column`,value:{name:`origin_class`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`memory_entry_origins`,kind:`column`,value:{name:`observed_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`memory_entry_origins`,kind:`primaryKey`,value:[`entry_key`,`agent_id`,`session_id`]},{table:`memory_entry_origins`,kind:`indexes`,value:1},{table:`memory_entry_origins`,kind:`checks`,value:1},{table:`memory_index_chunk_provenance`,kind:`table`,value:null},{table:`memory_index_chunk_provenance`,kind:`column`,value:{name:`chunk_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`memory_index_chunk_provenance`,kind:`column`,value:{name:`origin_class`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`memory_index_chunk_provenance`,kind:`column`,value:{name:`session_kind`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`memory_index_chunk_provenance`,kind:`column`,value:{name:`observed_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`memory_index_chunk_provenance`,kind:`column`,value:{name:`supersedes_key`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`memory_index_chunk_provenance`,kind:`primaryKey`,value:[`chunk_id`]},{table:`memory_index_chunk_provenance`,kind:`foreignKey`,value:{columns:[`chunk_id`],target:`memory_index_chunks`,targetColumns:[`id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`memory_index_chunk_provenance`,kind:`indexes`,value:1},{table:`memory_index_chunk_provenance`,kind:`checks`,value:2},{table:`memory_index_chunk_recall_metadata`,kind:`table`,value:null},{table:`memory_index_chunk_recall_metadata`,kind:`column`,value:{name:`chunk_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`memory_index_chunk_recall_metadata`,kind:`column`,value:{name:`importance`,type:`bigint`,nullable:!0,identity:!1,default:null,position:2}},{table:`memory_index_chunk_recall_metadata`,kind:`column`,value:{name:`triggers`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`memory_index_chunk_recall_metadata`,kind:`column`,value:{name:`project_key`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`memory_index_chunk_recall_metadata`,kind:`primaryKey`,value:[`chunk_id`]},{table:`memory_index_chunk_recall_metadata`,kind:`foreignKey`,value:{columns:[`chunk_id`],target:`memory_index_chunks`,targetColumns:[`id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`memory_index_chunk_recall_metadata`,kind:`indexes`,value:1},{table:`memory_index_chunk_recall_metadata`,kind:`checks`,value:1},{table:`memory_index_chunks`,kind:`table`,value:null},{table:`memory_index_chunks`,kind:`column`,value:{name:`chunk_rowid`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`memory_index_chunks`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`memory_index_chunks`,kind:`column`,value:{name:`path`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`memory_index_chunks`,kind:`column`,value:{name:`source`,type:`text`,nullable:!1,identity:!1,default:`'memory'`,position:4}},{table:`memory_index_chunks`,kind:`column`,value:{name:`start_line`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`memory_index_chunks`,kind:`column`,value:{name:`end_line`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`memory_index_chunks`,kind:`column`,value:{name:`hash`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`memory_index_chunks`,kind:`column`,value:{name:`model`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`memory_index_chunks`,kind:`column`,value:{name:`text`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`memory_index_chunks`,kind:`column`,value:{name:`embedding`,type:`bytea`,nullable:!1,identity:!1,default:null,position:10}},{table:`memory_index_chunks`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`memory_index_chunks`,kind:`primaryKey`,value:[`chunk_rowid`]},{table:`memory_index_chunks`,kind:`unique`,value:[`id`]},{table:`memory_index_chunks`,kind:`indexes`,value:4},{table:`memory_index_chunks`,kind:`checks`,value:0},{table:`memory_index_meta`,kind:`table`,value:null},{table:`memory_index_meta`,kind:`column`,value:{name:`key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`memory_index_meta`,kind:`column`,value:{name:`value`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`memory_index_meta`,kind:`primaryKey`,value:[`key`]},{table:`memory_index_meta`,kind:`indexes`,value:1},{table:`memory_index_meta`,kind:`checks`,value:0},{table:`memory_index_sources`,kind:`table`,value:null},{table:`memory_index_sources`,kind:`column`,value:{name:`id`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`memory_index_sources`,kind:`column`,value:{name:`path`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`memory_index_sources`,kind:`column`,value:{name:`source`,type:`text`,nullable:!1,identity:!1,default:`'memory'`,position:3}},{table:`memory_index_sources`,kind:`column`,value:{name:`hash`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`memory_index_sources`,kind:`column`,value:{name:`mtime`,type:`double precision`,nullable:!1,identity:!1,default:null,position:5}},{table:`memory_index_sources`,kind:`column`,value:{name:`size`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`memory_index_sources`,kind:`primaryKey`,value:[`id`]},{table:`memory_index_sources`,kind:`unique`,value:[`path`,`source`]},{table:`memory_index_sources`,kind:`indexes`,value:6},{table:`memory_index_sources`,kind:`checks`,value:0},{table:`memory_index_state`,kind:`table`,value:null},{table:`memory_index_state`,kind:`column`,value:{name:`id`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`memory_index_state`,kind:`column`,value:{name:`revision`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`memory_index_state`,kind:`primaryKey`,value:[`id`]},{table:`memory_index_state`,kind:`indexes`,value:1},{table:`memory_index_state`,kind:`checks`,value:1},{table:`memory_session_tombstones`,kind:`table`,value:null},{table:`memory_session_tombstones`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`memory_session_tombstones`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`memory_session_tombstones`,kind:`column`,value:{name:`reason`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`memory_session_tombstones`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`memory_session_tombstones`,kind:`primaryKey`,value:[`session_id`]},{table:`memory_session_tombstones`,kind:`indexes`,value:1},{table:`memory_session_tombstones`,kind:`checks`,value:0},{table:`message_tool_run_outcomes`,kind:`table`,value:null},{table:`message_tool_run_outcomes`,kind:`column`,value:{name:`id`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`message_tool_run_outcomes`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`message_tool_run_outcomes`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`message_tool_run_outcomes`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`message_tool_run_outcomes`,kind:`column`,value:{name:`provider`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`message_tool_run_outcomes`,kind:`column`,value:{name:`model`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`message_tool_run_outcomes`,kind:`column`,value:{name:`outcome`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`message_tool_run_outcomes`,kind:`column`,value:{name:`run_status`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`message_tool_run_outcomes`,kind:`column`,value:{name:`occurred_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`message_tool_run_outcomes`,kind:`primaryKey`,value:[`id`]},{table:`message_tool_run_outcomes`,kind:`indexes`,value:2},{table:`message_tool_run_outcomes`,kind:`checks`,value:2},{table:`schema_meta`,kind:`table`,value:null},{table:`schema_meta`,kind:`column`,value:{name:`meta_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`schema_meta`,kind:`column`,value:{name:`role`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`schema_meta`,kind:`column`,value:{name:`schema_version`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`schema_meta`,kind:`column`,value:{name:`agent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`schema_meta`,kind:`column`,value:{name:`app_version`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`schema_meta`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`schema_meta`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`schema_meta`,kind:`primaryKey`,value:[`meta_key`]},{table:`schema_meta`,kind:`indexes`,value:1},{table:`schema_meta`,kind:`checks`,value:0},{table:`session_canonical_validation_pending`,kind:`table`,value:null},{table:`session_canonical_validation_pending`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_canonical_validation_pending`,kind:`primaryKey`,value:[`session_key`]},{table:`session_canonical_validation_pending`,kind:`indexes`,value:1},{table:`session_canonical_validation_pending`,kind:`checks`,value:0},{table:`session_conversations`,kind:`table`,value:null},{table:`session_conversations`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_conversations`,kind:`column`,value:{name:`conversation_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_conversations`,kind:`column`,value:{name:`role`,type:`text`,nullable:!1,identity:!1,default:`'primary'`,position:3}},{table:`session_conversations`,kind:`column`,value:{name:`route_context_json`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`session_conversations`,kind:`column`,value:{name:`first_seen_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`session_conversations`,kind:`column`,value:{name:`last_seen_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`session_conversations`,kind:`primaryKey`,value:[`session_id`,`conversation_id`,`role`]},{table:`session_conversations`,kind:`foreignKey`,value:{columns:[`conversation_id`],target:`conversations`,targetColumns:[`conversation_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`session_conversations`,kind:`foreignKey`,value:{columns:[`session_id`],target:`session_windows`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`session_conversations`,kind:`indexes`,value:3},{table:`session_conversations`,kind:`checks`,value:1},{table:`session_creation_operations`,kind:`table`,value:null},{table:`session_creation_operations`,kind:`column`,value:{name:`operation_digest`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_creation_operations`,kind:`column`,value:{name:`request_fingerprint`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_creation_operations`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_creation_operations`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`session_creation_operations`,kind:`column`,value:{name:`lifecycle_revision`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`session_creation_operations`,kind:`column`,value:{name:`role`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`session_creation_operations`,kind:`column`,value:{name:`scopes_json`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`session_creation_operations`,kind:`column`,value:{name:`expires_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`session_creation_operations`,kind:`primaryKey`,value:[`operation_digest`]},{table:`session_creation_operations`,kind:`indexes`,value:2},{table:`session_creation_operations`,kind:`checks`,value:0},{table:`session_entry_snapshots`,kind:`table`,value:null},{table:`session_entry_snapshots`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_entry_snapshots`,kind:`column`,value:{name:`field`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_entry_snapshots`,kind:`column`,value:{name:`value_json`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_entry_snapshots`,kind:`primaryKey`,value:[`session_key`,`field`]},{table:`session_entry_snapshots`,kind:`foreignKey`,value:{columns:[`session_key`],target:`session_nodes`,targetColumns:[`session_key`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`session_entry_snapshots`,kind:`indexes`,value:1},{table:`session_entry_snapshots`,kind:`checks`,value:1},{table:`session_goal_operations`,kind:`table`,value:null},{table:`session_goal_operations`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_goal_operations`,kind:`column`,value:{name:`operation_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_goal_operations`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_goal_operations`,kind:`column`,value:{name:`request_fingerprint`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`session_goal_operations`,kind:`column`,value:{name:`result_json`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`session_goal_operations`,kind:`column`,value:{name:`expires_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`session_goal_operations`,kind:`primaryKey`,value:[`session_key`,`operation_id`]},{table:`session_goal_operations`,kind:`indexes`,value:2},{table:`session_goal_operations`,kind:`checks`,value:0},{table:`session_input_completions`,kind:`table`,value:null},{table:`session_input_completions`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_input_completions`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_input_completions`,kind:`column`,value:{name:`idempotency_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_input_completions`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`session_input_completions`,kind:`column`,value:{name:`request_hash`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`session_input_completions`,kind:`column`,value:{name:`outcome_json`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`session_input_completions`,kind:`column`,value:{name:`succeeded`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`session_input_completions`,kind:`column`,value:{name:`completed_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`session_input_completions`,kind:`primaryKey`,value:[`session_id`,`idempotency_key`]},{table:`session_input_completions`,kind:`foreignKey`,value:{columns:[`session_id`],target:`session_windows`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`session_input_completions`,kind:`foreignKey`,value:{columns:[`session_key`],target:`session_nodes`,targetColumns:[`session_key`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`session_input_completions`,kind:`indexes`,value:2},{table:`session_input_completions`,kind:`checks`,value:1},{table:`session_key_contract`,kind:`table`,value:null},{table:`session_key_contract`,kind:`column`,value:{name:`id`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`session_key_contract`,kind:`column`,value:{name:`main_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_key_contract`,kind:`column`,value:{name:`canonical_ready`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`session_key_contract`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`session_key_contract`,kind:`primaryKey`,value:[`id`]},{table:`session_key_contract`,kind:`indexes`,value:1},{table:`session_key_contract`,kind:`checks`,value:1},{table:`session_members`,kind:`table`,value:null},{table:`session_members`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_members`,kind:`column`,value:{name:`identity_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_members`,kind:`column`,value:{name:`added_by`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_members`,kind:`column`,value:{name:`added_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`session_members`,kind:`primaryKey`,value:[`session_key`,`identity_id`]},{table:`session_members`,kind:`foreignKey`,value:{columns:[`session_key`],target:`session_nodes`,targetColumns:[`session_key`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`session_members`,kind:`indexes`,value:2},{table:`session_members`,kind:`checks`,value:0},{table:`session_nodes`,kind:`table`,value:null},{table:`session_nodes`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_nodes`,kind:`column`,value:{name:`current_session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_nodes`,kind:`column`,value:{name:`entry_json`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_nodes`,kind:`column`,value:{name:`session_started_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:4}},{table:`session_nodes`,kind:`column`,value:{name:`has_optional_references`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:5}},{table:`session_nodes`,kind:`column`,value:{name:`snapshot_revision`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:6}},{table:`session_nodes`,kind:`column`,value:{name:`legacy_acp_migration_json`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`session_nodes`,kind:`column`,value:{name:`entry_valid`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:8}},{table:`session_nodes`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`session_nodes`,kind:`column`,value:{name:`status`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`session_nodes`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:11}},{table:`session_nodes`,kind:`column`,value:{name:`created_via`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`session_nodes`,kind:`column`,value:{name:`created_actor_type`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`session_nodes`,kind:`column`,value:{name:`created_actor_id`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`session_nodes`,kind:`column`,value:{name:`owner_actor_type`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`session_nodes`,kind:`column`,value:{name:`owner_actor_id`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`session_nodes`,kind:`column`,value:{name:`owner_assigned_by_type`,type:`text`,nullable:!0,identity:!1,default:null,position:17}},{table:`session_nodes`,kind:`column`,value:{name:`owner_assigned_by_id`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`session_nodes`,kind:`column`,value:{name:`owner_assigned_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:19}},{table:`session_nodes`,kind:`column`,value:{name:`project_id`,type:`text`,nullable:!0,identity:!1,default:null,position:20}},{table:`session_nodes`,kind:`column`,value:{name:`parent_session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:21}},{table:`session_nodes`,kind:`column`,value:{name:`spawned_by`,type:`text`,nullable:!0,identity:!1,default:null,position:22}},{table:`session_nodes`,kind:`column`,value:{name:`fork_source_session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:23}},{table:`session_nodes`,kind:`column`,value:{name:`fork_source_session_id`,type:`text`,nullable:!0,identity:!1,default:null,position:24}},{table:`session_nodes`,kind:`column`,value:{name:`fork_source_entry_id`,type:`text`,nullable:!0,identity:!1,default:null,position:25}},{table:`session_nodes`,kind:`column`,value:{name:`label`,type:`text`,nullable:!0,identity:!1,default:null,position:26}},{table:`session_nodes`,kind:`column`,value:{name:`display_name`,type:`text`,nullable:!0,identity:!1,default:null,position:27}},{table:`session_nodes`,kind:`column`,value:{name:`category`,type:`text`,nullable:!0,identity:!1,default:null,position:28}},{table:`session_nodes`,kind:`column`,value:{name:`icon`,type:`text`,nullable:!0,identity:!1,default:null,position:29}},{table:`session_nodes`,kind:`column`,value:{name:`pinned_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:30}},{table:`session_nodes`,kind:`column`,value:{name:`archived_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:31}},{table:`session_nodes`,kind:`column`,value:{name:`last_read_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:32}},{table:`session_nodes`,kind:`column`,value:{name:`last_interaction_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:33}},{table:`session_nodes`,kind:`column`,value:{name:`last_activity_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:34}},{table:`session_nodes`,kind:`primaryKey`,value:[`session_key`]},{table:`session_nodes`,kind:`indexes`,value:11},{table:`session_nodes`,kind:`checks`,value:4},{table:`session_participants`,kind:`table`,value:null},{table:`session_participants`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_participants`,kind:`column`,value:{name:`identity_namespace`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_participants`,kind:`column`,value:{name:`actor_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_participants`,kind:`column`,value:{name:`contribution_count`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`session_participants`,kind:`column`,value:{name:`first_prompted_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:5}},{table:`session_participants`,kind:`column`,value:{name:`last_prompted_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:6}},{table:`session_participants`,kind:`primaryKey`,value:[`session_key`,`identity_namespace`,`actor_id`]},{table:`session_participants`,kind:`foreignKey`,value:{columns:[`session_key`],target:`session_nodes`,targetColumns:[`session_key`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`session_participants`,kind:`indexes`,value:1},{table:`session_participants`,kind:`checks`,value:0},{table:`session_pending_inputs`,kind:`table`,value:null},{table:`session_pending_inputs`,kind:`column`,value:{name:`seq`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`session_pending_inputs`,kind:`column`,value:{name:`input_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_pending_inputs`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_pending_inputs`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`session_pending_inputs`,kind:`column`,value:{name:`idempotency_key`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`session_pending_inputs`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!1,identity:!1,default:null,position:6}},{table:`session_pending_inputs`,kind:`column`,value:{name:`request_hash`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`session_pending_inputs`,kind:`column`,value:{name:`message_json`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`session_pending_inputs`,kind:`column`,value:{name:`lifecycle_generation`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`session_pending_inputs`,kind:`column`,value:{name:`state`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`session_pending_inputs`,kind:`column`,value:{name:`accepted_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`session_pending_inputs`,kind:`column`,value:{name:`consumed_event_id`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`session_pending_inputs`,kind:`primaryKey`,value:[`seq`]},{table:`session_pending_inputs`,kind:`unique`,value:[`input_id`]},{table:`session_pending_inputs`,kind:`unique`,value:[`session_id`,`idempotency_key`]},{table:`session_pending_inputs`,kind:`foreignKey`,value:{columns:[`session_id`],target:`session_windows`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`session_pending_inputs`,kind:`foreignKey`,value:{columns:[`session_key`],target:`session_nodes`,targetColumns:[`session_key`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`session_pending_inputs`,kind:`indexes`,value:4},{table:`session_pending_inputs`,kind:`checks`,value:1},{table:`session_progress_cards`,kind:`table`,value:null},{table:`session_progress_cards`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_progress_cards`,kind:`column`,value:{name:`markdown`,type:`text`,nullable:!0,identity:!1,default:null,position:2}},{table:`session_progress_cards`,kind:`column`,value:{name:`steps_json`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`session_progress_cards`,kind:`column`,value:{name:`revision`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`session_progress_cards`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`session_progress_cards`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`session_progress_cards`,kind:`primaryKey`,value:[`session_key`]},{table:`session_progress_cards`,kind:`foreignKey`,value:{columns:[`session_key`],target:`session_nodes`,targetColumns:[`session_key`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`session_progress_cards`,kind:`indexes`,value:1},{table:`session_progress_cards`,kind:`checks`,value:0},{table:`session_reactions`,kind:`table`,value:null},{table:`session_reactions`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_reactions`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_reactions`,kind:`column`,value:{name:`message_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_reactions`,kind:`column`,value:{name:`emoji`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`session_reactions`,kind:`column`,value:{name:`identity_id`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`session_reactions`,kind:`column`,value:{name:`identity_label`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`session_reactions`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`session_reactions`,kind:`primaryKey`,value:[`session_key`,`session_id`,`message_id`,`emoji`,`identity_id`]},{table:`session_reactions`,kind:`foreignKey`,value:{columns:[`session_key`],target:`session_nodes`,targetColumns:[`session_key`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`session_reactions`,kind:`indexes`,value:1},{table:`session_reactions`,kind:`checks`,value:0},{table:`session_suggestions`,kind:`table`,value:null},{table:`session_suggestions`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_suggestions`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_suggestions`,kind:`column`,value:{name:`author_id`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_suggestions`,kind:`column`,value:{name:`author_label`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`session_suggestions`,kind:`column`,value:{name:`text`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`session_suggestions`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`session_suggestions`,kind:`column`,value:{name:`state`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`session_suggestions`,kind:`column`,value:{name:`dispatch_token`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`session_suggestions`,kind:`column`,value:{name:`dispatch_started_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:9}},{table:`session_suggestions`,kind:`column`,value:{name:`dispatch_resolution`,type:`text`,nullable:!0,identity:!1,default:null,position:10}},{table:`session_suggestions`,kind:`primaryKey`,value:[`id`]},{table:`session_suggestions`,kind:`foreignKey`,value:{columns:[`session_key`],target:`session_nodes`,targetColumns:[`session_key`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`session_suggestions`,kind:`indexes`,value:3},{table:`session_suggestions`,kind:`checks`,value:3},{table:`session_transcript_active_event_facts`,kind:`table`,value:null},{table:`session_transcript_active_event_facts`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_transcript_active_event_facts`,kind:`column`,value:{name:`seq`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_transcript_active_event_facts`,kind:`column`,value:{name:`serialized_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_transcript_active_event_facts`,kind:`column`,value:{name:`dependency_navigation_json`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`session_transcript_active_event_facts`,kind:`primaryKey`,value:[`session_id`,`seq`]},{table:`session_transcript_active_event_facts`,kind:`foreignKey`,value:{columns:[`session_id`,`seq`],target:`session_transcript_active_events`,targetColumns:[`session_id`,`event_seq`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`session_transcript_active_event_facts`,kind:`indexes`,value:1},{table:`session_transcript_active_event_facts`,kind:`checks`,value:1},{table:`session_transcript_active_events`,kind:`table`,value:null},{table:`session_transcript_active_events`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_transcript_active_events`,kind:`column`,value:{name:`active_position`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_transcript_active_events`,kind:`column`,value:{name:`event_seq`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_transcript_active_events`,kind:`column`,value:{name:`message_position`,type:`bigint`,nullable:!0,identity:!1,default:null,position:4}},{table:`session_transcript_active_events`,kind:`column`,value:{name:`context_eligible`,type:`bigint`,nullable:!0,identity:!1,default:null,position:5}},{table:`session_transcript_active_events`,kind:`primaryKey`,value:[`session_id`,`active_position`]},{table:`session_transcript_active_events`,kind:`foreignKey`,value:{columns:[`session_id`,`event_seq`],target:`transcript_events`,targetColumns:[`session_id`,`seq`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`session_transcript_active_events`,kind:`indexes`,value:4},{table:`session_transcript_active_events`,kind:`checks`,value:2},{table:`session_transcript_archives`,kind:`table`,value:null},{table:`session_transcript_archives`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_transcript_archives`,kind:`column`,value:{name:`generation`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_transcript_archives`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_transcript_archives`,kind:`column`,value:{name:`reason`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`session_transcript_archives`,kind:`column`,value:{name:`encoding`,type:`text`,nullable:!1,identity:!1,default:null,position:5}},{table:`session_transcript_archives`,kind:`column`,value:{name:`archive_blob`,type:`bytea`,nullable:!1,identity:!1,default:null,position:6}},{table:`session_transcript_archives`,kind:`column`,value:{name:`archive_sha256`,type:`text`,nullable:!1,identity:!1,default:null,position:7}},{table:`session_transcript_archives`,kind:`column`,value:{name:`archive_name`,type:`text`,nullable:!1,identity:!1,default:null,position:8}},{table:`session_transcript_archives`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`session_transcript_archives`,kind:`column`,value:{name:`published_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:10}},{table:`session_transcript_archives`,kind:`column`,value:{name:`publish_attempts`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:11}},{table:`session_transcript_archives`,kind:`column`,value:{name:`last_publish_attempt_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:12}},{table:`session_transcript_archives`,kind:`column`,value:{name:`last_publish_error`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`session_transcript_archives`,kind:`primaryKey`,value:[`session_id`,`generation`]},{table:`session_transcript_archives`,kind:`unique`,value:[`archive_name`]},{table:`session_transcript_archives`,kind:`indexes`,value:4},{table:`session_transcript_archives`,kind:`checks`,value:5},{table:`session_transcript_cold_archive_chunks`,kind:`table`,value:null},{table:`session_transcript_cold_archive_chunks`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_transcript_cold_archive_chunks`,kind:`column`,value:{name:`chunk_index`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_transcript_cold_archive_chunks`,kind:`column`,value:{name:`archive_name`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_transcript_cold_archive_chunks`,kind:`column`,value:{name:`archive_sha256`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`session_transcript_cold_archive_chunks`,kind:`column`,value:{name:`first_seq`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`session_transcript_cold_archive_chunks`,kind:`column`,value:{name:`last_seq`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`session_transcript_cold_archive_chunks`,kind:`column`,value:{name:`event_count`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`session_transcript_cold_archive_chunks`,kind:`column`,value:{name:`raw_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`session_transcript_cold_archive_chunks`,kind:`column`,value:{name:`archive_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`session_transcript_cold_archive_chunks`,kind:`column`,value:{name:`archive_blob`,type:`bytea`,nullable:!0,identity:!1,default:null,position:10}},{table:`session_transcript_cold_archive_chunks`,kind:`primaryKey`,value:[`session_id`,`chunk_index`]},{table:`session_transcript_cold_archive_chunks`,kind:`unique`,value:[`archive_name`]},{table:`session_transcript_cold_archive_chunks`,kind:`foreignKey`,value:{columns:[`session_id`],target:`session_transcript_cold_archives`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`session_transcript_cold_archive_chunks`,kind:`indexes`,value:2},{table:`session_transcript_cold_archive_chunks`,kind:`checks`,value:7},{table:`session_transcript_cold_archives`,kind:`table`,value:null},{table:`session_transcript_cold_archives`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_transcript_cold_archives`,kind:`column`,value:{name:`generation`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_transcript_cold_archives`,kind:`column`,value:{name:`archive_name`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`session_transcript_cold_archives`,kind:`column`,value:{name:`archive_sha256`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`session_transcript_cold_archives`,kind:`column`,value:{name:`event_count`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`session_transcript_cold_archives`,kind:`column`,value:{name:`raw_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`session_transcript_cold_archives`,kind:`column`,value:{name:`archive_bytes`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`session_transcript_cold_archives`,kind:`column`,value:{name:`last_seq`,type:`bigint`,nullable:!1,identity:!1,default:null,position:8}},{table:`session_transcript_cold_archives`,kind:`column`,value:{name:`archived_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:9}},{table:`session_transcript_cold_archives`,kind:`column`,value:{name:`storage`,type:`text`,nullable:!1,identity:!1,default:null,position:10}},{table:`session_transcript_cold_archives`,kind:`column`,value:{name:`archive_blob`,type:`bytea`,nullable:!0,identity:!1,default:null,position:11}},{table:`session_transcript_cold_archives`,kind:`primaryKey`,value:[`session_id`]},{table:`session_transcript_cold_archives`,kind:`unique`,value:[`archive_name`]},{table:`session_transcript_cold_archives`,kind:`foreignKey`,value:{columns:[`session_id`],target:`session_windows`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`session_transcript_cold_archives`,kind:`indexes`,value:2},{table:`session_transcript_cold_archives`,kind:`checks`,value:7},{table:`session_transcript_fts_rows`,kind:`table`,value:null},{table:`session_transcript_fts_rows`,kind:`column`,value:{name:`id`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`session_transcript_fts_rows`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_transcript_fts_rows`,kind:`column`,value:{name:`message_id`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`session_transcript_fts_rows`,kind:`primaryKey`,value:[`id`]},{table:`session_transcript_fts_rows`,kind:`indexes`,value:2},{table:`session_transcript_fts_rows`,kind:`checks`,value:0},{table:`session_transcript_index_state`,kind:`table`,value:null},{table:`session_transcript_index_state`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_transcript_index_state`,kind:`column`,value:{name:`indexed_seq`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_transcript_index_state`,kind:`column`,value:{name:`leaf_event_id`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`session_transcript_index_state`,kind:`column`,value:{name:`needs_rebuild`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:4}},{table:`session_transcript_index_state`,kind:`column`,value:{name:`active_event_count`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:5}},{table:`session_transcript_index_state`,kind:`column`,value:{name:`active_message_count`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:6}},{table:`session_transcript_index_state`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`session_transcript_index_state`,kind:`primaryKey`,value:[`session_id`]},{table:`session_transcript_index_state`,kind:`foreignKey`,value:{columns:[`session_id`],target:`session_windows`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`session_transcript_index_state`,kind:`indexes`,value:1},{table:`session_transcript_index_state`,kind:`checks`,value:0},{table:`session_windows`,kind:`table`,value:null},{table:`session_windows`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`session_windows`,kind:`column`,value:{name:`session_key`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`session_windows`,kind:`column`,value:{name:`previous_session_id`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`session_windows`,kind:`column`,value:{name:`reason`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`session_windows`,kind:`column`,value:{name:`session_scope`,type:`text`,nullable:!1,identity:!1,default:`'conversation'`,position:5}},{table:`session_windows`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:6}},{table:`session_windows`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`session_windows`,kind:`column`,value:{name:`transcript_updated_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:8}},{table:`session_windows`,kind:`column`,value:{name:`row_transcript_json`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`session_windows`,kind:`column`,value:{name:`row_transcript_updated_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:10}},{table:`session_windows`,kind:`column`,value:{name:`transcript_observed_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:11}},{table:`session_windows`,kind:`column`,value:{name:`session_entry_provenance`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:12}},{table:`session_windows`,kind:`column`,value:{name:`acp_owned`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:13}},{table:`session_windows`,kind:`column`,value:{name:`plugin_owner_id`,type:`text`,nullable:!0,identity:!1,default:null,position:14}},{table:`session_windows`,kind:`column`,value:{name:`hook_external_content_source`,type:`text`,nullable:!0,identity:!1,default:null,position:15}},{table:`session_windows`,kind:`column`,value:{name:`started_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:16}},{table:`session_windows`,kind:`column`,value:{name:`ended_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:17}},{table:`session_windows`,kind:`column`,value:{name:`status`,type:`text`,nullable:!0,identity:!1,default:null,position:18}},{table:`session_windows`,kind:`column`,value:{name:`chat_type`,type:`text`,nullable:!0,identity:!1,default:null,position:19}},{table:`session_windows`,kind:`column`,value:{name:`channel`,type:`text`,nullable:!0,identity:!1,default:null,position:20}},{table:`session_windows`,kind:`column`,value:{name:`account_id`,type:`text`,nullable:!0,identity:!1,default:null,position:21}},{table:`session_windows`,kind:`column`,value:{name:`primary_conversation_id`,type:`text`,nullable:!0,identity:!1,default:null,position:22}},{table:`session_windows`,kind:`column`,value:{name:`model_provider`,type:`text`,nullable:!0,identity:!1,default:null,position:23}},{table:`session_windows`,kind:`column`,value:{name:`model`,type:`text`,nullable:!0,identity:!1,default:null,position:24}},{table:`session_windows`,kind:`column`,value:{name:`agent_harness_id`,type:`text`,nullable:!0,identity:!1,default:null,position:25}},{table:`session_windows`,kind:`column`,value:{name:`parent_session_key`,type:`text`,nullable:!0,identity:!1,default:null,position:26}},{table:`session_windows`,kind:`column`,value:{name:`spawned_by`,type:`text`,nullable:!0,identity:!1,default:null,position:27}},{table:`session_windows`,kind:`column`,value:{name:`display_name`,type:`text`,nullable:!0,identity:!1,default:null,position:28}},{table:`session_windows`,kind:`primaryKey`,value:[`session_id`]},{table:`session_windows`,kind:`foreignKey`,value:{columns:[`primary_conversation_id`],target:`conversations`,targetColumns:[`conversation_id`],onUpdate:`NO ACTION`,onDelete:`SET NULL`,deferrable:!1,deferred:!1}},{table:`session_windows`,kind:`foreignKey`,value:{columns:[`session_key`],target:`session_nodes`,targetColumns:[`session_key`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`session_windows`,kind:`indexes`,value:5},{table:`session_windows`,kind:`checks`,value:7},{table:`standing_intents`,kind:`table`,value:null},{table:`standing_intents`,kind:`column`,value:{name:`intent_key`,type:`bigint`,nullable:!1,identity:!0,default:null,position:1}},{table:`standing_intents`,kind:`column`,value:{name:`id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`standing_intents`,kind:`column`,value:{name:`description`,type:`text`,nullable:!1,identity:!1,default:null,position:3}},{table:`standing_intents`,kind:`column`,value:{name:`trigger_keywords`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`standing_intents`,kind:`column`,value:{name:`trigger_embedding`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`standing_intents`,kind:`column`,value:{name:`channel_scope`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`standing_intents`,kind:`column`,value:{name:`sender_scope`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`standing_intents`,kind:`column`,value:{name:`creator_sender`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`standing_intents`,kind:`column`,value:{name:`status`,type:`text`,nullable:!1,identity:!1,default:null,position:9}},{table:`standing_intents`,kind:`column`,value:{name:`expires_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:10}},{table:`standing_intents`,kind:`column`,value:{name:`max_fires`,type:`bigint`,nullable:!1,identity:!1,default:null,position:11}},{table:`standing_intents`,kind:`column`,value:{name:`fire_count`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:12}},{table:`standing_intents`,kind:`column`,value:{name:`cooldown_seconds`,type:`bigint`,nullable:!1,identity:!1,default:`86400`,position:13}},{table:`standing_intents`,kind:`column`,value:{name:`last_fired_at`,type:`bigint`,nullable:!0,identity:!1,default:null,position:14}},{table:`standing_intents`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:15}},{table:`standing_intents`,kind:`column`,value:{name:`source_session_id`,type:`text`,nullable:!0,identity:!1,default:null,position:16}},{table:`standing_intents`,kind:`primaryKey`,value:[`intent_key`]},{table:`standing_intents`,kind:`unique`,value:[`id`]},{table:`standing_intents`,kind:`indexes`,value:4},{table:`standing_intents`,kind:`checks`,value:5},{table:`trajectory_runtime_events`,kind:`table`,value:null},{table:`trajectory_runtime_events`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`trajectory_runtime_events`,kind:`column`,value:{name:`seq`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`trajectory_runtime_events`,kind:`column`,value:{name:`run_id`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`trajectory_runtime_events`,kind:`column`,value:{name:`event_json`,type:`text`,nullable:!1,identity:!1,default:null,position:4}},{table:`trajectory_runtime_events`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:5}},{table:`trajectory_runtime_events`,kind:`column`,value:{name:`event_utf8_bytes`,type:`bigint`,nullable:!0,identity:!1,default:null,position:6}},{table:`trajectory_runtime_events`,kind:`column`,value:{name:`event_payload`,type:`bytea`,nullable:!0,identity:!1,default:null,position:7}},{table:`trajectory_runtime_events`,kind:`column`,value:{name:`event_codec`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`trajectory_runtime_events`,kind:`primaryKey`,value:[`session_id`,`seq`]},{table:`trajectory_runtime_events`,kind:`foreignKey`,value:{columns:[`session_id`],target:`session_windows`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`trajectory_runtime_events`,kind:`indexes`,value:2},{table:`trajectory_runtime_events`,kind:`checks`,value:0},{table:`transcript_event_identities`,kind:`table`,value:null},{table:`transcript_event_identities`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`transcript_event_identities`,kind:`column`,value:{name:`event_id`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`transcript_event_identities`,kind:`column`,value:{name:`seq`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`transcript_event_identities`,kind:`column`,value:{name:`event_type`,type:`text`,nullable:!0,identity:!1,default:null,position:4}},{table:`transcript_event_identities`,kind:`column`,value:{name:`parent_id`,type:`text`,nullable:!0,identity:!1,default:null,position:5}},{table:`transcript_event_identities`,kind:`column`,value:{name:`message_idempotency_key`,type:`text`,nullable:!0,identity:!1,default:null,position:6}},{table:`transcript_event_identities`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:7}},{table:`transcript_event_identities`,kind:`primaryKey`,value:[`session_id`,`event_id`]},{table:`transcript_event_identities`,kind:`foreignKey`,value:{columns:[`session_id`,`seq`],target:`transcript_events`,targetColumns:[`session_id`,`seq`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`transcript_event_identities`,kind:`indexes`,value:4},{table:`transcript_event_identities`,kind:`checks`,value:0},{table:`transcript_events`,kind:`table`,value:null},{table:`transcript_events`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`transcript_events`,kind:`column`,value:{name:`seq`,type:`bigint`,nullable:!1,identity:!1,default:null,position:2}},{table:`transcript_events`,kind:`column`,value:{name:`event_json`,type:`text`,nullable:!0,identity:!1,default:null,position:3}},{table:`transcript_events`,kind:`column`,value:{name:`created_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:4}},{table:`transcript_events`,kind:`column`,value:{name:`event_zstd`,type:`bytea`,nullable:!0,identity:!1,default:null,position:5}},{table:`transcript_events`,kind:`column`,value:{name:`event_utf8_bytes`,type:`bigint`,nullable:!0,identity:!1,default:null,position:6}},{table:`transcript_events`,kind:`column`,value:{name:`navigation_json`,type:`text`,nullable:!0,identity:!1,default:null,position:7}},{table:`transcript_events`,kind:`column`,value:{name:`navigation_type`,type:`text`,nullable:!0,identity:!1,default:null,position:8}},{table:`transcript_events`,kind:`column`,value:{name:`navigation_custom_type`,type:`text`,nullable:!0,identity:!1,default:null,position:9}},{table:`transcript_events`,kind:`column`,value:{name:`navigation_display`,type:`bigint`,nullable:!1,identity:!1,default:`0`,position:10}},{table:`transcript_events`,kind:`column`,value:{name:`message_role`,type:`text`,nullable:!0,identity:!1,default:null,position:11}},{table:`transcript_events`,kind:`column`,value:{name:`navigation_last_type`,type:`text`,nullable:!0,identity:!1,default:null,position:12}},{table:`transcript_events`,kind:`column`,value:{name:`navigation_last_custom_type`,type:`text`,nullable:!0,identity:!1,default:null,position:13}},{table:`transcript_events`,kind:`column`,value:{name:`navigation_valid`,type:`bigint`,nullable:!1,identity:!1,default:`1`,position:14}},{table:`transcript_events`,kind:`primaryKey`,value:[`session_id`,`seq`]},{table:`transcript_events`,kind:`foreignKey`,value:{columns:[`session_id`],target:`session_windows`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`transcript_events`,kind:`indexes`,value:1},{table:`transcript_events`,kind:`checks`,value:3},{table:`transcript_rewrite_watermarks`,kind:`table`,value:null},{table:`transcript_rewrite_watermarks`,kind:`column`,value:{name:`session_id`,type:`text`,nullable:!1,identity:!1,default:null,position:1}},{table:`transcript_rewrite_watermarks`,kind:`column`,value:{name:`generation`,type:`text`,nullable:!1,identity:!1,default:null,position:2}},{table:`transcript_rewrite_watermarks`,kind:`column`,value:{name:`updated_at`,type:`bigint`,nullable:!1,identity:!1,default:null,position:3}},{table:`transcript_rewrite_watermarks`,kind:`primaryKey`,value:[`session_id`]},{table:`transcript_rewrite_watermarks`,kind:`foreignKey`,value:{columns:[`session_id`],target:`session_windows`,targetColumns:[`session_id`],onUpdate:`NO ACTION`,onDelete:`CASCADE`,deferrable:!1,deferred:!1}},{table:`transcript_rewrite_watermarks`,kind:`indexes`,value:1},{table:`transcript_rewrite_watermarks`,kind:`checks`,value:0}];return Object.defineProperty(this,"expectedCatalog",{value:e,enumerable:!0,configurable:!0,writable:!0}),e}},Jp={get sql(){let e=`-- Generated by pnpm db:postgres:gen. PostgreSQL-only derived transcript content.

CREATE TABLE "session_transcript_fts" (
  "rowid" bigint PRIMARY KEY REFERENCES "session_transcript_fts_rows" ("id") ON DELETE CASCADE,
  "text" text COLLATE "C",
  "session_id" text COLLATE "C",
  "message_id" text COLLATE "C",
  "role" text COLLATE "C",
  "timestamp" double precision
);
`;return Object.defineProperty(this,"sql",{value:e,enumerable:!0,configurable:!0,writable:!0}),e}};function agentEngineInput(){return gr(`agent`)}function createAgentPostgresMigrations(){let e=Yp.postgres,t=withoutAgentPostgresToolUsage(e),n=withoutAgentPostgresActiveEventFacts(t),r=withoutAgentPostgresCreationOperations(n),i=withoutAgentPostgresColdNavigation(r),a=withoutAgentPostgresColdArchiveChunks(i),o=withLegacyAgentPostgresMemoryPaths(a),s=withLegacyPostgresIndexOrdering(o,`schema-nullability`),c=withLegacyPostgresIndexOrdering(s),l=withLegacyAgentPostgresMemoryRevisionTriggers(c),u=withLegacyAgentPostgresTrajectoryStorage(l),d=withLegacyAgentPostgresIndexes(u);return[{version:28,fromSchema:{postgres:withLegacyAgentPostgresWriteLayout(d)},schema:{postgres:d},sql:`
  DROP INDEX "idx_agent_transcript_event_parent";
  DROP INDEX "idx_agent_session_windows_conversation";
  CREATE INDEX "idx_agent_session_windows_conversation"
    ON "session_windows" (("primary_conversation_id") ASC NULLS FIRST)
    WHERE "primary_conversation_id" IS NOT NULL;

        UPDATE schema_meta
        SET schema_version = 28,
          app_version = '${J.replaceAll(`'`,`''`)}',
          updated_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint)
        WHERE meta_key = 'primary';`},{version:29,fromSchema:{postgres:d},schema:{postgres:u},sql:`
  DROP INDEX IF EXISTS idx_agent_session_nodes_last_interaction_at;
  DROP INDEX IF EXISTS idx_agent_session_reactions_message;

        ALTER FUNCTION openclaw_transcript_navigation_check(text)
          STRICT SET search_path = pg_catalog;
        UPDATE schema_meta
        SET schema_version = 29,
          app_version = '${J.replaceAll(`'`,`''`)}',
          updated_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint)
        WHERE meta_key = 'primary';`},{version:30,fromSchema:{postgres:u},schema:{postgres:l},sql:`
  ALTER TABLE "trajectory_runtime_events" ADD COLUMN "event_utf8_bytes" bigint;
  ALTER TABLE "trajectory_runtime_events" ADD COLUMN "event_payload" bytea;
  ALTER TABLE "trajectory_runtime_events" ADD COLUMN "event_codec" text COLLATE "C";
  DROP INDEX "idx_agent_trajectory_runtime_run";
  CREATE INDEX "idx_agent_trajectory_runtime_run"
    ON "trajectory_runtime_events" (("session_id") ASC NULLS FIRST,
      ("run_id") ASC NULLS FIRST, ("created_at") ASC NULLS FIRST,
      (COALESCE("event_utf8_bytes", octet_length("event_json"))) ASC NULLS FIRST);

        UPDATE schema_meta
        SET schema_version = 30,
          app_version = '${J.replaceAll(`'`,`''`)}',
          updated_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint)
        WHERE meta_key = 'primary';`},{version:31,fromSchema:{postgres:l},schema:{postgres:c},sql:`${mp}
        UPDATE schema_meta
        SET schema_version = 31,
          app_version = '${J.replaceAll(`'`,`''`)}',
          updated_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint)
        WHERE meta_key = 'primary';`},{version:32,fromSchema:{postgres:c},schema:{postgres:c,postgresVectorDecoderVersion:2},sql:`${Kp}
        UPDATE schema_meta
        SET schema_version = 32,
          app_version = '${J.replaceAll(`'`,`''`)}',
          updated_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint)
        WHERE meta_key = 'primary';`},{version:33,fromSchema:{postgres:c,postgresVectorDecoderVersion:2},schema:{postgres:c,postgresVectorDecoderVersion:2,postgresVectorSearchVersion:2},sql:`DO $migration$
DECLARE definition jsonb; vector_index jsonb; extension_schema text; dimensions integer; extension_version text[];
BEGIN
  SELECT regexp_match(extversion, '^([0-9]+)[.]([0-9]+)') INTO extension_version
  FROM pg_catalog.pg_extension WHERE extname = 'vector';
  FOR definition IN
    SELECT value FROM openclaw_schema_meta meta,
      jsonb_each(coalesce((to_jsonb(meta)->>'search_extensions')::jsonb, '{}'::jsonb))
    WHERE meta.store = 'agent'
  LOOP
    IF definition->>'mode' = 'keyword-only' THEN CONTINUE; END IF;
    extension_schema := coalesce(definition->>'extensionSchema', 'public');
    FOR vector_index IN SELECT value FROM jsonb_each(coalesce(definition->'vector', '{}'::jsonb))
    LOOP
      IF extension_version IS NULL OR (extension_version[1]::integer = 0 AND extension_version[2]::integer < 7) THEN
        RAISE EXCEPTION 'PostgreSQL binary vector search requires pgvector 0.7 or newer. Upgrade the server extension package, then have a database administrator run ALTER EXTENSION vector UPDATE before reopening the store.';
      END IF;
      dimensions := (vector_index->'postgres'->>'dimensions')::integer;
      EXECUTE format(
        'ALTER TABLE %I ADD COLUMN embedding_bits bit(%s) GENERATED ALWAYS AS (CASE WHEN %I.vector_norm(embedding) > 0 THEN %I.binary_quantize(embedding)::bit(%s) ELSE NULL END) STORED',
        vector_index->>'table', dimensions, extension_schema, extension_schema, dimensions);
    END LOOP;
  END LOOP;
END $migration$;
        UPDATE schema_meta
        SET schema_version = 33,
          app_version = '${J.replaceAll(`'`,`''`)}',
          updated_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint)
        WHERE meta_key = 'primary';`},{version:34,fromSchema:{postgres:c,postgresVectorDecoderVersion:2,postgresVectorSearchVersion:2},schema:{postgres:s,postgresVectorDecoderVersion:2,postgresVectorSearchVersion:2},sql:`${postgresIndexOrderingMigration(s)}
        UPDATE schema_meta
        SET schema_version = 34,
          app_version = '${J.replaceAll(`'`,`''`)}',
          updated_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint)
        WHERE meta_key = 'primary';`},{version:35,fromSchema:{postgres:s,postgresVectorDecoderVersion:2,postgresVectorSearchVersion:2},schema:{postgres:o,postgresVectorDecoderVersion:2,postgresVectorSearchVersion:2},sql:`${postgresIndexOrderingMigration(o,`schema-nullability`)}
        UPDATE schema_meta
        SET schema_version = 35,
          app_version = '${J.replaceAll(`'`,`''`)}',
          updated_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint)
        WHERE meta_key = 'primary';`},{version:36,fromSchema:{postgres:o,postgresVectorDecoderVersion:2,postgresVectorSearchVersion:2},schema:{postgres:a,postgresVectorDecoderVersion:2,postgresVectorSearchVersion:2},sql:`${Up}
        UPDATE schema_meta
        SET schema_version = 36,
          app_version = '${J.replaceAll(`'`,`''`)}',
          updated_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint)
        WHERE meta_key = 'primary';`},{version:37,fromSchema:{postgres:a,postgresVectorDecoderVersion:2,postgresVectorSearchVersion:2},schema:{postgres:i,postgresVectorDecoderVersion:2,postgresVectorSearchVersion:2},sql:`${agentColdArchiveChunksPostgresMigration(i)}
        UPDATE schema_meta
        SET schema_version = 37,
          app_version = '${J.replaceAll(`'`,`''`)}',
          updated_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint)
        WHERE meta_key = 'primary';`},{version:38,fromSchema:{postgres:i,postgresVectorDecoderVersion:2,postgresVectorSearchVersion:2},schema:{postgres:i,postgresVectorDecoderVersion:2,postgresVectorSearchVersion:2,postgresTextSearchVersion:2},sql:`${Gp}
        UPDATE schema_meta
        SET schema_version = 38,
          app_version = '${J.replaceAll(`'`,`''`)}',
          updated_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint)
        WHERE meta_key = 'primary';`},{version:39,fromSchema:{postgres:i,postgresVectorDecoderVersion:2,postgresVectorSearchVersion:2,postgresTextSearchVersion:2},schema:{postgres:r,postgresVectorDecoderVersion:2,postgresVectorSearchVersion:2,postgresTextSearchVersion:2},sql:`${agentColdNavigationPostgresMigration(r)}
        UPDATE schema_meta
        SET schema_version = 39,
          app_version = '${J.replaceAll(`'`,`''`)}',
          updated_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint)
        WHERE meta_key = 'primary';`},{version:40,fromSchema:{postgres:r,postgresVectorDecoderVersion:2,postgresVectorSearchVersion:2,postgresTextSearchVersion:2},schema:{postgres:n,postgresVectorDecoderVersion:2,postgresVectorSearchVersion:2,postgresTextSearchVersion:2},sql:`${agentCreationOperationsPostgresMigration(n)}
        UPDATE schema_meta
        SET schema_version = 40,
          app_version = '${J.replaceAll(`'`,`''`)}',
          updated_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint)
        WHERE meta_key = 'primary';`},{version:41,fromSchema:{postgres:n,postgresVectorDecoderVersion:2,postgresVectorSearchVersion:2,postgresTextSearchVersion:2},schema:{postgres:t,postgresVectorDecoderVersion:2,postgresVectorSearchVersion:2,postgresTextSearchVersion:2},sql:`${agentActiveEventFactsPostgresMigration(t)}
        UPDATE schema_meta
        SET schema_version = 41,
          app_version = '${J.replaceAll(`'`,`''`)}',
          updated_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint)
        WHERE meta_key = 'primary';`},{version:42,fromSchema:{postgres:t,postgresVectorDecoderVersion:2,postgresVectorSearchVersion:2,postgresTextSearchVersion:2},schema:{postgres:e,postgresVectorDecoderVersion:2,postgresVectorSearchVersion:2,postgresTextSearchVersion:2},sql:`${agentToolUsagePostgresMigration(e)}
        UPDATE schema_meta
        SET schema_version = 42,
          app_version = '${J.replaceAll(`'`,`''`)}',
          updated_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS bigint)
        WHERE meta_key = 'primary';`}]}const Yp={id:`agent`,version:42,sqlite:``,get postgres(){let e=`${qp.sql}\n${Jp.sql}`;return Object.defineProperty(this,"postgres",{value:e,enumerable:!0,configurable:!0,writable:!0}),e},postgresVectorDecoderVersion:2,postgresVectorSearchVersion:2,postgresTextSearchVersion:2,search:Wp,get postgresMigrations(){let e=createAgentPostgresMigrations();return Object.defineProperty(this,"postgresMigrations",{value:e,enumerable:!0,configurable:!0,writable:!0}),e}};function admitAgentPostgres(e,t,n,r){if(r){if(t===void 0)throw Error(`Creating an agent database requires an agent owner`);let n=Date.now();e.exec(`INSERT INTO session_key_contract (id, main_key, updated_at) VALUES (1, 'main', 0)`),e.exec(`INSERT INTO memory_index_state (id, revision) VALUES (1, 0)`),e.prepare(`INSERT INTO schema_meta
      (meta_key, role, schema_version, agent_id, app_version, created_at, updated_at)
      VALUES ('primary', 'agent', ?, ?, ?, ?, ?)`).run(42,t,J,n,n),publishAgentSchemaMetadata(e,{agentId:t,role:`agent`,schemaVersion:42})}let i=readExistingAgentSchemaMeta(e);if(assertCurrentAgentSchemaMetadata(i,t??i?.agentId??``,n,Yp.version),gs(e)?.version!==Yp.version)throw Error(`Agent database has no current PostgreSQL schema admission`);fs(e.anchor)}function openAgentEngineStore(e,t,n,r=!1,i,a=!1){if(t===void 0&&!r)throw Error(`Creating an agent database requires an agent owner`);let o=agentEngineInput(),inspectSqlite=()=>{let t=K(e)??Qa(e);return{hasEngineAnchor:t.tables.has(`openclaw_engine_anchor`),hasExistingData:[...t.tables,...t.views,...t.triggers.keys()].some(e=>e!==`openclaw_engine_anchor`&&!e.startsWith(`sqlite_`))}},s=!!(o&&inspectSqlite().hasEngineAnchor),open=()=>openEngineStore({anchor:e,schema:Yp,input:o,existingOnly:r||s,reusePostgresConnection:a,closeOnFailure:i,assertMigrationCurrent:assertAgentDatabaseMaintenanceAuthority,prepareAnchor:()=>{},openSqlite:()=>{},inspectSqlite,admitPostgres:(e,r)=>admitAgentPostgres(e,t,n,r)});return o&&!r&&!s?O(e,open):open()}new ec,er(`state/sqlite`);function terminalLatch(){return vn(Symbol.for(`openclaw.agentDatabaseLifecycle`))?.terminal}function assertAgentDatabaseTerminalOpenAllowed(e){let t=terminalLatch()?.get(e);if(t)throw t}function revalidateAgentDatabaseTerminalOpen(e){let t=terminalLatch(),n=t?.peek(e);if(t&&n?.name===`SqliteIntegrityError`){let r=ks(Es.databaseVerify),i=Tc(process.execPath,[...As(r),`--openclaw-database-verify-sync`,e],{timeout:Zo(`integrity check`,e).timeoutMs,killSignal:`SIGKILL`,stdio:`ignore`});if(i.error||i.status!==0)throw n;t.clear(e)}assertAgentDatabaseTerminalOpenAllowed(e)}function hasAdmittedAgentReadOnlySchema(e){let t=assertSupportedAgentSchemaVersion(e.db,e.path),n=readExistingAgentSchemaMeta(e.db);return assertCanonicalAgentPersistenceVersion(e.db,e.path,t),n?(assertExistingAgentSchemaOwner(n,e.agentId,e.path),assertCanonicalSessionValidationSchema(e.db),!0):!1}function openOpenClawAgentDatabaseReadOnly(e,t={}){let n=agentEngineInput();n&&Ie();let r=q(e.agentId),i=Uo({...e,agentId:r});if(jo(i,{agentId:r,env:e.env}))return{found:!1,reason:`database-missing`};if(Br(i)){let t=Do(e.env??process.env),n=Ko(r,t);if(!n||!Br(i,n)||prepareAgentDeletionJournalStatus(t,r)()!==`complete`)return{found:!1,reason:`database-missing`}}if(!Y.existsSync(i))return{found:!1,reason:`database-missing`};revalidateAgentDatabaseTerminalOpen(i);let a=At(`agent`,i,{env:e.env});if(a)throw recordOpenClawAgentDatabaseReadOpenFailure(a),a;let o;try{o=n?Ga(_o(i),{timeout:Wo}):Bt(i,{timeout:Wo,...t.allowExtension?{allowExtension:!0}:{}})}catch(e){throw recordOpenClawAgentDatabaseReadOpenFailure(e),e}let s=!1,c=o,l,close=()=>{s||(c!==o&&c.isOpen&&c.close(),o.isOpen&&o.close(),s=!0,l?.(),l=void 0)};try{let e;if(n)c=openAgentEngineStore(o,r,i,!0,(e,t)=>{throw c=e,t},!0),registerOpenClawAgentDatabaseIdentity(c),e={agentId:r,db:c,path:i,close};else{rt(o),so(o),registerOpenClawAgentDatabaseIdentity(o);let t=hs(`agent`,i)?o.location():void 0;if(e={agentId:r,db:o,path:t??i,close},!(adoptOpenClawAgentDatabaseSchema(e)||Xa(o,()=>{if(fs(o),!hasAdmittedAgentReadOnlySchema(e))return!1;let t=K(e.db);if(t&&di(t.tableSql))throw new N(`OpenClaw agent database ${e.path} requires writable startup admission before session reads; restart the Gateway or run openclaw doctor --fix.`);return!0})))return close(),{found:!1,reason:`schema-missing`};Vs||(loadOpenClawAgentCanonicalValidationReceipt(e),hasOpenClawAgentCanonicalValidation(e))}return t.lifecycle===`agent`&&(l=ds({agentId:r,path:i,revoke:close,close})),{found:!0,database:e}}catch(e){throw close(),recordOpenClawAgentDatabaseReadOpenFailure(e),e}}async function runWithSqliteMutationWorkerCoordination(e,t,n){let execute=()=>n({...t,env:{...t.env,...e.stateContext.environment}}),r=e.databaseAdmission;if(!r)return await execute();let i=!0;try{return await Da((t,n,a,o)=>{if(!i)throw Error(`SQLite mutation file admission outlived its request`);return a&&Je(e.databasePath),Tr(r,t,n,a,o)},execute)}finally{i=!1,r.close()}}const Xp=`openclaw.background-result-placement`;let Zp;function resolveZstdCodec(){return Zp??={compress:(e,t,n)=>t===void 0&&n===void 0?Pc.zstdCompressSync(e):Pc.zstdCompressSync(e,{params:{...t===void 0?{}:{[Pc.constants.ZSTD_c_compressionLevel]:t},...n===void 0?{}:{[Pc.constants.ZSTD_c_checksumFlag]:n}}}),decompress:(e,t)=>Pc.zstdDecompressSync(e,t===void 0?void 0:{maxOutputLength:t,chunkSize:Math.max(Pc.constants.Z_MIN_CHUNK,Math.min(Pc.constants.Z_DEFAULT_CHUNK,t+1))})}}string().pipe(Se([`new`,`reset`,`idle`,`daily`,`cron-stale`])),D({type:ce().optional().refine(e=>e!==`session`&&e!==`leaf`),id:S().min(1),parentId:Lt([S(),y()])}),D({type:s(`leaf`),id:S().min(1),parentId:Lt([S(),y()]),targetId:Lt([S(),y()]),appendParentId:Lt([S(),y()]).optional(),appendMode:s(`side`).optional(),billsDisplaced:s(!0).optional()}),D({type:s(`session`),id:S()});const Qp=`openclawSyntheticMissingToolResult`,$p=`[openclaw] missing tool result in session history; inserted synthetic error result for transcript repair.`;function isSyntheticMissingToolResult(e){if(!e.isError)return!1;if(bn(e.details)?.openclawSyntheticMissingToolResult===!0)return!0;let t=e.content;return Array.isArray(t)&&t.some(e=>{let t=bn(e);return t?.type===`text`&&t.text===`[openclaw] missing tool result in session history; inserted synthetic error result for transcript repair.`})}const em=[`upstreamUserText`],tm=memoizeFrozenPlainDataProjection(e=>{let t=Vn(e.details);if(t?.openclawSyntheticMissingToolResult===!0&&Object.keys(t).length===1)return e;let n={...e};return t?.openclawSyntheticMissingToolResult===!0?n.details={[Qp]:!0}:delete n.details,n});function stripToolResultDetails(e){let t=!1,n=e.map(e=>{let n=Vn(e);if(n?.role!==`toolResult`||!(`details`in n))return e;let r=tm(n);return t||=r!==e,r});return t?n:e}function projectModelContextMessages(e,t){let n=[];for(let r of stripToolResultDetails(e)){let e=Vn(r),i=Vn(e?.__openclaw);if(!i||!em.some(e=>e in i)){n.push(r);continue}let a={...i};for(let e of em)delete a[e];t?.(a),n.push({...e,__openclaw:a})}return n}function projectSessionModelContextEntry(e,{entry:t,omitCheckpoint:n,toolResultOmission:r}){let i={...e,parentId:t.parentId,...t.type===`compaction`||t.type===`reset`?{firstKeptEntryId:t.firstKeptEntryId}:{}};if(i.type!==`message`)return i;let[a]=projectModelContextMessages([i.message]),o={...i,message:a};return n&&o.message.role===`assistant`&&(o.message={...o.message},delete o.message.providerReplay),r!==void 0&&o.message.role===`toolResult`&&(o.message={...o.message,content:[{type:`text`,text:r}]}),o}const nm=[`type`,`id`,`parentId`,`targetId`,`appendParentId`,`appendMode`],rm=[...nm,`timestamp`,`version`,`cwd`,`firstKeptEntryId`,`reason`,`tokensBefore`,`thinkingLevel`,`provider`,`modelId`,`fromId`,`customType`,`display`,`excludeFromContext`,`label`,`name`],im=[`role`,`provider`,`model`,`timestamp`,`excludeFromContext`,`openclawModelPlacement`,`toolCallId`,`toolUseId`,`tool_call_id`,`tool_use_id`,`callId`,`call_id`,`toolName`,`isError`,`stopReason`,`customType`,`display`];function pickNavigation(e,t){return Object.fromEntries(t.filter(t=>Object.hasOwn(e,t)).map(t=>[t,e[t]]))}function projectSessionModelContextNavigation(e){let t={...pickNavigation({...e},rm),type:e.type,id:e.id,parentId:e.parentId,timestamp:e.timestamp};if(e.type===`message`){let n=e.message,r={...n},i=`content`in n&&Array.isArray(n.content)?n.content.flatMap(e=>I(e)&&[`toolCall`,`toolUse`,`functionCall`].includes(e.type)?[pickNavigation(e,[`type`,`id`,`name`])]:[]):[],a=I(r.details)?r.details:{},o=r.customType===`openclaw.system-update`&&(a.kind===`prompt-update`||a.kind===`runtime-context`)?a.kind:void 0;t.message={...pickNavigation(r,im),content:i,command:``,output:``,providerReplay:{type:I(r.providerReplay)?r.providerReplay.type:null},details:{[Qp]:isSyntheticMissingToolResult({isError:r.isError,details:r.details,content:r.content}),...o?{kind:o}:{}}}}else e.type===`compaction`||e.type===`branch_summary`?t.summary=``:e.type===`custom_message`?(t.content=[],e.customType===`openclaw.system-update`&&I(e.details)&&(e.details.kind===`prompt-update`||e.details.kind===`runtime-context`)&&(t.details={kind:e.details.kind})):e.type===`custom`&&e.customType===`openclaw.system-prompt`?t.data={restart:I(e.data)&&e.data.restart===!0}:e.type===`custom`&&e.customType===`openclaw.background-result-placement`&&(t.data=I(e.data)?pickNavigation(e.data,[`afterEntryId`,`resultEntryIds`]):e.data);return t}const am=/* @__PURE__ */ new WeakSet;function projectModelContextJson(e,t,n=!1,r){let i=JSON.parse(e);return JSON.stringify(t?projectSessionModelContextNavigation(i):projectSessionModelContextEntry(i,{entry:i,omitCheckpoint:n,toolResultOmission:r}))}function projectDeepModelContextSql(e,t,n,r=F.lit(0),i=F.lit(null)){let a=`openclaw_deep_model_context`;return am.has(e)||(e.function(a,{deterministic:!0,directOnly:!0},(e,t,n,r)=>{if(typeof e!=`string`)throw TypeError(`Deep transcript projection requires canonical JSON text`);return projectModelContextJson(e,t===1,n===1,typeof r==`string`?r:void 0)}),am.add(e)),w(e).fn(a,[t,F.lit(+!!n),r,i])}function projectModelContextEventSql(e,t,n,r,i=E(e,t,F.lit(`$.message.role`)),o=se(e,t)){if(z(e)){let e=postgresModelEventSql(t,i),a=r?F`CASE WHEN ${r} IS NOT NULL AND ${i} = 'toolResult'
          THEN jsonb_set(${e}, '{message,content}', jsonb_build_array(jsonb_build_object('type', 'text', 'text', ${r}::text)))
          ELSE ${e} END`:e;return F`(CASE WHEN ${n} = 1
      THEN ${a} #- '{message,providerReplay}' ELSE ${a} END)::text`}let s=em.map(e=>`$.message.__openclaw.${e}`),c=b(e,t,s.map(e=>F.val(e))),l=F`CASE WHEN ${i} = 'toolResult'
    THEN ${b(e,c,[F.lit(`$.message.details`)])} ELSE ${c} END`,u=r?F`CASE WHEN ${r} IS NOT NULL AND ${i} = 'toolResult'
      THEN ${le(e,l,F.lit(`$.message.content`),a(e,[te(e,{type:F.lit(`text`),text:r})]),!0)} ELSE ${l} END`:l;return F`CASE WHEN NOT ${o} THEN ${projectDeepModelContextSql(e,t,!1,n,r)}
    WHEN ${n} = 1
    THEN ${b(e,u,[F.lit(`$.message.providerReplay`)])} ELSE ${u} END`}function contentPropertySql(e,t){return F`CASE WHEN typeof(key) = 'integer' AND key < 8
    THEN json_extract(${e}, fullkey || ${`.${t}`})
    ELSE json_extract(value, ${`$.${t}`}) END`}function jsonMemberValue(e){let t=F.ref(`${e}.type`),n=F.ref(`${e}.value`);return F`CASE ${t}
    WHEN 'object' THEN json(${n})
    WHEN 'array' THEN json(${n})
    WHEN 'true' THEN json('true') WHEN 'false' THEN json('false')
    ELSE ${n} END`}function projectTranscriptPayloadNavigationSql(e,t){if(z(e))return F`(
      SELECT coalesce(json_object_agg(root_member.key, CASE
        WHEN root_member.key = 'message' AND json_typeof(root_member.value) = 'object' THEN (
          SELECT coalesce(json_object_agg(message_member.key, CASE
            WHEN message_member.key = '__openclaw' AND json_typeof(message_member.value) = 'object' THEN (
              SELECT coalesce(json_object_agg(internal.key, internal.value), '{}'::json)
              FROM json_each(message_member.value) AS internal
              WHERE internal.key IN ('runId', 'steerTargetRunId', 'contextFreeCommand'))
            ELSE message_member.value END), '{}'::json)
          FROM json_each(root_member.value) AS message_member
          WHERE message_member.key IN ('role', 'idempotencyKey', 'provenance', 'excludeFromContext', '__openclaw'))
        ELSE root_member.value END), '{}'::json)::text
      FROM json_each(${t}::json) AS root_member
      WHERE root_member.key IN (${F.join([...rm,`message`])}))`;let n=F.ref(`message_member.value`),r=Re(e,n,[`runId`,`steerTargetRunId`,`contextFreeCommand`]),i=F`(SELECT json_group_object(message_member.key,
    CASE WHEN message_member.key = '__openclaw' AND message_member.type = 'object'
      THEN json(${r}) ELSE ${jsonMemberValue(`message_member`)} END)
    FROM json_each(root_member.value) AS message_member
    WHERE message_member.key IN ('role', 'idempotencyKey', 'provenance', 'excludeFromContext', '__openclaw'))`;return F`(SELECT json_group_object(root_member.key,
    CASE WHEN root_member.key = 'message' AND root_member.type = 'object'
      THEN json(${i}) ELSE ${jsonMemberValue(`root_member`)} END)
    FROM json_each(${t}) AS root_member
    WHERE root_member.key IN (${F.join([...rm,`message`])}))`}function projectResetBoundaryNavigationSql(e,t){let n=Re(e,t,[...nm,`timestamp`,`firstKeptEntryId`,`customType`,`display`]);return F`CASE WHEN ${Fe(e,t)} THEN
    CASE WHEN ${It(e,t)} = 'object' THEN
      ${le(e,n,F.lit(`$.message`),te(e,{role:E(e,t,F.lit(`$.message.role`))}),!0)}
    ELSE ${t} END
    ELSE ${t} END`}function systemUpdateKindSql(e,t){return F`CASE
    WHEN ${E(e,t,F.lit(`$.customType`))} = 'openclaw.system-update'
      AND ${E(e,t,F.lit(`$.details.kind`))} IN ('prompt-update', 'runtime-context')
    THEN ${E(e,t,F.lit(`$.details.kind`))} ELSE NULL END`}function projectModelContextNavigationSql(e,t,n,r=se(e,t)){if(z(e)){let r=F.ref(`nav_parts.event`),i=F.ref(`nav_parts.message`),a=F.ref(`nav_parts.content`),o=n??F`${r} ->> 'type'`,s=Fe(e,t);return F`CASE WHEN ${s} THEN (
      WITH nav_input AS MATERIALIZED (SELECT (CASE WHEN ${s} THEN ${t} END)::jsonb AS event),
      nav_parts AS MATERIALIZED (SELECT event, event -> 'message' AS message,
        event #> '{message,content}' AS content FROM nav_input)
      SELECT ${postgresModelNavigationSql(r,i,a,o)}::text FROM nav_parts)
      ELSE ${t} END`}let i=n??E(e,t,F.lit(`$.type`)),a=Re(e,t,rm),o=br()?F`jsonb_extract(${t}, '$.message')`:F`json_extract(${t}, '$.message')`,s=Re(e,o,im),c=systemUpdateKindSql(e,o),l=systemUpdateKindSql(e,t),u=F`json_set(${a}, '$.content', json('[]'))`,d=F`(SELECT json_group_array(json_object(
    'type', ${contentPropertySql(t,`type`)}, 'id', ${contentPropertySql(t,`id`)},
    'name', ${contentPropertySql(t,`name`)}))
    FROM json_each(${t}, '$.message.content') WHERE type = 'object'
    AND ${contentPropertySql(t,`type`)} IN ('toolCall', 'toolUse', 'functionCall'))`,f=F`COALESCE(json_extract(${t}, ${`$.message.details.${Qp}`}), 0) = 1 OR EXISTS (
    SELECT 1 FROM json_each(${t}, '$.message.content') WHERE type = 'object'
    AND ${contentPropertySql(t,`type`)} = 'text' AND ${contentPropertySql(t,`text`)} = ${$p})`,p=F`CASE ${i}
    WHEN 'message' THEN json_set(${a}, '$.message', json_set(${s},
      '$.content', json(${d}), '$.command', '', '$.output', '',
      '$.providerReplay', json_object('type', json_extract(${t}, '$.message.providerReplay.type')),
      '$.details', json_patch(json_object(${Qp}, json(CASE WHEN (${f}) THEN 'true' ELSE 'false' END)),
        CASE WHEN ${c} IS NULL THEN json('{}') ELSE json_object('kind', ${c}) END)))
    WHEN 'custom_message' THEN CASE WHEN ${l} IS NULL THEN ${u}
      ELSE json_set(${u}, '$.details', json_object('kind', ${l})) END
    WHEN 'custom' THEN CASE WHEN ${E(e,t,F.lit(`$.customType`))} = 'openclaw.system-prompt'
      THEN json_set(${a}, '$.data', json_object('restart', json(CASE
        WHEN json_type(${t}, '$.data.restart') = 'true' THEN 'true' ELSE 'false' END)))
      WHEN ${E(e,t,F.lit(`$.customType`))} = ${Xp}
      THEN ${le(e,a,F.lit(`$.data`),w(e).fn(`json`,[Re(e,E(e,t,F.lit(`$.data`)),[`afterEntryId`,`resultEntryIds`])]),!0)}
      ELSE ${a} END
    WHEN 'compaction' THEN json_set(${a}, '$.summary', '')
    WHEN 'branch_summary' THEN json_set(${a}, '$.summary', '')
    ELSE ${a} END`;return F`CASE WHEN ${r} THEN ${p}
    ELSE ${projectDeepModelContextSql(e,t,!0)} END`}function postgresModelEventSql(e,t){let n=e;for(let e of em)n=F`(${n}::jsonb #- ${F.lit(`{message,__openclaw,${e}}`)}::text[])`;return F`CASE WHEN ${t} = 'toolResult'
    THEN ${n} #- '{message,details}' ELSE ${n} END`}function postgresNavigationObjectSql(e,t){return F`(
    SELECT coalesce(jsonb_object_agg(key, value), '{}'::jsonb)
    FROM jsonb_each(CASE WHEN jsonb_typeof(${e}) = 'object' THEN ${e} ELSE '{}'::jsonb END)
    WHERE key IN (${F.join(t.map(e=>F.lit(e)))})
  )`}function postgresModelNavigationSql(e,t,n,r){let i=postgresNavigationObjectSql(e,rm),a=postgresNavigationObjectSql(t,im),o=F`jsonb_array_elements(
    CASE WHEN jsonb_typeof(${n}) = 'array' THEN ${n} ELSE '[]'::jsonb END)`,s=F`(
    SELECT coalesce(jsonb_agg(jsonb_build_object('type', value ->> 'type', 'id', value ->> 'id', 'name', value ->> 'name')), '[]'::jsonb)
    FROM ${o} WHERE jsonb_typeof(value) = 'object' AND value ->> 'type' IN ('toolCall', 'toolUse', 'functionCall'))`,c=F`coalesce((${t} #> ${F.lit(`{details,${Qp}}`)}::text[])::text, 'false') IN ('true', '1') OR EXISTS (
    SELECT 1 FROM ${o} WHERE value ->> 'type' = 'text' AND value ->> 'text' = ${$p})`,l=F`CASE WHEN ${t} ->> 'customType' = 'openclaw.system-update'
    AND ${t} #>> '{details,kind}' IN ('prompt-update', 'runtime-context') THEN ${t} #>> '{details,kind}' END`,u=F`CASE WHEN ${e} ->> 'customType' = 'openclaw.system-update'
    AND ${e} #>> '{details,kind}' IN ('prompt-update', 'runtime-context') THEN ${e} #>> '{details,kind}' END`;return F`CASE ${r}
    WHEN 'message' THEN ${i} || jsonb_build_object('message', ${a} || jsonb_build_object(
      'content', ${s}, 'command', '', 'output', '',
      'providerReplay', jsonb_build_object('type', ${t} #>> '{providerReplay,type}'),
      'details', jsonb_build_object(${F.lit(Qp)}, (${c})) ||
        CASE WHEN ${l} IS NULL THEN '{}'::jsonb ELSE jsonb_build_object('kind', ${l}) END))
    WHEN 'custom_message' THEN ${i} || jsonb_build_object('content', '[]'::jsonb) ||
      CASE WHEN ${u} IS NULL THEN '{}'::jsonb ELSE jsonb_build_object('details', jsonb_build_object('kind', ${u})) END
    WHEN 'custom' THEN CASE WHEN ${e} ->> 'customType' = 'openclaw.system-prompt'
      THEN ${i} || jsonb_build_object('data', jsonb_build_object('restart', coalesce((${e} #> '{data,restart}')::text, 'false') = 'true'))
      WHEN ${e} ->> 'customType' = ${Xp}
      THEN ${i} || jsonb_build_object('data', ${postgresNavigationObjectSql(F`${e} -> 'data'`,[`afterEntryId`,`resultEntryIds`])})
      ELSE ${i} END
    WHEN 'compaction' THEN ${i} || jsonb_build_object('summary', '')
    WHEN 'branch_summary' THEN ${i} || jsonb_build_object('summary', '')
    ELSE ${i} END`}mn(Symbol.for(`openclaw.sessionTranscriptListeners`),`close-and-restart`),mn(Symbol.for(`openclaw.internalSessionTranscriptListeners`),`close-and-restart`),R(Symbol.for(`openclaw.sessionTranscriptUpdateState`),()=>({version:0}));const om={id:S().min(1),parentId:Lt([S(),y()]).optional(),timestamp:S().optional(),appendMode:ce().optional()};D({kind:s(`canonical`),hasParentId:fe(),entry:an(`type`,[D({...om,type:s(`message`),assistantResponseId:S().optional(),assistantRunId:S().optional()}),D({...om,type:s(`custom_message`),customType:S().min(1)}),D({...om,type:s(`label`),targetId:S().min(1),label:S().optional()}),D({...om,type:Se([`thinking_level_change`,`model_change`,`compaction`,`reset`,`branch_summary`,`custom`,`session_info`])})])}).refine(({entry:e,hasParentId:t})=>t===(e.parentId!==void 0));const sm={version:1,report:null,navigation:{},reset:{},model:{},modelBytes:0,modelWithoutCheckpointBytes:0,withoutCustomDataBytes:0};function minimumNavigationBytes(e){return Buffer.byteLength(JSON.stringify({...sm,navigation:e,reset:e,model:e}))-4}minimumNavigationBytes({}),minimumNavigationBytes({type:0,id:0}),minimumNavigationBytes({type:0,id:0,parentId:0});function navigationProjection(e,t,n,r){if(z(e))return F`CASE
      WHEN ${se(e,r)} AND ${se(e,n)} THEN CASE
      WHEN json_typeof(${r}::json) != 'object'
        OR coalesce(json_typeof(${r}::json -> 'message'), 'null') NOT IN ('object', 'null') THEN NULL
      ELSE json_build_object('version', 1,
        'report', ${n}::json,
        'navigation', ${projectTranscriptPayloadNavigationSql(e,t)}::json,
        'reset', ${projectResetBoundaryNavigationSql(e,r)}::json,
        'model', ${projectModelContextNavigationSql(e,t)}::json,
        'modelBytes', octet_length(${projectModelContextEventSql(e,t,F.lit(0))}),
        'modelWithoutCheckpointBytes', octet_length(${projectModelContextEventSql(e,t,F.lit(1))}),
        'withoutCustomDataBytes', octet_length(${b(e,t,[F.lit(`$.data`)])}))::text
      END ELSE NULL END`;let i=te(e,{...Object.fromEntries(Object.entries(sm).map(([e,t])=>[e,typeof t==`number`?F.lit(t):F`json(${JSON.stringify(t)})`])),report:F`json(${n})`,navigation:F`json(${projectTranscriptPayloadNavigationSql(e,t)})`,reset:F`json(${projectResetBoundaryNavigationSql(e,r)})`,model:F`json(${projectModelContextNavigationSql(e,t,void 0,F.lit(1))})`,modelBytes:F`octet_length(${projectModelContextEventSql(e,t,F.lit(0),void 0,void 0,F.lit(1))})`,modelWithoutCheckpointBytes:F`octet_length(${projectModelContextEventSql(e,t,F.lit(1),void 0,void 0,F.lit(1))})`,withoutCustomDataBytes:F`octet_length(json_remove(${t}, '$.data'))`});return F`CASE WHEN json_valid(${r}) AND json_valid(${n}) THEN CASE
    WHEN json_type(${t}) != 'object'
      OR coalesce(json_type(${t}, '$.message'), 'null') NOT IN ('object', 'null') THEN NULL
    ELSE ${i} END ELSE NULL END`}r(e=>ae(e,t=>{let n=w(e),r=n.selectFrom(n.selectNoFrom([t(e=>e.eventJson).as(`event_json`),t(e=>e.reportJson).as(`report_json`)]).as(`input`)).select([`input.event_json`,`input.report_json`]).select(t=>!z(e)&&br()?F`CASE WHEN json_valid(${t.ref(`input.event_json`)})
                  THEN jsonb(${t.ref(`input.event_json`)}) ELSE ${t.ref(`input.event_json`)} END`.as(`event_projection`):t.ref(`input.event_json`).as(`event_projection`));return n.with(e=>e(`source`).notMaterialized(),()=>r).with(e=>e(`metadata`).materialized(),t=>t.selectFrom(`source`).select(t=>navigationProjection(e,t.ref(`source.event_projection`),t.ref(`source.report_json`),t.ref(`source.event_json`)).as(`navigation_json`))).selectFrom(`metadata`).select(t=>F`CASE WHEN ${se(e,t.ref(`metadata.navigation_json`))}
                AND octet_length(metadata.navigation_json) <= ${16384}
                THEN metadata.navigation_json ELSE NULL END`.as(`navigation_json`))}));var SessionTranscriptColdError=class extends Error{constructor(e=``){super(`Transcript${e?` ${e}`:``} is in cold storage. Restore its archive before reading or changing the transcript.`),this.sessionId=e,this.code=`TRANSCRIPT_COLD`,this.name=`SessionTranscriptColdError`}};const cm=`openclaw_transcript_payload_decode`,lm=/* @__PURE__ */ new WeakSet,um=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});function registerDecoder(e){lm.has(e)||(e.function(cm,{deterministic:!0,directOnly:!0},decodeCompressedTranscriptPayload),lm.add(e))}function decodeCompressedTranscriptPayload(e,t){if(e===null)throw new SessionTranscriptColdError;try{if(!(e instanceof Uint8Array)||e.byteLength===0||e.byteLength>4194304||typeof t!=`number`||!Number.isSafeInteger(t)||t<1||t>4194304)throw Error(`Invalid compressed transcript payload bounds`);let n=resolveZstdCodec().decompress(e,t);if(n.byteLength!==t)throw Error(`Compressed transcript payload length does not match its recorded UTF-8 size`);return um.decode(n)}catch(e){throw Object.assign(Error(`Corrupt transcript body: ${e instanceof Error?e.message:String(e)}. Restore a verified backup and run openclaw doctor.`,{cause:e}),{name:`SessionTranscriptCorruptionError`,code:`TRANSCRIPT_CORRUPT`})}}function transcriptEventJsonSql(e,t=`transcript_events`){if(z(e))return F.ref(`${t}.event_json`);registerDecoder(e);let n=F.ref(`${t}.event_json`),r=F.ref(`${t}.event_zstd`),i=F.ref(`${t}.event_utf8_bytes`),a=w(e).fn(cm,[r,i]);return F`coalesce(${n}, ${a})`}function transcriptEventNavigationSql(e,t=`transcript_events`){return storedProjectionSql(e,`navigation`,F.ref(`${t}.event_json`),t)}function transcriptPredicateSql(e,t,n=`transcript_events`){let r=F.ref(`${n}.${t}`);if(z(e))return r;let i=F.ref(`${n}.navigation_type`),a=F.ref(`${n}.navigation_valid`),o=F.ref(`${n}.event_json`),s=F.ref(`${n}.navigation_json`),c=F`coalesce(${o}, ${E(e,s,F.lit(`$.navigation`),`json`)})`,l=se(e,c),u=F`CASE WHEN ${l} THEN ${c} ELSE '{}' END`,d;if(t===`navigation_valid`)d=F`coalesce(${l}, 0)`;else if(t===`navigation_display`)d=F`CASE WHEN json_type(${u}, '$.display') = 'true' THEN 1 ELSE 0 END`;else{let n=t===`navigation_custom_type`||t===`navigation_last_custom_type`,r=t===`message_role`?`$.message.role`:n?`$.customType`:`$.type`,i=t===`navigation_last_type`||t===`navigation_last_custom_type`?F`(SELECT value FROM json_each(${u}) WHERE key = ${F.lit(n?`customType`:`type`)} ORDER BY id DESC LIMIT 1)`:E(e,u,F.lit(r)),a=t===`message_role`?[`user`,`assistant`,`toolResult`,`system`]:n?[`openclaw.runtime-context`,`openclaw.cache-ttl`]:[`session`,`message`,`reset`,`compaction`,`custom_message`,`custom`];d=F`CASE WHEN ${i} IN (${F.join(a.map(e=>F.lit(e)))}) THEN ${i} END`}return F`CASE WHEN ${i} IS NOT NULL OR ${a} = 0
    THEN ${r} ELSE ${d} END`}function storedProjectionSql(e,t,n,r){let i=F.ref(`${r}.navigation_json`);return F`CASE WHEN ${i} IS NULL THEN ${n}
    ELSE ${E(e,i,F.val(`$.${t}`),`json`)} END`}function transcriptEventModelNavigationSql(e,t=`transcript_events`,n){return storedProjectionSql(e,`model`,projectModelContextNavigationSql(e,F.ref(`${t}.event_json`),n),t)}function transcriptEventDependencyNavigationSql(e,t,n=`event`){let r=transcriptPredicateSql(e,`navigation_type`,n),i=transcriptPredicateSql(e,`message_role`,n);return F`CASE
    WHEN ${r} IN ('custom', 'reset') OR ${r} IS NULL
      OR (${r} = 'message' AND ${t} = 0 AND ${i} = 'assistant')
    THEN ${transcriptEventModelNavigationSql(e,n)}
    ELSE '{}' END`}function transcriptEventUtf8BytesSql(e=`transcript_events`){return F.ref(`${e}.event_utf8_bytes`)}function transcriptDependencyFactsProjectableSql(e,t){let n=F.ref(`${t}.event_json`),r=F.ref(`${t}.navigation_json`);return z(e)?F`${r} IS NOT NULL OR ${Fe(e,n)}`:F`CASE WHEN ${r} IS NOT NULL THEN 1
    WHEN NOT ${Fe(e,n)} THEN 0
    WHEN ${E(e,n,F.lit(`$.type`))} = 'custom'
      AND ${E(e,n,F.lit(`$.customType`))} = ${Xp}
      AND ${It(e,n,F.lit(`$.data`))} = 'text' THEN 0 ELSE 1 END`}function buildSessionTranscriptActiveFactsInsert(e,t,n,r,i=!1,a=!1){let o=w(e),readNavigation=e=>{let t=e.facts;return`dependencyNavigationJson`in t?t.dependencyNavigationJson:null};if(a&&!i)return o.insertInto(`session_transcript_active_event_facts`).values(Array.from({length:n},(e,n)=>({session_id:t,seq:r(e=>e[n].eventSeq),serialized_bytes:r(e=>e[n].facts.serializedBytes),dependency_navigation_json:r(e=>readNavigation(e[n]))})));let s=z(e),c={seq:e=>e.eventSeq,context_eligible:e=>e.contextEligible,serialized_bytes:e=>e.facts.serializedBytes,dependency_navigation_json:readNavigation,event_json:e=>e.facts&&`payload`in e.facts?e.facts.payload.event_json:null,navigation_json:e=>e.facts&&`payload`in e.facts?e.facts.payload.navigation_json:null,navigation_type:e=>e.facts&&`payload`in e.facts?e.facts.payload.navigation_type:null,navigation_valid:e=>e.facts&&`payload`in e.facts?e.facts.payload.navigation_valid:null,message_role:e=>e.facts&&`payload`in e.facts?e.facts.payload.message_role:null},l=a?[`seq`,`serialized_bytes`,`dependency_navigation_json`]:[`seq`,`context_eligible`,`serialized_bytes`,`dependency_navigation_json`,`event_json`,`navigation_json`,`navigation_type`,`navigation_valid`,`message_role`],u=/* @__PURE__ */ new Set([`seq`,`context_eligible`,`serialized_bytes`,`navigation_valid`]),d=F`(values ${F.join(Array.from({length:n},(e,t)=>F`(${F.join(l.map(e=>{let n=r(n=>c[e](n[t]));return s?F`${n}::${F.raw(u.has(e)?`bigint`:`text`)}`:n}))})`))})`;return o.with(a?`active_fact_input(seq, serialized_bytes, dependency_navigation_json)`:`active_fact_input(seq, context_eligible, serialized_bytes, dependency_navigation_json, event_json, navigation_json, navigation_type, navigation_valid, message_role)`,()=>d).insertInto(`session_transcript_active_event_facts`).columns([`session_id`,`seq`,`serialized_bytes`,`dependency_navigation_json`]).expression(n=>n.selectFrom(`active_fact_input as event`).select(n=>[typeof t==`string`?n.val(t).as(`session_id`):t.as(`session_id`),`event.seq`,`event.serialized_bytes`,a?F`event.dependency_navigation_json`.as(`dependency_navigation_json`):F`CASE WHEN event.dependency_navigation_json IS NOT NULL
            THEN event.dependency_navigation_json
            ELSE ${transcriptEventDependencyNavigationSql(e,n.ref(`event.context_eligible`),`event`)} END`.as(`dependency_navigation_json`)]).$if(!a,t=>t.where(t=>t.or([t(`event.dependency_navigation_json`,`is not`,null),transcriptDependencyFactsProjectableSql(e,`event`)]))).$if(i,e=>e.where(F`event.seq IN (SELECT event_seq FROM projection_active)`)))}r(e=>{let prepare=(t,n)=>v(e,r=>buildSessionTranscriptActiveFactsInsert(e,r(e=>e.sessionId),t,e=>r(t=>e(t.rows)),!1,n)),t=[],n=[];return{forCount(e,r){let i=+!!r;return e===1?t[i]??=prepare(e,r):e===512?n[i]??=prepare(e,r):prepare(e,r)}}});const dm=`openclawDisplayContent`;function projectAssistantDisplayContent(e){let t=e[dm];if(e.role!==`assistant`||!Array.isArray(t))return e;let{[dm]:n,...r}=e;return{...r,content:t}}function isCanonicalSessionEntryType(e){switch(e){case`message`:case`thinking_level_change`:case`model_change`:case`compaction`:case`reset`:case`branch_summary`:case`custom`:case`custom_message`:case`label`:case`session_info`:return!0;default:return!1}}function isCanonicalSessionTranscriptEntry(e){return I(e)&&isCanonicalSessionEntryType(e.type)}function isSessionTranscriptLeafControl(e){return I(e)&&e.type===`leaf`&&parseSessionTranscriptTreeEntry(e)!==void 0}function parseSessionTranscriptTreeEntry(e){if(!I(e)||e.type===`session`||!Object.hasOwn(e,`parentId`))return;let t=Wn(e.id),n=e.parentId===null?null:Wn(e.parentId)??void 0;if(t&&n!==void 0){if(e.type===`leaf`){let n=e.targetId===null?null:Wn(e.targetId)??void 0,r=e.appendParentId===void 0?n:e.appendParentId===null?null:Wn(e.appendParentId)??void 0,i=e.appendMode===void 0?void 0:e.appendMode===`side`?`side`:null;return n===void 0||r===void 0||i===null?void 0:{id:t,parentId:n,leafId:n,appendParentId:r,...i?{appendMode:i}:{}}}return{id:t,parentId:n,leafId:isCanonicalSessionTranscriptEntry(e)&&e.appendMode!==`side`?t:void 0,appendParentId:t,...e.appendMode===`side`?{appendMode:e.appendMode}:{}}}}function parseParentlessCanonicalEntry(e,t){if(!isCanonicalSessionTranscriptEntry(e)||Object.hasOwn(e,`parentId`))return;let n=Wn(e.id);return n?{id:n,parentId:t,leafId:e.appendMode===`side`?void 0:n,appendParentId:n,...e.appendMode===`side`?{appendMode:e.appendMode}:{}}:void 0}function resolveCanonicalParentId(e,t){let n,r=e;for(;r!==null;){if(n?.has(r))return r;let e=t.get(r);if(!e||!isSessionTranscriptLeafControl(e.entry))return r;(n??=/* @__PURE__ */ new Set).add(r),r=e.parentId}return null}function scanSessionTranscriptTree(e){let t=[],n=/* @__PURE__ */ new Map;return{nodes:t,byId:n,...scanSessionTranscriptNavigation(e,{byId:n,addNode:e=>t.push(e),resetDescendantIds:/* @__PURE__ */ new Set,invalidLeafControlIds:/* @__PURE__ */ new Set})}}function scanSessionTranscriptNavigation(e,t){let{byId:n,resetDescendantIds:r,invalidLeafControlIds:i}=t,a=null,o=null,s=!1,c=!1,l=!1,u=!1,d,f=0;for(let p of e){let e=f++,m=parseSessionTranscriptTreeEntry(p),h=m!==void 0&&I(p)&&p.type===`leaf`;d&&a!==null&&m?.leafId!==void 0&&h&&(m.leafId===null||!r.has(m.leafId))&&(m={...m,parentId:a,leafId:a,appendParentId:a});let isKnownLeafReference=e=>e===null||n.has(e)&&!i.has(e);if(m?.leafId!==void 0&&h&&(!isKnownLeafReference(m.leafId)||!isKnownLeafReference(m.appendParentId))&&m){u=!0,i.add(m.id);let r=p.parentId,a={...m,parentId:r,leafId:void 0,appendParentId:o,entry:p,index:e};t.addNode(a),n.set(a.id,a);continue}let g=m??parseParentlessCanonicalEntry(p,a);if(g&&isCanonicalSessionTranscriptEntry(p)){let e=m&&g.parentId!==null&&!n.has(g.parentId)&&a!==null,t=resolveCanonicalParentId(d!==void 0&&g.appendMode!==`side`&&(g.parentId===null||!r.has(g.parentId))||g.appendMode!==`side`&&e||m&&g.appendMode!==`side`&&g.parentId===o&&a!==o?a:g.parentId,n);t!==g.parentId&&(g={...g,parentId:t})}if(!g)continue;let _={...g,entry:p,index:e,...h?{displacedLeafId:a}:{}};t.addNode(_),n.set(_.id,_),I(p)&&p.type===`reset`?(d=_.id,r.clear(),r.add(_.id)):d!==void 0&&_.parentId!==null&&r.has(_.parentId)&&r.add(_.id),o=_.appendParentId,_.leafId!==void 0&&(a=_.leafId,c=!0,m&&(l=!0)),h&&(s=!0)}return{leafId:a,appendParentId:o,hasLeafControl:s,hasLeafUpdate:c,hasExplicitLeafUpdate:l,hasInvalidLeafControl:u}}function selectSessionTranscriptTreePathNodes(e,t){let n=[];return visitSessionTranscriptTreePathNodes(e.byId,t,/* @__PURE__ */ new Set,e=>{n.push(e)})?n.toReversed():[]}function visitSessionTranscriptTreePathNodes(e,t,n,r){let i=t;for(;i;){if(n.has(i))return!1;n.add(i);let t=e.get(i);if(!t)break;isSessionTranscriptLeafControl(t.entry)||r(t),i=t.parentId}return!0}function readMessageText(e){if(!I(e)||e.role!==`user`&&e.role!==`assistant`)return;if(typeof e.content==`string`)return e.content.trim()||void 0;if(typeof e.text==`string`)return e.text.trim()||void 0;if(!Array.isArray(e.content))return;let t=e.content.flatMap(e=>!I(e)||e.type!==`text`&&e.type!==`input_text`&&e.type!==`output_text`?[]:typeof e.text==`string`&&e.text.trim()?[e.text]:[]);return t.length>0?t.join(`
`):void 0}function extractTranscriptIndexEntry(e,t){if(!I(e)||e.type!==`message`||typeof e.id!=`string`)return;let n=I(e.message)?e.message:void 0,r=n?.role,i=e.id.trim();if(!n||!i||r!==`user`&&r!==`assistant`)return;let a=readMessageText(projectAssistantDisplayContent(n))?.replaceAll(`\0`,` `);if(!a)return;let o=typeof e.timestamp==`number`?e.timestamp:typeof e.timestamp==`string`?Date.parse(e.timestamp):NaN;return{messageId:i,role:r,text:a,timestamp:Number.isFinite(o)?o:t}}function hasTranscriptMessage(e){return I(e)&&Object.hasOwn(e,`message`)&&e.message!==void 0}function transcriptEventContextEligibility(e){let t=I(e)&&(e.type===`custom_message`?e:e.message);return I(t)&&t.excludeFromContext===!0?0:1}function shouldProjectActiveEvent(e){return I(e)&&e.type!==`session`&&(isCanonicalSessionTranscriptEntry(e)||parseSessionTranscriptTreeEntry(e)!==void 0||hasTranscriptMessage(e))}function transcriptEventReadBytesSql(e=`transcript_events`){let t=F.ref(`${e}.event_json`);return F`coalesce(${transcriptEventUtf8BytesSql(e)}, octet_length(${t}))`}function projectTranscriptNavigationFields(e,t={}){for(let n of[`type`,`id`,`parentId`,`targetId`,`appendParentId`,`appendMode`])Object.hasOwn(e,n)&&(t[n]=e[n]);return t}function getProjectionKysely(e){return w(e)}function projectionFactsColumns(e){return[F`${transcriptEventReadBytesSql()} + 1`.as(`serialized_bytes`),F`CASE WHEN ${transcriptDependencyFactsProjectableSql(e,`transcript_events`)}
      THEN ${transcriptEventDependencyNavigationSql(e,F.lit(0),`transcript_events`)} ELSE NULL END`.as(`dependency_navigation_json`),transcriptPredicateSql(e,`navigation_type`).as(`navigation_type`)]}function projectionRowFacts(e,t){return e.serialized_bytes===void 0||e.dependency_navigation_json==null?void 0:{serializedBytes:e.serialized_bytes,dependencyNavigationJson:e.navigation_type===`message`&&t!==0?`{}`:e.dependency_navigation_json}}function readProjectionSession(e,t){return C(e,getProjectionKysely(e).selectFrom(`session_windows as session`).leftJoin(`transcript_rewrite_watermarks as rewrite`,`rewrite.session_id`,`session.session_id`).select([`session.transcript_updated_at`,`rewrite.generation`]).where(`session.session_id`,`=`,t))}function readProjectionSource(e,t){let n=getProjectionKysely(e),r=readProjectionSession(e,t);if(!r)return;let i=n.selectFrom(`transcript_events`).select([transcriptEventJsonSql(e).as(`event_json`),`seq`,`created_at`]).select(projectionFactsColumns(e)).where(`session_id`,`=`,t),a=v(e,e=>i.where(`seq`,`=`,e(e=>e)));return{sessionId:t,transcriptGeneration:r.generation,transcriptUpdatedAt:r.transcript_updated_at,rows:t=>xe(e,(t?i.clearSelect().select([transcriptEventNavigationSql(e).as(`event_json`),`seq`,`created_at`]):i).orderBy(`seq`,`asc`)),row:e=>a(e).rows[0]}}function visitProjectionSource(e,t){let n=-1,r=scanSessionTranscriptTree((function*(){for(let t of e.rows(!0)){n=t.seq;let e=JSON.parse(t.event_json);yield{seq:t.seq,...I(e)?projectTranscriptNavigationFields(e):{}}}})());if(n<0)return;let i=selectSessionTranscriptTreePathNodes(r,r.leafId),a=i.length>0?(function*(){for(let t of i){let n=e.row(t.entry.seq);n&&(yield n)}})():r.hasLeafControl?[]:e.rows(),o=0,s=0;for(let e of a){let n=JSON.parse(e.event_json),r=extractTranscriptIndexEntry(n,e.created_at);if(r&&t.ftsRow(r,e.seq),!shouldProjectActiveEvent(n))continue;let i=hasTranscriptMessage(n),a=transcriptEventContextEligibility(n);t.activeRow({activePosition:o++,contextEligible:a,facts:projectionRowFacts(e,a),eventSeq:e.seq,messagePosition:i?s++:null})}return{activeEventCount:o,activeMessageCount:s,leafEventId:r.appendParentId,sessionId:e.sessionId,sourceHasInvalidLeafControl:r.hasInvalidLeafControl,sourceIndexedSeq:n,sourceTranscriptGeneration:e.transcriptGeneration,sourceTranscriptUpdatedAt:e.transcriptUpdatedAt}}function prepareProjectionSource(e){let t=[],n=[],r=visitProjectionSource(e,{activeRow:e=>t.push(e),ftsRow:(e,t)=>n.push(t)});if(r)return{...r,activeRows:t,ftsRows:(function*(){for(let t of n){let n=e.row(t);if(n){let e=extractTranscriptIndexEntry(JSON.parse(n.event_json),n.created_at);e&&(yield e)}}})()}}function prepareSessionTranscriptProjection(e,t){return Ct(e,()=>{let n=readProjectionSource(e,t);return n?prepareProjectionSource(n):void 0},{databaseLabel:`agent transcript projection`,operationLabel:`sessions.transcript-index.prepare`})}const fm=262144;function resolveLeaseEnvironment(e){return{OPENCLAW_STATE_DIR:e.stateDir,...e.externallySupervised?{OPENCLAW_SUPERVISOR_MODE:`external`}:{}}}function releaseLease(e,t,n=!1){let r;try{releaseOpenClawAgentDatabaseLease(e.leaseId,{env:resolveLeaseEnvironment(e),initializationAgentPaths:[e.path]},n?`read-only`:void 0)}catch(e){r=e instanceof Error?e:Error(String(e))}finally{Ye()}r?t.postMessage({type:`lease-release-failed`,error:r.message}):t.postMessage({type:`lease-released`}),t.close()}function waitForMessage(e){return new Promise(t=>{e.once(`message`,t)})}async function postAndWait(e,t,n=[]){return e.postMessage(t,n),await waitForMessage(e)}function encodeFtsChunk(e){let t=new TextEncoder,n=e.map(e=>({bytes:t.encode(e.text),row:e})),r=new Uint8Array(n.reduce((e,t)=>e+t.bytes.length,0)),i=0;return{rows:n.map(({bytes:e,row:t})=>{r.set(e,i);let n={messageId:t.messageId,role:t.role,textByteLength:e.length,textByteOffset:i,timestamp:t.timestamp};return i+=e.length,n}),textBytes:r}}async function streamPreparedProjection(e,t){let{activeRows:n,ftsRows:r,...i}=e;if(!(await postAndWait(t,{type:`plan-start`,plan:i})).accepted)return!1;for(let r=0;r<n.length;r+=512)if(!(await postAndWait(t,{type:`active-chunk`,rows:n.slice(r,r+512),sessionId:e.sessionId})).accepted)return!1;let a=[],o=0,flush=async()=>{let n=encodeFtsChunk(a);return a=[],o=0,(await postAndWait(t,{type:`fts-chunk`,chunk:n,sessionId:e.sessionId},[n.textBytes.buffer])).accepted};for(let e of r){let t=Buffer.byteLength(e.text,`utf8`);if(a.length>0&&o+t>fm&&!await flush()||(a.push(e),o+=t,(a.length>=128||o>=fm)&&!await flush()))return!1}return a.length>0&&!await flush()?!1:(await postAndWait(t,{type:`plan-finish`,sessionId:e.sessionId})).yield===!0}async function run(e,t,n,r){let assertSource=()=>{if(e.mode===`disk`){if(!r)throw Error(`Transcript worker lost its captured source identity`);oi(e.path,r)}};if(e.mode===`release`){releaseLease(e,t,!0);return}let i=e,a,o;try{let e=(()=>{let e={agentId:i.agentId,path:i.path,env:resolveLeaseEnvironment(i)};assertSource(),n?.reconciliation&&oi(n.databasePath,n.reconciliation.identity),claimOpenClawAgentDatabaseLease(e,i.leaseId);let t=openOpenClawAgentDatabaseReadOnly(e);if(!t.found)throw Error(`Cannot prepare transcript indexes: ${t.reason}`);return a=t.database.close,t.database})(),r=i.sessionIds,s=!1;for(let[n,i]of r.entries()){let a=prepareSessionTranscriptProjection(e.db,i);if(a&&await streamPreparedProjection(a,t)){s=n<r.length-1;break}}o={type:`done`,yielded:s}}catch(e){o={type:`failed`,error:e instanceof Error?e.message:String(e)}}t.postMessage(o),await waitForMessage(t),a?.(),releaseLease(i,t,a!==void 0)}serveWorkerTasks(async e=>{if(!e||typeof e!=`object`||!(`input`in e)||!(`port`in e))throw Error(`session transcript reconcile worker requires a task`);if(!(e.port instanceof Bs))throw Error(`session transcript reconcile worker requires valid task data`);let{input:t,port:n,coordination:r,sourceIdentity:i}=e;try{if(!r?.reconciliation)throw Error(`Transcript worker requires lifecycle coordination`);await runWithSqliteMutationWorkerCoordination(r,{env:resolveLeaseEnvironment(t)},()=>run(t,n,r,i))}finally{e.port.close()}},{retireOnError:!0});export{openSharedStateSqliteWorkerStore as a,runPluginSharedStateWork as c,isSqliteWorkerStoreAvailable as i,assertAppContainerSpawnSupported as l,getSqliteWorkerActorIdentity as n,retireSqliteWorkerActor as o,hasUnclaimedSharedStateSqliteCleanup as r,runSqliteWorkerStoreOperation as s,closeUnclaimedSharedStateSqliteWorkers as t};