UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,294 lines • 93.5 kB
import{o as e}from"./transcript-record-coerce-eN4p5mcq.mjs";import{l as t}from"./transcript-openclaw-agent-search-schema-BQwqsKhe.mjs";import"./transcript-plugin-instance-invocation-7pP9ZY8b.mjs";import{_ as n}from"./transcript-worker-cpu-DTToyx8O.mjs";import{T as r,c as i,et as a,j as o,rt as s,w as c}from"./transcript-sqlite-database-admission-Cro6ZHgY.mjs";import{d as l,m as u,r as d}from"./transcript-sqlite-worker-identity-C2ykgpDo.mjs";import{i as f,t as p}from"./transcript-subsystem-er2pCebD.mjs";import{R as m,r as h}from"./transcript-sqlite-table-layout-migration-6FYoXQ_h.mjs";import{n as g}from"./transcript-json-coercion-FJNyjMmt.mjs";import{t as _}from"./transcript-state-dir-BTeq06tQ.mjs";import{r as v}from"./transcript-src-DFL7yLCI.mjs";import"./transcript-paths-B5zwyc4S.mjs";import{r as y}from"./transcript-path-existence-DsAt-_G2.mjs";import{t as ee}from"./transcript-version-cakuJMg_.mjs";import{t as b}from"./transcript-deferred-B75K7ut7.mjs";import{n as x,r as S}from"./transcript-sql-connection-CRz-dHXM.mjs";import{c as C,s as w}from"./transcript-sqlite-post-commit-BDZjIt2B.mjs";import{c as T,l as te,s as ne}from"./transcript-session-metadata-unavailable-error-DL1m1RWN.mjs";import{s as E}from"./transcript-openclaw-state-db-contract-DiFTYPe3.mjs";import{a as re}from"./transcript-kysely-sync-cache-state-9JTloBF9.mjs";import{c as D,t as O}from"./transcript-sqlite-schema-sql-BnVx4b5A.mjs";import{_ as k,h as A,l as j,o as M,t as ie,u as N}from"./transcript-sqlite-schema-facts-C4Tsn8VX.mjs";import{n as P}from"./transcript-agent-id-DmscQLD6.mjs";import{a as F,i as I,l as L}from"./transcript-openclaw-agent-db.paths-5mfY5--s.mjs";import{a as R,i as ae,s as oe}from"./transcript-openclaw-state-db.paths-DYRyvCKa.mjs";import"./transcript-session-key-DI46891-.mjs";import{n as se}from"./transcript-artifact-preserving-state-reads-BHzs8nJG.mjs";import{E as ce,d as le,f as ue,g as de,m as fe,p as pe,u as me}from"./session-transcript.worker.js";import{a as z,c as B,r as V}from"./transcript-kysely-sync-DQ_Yn8jW.mjs";import{i as he,o as ge}from"./transcript-sqlite-transaction-BxeoS_ke.mjs";import{a as _e,i as ve}from"./transcript-sqlite-busy-timeout-DspDnAK7.mjs";import{G as ye,J as be,M as xe,X as Se,Y as Ce,a as we,i as Te,j as Ee,k as De,l as Oe,n as ke,nt as H,ot as Ae,q as je,r as Me,t as Ne,u as Pe,w as Fe,y as Ie}from"./transcript-openclaw-agent-db-schema-read-0j86l7zG.mjs";import{$ as Le,J as Re,et as ze,p as Be}from"./transcript-openclaw-state-db-cache-DY0tZ0IC.mjs";import{i as Ve,n as He,r as U}from"./transcript-openclaw-agent-db-borrower-CEWh9POj.mjs";import{n as Ue}from"./transcript-node-crypto-2Kpo-Xy-.mjs";import"./transcript-crypto-digest-1BMQKHCD.mjs";import{b as We,n as Ge,y as Ke}from"./transcript-openclaw-quarantine-store-Cpfq2f44.mjs";import{m as qe,v as Je}from"./transcript-worker-task-pool-xHbAfEur.mjs";import{At as Ye,Ft as Xe,Nt as Ze,R as Qe,et as $e,jt as et}from"./transcript-openclaw-state-db-readonly-wvpVS-us.mjs";import{n as tt,t as nt}from"./transcript-node-sqlite-dPq0UNII.mjs";import{a as rt,i as it,n as W}from"./transcript-openclaw-state-db-schema-helpers-DTvLbSq6.mjs";import{o as at,s as ot,t as st}from"./transcript-openclaw-agent-db-identity-BwKDyjmN.mjs";import{S as ct,T as lt,a as ut,g as dt,i as ft,k as pt,n as mt,p as ht,u as gt}from"./transcript-openclaw-agent-trajectory-storage-migration-DjoMAPIY.mjs";import{L as _t,M as vt,b as yt,h as bt,i as xt,j as St,k as Ct,l as wt,n as Tt,o as Et,p as Dt,s as Ot,t as kt,u as G,y as At}from"./transcript-openclaw-agent-db-validation-cache-CPj39b9d.mjs";import{b as jt,g as Mt,h as Nt,n as Pt,t as Ft,v as It,x as Lt,y as Rt}from"./transcript-openclaw-agent-schema-history-FA8O-tkY.mjs";import{n as zt,r as Bt,t as Vt}from"./transcript-openclaw-agent-db-engine-YRrMbR9J.mjs";import{c as Ht,l as Ut,o as Wt,s as Gt}from"./transcript-openclaw-agent-db-readonly-open-Cx-tx28d.mjs";import{n as Kt}from"./transcript-openclaw-agent-db-readonly-scope-BsN_9OGD.mjs";import{i as qt}from"./transcript-session-entry-json-Bunk1tNp.mjs";import{r as Jt}from"./transcript-session-entry-snapshots-BiQPPk-L.mjs";import{n as Yt}from"./transcript-transcript-payload-C58U6XNI.mjs";import{t as Xt}from"./transcript-zstd-codec-Bwg8OR0e.mjs";import"./transcript-transcript-payload-read-BfcV5CyI.mjs";import{$ as Zt,A as Qt,B as $t,C as en,D as tn,E as K,F as nn,G as rn,H as an,I as on,J as sn,K as cn,L as ln,N as q,O as un,P as dn,Q as fn,R as pn,S as mn,T as hn,U as gn,V as _n,W as vn,X as yn,Y as bn,Z as J,_ as xn,a as Sn,b as Y,c as Cn,d as wn,f as Tn,g as En,h as Dn,i as On,j as kn,k as An,l as jn,m as X,n as Mn,o as Nn,p as Pn,q as Fn,s as In,t as Ln,u as Rn,v as zn,w as Bn,x as Vn,y as Hn,z as Un}from"./transcript-session-worker-execution-source-Bovma__-.mjs";import{i as Wn,n as Gn,o as Kn,s as qn}from"./transcript-openclaw-state-db-DbakxDr-.mjs";import{c as Jn,i as Yn,r as Xn}from"./transcript-openclaw-agent-db-owner-read-DYchwk6B.mjs";import{t as Zn}from"./transcript-openclaw-agent-board-schema-c65OQI5T.mjs";import{isMainThread as Z}from"node:worker_threads";import Qn from"node:path";import{chmodSync as $n,existsSync as er,mkdirSync as tr,statSync as nr}from"node:fs";async function runSqliteIntegrityOperationInWorker(e,t){let n=m(t.signal)??t.signal,beforeResume=()=>{n.throwIfAborted(),t.beforeResume()};try{beforeResume();let r=e.next();for(;!r.done;){let i,a=!1;try{await Ht(r.value.databaseLabel,t.busyTimeoutMs,n,void 0,r.value.timing,{check:r.value.check,schemaOnly:r.value.schemaOnly,tables:r.value.tables,ftsSchemas:r.value.ftsSchemas},{onToleratedFts:()=>{a=!0}})}catch(e){i={error:e}}if(beforeResume(),!i&&r.value.check!==`quick`&&!a&&o(r.value.database),i&&t.repairIntegrityError){let e=i.error;try{await t.repairIntegrityError(r.value,e)&&(i=void 0)}catch(t){e instanceof Error&&(e.message+=` Startup FTS repair failed: ${String(t)}`)}beforeResume()}r=i?e.throw(i.error):e.next()}return r.value}finally{e.return(void 0)}}async function withWorkerAdmission(t,n,r,a,o,s){let c=L(t);ue(t),le(t);let d=pe(t),f=P(t.agentId),p=b(),m=!1,releaseExecution,assertAdmission=()=>{if(m)throw Error(`Agent database admission closed during worker preparation`);n?.(),o?.assertCurrent(),d?.assertCurrent(),r?.throwIfAborted()},h=Fe({agentId:f,path:c,revoke:()=>{m=!0},close:()=>p.promise},t);try{let n=o?i(c):void 0,d=n?{...n,canonicalPath:await u(c)}:await l(c);if(o&&(o.assertCurrent(),o.agentId!==f||o.path!==c))throw Error(`Agent worker admission differs from its captured execution`);assertAdmission();let p=d.canonicalPath===c?void 0:xt({agentId:f,path:c,canonicalPath:d.canonicalPath}),m=await import(`./transcript-openclaw-agent-execution-sefImfO-.mjs`).then(e=>e.r);if(assertAdmission(),!m.supportsOpenClawAgentDatabaseExecution(t))return await a(`native`);let h;if(o)h=o;else{let e=await m.captureOpenClawAgentDatabaseExecutionAsync(t,d.key.startsWith(`file:`)?{expectedIdentity:{kind:`file`,physicalIdentity:d.key.slice(5),nativeLocation:d.canonicalPath,birthtime:d.birthtime}}:{});h=e,releaseExecution=()=>e.release()}let g={assertCurrent:assertAdmission,onRegistryChange:s,createAdmission:t=>()=>({nativeLocations:t.nativeLocations,admission:qe((n,r)=>{if(t.authorize(n),assertAdmission(),p&&n.stage===`prepare`&&e(n.facts)&&n.facts.kind===`agent-validation-start`&&(p=xt({agentId:f,path:c,canonicalPath:d.canonicalPath})),!r())throw Error(`Agent database preparation lost its admission`)},t.attachment)})};return await kn(t,()=>h.prepare(g,r)),assertAdmission(),p?.(h.captureGenerationClaim().identity,Ot({agentId:f,path:d.canonicalPath,canonicalPath:d.canonicalPath})),await a(`worker`)}finally{try{await releaseExecution?.()}finally{h(),p.resolve()}}}function assertAgentDatabaseOpenAuthority(e,t){try{t?.()}catch(t){let n=Error(`Agent database open authority was refused`,{cause:t});try{e.throw(n)}catch(e){if(e!==n)throw AggregateError([t,e],`Agent database authority and cleanup failed: ${e instanceof Error?e.message:String(e)}`,{cause:e})}throw t}}function assertAgentDatabaseOperationCurrent(e,t,n,r){if(n.controller.signal.throwIfAborted(),Ve(e.agentId,{env:t.env}),q.databases.get(n.path)!==e||!e.db.isOpen)throw Error(`Agent database closed before its admitted operation: ${n.path}`);De(e,t),me(e,t),r?.()}function assertAgentDatabaseWriteAllowed(e){if(Qn.basename(e)===`incognito-openclaw-agent.sqlite`)throw Error(`Incognito sessions use the memory session actor, not a SQLite database.`);if(se(`agent`,e))throw Error(`Programming error: writable agent database open during read-only inspection.`)}function createOpenClawAgentDatabaseAdmissionOwner(e){function openOpenClawAgentDatabase(e,t,n){return openAgentDatabase(e,t,n)}function openAgentDatabase(t,n,r,i){assertAgentDatabaseWriteAllowed(L(t));let run=()=>{let a=e(t,void 0,n,r,i),assertCurrent=()=>{i?.assertCurrent?.(),n&&!Z&&Je({stage:`prepare`,facts:{kind:`agent-open-resume`,lease:n.receipt}})},o=n?.startupRepair;return Ce(a,()=>assertAgentDatabaseOpenAuthority(a,assertCurrent),o&&!Z?(e,t)=>o(e,t,assertCurrent):void 0,Z?Ut:void 0)},a=H();return a?a.run(run):run()}async function openOpenClawAgentDatabaseInWorker(t,n,r,i){assertAgentDatabaseWriteAllowed(L(t));let a=e(t,void 0,n,r),assertCurrent=()=>assertAgentDatabaseOpenAuthority(a,()=>{i.throwIfAborted(),Je({stage:`prepare`,facts:{kind:`agent-open-resume`,lease:n.receipt}})}),o=n.startupRepair,s=await runSqliteIntegrityOperationInWorker(a,{busyTimeoutMs:E,signal:i,beforeResume:assertCurrent,repairIntegrityError:o?(e,t)=>o(e,t,assertCurrent):void 0});if(!s)throw Error(`Agent database opening ended without its native owner`);return s}function runOpenClawAgentWriteTransaction(e,t,n={}){let{repairAdmission:r,singleStatement:i,...a}=n,o=openAgentDatabase(t,void 0,void 0,r),s=Ee(t)?.withCommit,c=r?e=>{r.assertCurrent?.(),r.expectedIdentity&&st(o,r.expectedIdentity),s?s(e):e()}:s,write=()=>(De(o,t),me(o,t),e(o));return i&&!c&&!x(o.db)?ve(o.db,a.busyTimeoutMs??5e3,()=>ge(o.db,write)):C(o.db,()=>he(o.db,write,{busyTimeoutMs:a.busyTimeoutMs??5e3,databaseLabel:o.path,...a,operationLabel:a.operationLabel??`agent.write`,withCommit:c}))}function withOpenClawAgentDatabaseAsync(e,t,n,r){let run=()=>runAgentDatabaseAsync(e,t,n,r,`native`),i=H();return i?i.run(run):run()}function withOpenClawAgentDatabaseRuntime(e,t,n,r,i){let run=()=>runAgentDatabaseAsync(e,t,n,r,void 0,void 0,i),a=H();return a?a.run(run):run()}function withOpenClawAgentDatabaseRuntimeFromExecution(e,t,n,r,i){let a=P(e.agentId),o=L({...e,agentId:a}),assertExecutionCurrent=()=>{if(t.assertCurrent(),t.agentId!==a||t.path!==o)throw Error(`Agent runtime admission differs from its captured execution`);r?.()},run=()=>runAgentDatabaseAsync(e,n,assertExecutionCurrent,i,void 0,t),s=H();return s?s.run(run):run()}async function runAgentDatabaseAsync(e,t,n,r,i,a,o){r?.throwIfAborted(),n?.();let s={...e,env:ce(e.env??process.env)},c=P(s.agentId),l=L({...s,agentId:c});assertAgentDatabaseWriteAllowed(l),s.env.OPENCLAW_STATE_DIR=_(s.env),s.path=l,q.terminal.peek(l)&&await Gt(l,n,r);let u=q.databases.get(l),d=Ot({agentId:c,path:l})?.schema;if(!i&&Z&&(!u?.db.isOpen||!d||Atomics.load(new Int32Array(d.valid),0)!==1)&&!q.pending.has(l))return withWorkerAdmission(s,n,r,e=>runAgentDatabaseAsync(s,t,n,r,e,a,o),a,o);let f=q.pending.get(l);if(f?.agentId!==void 0&&f.agentId!==c)throw Error(`Agent database ${l} is opening for ${f.agentId}`);if(f?.controller.signal.aborted)return f.promise.then(()=>runAgentDatabaseAsync(s,t,n,r,i,a,o),()=>runAgentDatabaseAsync(s,t,n,r,i,a,o));let p=f??startOpenClawAgentDatabaseAdmission(s,c,l,n,i===`worker`);return p.operations+=1,v(p.promise,r).then(e=>(r?.throwIfAborted(),assertAgentDatabaseOperationCurrent(e,s,p,n),Ae(e.db),t(e))).finally(()=>{--p.operations,p.operations||(p.releaseBorrow||p.controller.abort(/* @__PURE__ */ Error(`Agent database admission has no waiting callers`)),p.releaseBorrow?.())})}function withOpenClawAgentDatabaseAdmission(e,t,n){let run=()=>runAgentDatabaseAdmission(e,t,n),r=H();return r?r.run(()=>r.track(run())):run()}async function runAgentDatabaseAdmission(t,n,r){let i={...t,env:ce(t.env??process.env)},a=P(i.agentId),o=L({...i,agentId:a});assertAgentDatabaseWriteAllowed(o),q.terminal.peek(o)&&await Gt(o);let s=q.pending.get(o);if(s){if(s.agentId!==a)throw Error(`Agent database ${o} is opening for ${s.agentId}`);try{await s.promise}catch(e){if(!s.controller.signal.aborted)throw e}return withOpenClawAgentDatabaseAdmission(i,n,r)}let c=createOpenClawAgentDatabaseAdmission(a,o),{pending:l}=c;l.promise.catch(()=>{}),l.operations+=1;let u=e(i,l),d,f,p=!1;try{for(;;){let e=await n(async(e,t,n)=>{p=!1,assertAgentDatabaseOpenAuthority(u,()=>{e(),assertOpenClawAgentDatabaseAdmissionCurrent(i,l)}),l.validation=t,l.integrityRevoked=n;let a=f?u.throw(f.error):u.next();if(!a.done)return p=!0,{done:!1,check:a.value};l.releaseBorrow=U(a.value.db),c.complete(a.value);let assertOperationCurrent=()=>assertAgentDatabaseOperationCurrent(a.value,i,l,e);assertOperationCurrent();let o=Z||x(a.value.db)?void 0:Le(a.value.db);o?.(assertOperationCurrent);let s=await r(a.value);return o?.(assertOperationCurrent),{done:!0,result:s}});if(e.done)return e.result;d=e.check,f=void 0;try{l.controller.signal.throwIfAborted(),(Z?Ut:be)(d)}catch(e){f={error:e}}}}catch(e){let t=[e];if(p){let n=Error(`Agent database admission failed: ${o}`,{cause:e});try{u.throw(n)}catch(e){e!==n&&t.push(e)}}let n=t.length===1?e:AggregateError(t,`Agent database admission and cleanup failed`,{cause:e});throw c.fail(n),n}finally{--l.operations,l.operations||l.releaseBorrow?.()}}function createOpenClawAgentDatabaseAdmission(e,t){Ie({agentId:e,path:t});let n=b(),r={agentId:e,path:t,controller:new AbortController,promise:n.promise,operations:0};q.pending.set(t,r),q.activePending.add(r);let retire=()=>{q.pending.get(t)===r&&q.pending.delete(t),q.activePending.delete(r)};return{pending:r,complete:e=>{if(retire(),r.controller.signal.aborted||q.databases.get(t)!==e||!e.db.isOpen){let e=r.controller.signal.reason??/* @__PURE__ */ Error(`Agent database closed before admission completed: ${t}`);throw n.reject(e),e}n.resolve(e)},fail:e=>{retire(),n.reject(e)}}}function assertOpenClawAgentDatabaseAdmissionCurrent(e,t){let n=t.path;if(t.controller.signal.throwIfAborted(),Ve(t.agentId,{env:e.env}),q.pending.get(n)!==t)throw Error(`Agent database open was replaced: ${n}`);ue(e),Ee(e)?.assertCurrent(),t.assertHeld?.()}function startOpenClawAgentDatabaseAdmission(t,n,r,i,a=!1){let o=createOpenClawAgentDatabaseAdmission(n,r),{pending:s}=o;s.workerPrepared=a;let c=e(t,s);return(async()=>{assertAgentDatabaseOpenAuthority(c,i);let e=c.next();for(;!e.done;){let n,a=!1;try{await Ht(r,E,s.controller.signal,void 0,e.value.timing,{check:e.value.check,schemaOnly:e.value.schemaOnly,tables:e.value.tables})}catch(e){n=e,a=!0}assertAgentDatabaseOpenAuthority(c,()=>{assertOpenClawAgentDatabaseAdmissionCurrent(t,s),i?.()}),e=a?c.throw(n):c.next()}return s.releaseBorrow=U(e.value.db),e.value})().then(o.complete,o.fail).catch(o.fail),s}return{openOpenClawAgentDatabase,openOpenClawAgentDatabaseInWorker,runOpenClawAgentWriteTransaction,withOpenClawAgentDatabaseAsync,withOpenClawAgentDatabaseRuntime,withOpenClawAgentDatabaseRuntimeFromExecution,withOpenClawAgentDatabaseAdmission}}function ensureMode(e,t){(process.platform===`win32`||(nr(e).mode&4095)!==t)&&$n(e,t)}function ensureOpenClawAgentDatabasePermissions(e,t){let n=Qn.dirname(e),r=L({agentId:t.agentId,env:t.env}),i=Qn.resolve(e)===Qn.resolve(r),a=er(n);tr(n,{recursive:!0,mode:448}),(i||!a)&&ensureMode(n,448);for(let t of We(e))try{ensureMode(t,384)}catch(e){if(e.code!==`ENOENT`)throw e}}function resolveRegisteredAgentDatabaseStoredPath(e,t){let n=ae(e.path,t.path);if(t.path!==y(t.path))return n;let r=z(e.db),{rows:i}=V(e.db,r.selectFrom(`agent_databases`).select(`path`).where(`agent_id`,`=`,t.agentId));return i.some(e=>e.path===n)?n:i.find(n=>F(R(e.path,n.path),t.path))?.path??n}function registerOpenClawAgentDatabase(e,t){if(!I(e.path,e.env)){e.admittedDb&&bt({...e,db:e.admittedDb});return}let n=Zt({agentId:e.agentId,path:e.path},{env:e.env}),r=null;try{r=nr(e.path).size}catch{r=null}let i=Date.now();if(t?.starting?.(),Gn(a=>{fn(a,n);let o=resolveRegisteredAgentDatabaseStoredPath(a,e),s=z(a.db);V(a.db,s.insertInto(`agent_databases`).values({agent_id:e.agentId,path:o,schema_version:e.schemaVersion??42,last_seen_at:i,size_bytes:r}).onConflict(t=>t.columns([`agent_id`,`path`]).doUpdateSet({schema_version:e.schemaVersion??42,last_seen_at:i,size_bytes:r}))),Jn(a,`upsert`,[e]);let c=t?.committed;if(c){let t=Object.freeze({agentId:e.agentId,agentPath:e.path,stateDatabasePath:a.path,stateDatabaseIdentity:Be(a).key});if(!w(a.db,{stage(){},rollback(){},commit:()=>c(t)}))throw Error(`Agent registration requires its canonical transaction publication scope`)}Xn(e.agentId,a.db)},{env:e.env,initializationAgentPaths:[e.path]}),e.admittedDb){let t={...e,db:e.admittedDb};kt(t)||bt(t)}else G(e.path)}function backfillTranscriptMutationWatermarks(e){it(e,`transcript_events`)&&e.exec(`
    UPDATE sessions
    SET
      transcript_updated_at = COALESCE(
        transcript_updated_at,
        (SELECT MAX(transcript_events.created_at)
         FROM transcript_events
         WHERE transcript_events.session_id = sessions.session_id)
      ),
      transcript_observed_at = COALESCE(transcript_observed_at, updated_at)
    WHERE EXISTS (
      SELECT 1 FROM transcript_events
      WHERE transcript_events.session_id = sessions.session_id
    );
  `)}function migrateOpenClawAgentSchema(e){if(T(e)>=42)return;let t=K(e,`sessions`);if(t){for(let[n,r]of Object.entries({transcript_updated_at:`INTEGER DEFAULT NULL`,transcript_observed_at:`INTEGER DEFAULT NULL`,session_entry_provenance:`INTEGER NOT NULL DEFAULT 0 CHECK (session_entry_provenance IN (0, 1))`,acp_owned:`INTEGER NOT NULL DEFAULT 0 CHECK (acp_owned IN (0, 1))`,plugin_owner_id:`TEXT`,hook_external_content_source:`TEXT CHECK (hook_external_content_source IS NULL OR hook_external_content_source IN ('gmail', 'webhook'))`}))t.has(n)||e.exec(`ALTER TABLE sessions ADD COLUMN ${n} ${r};`);backfillTranscriptMutationWatermarks(e)}}function jsonText(e){return`CASE
    WHEN json_valid(entry_json) AND json_type(entry_json, '${e}') = 'text'
    THEN NULLIF(trim(CAST(json_extract(entry_json, '${e}') AS TEXT)), '')
    ELSE NULL
  END`}function jsonNumber(e){return`CASE
    WHEN json_valid(entry_json) AND json_type(entry_json, '${e}') IN ('integer', 'real')
    THEN CAST(json_extract(entry_json, '${e}') AS INTEGER)
    ELSE NULL
  END`}function createSessionNodes(e){e.exec(`
    CREATE TABLE IF NOT EXISTS session_nodes (
      session_key TEXT NOT NULL PRIMARY KEY,
      current_session_id TEXT NOT NULL,
      entry_json TEXT NOT NULL,
      updated_at INTEGER NOT NULL,
      status TEXT CHECK (status IS NULL OR status IN ('running', 'done', 'failed', 'killed', 'timeout')),
      created_at INTEGER,
      created_via TEXT CHECK (created_via IS NULL OR created_via IN ('operator', 'spawn', 'channel', 'cron', 'talk', 'run', 'plugin', 'internal')),
      created_actor_type TEXT CHECK (created_actor_type IS NULL OR created_actor_type IN ('human', 'agent', 'system')),
      created_actor_id TEXT,
      parent_session_key TEXT,
      spawned_by TEXT,
      fork_source_session_key TEXT,
      fork_source_session_id TEXT,
      fork_source_entry_id TEXT,
      label TEXT,
      display_name TEXT,
      category TEXT,
      icon TEXT,
      pinned_at INTEGER,
      archived_at INTEGER,
      last_read_at INTEGER,
      last_interaction_at INTEGER,
      last_activity_at INTEGER
    ) STRICT;
  `)}function backfillSessionNodes(e){let t=K(e,`session_entries`),n=K(e,`session_routes`);if(t){let n=X(t,`status`,`NULL`);e.exec(`INSERT OR REPLACE INTO session_nodes (
        session_key, current_session_id, entry_json, updated_at, status,
        created_at, created_via, created_actor_type, created_actor_id,
        parent_session_key, spawned_by, fork_source_session_key,
        fork_source_session_id, fork_source_entry_id, label, display_name,
        category, icon, pinned_at, archived_at, last_read_at,
        last_interaction_at, last_activity_at
      ) SELECT
        session_key,
        session_id,
        entry_json,
        updated_at,
        ${n},
        ${jsonNumber(`$.createdAt`)},
        CASE
          WHEN json_valid(entry_json)
            AND json_extract(entry_json, '$.createdVia') IN
              ('operator', 'spawn', 'channel', 'cron', 'talk', 'run', 'plugin', 'internal')
          THEN json_extract(entry_json, '$.createdVia')
          ELSE NULL
        END,
        CASE
          WHEN json_valid(entry_json)
            AND json_extract(entry_json, '$.createdActor.type') IN ('human', 'agent', 'system')
          THEN json_extract(entry_json, '$.createdActor.type')
          WHEN ${jsonText(`$.createdBy.id`)} IS NOT NULL THEN 'human'
          ELSE NULL
        END,
        COALESCE(${jsonText(`$.createdActor.id`)}, ${jsonText(`$.createdBy.id`)}),
        COALESCE(${jsonText(`$.parentSessionKey`)}, ${jsonText(`$.spawnedBy`)}),
        ${jsonText(`$.spawnedBy`)},
        ${jsonText(`$.forkSource.sessionKey`)},
        ${jsonText(`$.forkSource.sessionId`)},
        ${jsonText(`$.forkSource.entryId`)},
        ${jsonText(`$.label`)},
        ${jsonText(`$.displayName`)},
        ${jsonText(`$.category`)},
        NULL,
        ${jsonNumber(`$.pinnedAt`)},
        ${jsonNumber(`$.archivedAt`)},
        ${jsonNumber(`$.lastReadAt`)},
        ${jsonNumber(`$.lastInteractionAt`)},
        ${jsonNumber(`$.lastActivityAt`)}
      FROM session_entries;`)}n&&e.exec(`INSERT OR IGNORE INTO session_nodes
      (session_key, current_session_id, entry_json, updated_at)
      SELECT session_key, session_id, '{}', updated_at FROM session_routes;`),e.exec(`INSERT OR IGNORE INTO session_nodes
    (session_key, current_session_id, entry_json, updated_at)
    SELECT session_key, session_id, '{}', updated_at FROM sessions;`)}function createLegacySessionWindowSelect(e){let t=K(e,`sessions`);if(!t)return;let n=K(e,`session_entries`),r=K(e,`session_routes`),ownerValue=(e,t)=>`(SELECT candidate.${t}
        FROM ${e} AS candidate
        INNER JOIN session_windows AS owner_window ON owner_window.session_id = candidate.session_id
        WHERE candidate.session_id = session_windows.session_id
        ORDER BY CASE WHEN candidate.session_key = owner_window.session_key THEN 0 ELSE 1 END,
                 candidate.updated_at DESC,
                 candidate.session_key ASC
        LIMIT 1)`,i=n?ownerValue(`session_entries`,`session_key`):`NULL`,a=r?ownerValue(`session_routes`,`session_key`):`NULL`,o=n?ownerValue(`session_entries`,`entry_json`):`NULL`;return{columns:`session_id, session_key, previous_session_id, reason, session_scope,
      created_at, updated_at, transcript_updated_at, transcript_observed_at,
      session_entry_provenance, acp_owned, plugin_owner_id,
      hook_external_content_source, started_at, ended_at, status, chat_type,
      channel, account_id, primary_conversation_id, model_provider, model,
      agent_harness_id, parent_session_key, spawned_by, display_name`,sql:`SELECT
      session_id,
      COALESCE(${i}, ${a}, session_key),
      CASE
        WHEN json_valid(${o})
        THEN NULLIF(trim(CAST(json_extract(${o}, '$.previousSessionId') AS TEXT)), '')
        ELSE NULL
      END,
      NULL,
      ${X(t,`session_scope`,`'conversation'`)},
      created_at,
      updated_at,
      ${X(t,`transcript_updated_at`,`NULL`)},
      ${X(t,`transcript_observed_at`,`NULL`)},
      ${X(t,`session_entry_provenance`,`0`)},
      ${X(t,`acp_owned`,`0`)},
      ${X(t,`plugin_owner_id`,`NULL`)},
      ${X(t,`hook_external_content_source`,`NULL`)},
      ${X(t,`started_at`,`NULL`)},
      ${X(t,`ended_at`,`NULL`)},
      ${X(t,`status`,`NULL`)},
      ${X(t,`chat_type`,`NULL`)},
      ${X(t,`channel`,`NULL`)},
      ${X(t,`account_id`,`NULL`)},
      ${X(t,`primary_conversation_id`,`NULL`)},
      ${X(t,`model_provider`,`NULL`)},
      ${X(t,`model`,`NULL`)},
      ${X(t,`agent_harness_id`,`NULL`)},
      ${X(t,`parent_session_key`,`NULL`)},
      ${X(t,`spawned_by`,`NULL`)},
      ${X(t,`display_name`,`NULL`)}
    FROM session_windows`}}function migrateSessionWindows(e){let t=createLegacySessionWindowSelect(e);t&&(e.exec(`ALTER TABLE sessions RENAME TO session_windows;`),e.exec(`
    DROP TABLE IF EXISTS session_windows_new;
    CREATE TABLE session_windows_new (
      session_id TEXT NOT NULL PRIMARY KEY,
      session_key TEXT NOT NULL,
      previous_session_id TEXT,
      reason TEXT CHECK (reason IS NULL OR reason IN ('initial', 'reset', 'rollover', 'fork', 'rewind', 'switch', 'recovery', 'compaction')),
      session_scope TEXT NOT NULL DEFAULT 'conversation' CHECK (session_scope IN ('conversation', 'shared-main', 'group', 'channel')),
      created_at INTEGER NOT NULL,
      updated_at INTEGER NOT NULL,
      transcript_updated_at INTEGER DEFAULT NULL,
      transcript_observed_at INTEGER DEFAULT NULL,
      session_entry_provenance INTEGER NOT NULL DEFAULT 0 CHECK (session_entry_provenance IN (0, 1)),
      acp_owned INTEGER NOT NULL DEFAULT 0 CHECK (acp_owned IN (0, 1)),
      plugin_owner_id TEXT,
      hook_external_content_source TEXT CHECK (hook_external_content_source IS NULL OR hook_external_content_source IN ('gmail', 'webhook')),
      started_at INTEGER,
      ended_at INTEGER,
      status TEXT CHECK (status IS NULL OR status IN ('running', 'done', 'failed', 'killed', 'timeout')),
      chat_type TEXT CHECK (chat_type IS NULL OR chat_type IN ('direct', 'group', 'channel')),
      channel TEXT,
      account_id TEXT,
      primary_conversation_id TEXT,
      model_provider TEXT,
      model TEXT,
      agent_harness_id TEXT,
      parent_session_key TEXT,
      spawned_by TEXT,
      display_name TEXT,
      FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE,
      FOREIGN KEY (primary_conversation_id) REFERENCES conversations(conversation_id) ON DELETE SET NULL
    ) STRICT;
    INSERT INTO session_windows_new (${t.columns})
    ${t.sql};
    DROP TABLE session_windows;
    ALTER TABLE session_windows_new RENAME TO session_windows;
  `))}function renameTranscriptRewriteWatermarks(e){K(e,`session_transcript_generations`)&&!K(e,`transcript_rewrite_watermarks`)&&e.exec(`ALTER TABLE session_transcript_generations RENAME TO transcript_rewrite_watermarks;`)}function rebuildBoardTabs(e){K(e,`board_tabs`)&&(K(e,`board_widgets`)&&e.exec(`
      DELETE FROM board_widgets
      WHERE NOT EXISTS (
        SELECT 1 FROM session_nodes WHERE session_nodes.session_key = board_widgets.session_key
      );
    `),e.exec(`
    DROP TABLE IF EXISTS board_tabs_new;
    CREATE TABLE board_tabs_new (
      session_key TEXT NOT NULL,
      tab_id TEXT NOT NULL,
      title TEXT NOT NULL,
      position INTEGER NOT NULL CHECK (position >= 0),
      chat_dock TEXT NOT NULL DEFAULT 'right' CHECK (chat_dock IN ('left', 'right', 'bottom', 'hidden')),
      created_by TEXT NOT NULL CHECK (created_by IN ('user', 'agent')),
      revision INTEGER NOT NULL CHECK (revision >= 0),
      PRIMARY KEY (session_key, tab_id),
      FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
    ) STRICT;
    INSERT INTO board_tabs_new (
      session_key, tab_id, title, position, chat_dock, created_by, revision
    )
    SELECT b.session_key, b.tab_id, b.title, b.position, b.chat_dock, b.created_by, b.revision
    FROM board_tabs AS b
    INNER JOIN session_nodes AS n ON n.session_key = b.session_key;
    DROP TABLE board_tabs;
    ALTER TABLE board_tabs_new RENAME TO board_tabs;
  `))}function rebuildHeartbeatOutcomes(e){let t=K(e,`heartbeat_outcomes`);t&&e.exec(`
    DROP TABLE IF EXISTS heartbeat_outcomes_new;
    CREATE TABLE heartbeat_outcomes_new (
      session_key TEXT NOT NULL PRIMARY KEY,
      run_session_key TEXT NOT NULL,
      outcome TEXT NOT NULL CHECK (outcome IN ('progress', 'done', 'blocked', 'needs_attention')),
      summary TEXT NOT NULL,
      response_reason TEXT,
      priority TEXT CHECK (priority IS NULL OR priority IN ('low', 'normal', 'high')),
      next_check TEXT,
      task_names_json TEXT,
      wake_source TEXT,
      wake_reason TEXT,
      occurred_at INTEGER NOT NULL,
      context_run_id TEXT,
      context_claimed_at INTEGER,
      updated_at INTEGER NOT NULL,
      FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
    ) STRICT;
    INSERT INTO heartbeat_outcomes_new (
      session_key, run_session_key, outcome, summary, response_reason, priority,
      next_check, task_names_json, wake_source, wake_reason, occurred_at,
      context_run_id, context_claimed_at, updated_at
    )
    SELECT
      h.session_key,
      h.run_session_key,
      h.outcome,
      h.summary,
      ${X(t,`response_reason`,`NULL`)},
      ${X(t,`priority`,`NULL`)},
      ${X(t,`next_check`,`NULL`)},
      ${X(t,`task_names_json`,`NULL`)},
      ${X(t,`wake_source`,`NULL`)},
      ${X(t,`wake_reason`,`NULL`)},
      h.occurred_at,
      ${X(t,`context_run_id`,`NULL`)},
      ${X(t,`context_claimed_at`,`NULL`)},
      h.updated_at
    FROM heartbeat_outcomes AS h
    INNER JOIN session_nodes AS n ON n.session_key = h.session_key;
    DROP TABLE heartbeat_outcomes;
    ALTER TABLE heartbeat_outcomes_new RENAME TO heartbeat_outcomes;
  `)}function rebuildSessionMembers(e){K(e,`session_members`)&&e.exec(`
    DROP TABLE IF EXISTS session_members_new;
    CREATE TABLE session_members_new (
      session_key TEXT NOT NULL,
      identity_id TEXT NOT NULL,
      added_by TEXT NOT NULL,
      added_at INTEGER NOT NULL,
      PRIMARY KEY (session_key, identity_id),
      FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
    ) STRICT;
    INSERT INTO session_members_new (session_key, identity_id, added_by, added_at)
    SELECT m.session_key, m.identity_id, m.added_by, m.added_at
    FROM session_members AS m
    INNER JOIN session_nodes AS n ON n.session_key = m.session_key;
    DROP TABLE session_members;
    ALTER TABLE session_members_new RENAME TO session_members;
  `)}function rebuildTranscriptIndexState(e){let t=K(e,`session_transcript_index_state`);t&&e.exec(`
    DROP TABLE IF EXISTS session_transcript_index_state_new;
    CREATE TABLE session_transcript_index_state_new (
      session_id TEXT NOT NULL PRIMARY KEY,
      indexed_seq INTEGER NOT NULL,
      leaf_event_id TEXT,
      needs_rebuild INTEGER NOT NULL DEFAULT 0,
      active_event_count INTEGER NOT NULL DEFAULT 0,
      active_message_count INTEGER NOT NULL DEFAULT 0,
      updated_at INTEGER NOT NULL,
      FOREIGN KEY (session_id) REFERENCES session_windows(session_id) ON DELETE CASCADE
    ) STRICT;
    INSERT INTO session_transcript_index_state_new (
      session_id, indexed_seq, leaf_event_id, needs_rebuild,
      active_event_count, active_message_count, updated_at
    )
    SELECT
      i.session_id,
      i.indexed_seq,
      ${X(t,`leaf_event_id`,`NULL`)},
      ${X(t,`needs_rebuild`,`0`)},
      ${X(t,`active_event_count`,`0`)},
      ${X(t,`active_message_count`,`0`)},
      i.updated_at
    FROM session_transcript_index_state AS i
    INNER JOIN session_windows AS w ON w.session_id = i.session_id;
    DROP TABLE session_transcript_index_state;
    ALTER TABLE session_transcript_index_state_new RENAME TO session_transcript_index_state;
  `)}function migrateSessionNodesAndWindows(e,t){t>=14||!K(e,`sessions`)||(createSessionNodes(e),backfillSessionNodes(e),migrateSessionWindows(e),renameTranscriptRewriteWatermarks(e),rebuildBoardTabs(e),rebuildHeartbeatOutcomes(e),rebuildSessionMembers(e),rebuildTranscriptIndexState(e),e.exec(`
    DROP TABLE IF EXISTS session_routes;
    DROP TABLE IF EXISTS session_entries;
  `))}function migrateAgentJsonPredicatesInTransaction(e){W(e,`session_nodes`,`session_started_at INTEGER`),W(e,`session_nodes`,`has_optional_references INTEGER NOT NULL DEFAULT 0`),e.exec(`
    UPDATE session_nodes SET
      session_started_at = CASE WHEN json_valid(entry_json)
        THEN CAST(json_extract(entry_json, '$.sessionStartedAt') AS INTEGER) END,
      has_optional_references = CASE WHEN NOT json_valid(entry_json) OR instr(entry_json, char(0)) > 0 THEN 1
        WHEN json_type(entry_json, '$.previousSessionId') IS NOT NULL
          OR json_type(entry_json, '$.usageFamilySessionIds') IS NOT NULL
          OR json_type(entry_json, '$.compactionCheckpoints') IS NOT NULL THEN 1
        ELSE 0 END;
  `),it(e,`context_engine_turn_outbox`)&&(W(e,`context_engine_turn_outbox`,`payload_state TEXT`),e.exec(`
      UPDATE context_engine_turn_outbox SET payload_state = CASE
        WHEN json_valid(payload_json) THEN CASE
          WHEN json_type(payload_json, '$.state') = 'text'
          THEN json_extract(payload_json, '$.state') END END;
    `));for(let t of Ft.transcript_events)W(e,`transcript_events`,`${t} ${Pt[t]}`)}function migrateOutboxEnqueueSequenceInTransaction(e){if(!it(e,`context_engine_turn_outbox`)||rt(e,`context_engine_turn_outbox`,`enqueue_sequence`))return null;let t=performance.now(),n=M(e)??A(e),r=[...n.indexDefinitions.values(),...n.triggers.values()].filter(({table:e})=>e===`context_engine_turn_outbox`),i=O(a,`context_engine_turn_outbox`);e.exec(`
    ${i.replace(`IF NOT EXISTS context_engine_turn_outbox`,`context_engine_turn_outbox_sequence_migration`)}
    INSERT INTO context_engine_turn_outbox_sequence_migration
      (enqueue_sequence, advancement_key, engine_id, owner_plugin_id, session_id,
       payload_json, payload_state, attempt_count, last_attempt_at, last_error, created_at)
    SELECT rowid, advancement_key, engine_id, owner_plugin_id, session_id,
       payload_json, payload_state, attempt_count, last_attempt_at, last_error, created_at
    FROM context_engine_turn_outbox;
    DROP TABLE context_engine_turn_outbox;
    ALTER TABLE context_engine_turn_outbox_sequence_migration RENAME TO context_engine_turn_outbox;
  `);for(let t of r)t.sql!==null&&e.exec(t.sql);return performance.now()-t}function migrateSessionEntrySnapshotsInTransaction(e){e.exec(`ALTER TABLE session_nodes ADD COLUMN snapshot_revision INTEGER NOT NULL DEFAULT 0`),e.exec(jt(a));let t=z(e),n=t.selectFrom(`session_nodes`).select([`session_key`,`current_session_id`,`updated_at`,`entry_json`]).orderBy(`session_key`).limit(64),r=B(e,e=>n.where(`session_key`,`>`,e(e=>e))),i=B(e,e=>t.insertInto(`session_entry_snapshots`).values({session_key:e(e=>e.sessionKey),field:e(e=>e.field),value_json:e(e=>e.valueJson)})),o=B(e,e=>t.updateTable(`session_nodes`).set({entry_json:e(e=>e.entryJson)}).where(`session_key`,`=`,e(e=>e.sessionKey))),s=B(e,e=>t.updateTable(`session_nodes`).set({entry_valid:1}).where(`session_key`,`=`,e(e=>e))),c;for(;;){let{rows:t}=c===void 0?V(e,n):r(c);if(t.length===0)return;J();for(let e of t){if(typeof e.session_key!=`string`||typeof e.current_session_id!=`string`||typeof e.updated_at!=`number`||typeof e.entry_json!=`string`)throw Error(`Unreadable session row during snapshot migration`);c=e.session_key;let t=qt({current_session_id:e.current_session_id,updated_at:e.updated_at,entry_json:e.entry_json});if(!t)continue;let{entryJson:n,snapshots:r}=Jt(t);if(r.length!==0){for(let t of r)i({sessionKey:e.session_key,...t});o({entryJson:n,sessionKey:e.session_key}),s(e.session_key)}}}}const rr=`session-cost-usage-rollup-v3`,ir=`unpriced`,ar=Xt();function encodeUsageCostRollup(e){let t=JSON.stringify(e.rollup),n=Buffer.from(t,`utf8`),r=n.byteLength>=1024?ar.compress(n,1):void 0,i=r!==void 0&&r.byteLength<n.byteLength,a=i?r:n,o={version:e.version,pricingFingerprint:e.pricingFingerprint,checkpoint:e.checkpoint,scannedAt:e.scannedAt,parsedRecords:e.parsedRecords,countedRecords:e.countedRecords,format:1,body:{encoding:i?`zstd`:`identity`,bytes:n.byteLength,storedBytes:a.byteLength,utf16Length:t.length,sha256:Ue(n)}};return{valueJson:JSON.stringify(o),blob:Uint8Array.from(a)}}function readUsageCostDeferredMetadata(e){let t=e.checkpoint,n=t.kind===`jsonl`?{kind:t.kind,observedSize:t.observedSize,observedMtimeMs:t.observedMtimeMs,device:t.device,inode:t.inode,...t.undecodable?{undecodable:t.undecodable}:{}}:{kind:t.kind,maxSeq:t.maxSeq,eventCount:t.eventCount,size:t.size,mtimeMs:t.mtimeMs};if(Object.entries(n).every(([e,t])=>e===`kind`||typeof t==`number`&&Number.isFinite(t))&&Number.isFinite(e.scannedAt))return{checkpoint:n,scannedAt:e.scannedAt,...t.kind===`sqlite`?{sqliteGenerationHash:Ue(JSON.stringify(t.generation??null))}:{}}}function decodeUsageCostRollupEnvelope(t,n){try{let r=JSON.parse(t);return!e(r)||r.version!==12||r.format!==1||typeof r.pricingFingerprint!=`string`||n!==void 0&&r.pricingFingerprint!==n&&r.pricingFingerprint!==`unpriced`||!e(r.checkpoint)||r.checkpoint.kind!==`jsonl`&&r.checkpoint.kind!==`sqlite`||typeof r.scannedAt!=`number`||typeof r.parsedRecords!=`number`||typeof r.countedRecords!=`number`||!e(r.body)||r.body.encoding!==`identity`&&r.body.encoding!==`zstd`||typeof r.body.bytes!=`number`||!Number.isSafeInteger(r.body.bytes)||r.body.bytes<=0||typeof r.body.storedBytes!=`number`||!Number.isSafeInteger(r.body.storedBytes)||r.body.storedBytes<=0||typeof r.body.utf16Length!=`number`||!Number.isSafeInteger(r.body.utf16Length)||r.body.utf16Length<=0||r.body.bytes<r.body.utf16Length||r.body.bytes>3*r.body.utf16Length||(r.body.encoding===`identity`?r.body.bytes!==r.body.storedBytes:r.body.bytes<=r.body.storedBytes)||typeof r.body.sha256!=`string`||!/^[0-9a-f]{64}$/.test(r.body.sha256)||r.projection!==void 0&&(!e(r.projection)||r.projection.version!==3||!Array.isArray(r.projection.dates)||!r.projection.dates.every(e=>typeof e==`string`&&/^\d{4}-\d{2}-\d{2}$/.test(e))||typeof r.projection.canonicalNumbers!=`boolean`)?void 0:r}catch{return}}function decodeUsageCostRollup(t,n,r,i){let a=decodeUsageCostRollupEnvelope(t,n);if(a&&r&&r.byteLength===a.body.storedBytes){if(i){if(a.body.bytes>i.remainingBytes)return null;i.remainingBytes-=a.body.bytes}try{let t=a.body.encoding===`zstd`?ar.decompress(r,a.body.bytes):Buffer.from(r.buffer,r.byteOffset,r.byteLength);if(t.byteLength!==a.body.bytes||Ue(t)!==a.body.sha256)return;let n=t.toString(`utf8`);if(n.length!==a.body.utf16Length)return;let i=JSON.parse(n);if(!e(i)||!e(i.buckets)||!e(i.untimestamped))return;let{format:o,body:s,...c}=a;return{...c,rollup:i}}catch{return}}}function isUsageCostRollupFresh(e){let{checkpoint:t}=e;return!t||t.kind!==e.file.kind?!1:t.kind===`jsonl`?!t.undecodable&&t.observedSize===e.file.size&&t.observedMtimeMs===e.file.mtimeMs&&t.device===e.file.device&&t.inode===e.file.inode:t.size===e.file.size&&t.mtimeMs===e.file.mtimeMs&&t.eventCount===e.file.eventCount&&t.maxSeq===e.file.maxSeq}function canUseUsageCostRollupForPartial(e){let t=e.checkpoint;return!t||t.kind!==e.file.kind?!1:t.kind===`jsonl`?t.parsedOffset<=e.file.size&&t.device===e.file.device&&t.inode===e.file.inode:t.maxSeq<=(e.file.maxSeq??0)}const or=`session-cost-usage-rollup-v2`;function decodePreviousRollup(t){let n=g(t??``);if(n&&n.version===6&&typeof n.pricingFingerprint==`string`&&e(n.checkpoint)&&(n.checkpoint.kind===`jsonl`||n.checkpoint.kind===`sqlite`)&&typeof n.scannedAt==`number`&&typeof n.parsedRecords==`number`&&typeof n.countedRecords==`number`&&e(n.rollup)&&e(n.rollup.buckets)&&e(n.rollup.untimestamped))return n}function migrateSessionCostUsageRollupStorage(e,t){let n=z(e),r;for(;;){t?.();let i=n.selectFrom(`cache_entries`).select([`key`,`value_json`,`updated_at`]).where(`scope`,`=`,or).orderBy(`key`,`asc`).limit(1);r!==void 0&&(i=i.where(`key`,`>`,r));let a=V(e,i).rows[0];if(!a)break;r=a.key;let o=decodePreviousRollup(a.value_json);if(o){let t=encodeUsageCostRollup(o);V(e,n.insertInto(`cache_entries`).values({scope:rr,key:a.key,value_json:t.valueJson,blob:t.blob,updated_at:a.updated_at,expires_at:null}).onConflict(e=>e.columns([`scope`,`key`]).doNothing()))}V(e,n.deleteFrom(`cache_entries`).where(`scope`,`=`,or).where(`key`,`=`,a.key))}}const Q=`session_transcript_fts_rows_legacy22`;function migrateDeployedTranscriptFtsRowsInTransaction(e,t){if(!e.isTransaction||e.prepare(`PRAGMA foreign_keys`).get()?.foreign_keys!==0)throw Error(`Transcript FTS migration requires an admitted transaction with foreign keys off`);Pe(e,`deployed transcript FTS ownership`,Rt);let n=e.prepare(`PRAGMA table_xinfo(session_transcript_fts_rows)`).all();if(n.length!==2||n.some(e=>e.name!==`session_id`&&e.name!==`fts_rowid`))throw Error(`Transcript FTS migration cannot discard unknown row-map columns`);let r=e.prepare(`SELECT name FROM sqlite_schema
    WHERE (tbl_name = 'session_transcript_fts_rows' AND sql IS NOT NULL
      AND type IN ('index', 'trigger') AND name != 'idx_agent_transcript_fts_rows_session')
      OR (type IN ('view', 'trigger') AND sql LIKE '%session_transcript_fts_rows%')`).all(),i=e.prepare(`SELECT schema.name FROM sqlite_schema AS schema
    JOIN pragma_foreign_key_list(schema.name) AS fk
    WHERE schema.type = 'table' AND fk."table" = 'session_transcript_fts_rows'`).all();if(r.length||i.length)throw Error(`Transcript FTS migration cannot discard unknown row-map dependencies`);if(e.prepare(`SELECT 1 FROM sqlite_schema WHERE name = ?`).get(Q))throw Error(`Transcript FTS migration table already exists`);e.exec(`ALTER TABLE session_transcript_fts_rows RENAME TO ${Q}`),e.exec(O(t,`session_transcript_fts_rows`,{endMarker:`INSERT OR IGNORE INTO memory_index_state`,includeEndMarker:!1})),e.exec(`INSERT INTO session_transcript_fts_rows (id, session_id, message_id)
    SELECT rowid, session_id, message_id FROM session_transcript_fts`),e.exec(`UPDATE session_transcript_index_state AS state SET needs_rebuild = 1
    WHERE needs_rebuild = 0 AND (
      fts_row_count IS NULL
      OR fts_row_count != (SELECT count(*) FROM ${Q} AS old WHERE old.session_id = state.session_id)
      OR EXISTS (
        SELECT 1 FROM ${Q} AS old
        WHERE old.session_id = state.session_id AND NOT EXISTS (
          SELECT 1 FROM session_transcript_fts_rows AS current
          WHERE current.id = old.fts_rowid AND current.session_id = old.session_id))
      OR EXISTS (
        SELECT 1 FROM session_transcript_fts_rows AS current
        WHERE current.session_id = state.session_id AND NOT EXISTS (
          SELECT 1 FROM ${Q} AS old
          WHERE old.fts_rowid = current.id AND old.session_id = current.session_id))
    );
    DROP TABLE ${Q};
    ALTER TABLE session_transcript_index_state DROP COLUMN fts_row_count;`)}const $=`transcript_events_payload_migration`,sr=/* @__PURE__ */ new Set([`transcript_event_identities`,`session_transcript_active_events`]);function assertTranscriptRebuildInputs(e){Pe(e,`transcript payload migration`,O(It(a),`transcript_events`));let t=e.prepare(`PRAGMA table_xinfo(transcript_events)`).all(),n=/* @__PURE__ */ new Set([`session_id`,`seq`,`event_json`,`created_at`]);if(t.length!==n.size||t.some(e=>typeof e.name!=`string`||!n.has(e.name)))throw Error(`Transcript payload migration cannot discard unknown columns`);if(e.prepare(`SELECT name FROM sqlite_schema
      WHERE (type IN ('trigger', 'index') AND tbl_name = 'transcript_events' AND sql IS NOT NULL)
         OR (type IN ('view', 'trigger') AND sql LIKE '%transcript_events%')`).all().length>0)throw Error(`Transcript payload migration cannot rebuild unknown indexes, views, or triggers`);if(e.prepare(`SELECT 1 FROM sqlite_schema WHERE name = ?`).get($))throw Error(`Transcript payload migration table already exists`);for(let t of e.prepare(`SELECT name FROM sqlite_schema WHERE type = 'table'`).all()){if(typeof t.name!=`string`)throw Error(`Invalid table name during transcript payload migration`);if(!sr.has(t.name)&&e.prepare(`PRAGMA foreign_key_list(${D(t.name)})`).all().some(e=>e.table===`transcript_events`))throw Error(`Transcript payload migration cannot rebuild an unknown foreign-key target`)}}function migrateTranscriptPayloadStorageInTransaction(e,t){if(!e.isTransaction||e.prepare(`PRAGMA foreign_keys`).get()?.foreign_keys!==0)throw Error(`Transcript payload migration requires an admitted transaction with foreign keys off`);assertTranscriptRebuildInputs(e);let n=k(e)===`UTF-8`,r=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}),i=Xt();e.exec(O(t,`transcript_events`).replace(`IF NOT EXISTS transcript_events`,$));let a=e.prepare(`
    INSERT INTO ${$}
      (rowid, session_id, seq, event_json, created_at, event_zstd, event_utf8_bytes, navigation_json)
    SELECT rowid, session_id, seq, event_json, created_at, NULL,
           CASE WHEN ? THEN octet_length(event_json) ELSE NULL END, ?
    FROM transcript_events WHERE rowid = ?`),o=e.prepare(`
    INSERT INTO ${$}
      (rowid, session_id, seq, event_json, created_at, event_zstd, event_utf8_bytes, navigation_json)
    SELECT rowid, session_id, seq, NULL, created_at, ?, ?, ?
    FROM transcript_events WHERE rowid = ?`);a.setReadBigInts(!0),o.setReadBigInts(!0);let s=e.prepare(`SELECT CAST(event_json AS BLOB) AS bytes FROM transcript_events WHERE rowid = ?`),c=e.prepare(`SELECT rowid AS storage_rowid, octet_length(event_json) AS bytes FROM transcript_events ORDER BY rowid`);c.setReadBigInts(!0);let l=performance.now();for(let t of c.iterate()){if(performance.now()-l>=1e3&&(J(),l=performance.now()),typeof t.storage_rowid!=`bigint`||typeof t.bytes!=`bigint`)throw Error(`Invalid transcript storage identity during migration`);let c=null,u=!1;if(n&&t.bytes<=BigInt(4194304)){let n=s.get(t.storage_rowid)?.bytes;if(!(n instanceof Uint8Array))throw Error(`Transcript payload disappeared during migration`);let a;try{a=r.decode(n)}catch{}if(a!==void 0){let r=Yt(e,a,void 0,`UTF-8`);if(c=r.navigation_json,r.event_zstd!==null){if(r.event_utf8_bytes===null||!i.decompress(r.event_zstd,r.event_utf8_bytes).equals(n))throw Error(`Transcript compression did not preserve canonical bytes`);let e=o.run(r.event_zstd,r.event_utf8_bytes,c,t.storage_rowid);if(Number(e.changes)!==1)throw Error(`Transcript payload disappeared before migration publication`);u=!0}}}if(!u&&Number(a.run(+!!n,c,t.storage_rowid).changes)!==1)throw Error(`Transcript identity payload disappeared before migration publication`)}J(),e.exec(`DROP TABLE transcript_events;
    ALTER TABLE ${$} RENAME TO transcript_events;`)}function migrateAgentStorageInTransaction(e,t,n,r){if(J(),vt(e,{renewAuthority:J,onWarning:e=>r.push(e)}),J(),n===22)migrateDeployedTranscriptFtsRowsInTransaction(e,t);else if(e.prepare(`SELECT 1 FROM sqlite_schema WHERE name = ?`).get(`session_transcript_fts_rows`))throw Error(`Transcript FTS row map already exists before the schema-23 storage migration.`);J(),migrateTranscriptPayloadStorageInTransaction(e,t),J(),migrateSessionCostUsageRollupStorage(e,J),J(),e.exec(t),n!==22&&e.exec(`
    INSERT INTO session_transcript_fts_rows (id, session_id, message_id)
    SELECT rowid, session_id, message_id FROM session_transcript_fts;
  `)}const cr=p(`state/agent-db`);function*agentDatabaseIntegrityBeforeMutationSteps(e,t,n,{runtimeAdmission:r=!1,diagnostics:i,verification:a,reuseRuntimeIntegrity:o=!1,admittedSchema:s=!1,integrityCheck:c,integrityTables:l}={}){let u=r&&o;if(u&&s)return i&&(i.integrityGateOutcome=`cached`),!1;_e(e,E);let d=M(e)?.userVersion??T(e),f=d===0&&we(e),p=d===0&&f||d>0&&d<42;p&&cr.info(`agent database schema migration pending; verifying integrity first`,{fromVersion:d,path:n,toVersion:42});let m=d===42&&Rn(e),h=Wn({kind:`agent`,foundVersion:d,supportedVersion:42},c),g=performance.now();if(d===42&&!m){let o=r&&!a&&!u&&c!==`full`?Mn(e,n,t,i):void 0,s=u||a!==void 0&&!p&&!m,validateSchema=r=>Sn(e,{agentId:t,pathname:n},r),d=o??(yield*qn(e,n,`-- Session storage doctrine: session_nodes.entry_json owns hot logical-session facts;
-- session_entry_snapshots owns keyed cold values. Promoted node columns are query
-- indexes; session_windows and their children own transcript generations.
-- Legacy ACP provenance is private import evidence carried with its logical session.

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 session_nodes (
  session_key TEXT NOT NULL PRIMARY KEY,
  current_session_id TEXT NOT NULL,
  entry_json TEXT NOT NULL,
  session_started_at INTEGER,
  has_optional_references INTEGER NOT NULL DEFAULT 0,
  snapshot_revision INTEGER NOT NULL DEFAULT 0,
  legacy_acp_migration_json TEXT,
  entry_valid INTEGER NOT NULL DEFAULT 0 CHECK (entry_valid IN (-1, 0, 1)),
  updated_at INTEGER NOT NULL,
  status TEXT CHECK (status IS NULL OR status IN ('running', 'done', 'failed', 'killed', 'timeout')),
  created_at INTEGER,
  created_via TEXT CHECK (created_via IS NULL OR created_via IN ('operator', 'spawn', 'channel', 'cron', 'talk', 'run', 'plugin', 'internal')),
  created_actor_type TEXT CHECK (created_actor_type IS NULL OR created_actor_type IN ('human', 'agent', 'system')),
  created_actor_id TEXT,
  owner_actor_type TEXT,
  owner_actor_id TEXT,
  owner_assigned_by_type TEXT,
  owner_assigned_by_id TEXT,
  owner_assigned_at INTEGER,
  project_id TEXT,
  parent_session_key TEXT,
  spawned_by TEXT,
  fork_source_session_key TEXT,
  fork_source_session_id TEXT,
  fork_source_entry_id TEXT,
  label TEXT,
  display_name TEXT,
  category TEXT,
  icon TEXT,
  pinned_at INTEGER,
  archived_at INTEGER,
  last_read_at INTEGER,
  last_interaction_at INTEGER,
  last_activity_at INTEGER
) STRICT;

CREATE TABLE IF NOT EXISTS session_entry_snapshots (
  session_key TEXT NOT NULL,
  field TEXT NOT NULL CHECK (field IN ('sessionDiffBaseline', 'skillsSnapshot', 'systemPromptReport')),
  value_json TEXT NOT NULL,
  PRIMARY KEY (session_key, field),
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT, WITHOUT ROWID;

CREATE TRIGGER IF NOT EXISTS session_entry_snapshots_after_insert
AFTER INSERT ON session_entry_snapshots
BEGIN
  UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1
  WHERE session_key = NEW.session_key;
END;

CREATE TRIGGER IF NOT EXISTS session_entry_snapshots_after_update
AFTER UPDATE OF session_key, field, value_json ON session_entry_snapshots
WHEN NEW.session_key IS NOT OLD.session_key
  OR NEW.field IS NOT OLD.field OR NEW.value_json IS NOT OLD.value_json
BEGIN
  UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1
  WHERE session_key IN (OLD.session_key, NEW.session_key);
END;

CREATE TRIGGER IF NOT EXISTS session_entry_snapshots_after_delete
AFTER DELETE ON session_entry_snapshots
BEGIN
  UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1
  WHERE session_key = OLD.session_key;
END;

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_updated_at
  ON session_nodes(updated_at DESC, session_key);

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_label
  ON session_nodes(label, session_key)
  WHERE label IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_parent_session_key
  ON session_nodes(parent_session_key, session_key);

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_spawned_by
  ON session_nodes(spawned_by, session_key);

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_status
  ON session_nodes(status, session_key)
  WHERE status IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_archived_at
  ON session_nodes(archived_at, session_key)
  WHERE archived_at IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_active
  ON session_nodes(session_key)
  WHERE archived_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_current_session_id
  ON session_nodes(current_session_id);

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_entry_valid_pending
  ON session_nodes(session_key)
  WHERE entry_valid = 0;

CREATE INDEX IF NOT EXISTS idx_agent_session_nodes_entry_not_valid
  ON session_nodes(session_key)
  WHERE entry_valid != 1;

CREATE TABLE IF NOT EXISTS session_participants (
  session_key TEXT NOT NULL,
  identity_namespace TEXT NOT NULL,
  actor_id TEXT NOT NULL,
  contribution_count INTEGER NOT NULL,
  first_prompted_at INTEGER,
  last_prompted_at INTEGER,
  PRIMARY KEY (session_key, identity_namespace, actor_id),
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS session_key_contract (
  id INTEGER NOT NULL PRIMARY KEY CHECK (id = 1),
  main_key TEXT NOT NULL,
  canonical_ready TEXT,
  updated_at INTEGER NOT NULL
) STRICT;

INSERT OR IGNORE INTO session_key_contract (id, main_key, updated_at) VALUES (1, 'main', 0);

CREATE TABLE IF NOT EXISTS session_windows (
  session_id TEXT NOT NULL PRIMARY KEY,
  session_key TEXT NOT NULL,
  previous_session_id TEXT,
  reason TEXT CHECK (reason IS NULL OR reason IN ('initial', 'reset', 'rollover', 'fork', 'rewind', 'switch', 'recovery', 'compaction')),
  session_scope TEXT NOT NULL DEFAULT 'conversation' CHECK (session_scope IN ('conversation', 'shared-main', 'group', 'channel')),
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  transcript_updated_at INTEGER DEFAULT NULL,
  row_transcript_json TEXT,
  row_transcript_updated_at INTEGER,
  transcript_observed_at INTEGER DEFAULT NULL,
  session_entry_provenance INTEGER NOT NULL DEFAULT 0 CHECK (session_entry_provenance IN (0, 1)),
  acp_owned INTEGER NOT NULL DEFAULT 0 CHECK (acp_owned IN (0, 1)),
  plugin_owner_id TEXT,
  hook_external_content_source TEXT CHECK (hook_external_content_source IS NULL OR hook_external_content_source IN ('gmail', 'webhook')),
  started_at INTEGER,
  ended_at INTEGER,
  status TEXT CHECK (status IS NULL OR status IN ('running', 'done', 'failed', 'killed', 'timeout')),
  chat_type TEXT CHECK (chat_type IS NULL OR chat_type IN ('direct', 'group', 'channel')),
  channel TEXT,
  account_id TEXT,
  primary_conversation_id TEXT,
  model_provider TEXT,
  model TEXT,
  agent_harness_id TEXT,
  parent_session_key TEXT,
  spawned_by TEXT,
  display_name TEXT,
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE,
  FOREIGN KEY (primary_conversation_id) REFERENCES conversations(conversation_id) ON DELETE SET NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_session_windows_updated_at
  ON session_windows(updated_at DESC, session_id);

CREATE INDEX IF NOT EXISTS idx_agent_session_windows_session_key
  ON session_windows(session_key, updated_at DESC, session_id);

CREATE INDEX IF NOT EXISTS idx_agent_session_windows_created_at
  ON session_windows(created_at DESC, session_id);

CREATE INDEX IF NOT EXISTS idx_agent_session_windows_conversation
  ON session_windows(primary_conversation_id)
  WHERE primary_conversation_id IS NOT NULL;

-- Offline imports and repairs queue explicit work; admission also settles keys
-- removed during repair, so the queue deliberately has no node foreign key.
CREATE TABLE IF NOT EXISTS session_canonical_validation_pending (
  session_key TEXT NOT NULL PRIMARY KEY
) STRICT;

CREATE TABLE IF NOT EXISTS conversations (
  conversation_id TEXT NOT NULL PRIMARY KEY,
  channel TEXT NOT NULL,
  account_id TEXT NOT NULL,
  kind TEXT NOT NULL CHECK (kind IN ('direct', 'group', 'channel')),
  peer_id TEXT NOT NULL,
  delivery_target TEXT NOT NULL,
  parent_conversation_id TEXT,
  thread_id TEXT,
  native_channel_id TEXT,
  native_direct_user_id TEXT,
  label TEXT,
  metadata_json TEXT,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_conversations_lookup
  ON conversations(channel, account_id, kind, peer_id, thread_id);

CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_conversations_identity
  ON conversations(
    channel,
    account_id,
    kind,
    peer_id,
    IFNULL(parent_conversation_id, ''),
    IFNULL(thread_id, '')
  );

CREATE INDEX IF NOT EXISTS idx_agent_conversations_updated
  ON conversations(updated_at DESC, conversation_id);

CREATE TABLE IF NOT EXISTS conversation_deliveries (
  operation_id TEXT NOT NULL PRIMARY KEY,
  operation_kind TEXT NOT NULL CHECK (operation_kind IN ('send', 'turn')),
  conversation_id TEXT NOT NULL,
  source_session_key TEXT,
  message_hash TEXT NOT NULL,
  status TEXT NOT NULL CHECK (status IN ('created', 'queued', 'sent', 'suppressed', 'rejected', 'unknown', 'replied')),
  prepared_message_id TEXT,
  platform_message_id TEXT,
  queue_id TEXT,
  rejection_error TEXT,
  reply_message_id TEXT,
  reply_to_id TEXT,
  reply_thread_id TEXT,
  reply_text TEXT,
  reply_timestamp INTEGER,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  CHECK (
    (status = 'rejected' AND rejection_error IS NOT NULL) OR
    (status != 'rejected' AND rejection_error IS NULL)
  ),
  FOREIGN KEY (conversation_id) REFERENCES conversations(conversation_id) ON DELETE CASCADE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_conversation_deliveries_reply
  ON conversation_deliveries(conversation_id, platform_message_id, prepared_message_id)
  WHERE status IN ('queued', 'sent', 'replied');

CREATE INDEX IF NOT EXISTS idx_agent_conversation_deliveries_updated
  ON conversation_deliveries(updated_at DESC, operation_id);

CREATE INDEX IF NOT EXISTS idx_agent_conversation_deliveries_source_session
  ON conversation_deliveries(source_session_key, operation_id);

CREATE TABLE IF NOT EXISTS session_conversations (
  session_id TEXT NOT NULL,
  conversation_id TEXT NOT NULL,
  role TEXT NOT NULL DEFAULT 'primary' CHECK (role IN ('primary', 'participant', 'related')),
  route_context_json TEXT,
  first_seen_at INTEGER NOT NULL,
  last_seen_at INTEGER NOT NULL,
  PRIMARY KEY (session_id, conversation_id, role),
  FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE,
  FOREIGN KEY (conversation_id) REFERENCES conversations(conversation_id) ON DELETE CASCADE
) STRICT;

-- Older same-version writers preserve the envelope while updating the association.
CREATE TRIGGER IF NOT EXISTS session_conversations_route_context_invalidate_after_update
AFTER UPDATE OF role, last_seen_at ON session_conversations
WHEN NEW.route_context_json IS OLD.route_context_json
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;
END;

CREATE INDEX IF NOT EXISTS idx_agent_session_conversations_conversation
  ON session_conversations(conversation_id, last_seen_at DESC, session_id);

CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_session_conversations_primary
  ON session_conversations(session_id)
  WHERE role = 'primary';

CREATE TABLE IF NOT EXISTS session_members (
  session_key TEXT NOT NULL,
  identity_id TEXT NOT NULL,
  added_by TEXT NOT NULL,
  added_at INTEGER NOT NULL,
  PRIMARY KEY (session_key, identity_id),
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_session_members_identity
  ON session_members(identity_id, session_key);

CREATE TABLE IF NOT EXISTS session_suggestions (
  id TEXT PRIMARY KEY,
  session_key TEXT NOT NULL,
  author_id TEXT NOT NULL,
  author_label TEXT,
  text TEXT NOT NULL,
  created_at INTEGER NOT NULL,
  state TEXT NOT NULL CHECK (state IN ('pending', 'accepted', 'dismissed')),
  dispatch_token TEXT,
  dispatch_started_at INTEGER,
  dispatch_resolution TEXT 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)
  ),
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_session_suggestions_session_state_created
  ON session_suggestions(session_key, state, created_at, id);

CREATE INDEX IF NOT EXISTS idx_agent_session_suggestions_author_created
  ON session_suggestions(author_id, created_at, id);

CREATE TABLE IF NOT EXISTS session_reactions (
  session_key TEXT NOT NULL,
  session_id TEXT NOT NULL,
  message_id TEXT NOT NULL,
  emoji TEXT NOT NULL,
  identity_id TEXT NOT NULL,
  identity_label TEXT,
  created_at INTEGER NOT NULL,
  PRIMARY KEY (session_key, session_id, message_id, emoji, identity_id),
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS board_tabs (
  session_key TEXT NOT NULL,
  tab_id TEXT NOT NULL,
  title TEXT NOT NULL,
  position INTEGER NOT NULL CHECK (position >= 0),
  chat_dock TEXT NOT NULL DEFAULT 'right' CHECK (chat_dock IN ('left', 'right', 'bottom', 'hidden')),
  created_by TEXT NOT NULL CHECK (created_by IN ('user', 'agent')),
  revision INTEGER NOT NULL CHECK (revision >= 0),
  PRIMARY KEY (session_key, tab_id),
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS board_widgets (
  session_key TEXT NOT NULL,
  name TEXT NOT NULL,
  tab_id TEXT NOT NULL,
  title TEXT,
  content_kind TEXT NOT NULL CHECK (content_kind IN ('html', 'mcp-app', 'plugin')),
  html BLOB,
  descriptor_json TEXT,
  sha256 TEXT NOT NULL,
  view_generation TEXT,
  revision INTEGER NOT NULL CHECK (revision >= 1),
  size_w INTEGER NOT NULL CHECK (size_w BETWEEN 1 AND 12),
  size_h INTEGER NOT NULL CHECK (size_h BETWEEN 1 AND 20),
  position INTEGER NOT NULL CHECK (position >= 0),
  manifest TEXT NOT NULL DEFAULT '{}',
  grant_state TEXT NOT NULL DEFAULT 'none' CHECK (grant_state IN ('none', 'pending', 'granted', 'rejected')),
  granted_sha TEXT,
  created_by TEXT NOT NULL CHECK (created_by IN ('user', 'agent')),
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (session_key, name),
  FOREIGN KEY (session_key, tab_id) REFERENCES board_tabs(session_key, tab_id) ON DELETE CASCADE,
  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)
  )
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_board_widgets_tab_position
  ON board_widgets(session_key, tab_id, position);

CREATE TABLE IF NOT EXISTS session_progress_cards (
  session_key TEXT NOT NULL PRIMARY KEY,
  markdown TEXT,
  steps_json TEXT,
  revision INTEGER NOT NULL,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS heartbeat_outcomes (
  session_key TEXT NOT NULL PRIMARY KEY,
  run_session_key TEXT NOT NULL,
  outcome TEXT NOT NULL CHECK (outcome IN ('progress', 'done', 'blocked', 'needs_attention')),
  summary TEXT NOT NULL,
  response_reason TEXT,
  priority TEXT CHECK (priority IS NULL OR priority IN ('low', 'normal', 'high')),
  next_check TEXT,
  task_names_json TEXT,
  wake_source TEXT,
  wake_reason TEXT,
  occurred_at INTEGER NOT NULL,
  context_run_id TEXT,
  context_claimed_at INTEGER,
  updated_at INTEGER NOT NULL,
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS message_tool_run_outcomes (
  id INTEGER PRIMARY KEY,
  run_id TEXT NOT NULL,
  session_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  provider TEXT NOT NULL,
  model TEXT NOT NULL,
  outcome TEXT NOT NULL CHECK (outcome IN ('tool_delivered', 'mute')),
  run_status TEXT NOT NULL CHECK (run_status IN ('completed', 'errored', 'aborted')),
  occurred_at INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_message_tool_run_outcomes_occurred
  ON message_tool_run_outcomes(occurred_at DESC, id DESC);

-- Receipts outlive Goal clear and session reset so a delayed retry cannot recreate a Goal.
-- They intentionally have no session FK; bounded retention belongs to the operation owner.
CREATE TABLE IF NOT EXISTS session_creation_operations (
  operation_digest TEXT PRIMARY KEY,
  request_fingerprint TEXT NOT NULL,
  session_key TEXT NOT NULL,
  session_id TEXT NOT NULL,
  lifecycle_revision TEXT,
  role TEXT,
  scopes_json TEXT NOT NULL,
  expires_at INTEGER NOT NULL
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_session_creation_operations_expiry
  ON session_creation_operations(expires_at);
-- END SESSION CREATION OPERATIONS

CREATE TABLE IF NOT EXISTS session_goal_operations (
  session_key TEXT NOT NULL,
  operation_id TEXT NOT NULL,
  session_id TEXT NOT NULL,
  request_fingerprint TEXT NOT NULL,
  result_json TEXT NOT NULL,
  expires_at INTEGER NOT NULL,
  PRIMARY KEY (session_key, operation_id)
) STRICT;
CREATE INDEX IF NOT EXISTS idx_agent_session_goal_operations_expiry
  ON session_goal_operations(expires_at);

CREATE TABLE IF NOT EXISTS transcript_events (
  session_id TEXT NOT NULL,
  seq INTEGER NOT NULL,
  event_json TEXT,
  created_at INTEGER NOT NULL,
  event_zstd BLOB,
  event_utf8_bytes INTEGER CHECK (event_utf8_bytes IS NULL OR event_utf8_bytes >= 0),
  navigation_json 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,
  PRIMARY KEY (session_id, seq),
  FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE,
  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 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 (
    navigation_json IS NULL OR CASE WHEN json_valid(navigation_json) THEN coalesce(
      octet_length(navigation_json) <= 16384
      AND json_type(navigation_json, '$.version') = 'integer'
      AND json_extract(navigation_json, '$.version') = 1
      AND json_type(navigation_json, '$.report') = 'object'
      AND json_extract(navigation_json, '$.report.kind') IN ('canonical', 'leaf', 'link', 'ignored')
      AND json_type(navigation_json, '$.navigation') = 'object'
      AND json_type(navigation_json, '$.reset') = 'object'
      AND json_type(navigation_json, '$.model') = 'object'
      AND json_type(navigation_json, '$.modelBytes') = 'integer'
      AND json_extract(navigation_json, '$.modelBytes') BETWEEN 0 AND 4194304
      AND json_type(navigation_json, '$.modelWithoutCheckpointBytes') = 'integer'
      AND json_extract(navigation_json, '$.modelWithoutCheckpointBytes') BETWEEN 0 AND 4194304
      AND json_type(navigation_json, '$.withoutCustomDataBytes') = 'integer'
      AND json_extract(navigation_json, '$.withoutCustomDataBytes') BETWEEN 0 AND 4194304,
      0) ELSE 0 END
  )
) STRICT;

-- Canonical cold-tier owner for reclaimed transcript generations. The derived
-- .deleted/.reset file may be recreated from this row after a crash.
CREATE TABLE IF NOT EXISTS session_transcript_archives (
  session_id TEXT NOT NULL,
  generation TEXT NOT NULL,
  session_key TEXT NOT NULL,
  reason TEXT NOT NULL CHECK (reason IN ('deleted', 'reset')),
  encoding TEXT NOT NULL CHECK (encoding IN ('identity', 'zstd')),
  archive_blob BLOB NOT NULL,
  archive_sha256 TEXT NOT NULL CHECK (length(archive_sha256) = 64),
  archive_name TEXT NOT NULL UNIQUE,
  created_at INTEGER NOT NULL,
  published_at INTEGER,
  publish_attempts INTEGER NOT NULL DEFAULT 0 CHECK (publish_attempts >= 0),
  last_publish_attempt_at INTEGER,
  last_publish_error TEXT,
  PRIMARY KEY (session_id, generation),
  CHECK (archive_name NOT LIKE '%/%' AND archive_name NOT LIKE '%\\%')
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_session_transcript_archives_pending
  ON session_transcript_archives(created_at, session_id, generation)
  WHERE published_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_agent_session_transcript_archives_retention
  ON session_transcript_archives(created_at, session_id, generation);

CREATE TABLE IF NOT EXISTS session_transcript_cold_archives (
  session_id TEXT NOT NULL PRIMARY KEY,
  generation TEXT NOT NULL,
  archive_name TEXT NOT NULL UNIQUE,
  archive_sha256 TEXT NOT NULL CHECK (length(archive_sha256) = 64),
  event_count INTEGER NOT NULL CHECK (event_count >= 1),
  raw_bytes INTEGER NOT NULL CHECK (raw_bytes >= 0),
  archive_bytes INTEGER NOT NULL CHECK (archive_bytes >= 0),
  last_seq INTEGER NOT NULL,
  archived_at INTEGER NOT NULL,
  storage TEXT NOT NULL CHECK (storage IN ('file', 'sqlite')),
  archive_blob BLOB,
  FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE,
  CHECK (length(archive_name) > 0 AND archive_name NOT IN ('.', '..') AND archive_name NOT LIKE '%/%' AND archive_name NOT LIKE '%\\%'),
  CHECK ((storage = 'file' AND archive_blob IS NULL) OR (storage = 'sqlite' AND archive_blob IS NOT NULL))
) STRICT;

CREATE TABLE IF NOT EXISTS session_transcript_cold_archive_chunks (
  session_id TEXT NOT NULL,
  chunk_index INTEGER NOT NULL CHECK (chunk_index >= 0),
  archive_name TEXT NOT NULL UNIQUE,
  archive_sha256 TEXT NOT NULL CHECK (length(archive_sha256) = 64),
  first_seq INTEGER NOT NULL,
  last_seq INTEGER NOT NULL CHECK (last_seq >= first_seq),
  event_count INTEGER NOT NULL CHECK (event_count >= 1),
  raw_bytes INTEGER NOT NULL CHECK (raw_bytes >= 0),
  archive_bytes INTEGER NOT NULL CHECK (archive_bytes >= 0),
  archive_blob BLOB,
  PRIMARY KEY (session_id, chunk_index),
  FOREIGN KEY (session_id) REFERENCES session_transcript_cold_archives(session_id) ON DELETE CASCADE,
  CHECK (length(archive_name) > 0 AND archive_name NOT IN ('.', '..') AND archive_name NOT LIKE '%/%' AND archive_name NOT LIKE '%\\%')
) STRICT, WITHOUT ROWID;

CREATE TABLE IF NOT EXISTS transcript_rewrite_watermarks (
  session_id TEXT NOT NULL PRIMARY KEY,
  generation TEXT NOT NULL,
  updated_at INTEGER NOT NULL,
  FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS trajectory_runtime_events (
  session_id TEXT NOT NULL,
  seq INTEGER NOT NULL,
  run_id TEXT,
  event_json TEXT NOT NULL,
  created_at INTEGER NOT NULL,
  event_utf8_bytes INTEGER,
  event_payload BLOB,
  event_codec TEXT,
  PRIMARY KEY (session_id, seq),
  FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_trajectory_runtime_run
  ON trajectory_runtime_events(session_id, run_id, created_at, COALESCE(event_utf8_bytes, octet_length(event_json)));

CREATE TABLE IF NOT EXISTS acp_parent_stream_events (
  session_id TEXT NOT NULL,
  run_id TEXT NOT NULL,
  seq INTEGER NOT NULL,
  event_json TEXT NOT NULL,
  created_at INTEGER NOT NULL,
  PRIMARY KEY (session_id, run_id, seq),
  FOREIGN KEY (session_id) REFERENCES "session_windows"(session_id) ON DELETE CASCADE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_acp_parent_stream_run
  ON acp_parent_stream_events(run_id, seq);

CREATE TABLE IF NOT EXISTS transcript_event_identities (
  session_id TEXT NOT NULL,
  event_id TEXT NOT NULL,
  seq INTEGER NOT NULL,
  event_type TEXT,
  parent_id TEXT,
  message_idempotency_key TEXT,
  created_at INTEGER NOT NULL,
  PRIMARY KEY (session_id, event_id),
  FOREIGN KEY (session_id, seq) REFERENCES transcript_events(session_id, seq) ON DELETE CASCADE
) STRICT;

CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_transcript_message_idempotency
  ON transcript_event_identities(session_id, message_idempotency_key)
  WHERE message_idempotency_key IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_agent_transcript_event_identity_sequence
  ON transcript_event_identities(session_id, seq);

CREATE INDEX IF NOT EXISTS idx_agent_transcript_event_sequence
  ON transcript_event_identities(session_id, event_type, seq DESC);

CREATE TABLE IF NOT EXISTS context_engine_turn_outbox (
  enqueue_sequence INTEGER PRIMARY KEY,
  advancement_key TEXT NOT NULL UNIQUE,
  engine_id TEXT NOT NULL,
  owner_plugin_id TEXT,
  session_id TEXT NOT NULL,
  payload_json TEXT NOT NULL,
  payload_state TEXT,
  attempt_count INTEGER NOT NULL DEFAULT 0,
  last_attempt_at INTEGER,
  last_error TEXT,
  created_at INTEGER NOT NULL
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_context_engine_turn_outbox_engine
  ON context_engine_turn_outbox(engine_id, created_at);

CREATE TABLE IF NOT EXISTS agent_tool_usage (
  tool_id TEXT PRIMARY KEY NOT NULL,
  score REAL NOT NULL CHECK (score >= 0),
  updated_at INTEGER NOT NULL
) STRICT;
-- END AGENT TOOL USAGE

CREATE TABLE IF NOT EXISTS cache_entries (
  scope TEXT NOT NULL,
  key TEXT NOT NULL,
  value_json TEXT,
  blob BLOB,
  expires_at INTEGER,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (scope, key)
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_cache_expiry
  ON cache_entries(scope, expires_at, key)
  WHERE expires_at IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_agent_cache_updated
  ON cache_entries(scope, updated_at DESC, key);

CREATE INDEX IF NOT EXISTS idx_agent_voice_session_open_scope
  ON cache_entries(CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.agentId') END,
    CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.sessionKey') END, CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.origin') END)
  WHERE scope = 'talk-client-voice-sessions'
    AND CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.status') END = 'open';

CREATE INDEX IF NOT EXISTS idx_agent_voice_session_open_updated
  ON cache_entries(scope, updated_at)
  WHERE scope = 'talk-client-voice-sessions'
    AND CASE WHEN json_valid(value_json) THEN json_extract(value_json, '$.status') END = 'open';

CREATE TABLE IF NOT EXISTS auth_profile_store (
  store_key TEXT NOT NULL PRIMARY KEY,
  store_json TEXT NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS auth_profile_state (
  state_key TEXT NOT NULL PRIMARY KEY,
  state_json TEXT NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS memory_index_meta (
  key TEXT PRIMARY KEY,
  value TEXT NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS memory_index_sources (
  id INTEGER PRIMARY KEY,
  path TEXT NOT NULL,
  source TEXT NOT NULL DEFAULT 'memory',
  hash TEXT NOT NULL,
  mtime REAL NOT NULL,
  size INTEGER NOT NULL,
  UNIQUE (path, source)
) STRICT;

CREATE TABLE IF NOT EXISTS memory_index_chunks (
  chunk_rowid INTEGER PRIMARY KEY,
  id TEXT NOT NULL UNIQUE,
  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 BLOB NOT NULL,
  updated_at INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS memory_index_chunk_recall_metadata (
  chunk_id TEXT PRIMARY KEY,
  importance INTEGER CHECK (importance IS NULL OR importance BETWEEN 1 AND 10),
  triggers TEXT,
  project_key TEXT,
  FOREIGN KEY (chunk_id) REFERENCES memory_index_chunks(id) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS memory_index_chunk_provenance (
  chunk_id TEXT PRIMARY KEY,
  origin_class TEXT NOT NULL CHECK (origin_class IN ('owner', 'agent', 'untrusted', 'system')),
  session_kind TEXT NOT NULL CHECK (session_kind IN ('interactive', 'cron', 'heartbeat', 'subagent', 'unknown')),
  observed_at INTEGER NOT NULL,
  supersedes_key TEXT,
  FOREIGN KEY (chunk_id) REFERENCES memory_index_chunks(id) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS memory_entry_origins (
  entry_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  session_id TEXT NOT NULL,
  session_key TEXT,
  origin_class TEXT NOT NULL CHECK (origin_class IN ('owner', 'agent', 'untrusted', 'system')),
  observed_at INTEGER NOT NULL,
  PRIMARY KEY (entry_key, agent_id, session_id)
) STRICT, WITHOUT ROWID;

CREATE TABLE IF NOT EXISTS memory_session_tombstones (
  session_id TEXT NOT NULL PRIMARY KEY,
  agent_id TEXT NOT NULL,
  reason TEXT NOT NULL,
  created_at INTEGER NOT NULL
) STRICT;

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 BLOB NOT NULL,
  dims INTEGER,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (provider, model, provider_key, hash)
) STRICT;

CREATE TABLE IF NOT EXISTS memory_index_state (
  id INTEGER PRIMARY KEY CHECK (id = 1),
  revision INTEGER NOT NULL
) STRICT;

CREATE TABLE IF NOT EXISTS standing_intents (
  intent_key INTEGER PRIMARY KEY,
  id TEXT NOT NULL UNIQUE,
  description TEXT NOT NULL,
  trigger_keywords TEXT NOT NULL,
  trigger_embedding TEXT,
  channel_scope TEXT,
  sender_scope TEXT,
  creator_sender TEXT CHECK (creator_sender IS NULL OR length(trim(creator_sender)) > 0),
  status TEXT NOT NULL CHECK (status IN ('pending', 'armed', 'fired', 'done', 'cancelled', 'expired')),
  expires_at INTEGER NOT NULL,
  max_fires INTEGER NOT NULL CHECK (max_fires > 0),
  fire_count INTEGER NOT NULL DEFAULT 0 CHECK (fire_count >= 0),
  cooldown_seconds INTEGER NOT NULL DEFAULT 86400 CHECK (cooldown_seconds >= 0),
  last_fired_at INTEGER,
  created_at INTEGER NOT NULL,
  source_session_id TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_standing_intents_lifecycle
  ON standing_intents(status, expires_at, last_fired_at);

CREATE INDEX IF NOT EXISTS idx_standing_intents_scope
  ON standing_intents(status, channel_scope, sender_scope);

CREATE VIRTUAL TABLE IF NOT EXISTS standing_intents_fts USING fts5(
  trigger_keywords,
  content = 'standing_intents',
  content_rowid = 'intent_key',
  tokenize = 'unicode61 remove_diacritics 2'
);

CREATE TRIGGER IF NOT EXISTS standing_intents_fts_after_insert
AFTER INSERT ON standing_intents
BEGIN
  INSERT INTO standing_intents_fts(rowid, trigger_keywords)
  VALUES (new.intent_key, new.trigger_keywords);
END;

CREATE TRIGGER IF NOT EXISTS standing_intents_fts_after_delete
AFTER DELETE ON standing_intents
BEGIN
  INSERT INTO standing_intents_fts(standing_intents_fts, rowid, trigger_keywords)
  VALUES ('delete', old.intent_key, old.trigger_keywords);
END;

CREATE TRIGGER IF NOT EXISTS standing_intents_fts_after_update
AFTER UPDATE OF trigger_keywords ON standing_intents
BEGIN
  INSERT INTO standing_intents_fts(standing_intents_fts, rowid, trigger_keywords)
  VALUES ('delete', old.intent_key, old.trigger_keywords);
  INSERT INTO standing_intents_fts(rowid, trigger_keywords)
  VALUES (new.intent_key, new.trigger_keywords);
END;

CREATE TABLE IF NOT EXISTS session_transcript_index_state (
  session_id TEXT NOT NULL PRIMARY KEY,
  indexed_seq INTEGER NOT NULL,
  leaf_event_id TEXT,
  needs_rebuild INTEGER NOT NULL DEFAULT 0,
  active_event_count INTEGER NOT NULL DEFAULT 0,
  active_message_count INTEGER NOT NULL DEFAULT 0,
  updated_at INTEGER NOT NULL,
  FOREIGN KEY (session_id) REFERENCES session_windows(session_id) ON DELETE CASCADE
) STRICT;

CREATE TABLE IF NOT EXISTS session_transcript_active_events (
  session_id TEXT NOT NULL,
  active_position INTEGER NOT NULL CHECK (active_position >= 0),
  event_seq INTEGER NOT NULL,
  message_position INTEGER CHECK (message_position IS NULL OR message_position >= 0),
  context_eligible INTEGER,
  PRIMARY KEY (session_id, active_position),
  FOREIGN KEY (session_id, event_seq) REFERENCES transcript_events(session_id, seq) ON DELETE CASCADE
) STRICT;

CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_transcript_active_event_seq
  ON session_transcript_active_events(session_id, event_seq);

CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_transcript_active_messages
  ON session_transcript_active_events(session_id, message_position)
  WHERE message_position IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_agent_transcript_context_pending
  ON session_transcript_active_events(session_id)
  WHERE context_eligible IS NULL;

CREATE TABLE IF NOT EXISTS session_transcript_active_event_facts (
  session_id TEXT NOT NULL,
  seq INTEGER NOT NULL,
  serialized_bytes INTEGER NOT NULL CHECK (serialized_bytes >= 1),
  dependency_navigation_json TEXT NOT NULL,
  PRIMARY KEY (session_id, seq),
  FOREIGN KEY (session_id, seq)
    REFERENCES session_transcript_active_events(session_id, event_seq) ON DELETE CASCADE
) STRICT, WITHOUT ROWID;
-- END ACTIVE EVENT FACTS

CREATE VIRTUAL TABLE IF NOT EXISTS session_transcript_fts USING fts5(
  text,
  session_id UNINDEXED,
  message_id UNINDEXED,
  role UNINDEXED,
  timestamp UNINDEXED,
  tokenize = 'unicode61 remove_diacritics 2'
);

CREATE TABLE IF NOT EXISTS session_transcript_fts_rows (
  id INTEGER PRIMARY KEY,
  session_id TEXT NOT NULL,
  message_id TEXT
) STRICT;

CREATE INDEX IF NOT EXISTS idx_session_transcript_fts_rows_session_message
  ON session_transcript_fts_rows(session_id, message_id);

CREATE TRIGGER IF NOT EXISTS session_transcript_fts_rows_after_delete
AFTER DELETE ON session_transcript_fts_rows
BEGIN
  DELETE FROM session_transcript_fts WHERE rowid = OLD.id;
END;

INSERT OR IGNORE INTO memory_index_state (id, revision) VALUES (1, 0);

CREATE INDEX IF NOT EXISTS idx_memory_embedding_cache_updated_at
  ON memory_embedding_cache(updated_at);

CREATE INDEX IF NOT EXISTS idx_memory_index_sources_source
  ON memory_index_sources(source);

CREATE INDEX IF NOT EXISTS idx_memory_index_chunks_path_source
  ON memory_index_chunks(path, source);

CREATE INDEX IF NOT EXISTS idx_memory_index_chunks_source
  ON memory_index_chunks(source);

-- Accepted input stays outside the active transcript until its exact turn owns execution.
CREATE TABLE IF NOT EXISTS session_pending_inputs (
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
  input_id TEXT NOT NULL UNIQUE,
  session_key TEXT NOT NULL,
  session_id TEXT NOT NULL,
  idempotency_key TEXT NOT NULL,
  run_id TEXT NOT NULL,
  request_hash TEXT NOT NULL,
  message_json TEXT NOT NULL,
  lifecycle_generation TEXT NOT NULL,
  state TEXT NOT NULL CHECK (state IN ('queued', 'interrupted', 'cancelled')),
  accepted_at INTEGER NOT NULL,
  consumed_event_id TEXT,
  UNIQUE (session_id, idempotency_key),
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE,
  FOREIGN KEY (session_id) REFERENCES session_windows(session_id) ON DELETE CASCADE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_session_pending_inputs_session
  ON session_pending_inputs(session_key, session_id, seq DESC);

-- Processing completion is separate from input consumption; neither schedules replay.
CREATE TABLE IF NOT EXISTS session_input_completions (
  session_key TEXT NOT NULL,
  session_id TEXT NOT NULL,
  idempotency_key TEXT NOT NULL,
  run_id TEXT NOT NULL,
  request_hash TEXT NOT NULL,
  outcome_json TEXT NOT NULL,
  succeeded INTEGER NOT NULL CHECK (succeeded IN (0, 1)),
  completed_at INTEGER NOT NULL,
  PRIMARY KEY (session_id, idempotency_key),
  FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE,
  FOREIGN KEY (session_id) REFERENCES session_windows(session_id) ON DELETE CASCADE
) STRICT;

CREATE INDEX IF NOT EXISTS idx_agent_session_input_completions_session_key
  ON session_input_completions(session_key);
`,{allowMissingColumns:!0,validateAfterRepair:validateSchema,validateUnchanged:validateSchema,diagnostics:i,reuseIntegrity:s,integrity:c?{...h,tables:l??h.tables}:void 0}));d.length>0&&cr.warn(`Rebuilt canonical agent SQLite indexes for ${t} (${n}): ${d.join(`, `)}`,{agentId:t,path:n,indexes:d,elapsedMs:Math.floor(performance.now()-g)})}else d===0&&!f&&e.prepare(`PRAGMA page_count`).get()?.page_count===0?ye(e,n,c?h:void 0):yield*Se(e,n,i,h);return m}function ensureAgentSchema(e,t,n,r=42,i=e=>e(),a,o=!1,s){let c=[],l=Mt(r);e.exec(`PRAGMA foreign_keys = OFF; PRAGMA legacy_alter_table = OFF;`);let u=!1;try{he(e,()=>{j(e);let i=Oe(e);Me(i,t,n);let a=Te(e,n),d=Wn({kind:`agent`,foundVersion:a,supportedVersion:r},s),f=a===0&&!we(e),p=a<r&&(a>0||i!==null),m=r>=18&&p;if(m&&i?.schemaVersion!==a)throw Error(`Agent schema markers disagree for ${n}; repair ownership metadata before migration.`);if(a>r)throw Error(`OpenClaw agent database ${n} uses schema version ${a}; expected at most ${r} for this migration.`);!f&&a<r&&zn(e,n,a);let assertMigration=()=>{p&&(m&&h(),H()?.assertAgentSchemaMigration({agentId:t,path:n,foundVersion:a,supportedVersion:r}))};if(assertMigration(),a<r&&Ct(e,a),f&&r===42){e.exec(l),e.exec(`PRAGMA user_version = ${r};`),tn(e,t,r),u=!0;return}let crossesVersion=e=>!f&&a<e&&r>=e,g=crossesVersion(25),_=crossesVersion(23),v=crossesVersion(24),y=crossesVersion(30),ee=y?ft(l):l,b=v?Lt(ee):ee,x=_?It(b,a):b,finishStorageMigration=()=>{if(_&&migrateAgentStorageInTransaction(e,b,a,c),v&&migrateSessionEntrySnapshotsInTransaction(e),g&&An(e),crossesVersion(26)&&migrateAgentJsonPredicatesInTransaction(e),a<27&&r>=27){let r=migrateOutboxEnqueueSequenceInTransaction(e);r!==null&&cr.info(`agent outbox enqueue sequence rebuilt`,{agentId:t,pathname:n,elapsedMs:r})}crossesVersion(28)&&Bt(e),crossesVersion(29)&&e.exec(ht),y&&mt(e),crossesVersion(31)&&e.exec(gt),crossesVersion(37)&&e.exec(lt),crossesVersion(39)&&ct(e),crossesVersion(40)&&e.exec(dt),crossesVersion(41)&&e.exec(pt),crossesVersion(42)&&e.exec(ut),a<25&&Kn(e,n,l,{verifyPhysicalIntegrity:!1,integrity:d}),jn(e,t,n,r,l,m,assertMigration,p?{tables:Qe({kind:`agent`,foundVersion:a,supportedVersion:r}),...a>=40&&r<=42&&d.check===`quick`?{foreignKeyTables:a<41?[`session_transcript_active_event_facts`]:[]}:{}}:void 0)};if(a>=25&&a<r)On(e,{agentId:t,pathname:n,version:a},Mt(a)),o||Y(e),finishStorageMigration();else if(a<r&&a>=20&&a<25&&r>=21){a>=21&&(Pn(e,n,r),Y(e),Vn(e),un(e),In(e),wn(e)&&Tn(e));let i=Mt(a);Kn(e,n,i,{verifyPhysicalIntegrity:!1,integrity:d}),On(e,{agentId:t,pathname:n,version:a},i),a<21&&(e.exec(Nt(x)),g||Qt(e)),finishStorageMigration()}else a===17&&(Y(e),un(e),ye(e,n,d),Tn(e),Nn(e,n,Mt(a),`legacy`,!0)),Pn(e,n,r),a===r?(Y(e),Vn(e),In(e),Cn(e),wn(e)&&(Tn(e),e.exec(l)),Kn(e,n,l,{verifyPhysicalIntegrity:!1,integrity:s?d:void 0}),a===16&&En(e,n,l),tn(e,t,r),On(e,{agentId:t,pathname:n,version:r},l),rn()):(a===14&&Dn(e,{agentId:t,pathname:n}),J(),St(e),migrateOpenClawAgentSchema(e),mn(e),a<11&&Hn(e),migrateSessionNodesAndWindows(e,a),J(),Y(e),r>=18&&a<18&&xn(e,n),r>=19&&en(e,a),Vn(e),J(),e.exec(x),a!==17&&Tn(e),a<r&&Zn(e),hn(e,a),Bn(e,a),a<11&&_t(e,x,{databaseLabel:n,integrityCheck:s}),a<21&&r>=21&&!g&&Qt(e),finishStorageMigration())},{databaseLabel:n,operationLabel:`agent.schema.ensure`,withCommit:i})}finally{e.isOpen&&e.exec(`PRAGMA foreign_keys = ON;`)}u&&(N(e)||M(e))&&(ie(e),At(e));for(let e of c){let n=`Agent ${t}: ${e}`;cr.warn(n),a?.(n)}}function registerOpenClawAgentWalMaintenance(e,t){if(x(e.db))return;let n={agentId:e.agentId,path:e.path,env:t},r=at(e),i={kind:`file`,physicalIdentity:r.identity,birthtime:r.birthtime,nativeLocation:r.filename},a=new AbortController,o,s,cancel=()=>{a.abort()},assertCurrent=()=>{if(a.signal.throwIfAborted(),q.databases.get(e.path)!==e||!e.db.isOpen)throw Error(`Agent WAL maintenance owner changed`)};ze(e.db,async t=>{if(a.signal.aborted)return;let r=U(e.db),c=kn(n,async()=>{assertCurrent(),s=Fe({...n,revoke:cancel,async close(){cancel(),await o?.catch(()=>{})}});let{captureOpenClawAgentDatabaseExecution:e}=await import(`./transcript-openclaw-agent-execution-sefImfO-.mjs`).then(e=>e.r);assertCurrent();let r=e(n,{expectedIdentity:i});try{let e=await r.runExisting(Ln(assertCurrent,`Agent WAL maintenance authority expired`),e=>e.execute({type:`database.walMaintenance`,input:t}));return assertCurrent(),r.assertCurrent(),e}finally{await r.release()}},void 0,a.signal);o=c;try{return await c}finally{r(),o=void 0,s?.(),s=void 0}},cancel)}const{openOpenClawAgentDatabase:lr,openOpenClawAgentDatabaseInWorker:ur,runOpenClawAgentWriteTransaction:dr,withOpenClawAgentDatabaseAsync:fr,withOpenClawAgentDatabaseRuntime:pr,withOpenClawAgentDatabaseRuntimeFromExecution:mr,withOpenClawAgentDatabaseAdmission:hr}=createOpenClawAgentDatabaseAdmissionOwner(openOpenClawAgentDatabaseSteps);function*openOpenClawAgentDatabaseSteps(e,i,a,o,l){let u=Vt(),p=u?void 0:l?.integrityCheck??H()?.sqliteIntegrityCheck;u&&t();let m=P(e.agentId);Ve(m,{env:e.env});let h={...e,agentId:m},g=L(h),assertCurrent=e=>{l?.assertCurrent?.(),l?.expectedIdentity&&(e?st(e,l.expectedIdentity):d(g,l.expectedIdentity.key,l.expectedIdentity.birthtime))};assertCurrent(),ue(h),Ee(h)?.assertCurrent();let v=He(h);if(v){if(assertCurrent(v),a)throw Error(`A prepared Worker lease cannot adopt an existing agent database handle`);return i?.workerPrepared&&kt(v,!0,!0),v}Ie({agentId:m,path:g}),i||gn(g);let y=q.databases.get(g),b=!process.permission&&s();l?.expectedIdentity||Ke(g),Wt(g);let C=Ge(`agent`,g,{env:h.env});if(C)throw Un(g,C),C;y&&(dn(y),q.databases.delete(g),q.failures.delete(g));let w={...e.env??process.env,OPENCLAW_STATE_DIR:_(e.env??process.env),...Re(e.env??process.env)?{OPENCLAW_SUPERVISOR_MODE:`external`}:{}};if(a&&(a.receipt.agentId!==m||a.receipt.path!==g))throw Error(`Prepared agent database lease belongs to another store`);let T=!1,D,O={},k=i?.validation??a?.validation,captureVerification=(e,t)=>{T=e,D=t},A={env:w,initializationAgentPaths:[g]};assertCurrent();let j=a?a.claim(captureVerification):Fn({agentId:m,path:g,env:w},void 0,captureVerification);i&&(i.assertHeld=()=>cn(j,{agentId:m,path:g,env:w}));let M=vn(m,g,i?`async`:`sync`,O),N,F,I,R;try{if(assertCurrent(),a&&!Z)try{Je({stage:`prepare`,facts:{kind:`agent-validation-start`,lease:a.receipt}})}catch(e){throw new n(e)}l?.expectedIdentity||(ensureOpenClawAgentDatabasePermissions(g,h),Xe(g)),Kt(g);let t=nt(l?.expectedIdentity?tt(g):g,{allowExtension:b,timeout:u?void 0:E});N=t;let s=t;ot(t,oe(w)),assertCurrent({db:t,path:g}),l?.expectedIdentity&&ensureOpenClawAgentDatabasePermissions(g,h),t.enableLoadExtension(!1),re(t),a&&t.exec(`PRAGMA temp_store = FILE`),M(`open`);let d={db:t,path:g,agentId:m};k&&!u&&Tt(d,k);let _=!!Et(d),v=T||i?.workerPrepared===!0&&i.integrityRevoked!==!0,y=!1,S;try{if(u)i&&(R=de(i,h,async()=>{await on(g,m)})),s=zt(t,m,g,!1,(e,t)=>{throw s=N=e,t}),N=s,S={checkpoint:()=>!1,stop:async()=>{},reclaimFreePages:Ze,close:()=>!0},bt({db:s,path:g,agentId:m}),_=!0,y=!0;else{y=kt(d,v,i?.workerPrepared),y||ie(t,e=>{Te(t,g,e)});let e=Oe(t);Me(e,m,g),y&&ke(e,m,g),i&&(R=de(i,h,async()=>{await on(g,m)})),O.integrityGateReason=a?.integrityRevoked===!0||i?.integrityRevoked===!0||wt(g,k)?`revoked`:T?c(t)??`no-proof`:`lease-class`;let n;O.integrityGateReason===`revoked`?(_=!1,y=!1):T&&(n=r(t));let o=yield*agentDatabaseIntegrityBeforeMutationSteps(t,m,g,{runtimeAdmission:!a?.startupIntegrityRequired,diagnostics:O,verification:n,reuseRuntimeIntegrity:_&&v||O.integrityGateReason===`lease-class`&&D!==void 0&&$e(g)===D,admittedSchema:y,integrityCheck:p,integrityTables:l?.integrityTables??[]});assertCurrent(d),O.integrityGateOutcome&&O.integrityGateOutcome!==`cached`||delete O.integrityGateReason,_&&(!e||o)&&(G(g),_=!1),Ne(t,g),M(`validation`),et(t,{busyTimeoutMs:E}),S=Ye(t,{busyTimeoutMs:E,autoCheckpointPages:0,databaseLabel:`openclaw-agent:${m}`,databasePath:g,foreignKeys:!0,synchronous:`NORMAL`}),I=S,M(`configuration`),assertCurrent(d),(!e||o||!_&&te(t)!==ee)&&ensureAgentSchema(t,m,g,void 0,void 0,void 0,!1,p),M(`schema`),s=zt(t,m,g)}}catch(e){O.integrityGateOutcome===`failed`&&M(`validation`),I?.close(),s.isOpen&&s.close(),x(s)&&t.isOpen&&t.close();let n=q.databases.get(g);throw n&&n.db!==t||G(g),e instanceof Error&&(ne(e)||je(e))&&Un(g,e),e}assertCurrent({db:s,path:g}),ensureOpenClawAgentDatabasePermissions(g,h),y||(ie(t),yt(t));let C={agentId:m,db:s,path:g,walMaintenance:S};if(F=C,sn())throw Error(`Agent database maintenance is in progress; retry after openclaw doctor --fix completes.`);return xe(C,h)?.registerClose(pn(C,`Agent deletion cleanup`)),fe(C,h)?.registerClose(pn(C,`Agent creation claim`)),!_||!Yn(C,{env:e.env})?(assertCurrent(C),registerOpenClawAgentDatabase({agentId:m,path:g,env:e.env,admittedDb:p===`quick`&&O.integrityGateOutcome!==`pending`?void 0:s},o)):y||Dt(C),q.terminal.clear(g),q.unregisterExitClose??=f(ln),M(`registration`),_n(C,j,w),assertCurrent(C),bn(j,{agentId:m,path:g,env:w}),$t(C),Z&&registerOpenClawAgentWalMaintenance(C,w),H()?.own(C.db,`agent-handles`,()=>nn(C)),R?.(),C}catch(e){let t=a!==void 0&&!Z&&e instanceof n,r;if(F)try{dn(F)}catch(e){r=e}if(N&&(N.isOpen||S(N).isOpen)){let t=q.databases.get(g);if(i&&t&&t.db!==N){let t=N;throw an(m,g,()=>{I?.close(),t.isOpen&&t.close();let e=S(t);x(t)&&e.isOpen&&e.close(),yn(j,A)}),e}G(g);let n=F??{agentId:m,db:N,path:g,walMaintenance:I??{checkpoint:()=>!1,stop:async()=>{},reclaimFreePages:Ze,close:()=>!1}};q.databases.set(g,n),$t(n),q.leases.set(g,{leaseId:j,env:w}),q.failures.set(g,r??e),H()?.own(n.db,`agent-handles`,()=>nn(n)),q.unregisterExitClose??=f(ln)}else if(!t){let t=e instanceof n?`read-only`:void 0;try{yn(j,A,t)}catch(e){throw an(m,g,()=>yn(j,A,t)),e}}throw r??e}}function borrowOpenClawAgentDatabase(e){let{db:t}=lr(e);return{db:t,release:U(t)}}export{rr as a,decodeUsageCostRollup as c,isUsageCostRollupFresh as d,readUsageCostDeferredMetadata as f,pr as i,decodeUsageCostRollupEnvelope as l,lr as n,ir as o,dr as r,canUseUsageCostRollupForPartial as s,borrowOpenClawAgentDatabase as t,encodeUsageCostRollup as u};