import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as n,readFileSync as r,renameSync as i,unlinkSync as a,writeFileSync as o}from"node:fs";import{basename as s,dirname as c,extname as l,join as u}from"node:path";import{homedir as d}from"node:os";import{AIKIT_PATHS as f,EMBEDDING_DEFAULTS as p,SEARCH_DEFAULTS as m,STORE_DEFAULTS as ee,createLogger as te,serializeError as h,sourceTypeContentTypes as ne}from"../../core/dist/index.js";var re=e(import.meta.url);function ie(e){e.exec(`
    CREATE TABLE IF NOT EXISTS _migrations (
      version INTEGER PRIMARY KEY,
      name TEXT NOT NULL,
      applied_at TEXT NOT NULL DEFAULT (datetime('now'))
    )
  `)}function g(e,t){ie(e);let n=new Set(e.queryAll(`SELECT version FROM _migrations`).map(e=>e.version)),r=[...t].sort((e,t)=>e.version-t.version).filter(e=>!n.has(e.version));for(let t of r){e.exec(`BEGIN`);try{t.up(e),e.run(`INSERT INTO _migrations (version, name) VALUES (?, ?)`,[t.version,t.name]),e.exec(`COMMIT`)}catch(t){try{e.exec(`ROLLBACK`)}catch{}throw t}}}const _=[{version:1,name:`create state store tables`,up(e){e.exec(`
        CREATE TABLE IF NOT EXISTS stash (
          key TEXT PRIMARY KEY,
          value TEXT NOT NULL,
          created_at TEXT NOT NULL DEFAULT (datetime('now')),
          updated_at TEXT NOT NULL DEFAULT (datetime('now'))
        );

        CREATE TABLE IF NOT EXISTS checkpoints (
          id TEXT PRIMARY KEY,
          label TEXT NOT NULL,
          data TEXT NOT NULL,
          notes TEXT,
          created_at TEXT NOT NULL DEFAULT (datetime('now'))
        );

        CREATE TABLE IF NOT EXISTS sessions (
          session_id TEXT PRIMARY KEY,
          created_at TEXT NOT NULL DEFAULT (datetime('now')),
          last_activity TEXT NOT NULL DEFAULT (datetime('now')),
          metadata TEXT
        );

        CREATE TABLE IF NOT EXISTS signals (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          workspace TEXT NOT NULL,
          key TEXT NOT NULL,
          value TEXT NOT NULL,
          agent TEXT,
          ttl_seconds INTEGER NOT NULL DEFAULT 300,
          created_at TEXT NOT NULL DEFAULT (datetime('now')),
          expires_at TEXT NOT NULL
        );

        CREATE TABLE IF NOT EXISTS leases (
          workspace TEXT NOT NULL,
          resource TEXT NOT NULL,
          holder TEXT NOT NULL,
          intent TEXT,
          ttl_minutes INTEGER NOT NULL DEFAULT 10,
          acquired_at TEXT NOT NULL DEFAULT (datetime('now')),
          expires_at TEXT NOT NULL,
          PRIMARY KEY (workspace, resource)
        );

        CREATE TABLE IF NOT EXISTS memory_meta (
          entry_id TEXT PRIMARY KEY,
          tier TEXT NOT NULL DEFAULT 'working',
          retention_score REAL NOT NULL DEFAULT 1.0,
          access_count INTEGER NOT NULL DEFAULT 0,
          last_accessed_at TEXT,
          created_at TEXT NOT NULL DEFAULT (datetime('now')),
          promoted_at TEXT,
          superseded_by TEXT,
          confidence INTEGER DEFAULT 50
        )
      `)}},{version:2,name:`scope leases by workspace and resource`,up(e){let t=e.queryAll(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'leases'`)[0]?.sql??``;/PRIMARY KEY\s*\(\s*workspace\s*,\s*resource\s*\)/i.test(t)||e.exec(`
        ALTER TABLE leases RENAME TO leases_legacy;

        CREATE TABLE leases (
          workspace TEXT NOT NULL,
          resource TEXT NOT NULL,
          holder TEXT NOT NULL,
          intent TEXT,
          ttl_minutes INTEGER NOT NULL DEFAULT 10,
          acquired_at TEXT NOT NULL DEFAULT (datetime('now')),
          expires_at TEXT NOT NULL,
          PRIMARY KEY (workspace, resource)
        );

        INSERT INTO leases (workspace, resource, holder, intent, ttl_minutes, acquired_at, expires_at)
        SELECT workspace, resource, holder, intent, ttl_minutes, acquired_at, expires_at
        FROM leases_legacy;

        DROP TABLE leases_legacy;
      `)}}],v=te(`sqlite-adapter`),y=e(import.meta.url),b=`better-sqlite3`;function ae(e){return e.replace(/\\/g,`/`)}function x(){return y.resolve(`@vpxa/aikit/package.json`).replace(/[\\/]package\.json$/,``)}function S(){return x().replace(/[\\/]node_modules[\\/]@vpxa[\\/]aikit$/,``)}function oe(e){return ae(e).includes(`/_npx/`)}function C(){try{return JSON.parse(r(u(x(),`package.json`),`utf8`)).optionalDependencies?.[b]??`latest`}catch{return`latest`}}function se(e){return e.replace(/[^a-zA-Z0-9._-]+/g,`_`)}function ce(){let e=`${se(C())}-${process.platform}-${process.arch}-abi${process.versions.modules}`;return u(d(),`.aikit`,`cache`,`native-modules`,b,e)}function w(e){n(e,{recursive:!0});let r=u(e,`package.json`);t(r)||o(r,`${JSON.stringify({name:`aikit-native-runtime-cache`,private:!0},null,2)}\n`,`utf8`)}function T(e){let t=k(e);if(!t)return null;try{return JSON.parse(r(u(t,`package.json`),`utf8`)).version??null}catch{return null}}function E(e,t){try{let n={packageName:b,packageSpec:C(),packageVersion:T(e),platform:process.platform,arch:process.arch,nodeAbi:process.versions.modules,installedAt:new Date().toISOString(),source:t};o(u(e,`.aikit-native-module.json`),`${JSON.stringify(n,null,2)}\n`,`utf8`)}catch(e){v.debug(`Failed to write better-sqlite3 runtime marker`,h(e))}}var D=class{runtimeRoot;type=`better-sqlite3`;vectorCapable=!1;db=null;stmtCache=new Map;dbPath=``;DatabaseCtor=null;recovering=!1;constructor(e){this.runtimeRoot=e}async open(t){let n;try{let t=y;this.runtimeRoot!=null&&(w(this.runtimeRoot),t=e(u(this.runtimeRoot,`package.json`))),n=t(b)}catch(e){throw Error(`better-sqlite3 native binding unavailable: ${e instanceof Error?e.message:String(e)}`)}this.db=new n(t),this.dbPath=t,this.DatabaseCtor=n,this.db.pragma(`journal_mode = WAL`),this.db.pragma(`foreign_keys = ON`),this.db.pragma(`synchronous = NORMAL`),this.runIntegrityCheck(t,n)||(this.db?.pragma(`journal_mode = WAL`),this.db?.pragma(`foreign_keys = ON`),this.db?.pragma(`synchronous = NORMAL`));try{y(`sqlite-vec`).load(this.db),this.vectorCapable=!0,v.debug(`sqlite-vec extension loaded`)}catch(e){this.vectorCapable=!1,v.warn(`sqlite-vec extension failed to load; vector search disabled`,h(e))}}exec(e){try{this.getDb().exec(e)}catch(t){if(this.isCorruptionError(t)){this.recover(),this.getDb().exec(e);return}throw t}}pragma(e){this.getDb().pragma(e)}queryAll(e,t=[]){try{let n=this.prepareCached(e);return t.length>0?n.all(...t):n.all()}catch(n){if(this.isCorruptionError(n))return this.recover(),this.queryAll(e,t);throw n}}run(e,t=[]){try{let n=this.prepareCached(e);t.length>0?n.run(...t):n.run()}catch(n){if(this.isCorruptionError(n)){this.recover(),this.run(e,t);return}throw n}}flush(){}close(){this.db&&=(this.stmtCache.clear(),this.db.close(),null)}runIntegrityCheck(e,t){try{let t=this.db?.pragma(`integrity_check`);if(t.length===1&&t[0]?.integrity_check===`ok`)return!0;let n=t.map(e=>e.integrity_check).slice(0,5).join(`; `);v.warn(`Database integrity check failed — recreating`,{dbPath:e,issues:n})}catch(t){v.warn(`Integrity check query failed — recreating database`,{dbPath:e,error:h(t)})}try{this.db?.close()}catch{}this.db=null,this.stmtCache.clear();try{a(e)}catch{}try{a(`${e}-wal`)}catch{}try{a(`${e}-shm`)}catch{}return this.db=new t(e),v.info(`Database recreated successfully — full reindex required`,{dbPath:e}),!1}isCorruptionError(e){if(this.recovering)return!1;let t=e instanceof Error?e.message:String(e);return/database disk image is malformed|file is not a database|database or disk is full/.test(t)}recover(){if(this.recovering)throw Error(`BetterSqlite3Adapter: recovery already in progress`);this.recovering=!0;try{v.warn(`Runtime corruption detected — recovering database`,{dbPath:this.dbPath});try{this.db?.close()}catch{}this.db=null,this.stmtCache.clear();try{a(this.dbPath)}catch{}try{a(`${this.dbPath}-wal`)}catch{}try{a(`${this.dbPath}-shm`)}catch{}if(!this.DatabaseCtor)throw Error(`DatabaseCtor is not initialized`);this.db=this.DatabaseCtor(this.dbPath),this.db.pragma(`journal_mode = WAL`),this.db.pragma(`foreign_keys = ON`),this.db.pragma(`synchronous = NORMAL`);try{y(`sqlite-vec`).load(this.db),this.vectorCapable=!0}catch{this.vectorCapable=!1}v.info(`Database recovered — full reindex required`,{dbPath:this.dbPath})}finally{this.recovering=!1}}getDb(){if(!this.db)throw Error(`BetterSqlite3Adapter: database not opened`);return this.db}prepareCached(e){let t=this.stmtCache.get(e);if(t)return t;let n=this.getDb().prepare(e);return this.stmtCache.set(e,n),n}};function le(e){return y.resolve(`sql.js/dist/${e}`)}function ue(e){return e.match(/^\s*(?:INSERT(?:\s+OR\s+\w+)?\s+INTO|UPDATE)\s+([A-Za-z_][A-Za-z0-9_]*)/i)?.[1]??null}var O=class{type=`sql.js`;vectorCapable=!1;db=null;dbPath=``;dirty=!1;inTransaction=!1;foreignKeysEnabled=!1;async open(e){this.dbPath=e;let n=(await import(`sql.js`)).default,i=await n({locateFile:e=>le(e)});if(t(e)){let t=r(e);this.db=new i.Database(t)}else this.db=new i.Database}exec(e){let t=e.trimStart().toUpperCase();this.getDb().run(e),t.startsWith(`BEGIN`)?this.inTransaction=!0:(t.startsWith(`COMMIT`)||t.startsWith(`ROLLBACK`))&&(this.inTransaction=!1),this.dirty=!0}pragma(e){let t=e.trim().toLowerCase();t===`foreign_keys = on`||t===`foreign_keys=on`?this.foreignKeysEnabled=!0:(t===`foreign_keys = off`||t===`foreign_keys=off`)&&(this.foreignKeysEnabled=!1),this.getDb().exec(`PRAGMA ${e}`)}queryAll(e,t=[]){let n=this.getDb().prepare(e);try{t.length>0&&n.bind(t);let e=[];for(;n.step();)e.push(n.getAsObject());return e}finally{n.free()}}run(e,t=[]){let n=this.getDb(),r=e.trimStart().toUpperCase(),i=ue(e),a=this.foreignKeysEnabled&&!this.inTransaction&&i!==null&&(r.startsWith(`INSERT`)||r.startsWith(`UPDATE`));a&&n.run(`SAVEPOINT fk_check`);try{if(t.length>0){let r=n.prepare(e);try{r.bind(t),r.step()}finally{r.free()}}else n.run(e);if(a){if(n.exec(`PRAGMA foreign_key_check(${i})`).length>0)throw n.run(`ROLLBACK TO fk_check`),n.run(`RELEASE fk_check`),Error(`FOREIGN KEY constraint failed`);n.run(`RELEASE fk_check`)}}catch(e){if(a)try{n.run(`ROLLBACK TO fk_check`),n.run(`RELEASE fk_check`)}catch{}throw e}this.dirty=!0}flush(){if(!this.dirty||!this.db)return;let e=this.db.export(),r=`${this.dbPath}.tmp`,a=c(this.dbPath);a&&!t(a)&&n(a,{recursive:!0}),o(r,Buffer.from(e)),i(r,this.dbPath),this.dirty=!1}close(){if(this.db){let e=this.db,t;try{this.flush()}catch(e){t=e;try{a(`${this.dbPath}.tmp`)}catch{}}try{e.close()}finally{this.db=null}if(t)throw t}}getDb(){if(!this.db)throw Error(`SqlJsAdapter: database not opened`);return this.db}};function k(e){if(e){let n=u(e,`node_modules`,b);return t(u(n,`package.json`))?n:null}try{return y.resolve(`${b}/package.json`).replace(/[\\/]package\.json$/,``)}catch{return null}}function de(e){let n=k(e);if(!n)return null;let r=u(n,`build`,`Release`,`better_sqlite3.node`);return t(r)?r:null}async function fe(e){let n=k(e);if(!n)return`package-missing`;if(!t(u(n,`build`,`Release`,`better_sqlite3.node`)))return`binding-missing`;try{let{execFileSync:t}=await import(`node:child_process`),n=e??S();return e&&w(e),t(process.execPath,[`-e`,`require('${b}')`],{cwd:n,stdio:`pipe`,timeout:15e3,windowsHide:!0}),`ok`}catch(e){let t=e instanceof Error&&`stderr`in e?String(e.stderr):``;return/NODE_MODULE_VERSION/.test(t)?`abi-mismatch`:/Could not locate the bindings file|no native build was found/.test(t)?`binding-missing`:`error`}}async function pe(e,n=!1){let r=k(e);if(!r)return v.info(`better-sqlite3 package is not installed — skipping native rebuild`),!1;try{let{execFileSync:i}=await import(`node:child_process`),o=e??r.replace(/[\\/]node_modules[\\/]better-sqlite3$/,``),s=process.platform===`win32`?`npm.cmd`:`npm`;if(e&&w(e),n){let e=u(r,`build`,`Release`,`better_sqlite3.node`);if(t(e))try{a(e),v.info(`Deleted stale native binding before rebuild`,{path:e})}catch(t){v.warn(`Cannot delete stale native binding — file may be locked by another process`,{path:e,error:t instanceof Error?t.message:String(t)})}}return v.info(`Attempting native module rebuild for better-sqlite3`,{cwd:o}),i(s,[`rebuild`,b],{cwd:o,stdio:`pipe`,timeout:6e4,windowsHide:!0}),v.info(`Native module rebuild completed successfully`),E(o,`rebuild`),!0}catch(e){return v.warn(`Native module rebuild failed — continuing with sql.js fallback`,h(e)),!1}}async function me(e){try{let{execFileSync:t}=await import(`node:child_process`),n=e??S(),r=process.platform===`win32`?`npm.cmd`:`npm`,i=C();return w(n),v.info(`Attempting to install better-sqlite3 for native adapter recovery`,{cwd:n,packageSpec:i}),t(r,[`install`,`--no-save`,`--package-lock=false`,`--no-audit`,`--no-fund`,`--omit=dev`,`${b}@${i}`],{cwd:n,stdio:`pipe`,timeout:12e4,windowsHide:!0}),v.info(`better-sqlite3 install completed successfully`),E(n,`install`),!0}catch(e){return v.warn(`better-sqlite3 install failed — continuing with sql.js fallback`,h(e)),!1}}let A=!1;function he(){return!!process.env.VITEST||process.argv.some(e=>e.includes(`vitest`))}async function ge(){let e=M.resolveAikitRuntimeRoot(),t=await M.probeNativeModuleAbi(e);if(t===`ok`)return e;if(M.isNpxRuntimeRoot(e)){let e=M.resolvePersistentNativeRuntimeRoot(),t=await M.probeNativeModuleAbi(e);if(t===`ok`)return v.info(`Using cached better-sqlite3 native runtime`,{runtimeRoot:e,version:M.resolveNativeModuleVersion(e)}),e;let n=!1;if(t===`abi-mismatch`?(v.info(`Persistent better-sqlite3 cache ABI mismatch — rebuilding cached binding`),n=await M.tryRebuildNativeModule(e,!0)):t===`binding-missing`?(v.info(`Persistent better-sqlite3 cache missing binding — rebuilding cache`),n=await M.tryRebuildNativeModule(e,!1)):(v.info(`Persistent better-sqlite3 cache missing — installing cached runtime`,{runtimeRoot:e,packageSpec:M.readAikitPackageSpec()}),n=await M.tryInstallNativeModule(e)),n&&await M.probeNativeModuleAbi(e)===`ok`)return v.info(`Persistent better-sqlite3 cache ready`,{runtimeRoot:e,version:M.resolveNativeModuleVersion(e)}),e}if(t===`abi-mismatch`){if(v.info(`Detected NODE_MODULE_VERSION mismatch via pre-flight probe — rebuilding before load`),await M.tryRebuildNativeModule(e,!0)&&await M.probeNativeModuleAbi(e)===`ok`)return v.info(`Pre-flight rebuild succeeded — proceeding with native adapter`),e}else if(t===`binding-missing`){if(v.info(`No native binding found — attempting rebuild before load`),await M.tryRebuildNativeModule(e,!1)&&await M.probeNativeModuleAbi(e)===`ok`)return e}else if(t===`package-missing`&&(v.info(`better-sqlite3 package is not installed — attempting install before load`),await M.tryInstallNativeModule(e)&&await M.probeNativeModuleAbi(e)===`ok`))return e;return null}async function j(e){let t=null;M.isVitestRuntime()||(t=await M.preparePreferredNativeRuntime());{let n=M.createNativeAdapter(t??void 0);try{return await n.open(e),n}catch(n){let r=n instanceof Error?n.message:String(n);if(!M.isVitestRuntime()&&/NODE_MODULE_VERSION|Could not locate the bindings file|no native build was found/.test(r)){let n=t??M.resolveAikitRuntimeRoot();if(await M.tryRebuildNativeModule(n,!1)){let t=M.createNativeAdapter(n);try{return await t.open(e),v.info(`better-sqlite3 recovered after native module rebuild`),t}catch{}}}A||(A=!0,v.warn(`[aikit] better-sqlite3 unavailable — falling back to sql.js (vector search disabled). Reinstall with prebuild support or rebuild from source to enable vector search.`,h(n)))}}let n=M.createFallbackAdapter();try{return await n.open(e),n}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`[aikit] SQLite adapter "sql.js" failed to load: ${t}`)}}async function _e(e){let t=new O;return await t.open(e),t}const M={BetterSqlite3Adapter:D,SqlJsAdapter:O,isVitestRuntime:he,resolveAikitPackageRoot:x,resolveAikitRuntimeRoot:S,isNpxRuntimeRoot:oe,readAikitPackageSpec:C,resolvePersistentNativeRuntimeRoot:ce,ensureRuntimeRootPackageJson:w,resolveNativeModulePackageDir:k,resolveNativeBindingPath:de,resolveNativeModuleVersion:T,probeNativeModuleAbi:fe,tryRebuildNativeModule:pe,tryInstallNativeModule:me,preparePreferredNativeRuntime:ge,createNativeAdapter:e=>new D(e),createFallbackAdapter:()=>new O},N=new Set([`sessions`,`stash`,`checkpoints`,`leases`,`signals`,`audit_log`,`replay_entries`,`session_metadata`]);function ve(e){let t=l(e)||`.db`,n=s(e,t);return u(c(e),`${n}-control${t}`)}function ye(e){return N.has(e)?`control`:`content`}function P(e,t={}){let n=t.splitEnabled??!1;return{splitEnabled:n,contentDbPath:t.contentDbPath??e,controlDbPath:t.controlDbPath??(n?ve(e):e)}}function be(e,t=process.env){let n=t.AIKIT_SPLIT_STATE?.trim().toLowerCase();return P(e,{splitEnabled:n===`1`||n===`true`||n===`yes`||n===`on`})}const F=`_state_partition_meta`;function I(e){return`"${e.replaceAll(`"`,`""`)}"`}function xe(e){let r=c(e);t(r)||n(r,{recursive:!0})}async function Se(e){return xe(e),j(e)}function L(e,t){return e.queryAll(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`,[t]).length>0}function Ce(e,t){return e.queryAll(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?`,[t])[0]?.sql??void 0}function we(e,t){return e.queryAll(`PRAGMA table_info(${I(t)})`).map(e=>e.name)}function R(e,t){return e.queryAll(`SELECT COUNT(*) AS count FROM ${I(t)}`)[0]?.count??0}function Te(e,t,n){if(!L(e,n))return;if(!L(t,n)){let r=Ce(e,n);if(!r)return;t.exec(r)}let r=we(t,n);if(r.length===0)return;let i=r.map(I).join(`, `),a=r.map(()=>`?`).join(`, `),o=e.queryAll(`SELECT ${i} FROM ${I(n)}`);if(o.length===0)return;let s=`INSERT OR REPLACE INTO ${I(n)} (${i}) VALUES (${a})`;for(let e of o)t.run(s,r.map(t=>e[t]??null))}function Ee(e){e.exec(`
    CREATE TABLE IF NOT EXISTS ${F} (
      key TEXT PRIMARY KEY,
      value TEXT NOT NULL,
      updated_at TEXT NOT NULL DEFAULT (datetime('now'))
    )
  `)}function De(e,t,n){Ee(e),e.run(`INSERT INTO ${F} (key, value, updated_at)
     VALUES (?, ?, datetime('now'))
     ON CONFLICT(key) DO UPDATE SET
       value = excluded.value,
       updated_at = datetime('now')`,[`split-state`,JSON.stringify({splitEnabled:t.splitEnabled,contentDbPath:t.contentDbPath,controlDbPath:t.controlDbPath,migratedTables:n})])}async function Oe(e){let t=e.contentDbPath??e.controlDbPath;if(!t)throw Error(`migrateToSplitState requires at least one database path in config`);let n=P(t,e);if(!n.splitEnabled||n.controlDbPath===n.contentDbPath)return;let r=await Se(n.contentDbPath),i=await Se(n.controlDbPath);try{g(i,_);let e=[];for(let t of N){if(!L(r,t))continue;Te(r,i,t);let n=R(r,t),a=R(i,t);if(a<n)throw Error(`Split-state migration verification failed for ${t}: source=${n} target=${a}`);e.push(t)}De(i,n,e)}finally{r.close(),i.close()}}var ke=class{adapter=null;reopenPromise=null;dbPath;externalAdapter;constructor(e={}){if(e.adapter)this.adapter=e.adapter,this.externalAdapter=!0,this.dbPath=``;else{let t=e.path??f.data;this.dbPath=u(t,`graph.db`),this.externalAdapter=!1}}async initialize(){if(this.externalAdapter){let e=this.getAdapter();this.createTables(e),this.migrateSchema(e),e.flush();return}let e=c(this.dbPath);t(e)||n(e,{recursive:!0}),this.adapter=await j(this.dbPath),this.configureAdapter(this.adapter),this.createTables(this.adapter),this.migrateSchema(this.adapter),this.adapter.flush()}configureAdapter(e){e.pragma(`journal_mode = WAL`),e.pragma(`foreign_keys = ON`)}createTables(e){e.exec(`
      CREATE TABLE IF NOT EXISTS nodes (
        id TEXT PRIMARY KEY,
        type TEXT NOT NULL,
        name TEXT NOT NULL,
        properties TEXT NOT NULL DEFAULT '{}',
        source_record_id TEXT,
        source_path TEXT,
        created_at TEXT NOT NULL DEFAULT (datetime('now')),
        community TEXT
      )
    `),e.exec(`
      CREATE TABLE IF NOT EXISTS edges (
        id TEXT PRIMARY KEY,
        from_id TEXT NOT NULL,
        to_id TEXT NOT NULL,
        type TEXT NOT NULL,
        weight REAL DEFAULT 1.0,
        confidence REAL DEFAULT 1.0,
        properties TEXT NOT NULL DEFAULT '{}',
        FOREIGN KEY (from_id) REFERENCES nodes(id) ON DELETE CASCADE,
        FOREIGN KEY (to_id) REFERENCES nodes(id) ON DELETE CASCADE
      )
    `),e.exec(`CREATE INDEX IF NOT EXISTS idx_nodes_type ON nodes(type)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_nodes_source_path ON nodes(source_path)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_edges_from ON edges(from_id)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_edges_to ON edges(to_id)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_edges_type ON edges(type)`),e.exec(`
      CREATE TABLE IF NOT EXISTS processes (
        id TEXT PRIMARY KEY,
        entry_node_id TEXT NOT NULL,
        label TEXT NOT NULL,
        properties TEXT NOT NULL DEFAULT '{}',
        created_at TEXT NOT NULL DEFAULT (datetime('now')),
        FOREIGN KEY (entry_node_id) REFERENCES nodes(id) ON DELETE CASCADE
      )
    `),e.exec(`
      CREATE TABLE IF NOT EXISTS process_steps (
        process_id TEXT NOT NULL,
        node_id TEXT NOT NULL,
        step_order INTEGER NOT NULL,
        PRIMARY KEY (process_id, node_id),
        FOREIGN KEY (process_id) REFERENCES processes(id) ON DELETE CASCADE,
        FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
      )
    `),e.exec(`CREATE INDEX IF NOT EXISTS idx_process_steps_node ON process_steps(node_id)`)}migrateSchema(e){for(let t of[`ALTER TABLE edges ADD COLUMN confidence REAL DEFAULT 1.0`,`ALTER TABLE nodes ADD COLUMN community TEXT`])try{e.exec(t)}catch{}e.exec(`CREATE INDEX IF NOT EXISTS idx_nodes_community ON nodes(community)`)}getAdapter(){if(!this.adapter)throw Error(`SqliteGraphStore not initialized — call initialize() first`);return this.adapter}async ensureOpen(){if(this.adapter)return;if(this.externalAdapter)throw Error(`SqliteGraphStore: external adapter has been closed by its owner; cannot reopen`);if(this.reopenPromise)return this.reopenPromise;let e=this.reopenAdapter();this.reopenPromise=e;try{await e}finally{this.reopenPromise===e&&(this.reopenPromise=null)}}async reopenAdapter(){let e=await j(this.dbPath);this.configureAdapter(e),this.adapter=e}query(e,t=[]){return this.getAdapter().queryAll(e,t)}run(e,t=[]){this.getAdapter().run(e,t)}async upsertNode(e){await this.ensureOpen(),this.run(`INSERT INTO nodes (id, type, name, properties, source_record_id, source_path, created_at, community)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?)
       ON CONFLICT(id) DO UPDATE SET
         type = excluded.type, name = excluded.name, properties = excluded.properties,
         source_record_id = excluded.source_record_id, source_path = excluded.source_path,
         community = excluded.community`,[e.id,e.type,e.name,JSON.stringify(e.properties),e.sourceRecordId??null,e.sourcePath??null,e.createdAt??new Date().toISOString(),e.community??null]),this.getAdapter().flush()}async upsertEdge(e){await this.ensureOpen(),this.run(`INSERT INTO edges (id, from_id, to_id, type, weight, confidence, properties)
       VALUES (?, ?, ?, ?, ?, ?, ?)
       ON CONFLICT(id) DO UPDATE SET
         from_id = excluded.from_id, to_id = excluded.to_id,
         type = excluded.type, weight = excluded.weight, confidence = excluded.confidence, properties = excluded.properties`,[e.id,e.fromId,e.toId,e.type,e.weight??1,e.confidence??1,JSON.stringify(e.properties??{})]),this.getAdapter().flush()}async upsertNodes(e){if(e.length===0)return;await this.ensureOpen();let t=this.getAdapter();t.exec(`BEGIN TRANSACTION`);try{for(let t of e)this.run(`INSERT INTO nodes (id, type, name, properties, source_record_id, source_path, created_at, community)
           VALUES (?, ?, ?, ?, ?, ?, ?, ?)
           ON CONFLICT(id) DO UPDATE SET
             type = excluded.type, name = excluded.name, properties = excluded.properties,
             source_record_id = excluded.source_record_id, source_path = excluded.source_path,
             community = excluded.community`,[t.id,t.type,t.name,JSON.stringify(t.properties),t.sourceRecordId??null,t.sourcePath??null,t.createdAt??new Date().toISOString(),t.community??null]);t.exec(`COMMIT`),t.flush()}catch(e){throw t.exec(`ROLLBACK`),e}}async upsertEdges(e){if(e.length===0)return;await this.ensureOpen();let t=this.getAdapter();t.pragma(`foreign_keys = OFF`),t.exec(`BEGIN TRANSACTION`);try{for(let t of e)this.run(`INSERT INTO edges (id, from_id, to_id, type, weight, confidence, properties)
           VALUES (?, ?, ?, ?, ?, ?, ?)
           ON CONFLICT(id) DO UPDATE SET
             from_id = excluded.from_id, to_id = excluded.to_id,
             type = excluded.type, weight = excluded.weight, confidence = excluded.confidence, properties = excluded.properties`,[t.id,t.fromId,t.toId,t.type,t.weight??1,t.confidence??1,JSON.stringify(t.properties??{})]);t.exec(`COMMIT`),t.flush()}catch(e){throw t.exec(`ROLLBACK`),e}finally{t.pragma(`foreign_keys = ON`)}}async getNode(e){await this.ensureOpen();let t=this.query(`SELECT * FROM nodes WHERE id = ?`,[e]);return t.length>0?B(t[0]):null}async getNeighbors(e,t){await this.ensureOpen();let n=t?.direction??`both`,r=t?.edgeType,i=t?.limit??50,a=[],o=[],s=new Set;if(n===`outgoing`||n===`both`){let t=`
          SELECT e.id AS edge_id, e.from_id, e.to_id, e.type AS edge_type, e.weight,
            e.confidence AS edge_confidence, e.properties AS edge_props,
             n.id AS node_id, n.type AS node_type, n.name AS node_name, n.properties AS node_props,
            n.source_record_id AS node_src_rec, n.source_path AS node_src_path,
            n.created_at AS node_created, n.community AS node_community
      FROM edges e JOIN nodes n ON e.to_id = n.id WHERE e.from_id = ?`,n=[e];r&&(t+=` AND e.type = ?`,n.push(r)),t+=` LIMIT ?`,n.push(i);let c=this.query(t,n);for(let e of c)o.push(V(e)),s.has(e.node_id)||(s.add(e.node_id),a.push(H(e)))}if(n===`incoming`||n===`both`){let t=`
          SELECT e.id AS edge_id, e.from_id, e.to_id, e.type AS edge_type, e.weight,
            e.confidence AS edge_confidence, e.properties AS edge_props,
             n.id AS node_id, n.type AS node_type, n.name AS node_name, n.properties AS node_props,
            n.source_record_id AS node_src_rec, n.source_path AS node_src_path,
            n.created_at AS node_created, n.community AS node_community
      FROM edges e JOIN nodes n ON e.from_id = n.id WHERE e.to_id = ?`,n=[e];r&&(t+=` AND e.type = ?`,n.push(r)),t+=` LIMIT ?`,n.push(i);let c=this.query(t,n);for(let e of c)o.push(V(e)),s.has(e.node_id)||(s.add(e.node_id),a.push(H(e)))}return{nodes:a,edges:o}}async traverse(e,t){await this.ensureOpen();let n=t?.maxDepth??2,r=t?.direction??`both`,i=t?.edgeType,a=t?.limit??50,o=new Map,s=new Map,c=new Set,l=[{nodeId:e,depth:0}];for(;l.length>0&&o.size<a;){let e=l.shift();if(!e||c.has(e.nodeId)||e.depth>n)continue;c.add(e.nodeId);let t=await this.getNeighbors(e.nodeId,{direction:r,edgeType:i,limit:a-o.size});for(let r of t.nodes)o.has(r.id)||(o.set(r.id,r),e.depth+1<n&&l.push({nodeId:r.id,depth:e.depth+1}));for(let e of t.edges)s.set(e.id,e)}return{nodes:[...o.values()],edges:[...s.values()]}}async findNodes(e){await this.ensureOpen();let t=[],n=[];e.type&&(t.push(`type = ?`),n.push(e.type)),e.namePattern&&(t.push(`name LIKE ?`),n.push(`%${e.namePattern}%`)),e.sourcePath&&(t.push(`source_path = ?`),n.push(e.sourcePath));let r=t.length>0?`WHERE ${t.join(` AND `)}`:``,i=e.limit??100;return this.query(`SELECT * FROM nodes ${r} LIMIT ?`,[...n,i]).map(e=>B(e))}async findEdges(e){await this.ensureOpen();let t=[],n=[];e.type&&(t.push(`type = ?`),n.push(e.type)),e.fromId&&(t.push(`from_id = ?`),n.push(e.fromId)),e.toId&&(t.push(`to_id = ?`),n.push(e.toId));let r=t.length>0?`WHERE ${t.join(` AND `)}`:``,i=e.limit??100;return this.query(`SELECT * FROM edges ${r} LIMIT ?`,[...n,i]).map(e=>Ae(e))}async deleteNode(e){await this.ensureOpen();let t=this.getAdapter();t.exec(`BEGIN TRANSACTION`);try{this.run(`DELETE FROM edges WHERE from_id = ? OR to_id = ?`,[e,e]),this.run(`DELETE FROM nodes WHERE id = ?`,[e]),t.exec(`COMMIT`),t.flush()}catch(e){throw t.exec(`ROLLBACK`),e}}async deleteBySourcePath(e){await this.ensureOpen();let t=this.query(`SELECT id FROM nodes WHERE source_path = ?`,[e]);if(t.length===0)return 0;let n=this.getAdapter();n.exec(`BEGIN TRANSACTION`);try{for(let e of t)this.run(`DELETE FROM edges WHERE from_id = ? OR to_id = ?`,[e.id,e.id]);this.run(`DELETE FROM nodes WHERE source_path = ?`,[e]),n.exec(`COMMIT`),n.flush()}catch(e){throw n.exec(`ROLLBACK`),e}return t.length}async clear(){await this.ensureOpen();let e=this.getAdapter();e.exec(`BEGIN TRANSACTION`);try{this.run(`DELETE FROM process_steps`),this.run(`DELETE FROM processes`),this.run(`DELETE FROM edges`),this.run(`DELETE FROM nodes`),e.exec(`COMMIT`)}catch(t){throw e.exec(`ROLLBACK`),t}e.flush()}async getStats(){await this.ensureOpen();let e=this.query(`SELECT COUNT(*) as count FROM nodes`)[0]?.count??0,t=this.query(`SELECT COUNT(*) as count FROM edges`)[0]?.count??0,n=this.query(`SELECT type, COUNT(*) as count FROM nodes GROUP BY type`),r={};for(let e of n)r[e.type]=e.count;let i=this.query(`SELECT type, COUNT(*) as count FROM edges GROUP BY type`),a={};for(let e of i)a[e.type]=e.count;return{nodeCount:e,edgeCount:t,nodeTypes:r,edgeTypes:a}}async validate(){await this.ensureOpen();let e=await this.getStats(),t=this.query(`SELECT e.id AS edgeId,
              CASE
                WHEN n1.id IS NULL THEN e.from_id
                WHEN n2.id IS NULL THEN e.to_id
              END AS missingNodeId
       FROM edges e
       LEFT JOIN nodes n1 ON e.from_id = n1.id
       LEFT JOIN nodes n2 ON e.to_id = n2.id
       WHERE n1.id IS NULL OR n2.id IS NULL`),n=this.query(`SELECT n.id AS id
       FROM nodes n
       LEFT JOIN edges e1 ON n.id = e1.from_id
       LEFT JOIN edges e2 ON n.id = e2.to_id
       WHERE e1.id IS NULL AND e2.id IS NULL`).map(e=>e.id);return{valid:t.length===0,orphanNodes:n,danglingEdges:t,stats:e}}async setNodeCommunity(e,t){await this.ensureOpen(),this.run(`UPDATE nodes SET community = ? WHERE id = ?`,[t,e]),this.getAdapter().flush()}async detectCommunities(){await this.ensureOpen();let e=this.query(`SELECT id FROM nodes`),t=new Map;for(let n of e)t.set(n.id,n.id);for(let n=0;n<10;n++){let n=!1,r=new Map(t);for(let i of e){let e=this.query(`SELECT to_id AS neighbor_id FROM edges WHERE from_id = ?
           UNION
           SELECT from_id AS neighbor_id FROM edges WHERE to_id = ?`,[i.id,i.id]),a=new Map,o=t.get(i.id)??i.id;a.set(o,1);for(let n of e){let e=t.get(n.neighbor_id)??n.neighbor_id;a.set(e,(a.get(e)??0)+1)}let s=o,c=0;for(let[e,t]of a)(t>c||t===c&&e<s)&&(c=t,s=e);o!==s&&(r.set(i.id,s),n=!0)}t.clear();for(let[e,n]of r)t.set(e,n);if(!n)break}let n=this.getAdapter();n.exec(`BEGIN TRANSACTION`);try{for(let[e,n]of t)this.run(`UPDATE nodes SET community = ? WHERE id = ?`,[n,e]);n.exec(`COMMIT`),n.flush()}catch(e){throw n.exec(`ROLLBACK`),e}let r={};for(let[e,n]of t)r[n]||(r[n]=[]),r[n].push(e);return r}async traceProcess(e,t){await this.ensureOpen();let n=[],r=new Set,i=[e];for(;i.length>0;){let e=i.shift();if(!e||r.has(e))continue;r.add(e),n.push(e);let t=this.query(`SELECT to_id FROM edges WHERE from_id = ? AND type = 'calls'`,[e]);for(let e of t)r.has(e.to_id)||i.push(e.to_id)}let a=`proc_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=new Date().toISOString(),s=this.getAdapter();s.exec(`BEGIN TRANSACTION`);try{this.run(`INSERT INTO processes (id, entry_node_id, label, properties, created_at)
         VALUES (?, ?, ?, '{}', ?)`,[a,e,t,o]);for(let e=0;e<n.length;e++)this.run(`INSERT INTO process_steps (process_id, node_id, step_order) VALUES (?, ?, ?)`,[a,n[e],e]);s.exec(`COMMIT`),s.flush()}catch(e){throw s.exec(`ROLLBACK`),e}return{id:a,entryNodeId:e,label:t,properties:{},steps:n,createdAt:o}}async getProcesses(e){await this.ensureOpen();let t;t=e?this.query(`SELECT DISTINCT p.id, p.entry_node_id, p.label, p.properties, p.created_at
         FROM processes p
         JOIN process_steps ps ON p.id = ps.process_id
         WHERE ps.node_id = ?`,[e]):this.query(`SELECT * FROM processes`);let n=[];for(let e of t){let t=this.query(`SELECT node_id FROM process_steps WHERE process_id = ? ORDER BY step_order`,[e.id]);n.push({id:e.id,entryNodeId:e.entry_node_id,label:e.label,properties:z(e.properties),steps:t.map(e=>e.node_id),createdAt:e.created_at})}return n}async deleteProcess(e){await this.ensureOpen();let t=this.getAdapter();t.exec(`BEGIN TRANSACTION`);try{this.run(`DELETE FROM process_steps WHERE process_id = ?`,[e]),this.run(`DELETE FROM processes WHERE id = ?`,[e]),t.exec(`COMMIT`),t.flush()}catch(e){throw t.exec(`ROLLBACK`),e}}async depthGroupedTraversal(e,t=3,n){await this.ensureOpen();let r=n?.direction??`both`,i=n?.edgeType,a=n?.limit??100,o={},s=new Set;s.add(e);let c=[e];for(let e=1;e<=t;e++){let t=[],n=[];for(let e of c){let o=await this.getNeighbors(e,{direction:r,edgeType:i,limit:a});for(let e of o.nodes)s.has(e.id)||(s.add(e.id),t.push(e.id),n.push(e))}if(n.length>0&&(o[e]=n),c=t,c.length===0||s.size>=a)break}return o}async getCohesionScore(e){await this.ensureOpen();let t=this.query(`SELECT id FROM nodes WHERE community = ?`,[e]);if(t.length===0)return 0;let n=new Set(t.map(e=>e.id)),r=t.map(()=>`?`).join(`,`),i=t.map(e=>e.id),a=this.query(`SELECT from_id, to_id FROM edges WHERE from_id IN (${r}) OR to_id IN (${r})`,[...i,...i]);if(a.length===0)return 0;let o=0;for(let e of a)n.has(e.from_id)&&n.has(e.to_id)&&o++;return o/a.length}async getSymbol360(e){let t=await this.getNode(e);if(!t)throw Error(`Node '${e}' not found`);let n=await this.findEdges({toId:e}),r=await this.findEdges({fromId:e}),i=await this.getProcesses(e);return{node:t,incoming:n,outgoing:r,community:t.community??null,processes:i}}releaseMemory(){if(this.adapter)try{this.adapter.exec(`PRAGMA shrink_memory`),this.adapter.exec(`PRAGMA wal_checkpoint(TRUNCATE)`)}catch{}}async close(){this.adapter&&=(this.externalAdapter||this.adapter.close(),null)}};function z(e){if(!e)return{};try{return JSON.parse(e)}catch{return{}}}function B(e){return{id:e.id,type:e.type,name:e.name,properties:z(e.properties),sourceRecordId:e.source_record_id??void 0,sourcePath:e.source_path??void 0,createdAt:e.created_at,community:e.community??void 0}}function Ae(e){return{id:e.id,fromId:e.from_id,toId:e.to_id,type:e.type,weight:e.weight??1,confidence:e.confidence??1,properties:z(e.properties)}}function V(e){return{id:e.edge_id,fromId:e.from_id,toId:e.to_id,type:e.edge_type,weight:e.weight??1,confidence:e.edge_confidence??1,properties:z(e.edge_props??`{}`)}}function H(e){return{id:e.node_id,type:e.node_type,name:e.node_name,properties:z(e.node_props??`{}`),sourceRecordId:e.node_src_rec??void 0,sourcePath:e.node_src_path??void 0,createdAt:e.node_created,community:e.node_community??void 0}}function U(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n]<0?-e[n]:e[n];r>t&&(t=r)}let n=new Int8Array(e.length);if(t===0)return Buffer.from(n.buffer,n.byteOffset,n.byteLength);let r=127/t;for(let t=0;t<e.length;t++){let i=Math.round(e[t]*r);n[t]=i<-127?-127:i>127?127:i}return Buffer.from(n.buffer,n.byteOffset,n.byteLength)}const W=te(`sqlite-vec-store`);function je(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function G(e){return!e||e.length===0?[]:[...new Set(e.filter(e=>typeof e==`string`&&e.length>0))]}const K=`knowledge_meta`,q=`embedding_profile`,J=Object.freeze({additionalFilterMultiplier:4,baseOverfetchMultiplier:4,filteredOverfetchMultiplier:8,filteredRetryMultiplier:2,maxCandidateLimit:512,maxExpansionFactor:4,minFilteredCandidateLimit:16,tagFilterMultiplier:4});function Y(e){return{model:e.model,nativeDim:e.nativeDim,dimensions:e.dimensions,queryPrefix:e.queryPrefix}}function X(e){return JSON.stringify(Y(e))}var Z=class{adapter=null;externalAdapter;dbPath;embeddingDim;embeddingProfile;coarseDim;vectorEnabled=!1;ftsEnabled=!1;warnedVectorDisabled=!1;_draining=!1;_priorityQueue=[];_normalQueue=[];_closeWaiter=null;_onCloseHooks=[];constructor(e={}){let t=e.embeddingProfile?.dimensions??e.embeddingDim??p.dimensions;if(this.embeddingDim=t,this.embeddingProfile=Y(e.embeddingProfile??{model:p.model,nativeDim:p.nativeDim,dimensions:t,queryPrefix:p.queryPrefix}),this.coarseDim=Math.min(128,this.embeddingDim),e.adapter)this.adapter=e.adapter,this.externalAdapter=!0,this.dbPath=``;else{let t=P(e.path??`${ee.path}/aikit.db`,e.partition);this.dbPath=t.contentDbPath,this.externalAdapter=!1}}async initialize(){if(!this.adapter){let e=c(this.dbPath);t(e)||n(e,{recursive:!0}),this.adapter=await j(this.dbPath)}this.configureConnectionPragmas(),this.vectorEnabled=this.adapter.vectorCapable,g(this.adapter,_),this.createKnowledgeTable(),this.createKnowledgeTagsTable(),this.createFtsTable(),this.vectorEnabled?this.ensureVecTable():this.warnedVectorDisabled||(this.warnedVectorDisabled=!0,W.warn(`SqliteVecStore: vector search disabled (sqlite-vec extension not loaded). Hybrid search will return FTS-only results.`))}configureConnectionPragmas(){let e=this.getAdapter();e.pragma(`journal_mode = WAL`),e.pragma(`busy_timeout = 5000`)}getDiagnostics(){let e=this.adapter,t=e?e.constructor.name:`unknown`,n=null,r=this.externalAdapter?``:this.dbPath;if(r)try{let{statSync:e}=re(`node:fs`);n=e(r).size}catch{n=null}return{adapterType:t,vectorSearchEnabled:this.vectorEnabled,ftsEnabled:this.ftsEnabled,degradedMode:!this.vectorEnabled,dbPath:r,dbSizeBytes:n,embeddingDim:this.embeddingDim,vectorDtype:`int8`,embeddingModel:this.embeddingProfile.model,embeddingProfile:this.embeddingProfile}}createKnowledgeTable(){let e=this.getAdapter();e.exec(`
      CREATE TABLE IF NOT EXISTS knowledge (
        id           TEXT PRIMARY KEY,
        content      TEXT NOT NULL,
        sourcePath   TEXT NOT NULL,
        contentType  TEXT NOT NULL,
        headingPath  TEXT NOT NULL DEFAULT '',
        chunkIndex   INTEGER NOT NULL DEFAULT 0,
        totalChunks  INTEGER NOT NULL DEFAULT 1,
        startLine    INTEGER NOT NULL DEFAULT 0,
        endLine      INTEGER NOT NULL DEFAULT 0,
        fileHash     TEXT NOT NULL DEFAULT '',
        content_hash TEXT NOT NULL DEFAULT '',
        indexedAt    TEXT NOT NULL,
        origin       TEXT NOT NULL DEFAULT 'indexed',
        tags         TEXT NOT NULL DEFAULT '[]',
        category     TEXT NOT NULL DEFAULT '',
        version      INTEGER NOT NULL DEFAULT 1
      )
    `),e.queryAll(`PRAGMA table_info(knowledge)`).some(e=>e.name===`content_hash`)||e.exec(`ALTER TABLE knowledge ADD COLUMN content_hash TEXT NOT NULL DEFAULT ''`),e.exec(`CREATE INDEX IF NOT EXISTS idx_knowledge_sourcePath ON knowledge(sourcePath)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_knowledge_contentType ON knowledge(contentType)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_knowledge_content_hash ON knowledge(content_hash)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_knowledge_origin ON knowledge(origin)`)}createKnowledgeTagsTable(){let e=this.getAdapter();e.exec(`
      CREATE TABLE IF NOT EXISTS knowledge_tags (
        knowledge_id TEXT NOT NULL,
        tag TEXT NOT NULL,
        PRIMARY KEY (knowledge_id, tag)
      )
    `),e.exec(`CREATE INDEX IF NOT EXISTS idx_knowledge_tags_tag ON knowledge_tags(tag, knowledge_id)`)}createFtsTable(){let e=this.getAdapter();try{e.exec(`
        CREATE VIRTUAL TABLE IF NOT EXISTS knowledge_fts USING fts5(
          id UNINDEXED,
          content,
          tokenize = 'unicode61 remove_diacritics 2'
        )
      `),this.ftsEnabled=!0}catch(e){this.ftsEnabled=!1,W.warn(`FTS5 unavailable — keyword search disabled`,h(e))}}createEmbeddingProfileTable(){this.getAdapter().exec(`
      CREATE TABLE IF NOT EXISTS ${K} (
        key TEXT PRIMARY KEY,
        value TEXT NOT NULL
      )
    `)}getStoredEmbeddingProfile(){return this.getAdapter().queryAll(`SELECT value FROM ${K} WHERE key = ? LIMIT 1`,[q])[0]?.value??null}saveEmbeddingProfile(){this.getAdapter().run(`INSERT INTO ${K} (key, value)
       VALUES (?, ?)
       ON CONFLICT(key) DO UPDATE SET value = excluded.value`,[q,X(this.embeddingProfile)])}dropVectorTables(){let e=this.getAdapter();e.exec(`DROP TABLE IF EXISTS vec_knowledge_coarse`),e.exec(`DROP TABLE IF EXISTS vec_knowledge`)}ensureVecTable(){let e=this.getAdapter();this.createEmbeddingProfileTable();let t=X(this.embeddingProfile),n=this.getStoredEmbeddingProfile(),r=!1;n!==null&&n!==t&&(r=!0,W.warn(`Vec profile mismatch — dropping vector tables for recreation`,{storedProfile:n,activeProfile:t}));let i=e.queryAll(`SELECT name, sql FROM sqlite_master WHERE type='table' AND name='vec_knowledge'`);if(!r&&i.length>0){let e=i[0].sql??``,t=e.match(/(?:float|int8)\[(\d+)\]/i),n=t?Number(t[1]):null,a=/int8\[/i.test(e);(n!==null&&n!==this.embeddingDim||!a)&&(r=!0,W.warn(`Vec table schema mismatch — dropping for recreation`,{existingDim:n,newDim:this.embeddingDim,wasInt8:a}))}r&&this.dropVectorTables(),e.exec(`
      CREATE VIRTUAL TABLE IF NOT EXISTS vec_knowledge USING vec0(
        embedding int8[${this.embeddingDim}] distance_metric=cosine,
        +knowledge_id TEXT
      )
    `),this.coarseDim<this.embeddingDim&&e.exec(`
        CREATE VIRTUAL TABLE IF NOT EXISTS vec_knowledge_coarse USING vec0(
          embedding int8[${this.coarseDim}] distance_metric=cosine,
          +knowledge_id TEXT
        )
      `),this.saveEmbeddingProfile()}enqueueWrite(e,t=!1){return new Promise((n,r)=>{let i=async()=>{try{n(await e())}catch(e){r(e)}};t?this._priorityQueue.push(i):this._normalQueue.push(i),this._drain()})}async _drain(){if(!this._draining){this._draining=!0;try{for(;this._priorityQueue.length>0||this._normalQueue.length>0;){let e=this._priorityQueue.shift()??this._normalQueue.shift();e&&await e()}}finally{if(this._draining=!1,this._closeWaiter){let e=this._closeWaiter;this._closeWaiter=null,e.resolve()}}}}async upsert(e,t){if(e.length!==0){if(e.length!==t.length)throw Error(`Record count (${e.length}) does not match vector count (${t.length})`);for(let n=0;n<t.length;n++)if(t[n].length===0)throw Error(`Zero-length vector at index ${n} for record ${e[n].sourcePath}`);return this.enqueueWrite(()=>this._upsertImpl(e,t))}}async upsertInteractive(e,t){if(e.length!==0){if(e.length!==t.length)throw Error(`Record count (${e.length}) does not match vector count (${t.length})`);for(let n=0;n<t.length;n++)if(t[n].length===0)throw Error(`Zero-length vector at index ${n} for record ${e[n].sourcePath}`);return this.enqueueWrite(()=>this._upsertImpl(e,t),!0)}}async upsertWithoutVector(e,t){return this.enqueueWrite(async()=>{let n=this.getAdapter(),r=e;n.exec(`BEGIN`);try{if(this.upsertKnowledgeRow(r),this.ftsEnabled&&(n.run(`DELETE FROM knowledge_fts WHERE id = ?`,[r.id]),n.run(`INSERT INTO knowledge_fts (id, content) VALUES (?, ?)`,[r.id,r.content])),this.vectorEnabled){let e=n.queryAll(`SELECT embedding FROM vec_knowledge WHERE knowledge_id = ?`,[t]);if(e.length>0){if(n.run(`DELETE FROM vec_knowledge WHERE knowledge_id = ?`,[r.id]),n.run(`INSERT INTO vec_knowledge (embedding, knowledge_id) VALUES (vec_int8(?), ?)`,[e[0].embedding,r.id]),this.coarseDim<this.embeddingDim){let e=n.queryAll(`SELECT embedding FROM vec_knowledge_coarse WHERE knowledge_id = ?`,[t]);e.length>0&&(n.run(`DELETE FROM vec_knowledge_coarse WHERE knowledge_id = ?`,[r.id]),n.run(`INSERT INTO vec_knowledge_coarse (embedding, knowledge_id) VALUES (vec_int8(?), ?)`,[e[0].embedding,r.id]))}}else W.warn(`upsertWithoutVector: source vector not found, record will lack vector`,{recordId:r.id,sourceRecordId:t})}n.exec(`COMMIT`)}catch(e){try{n.exec(`ROLLBACK`)}catch{}throw e}n.flush()})}upsertKnowledgeRow(e){this.getAdapter().run(`INSERT INTO knowledge (id, content, sourcePath, contentType, headingPath, chunkIndex,
          totalChunks, startLine, endLine, fileHash, content_hash, indexedAt, origin, tags, category, version)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
       ON CONFLICT(id) DO UPDATE SET
         content = excluded.content,
         sourcePath = excluded.sourcePath,
         contentType = excluded.contentType,
         headingPath = excluded.headingPath,
         chunkIndex = excluded.chunkIndex,
         totalChunks = excluded.totalChunks,
         startLine = excluded.startLine,
         endLine = excluded.endLine,
         fileHash = excluded.fileHash,
         content_hash = excluded.content_hash,
         indexedAt = excluded.indexedAt,
         origin = excluded.origin,
         tags = excluded.tags,
         category = excluded.category,
         version = excluded.version`,[e.id,e.content,e.sourcePath,e.contentType,e.headingPath??``,e.chunkIndex,e.totalChunks,e.startLine,e.endLine,e.fileHash,e.contentHash??``,e.indexedAt,e.origin,JSON.stringify(G(e.tags)),e.category??``,e.version])}replaceKnowledgeTags(e,t){let n=this.getAdapter(),r=G(t);if(n.run(`DELETE FROM knowledge_tags WHERE knowledge_id = ?`,[e]),r.length===0)return;let i=r.map(()=>`(?, ?)`).join(`, `),a=[];for(let t of r)a.push(e,t);n.run(`INSERT INTO knowledge_tags (knowledge_id, tag) VALUES ${i}`,a)}async _upsertImpl(e,t){let n=this.getAdapter();n.exec(`BEGIN`);try{for(let r=0;r<e.length;r++){let i=e[r];if(this.upsertKnowledgeRow(i),this.replaceKnowledgeTags(i.id,i.tags),this.ftsEnabled&&(n.run(`DELETE FROM knowledge_fts WHERE id = ?`,[i.id]),n.run(`INSERT INTO knowledge_fts (id, content) VALUES (?, ?)`,[i.id,i.content])),this.vectorEnabled&&(n.run(`DELETE FROM vec_knowledge WHERE knowledge_id = ?`,[i.id]),n.run(`INSERT INTO vec_knowledge (embedding, knowledge_id) VALUES (vec_int8(?), ?)`,[U(t[r]),i.id]),this.coarseDim<this.embeddingDim)){let e=t[r].subarray(0,this.coarseDim);n.run(`DELETE FROM vec_knowledge_coarse WHERE knowledge_id = ?`,[i.id]),n.run(`INSERT INTO vec_knowledge_coarse (embedding, knowledge_id) VALUES (vec_int8(?), ?)`,[U(e),i.id])}}n.exec(`COMMIT`)}catch(e){try{n.exec(`ROLLBACK`)}catch{}throw e}n.flush()}async search(e,t){if(e.length===0)return[];if(!this.vectorEnabled)return this.warnedVectorDisabled||(this.warnedVectorDisabled=!0,W.warn(`search() called but vector backend is disabled — returning []`)),[];let n=t?.limit??m.maxResults,r=t?.minScore??m.minScore,i;try{i=this.runAdaptiveVectorSearch(`vec_knowledge`,U(e),t)}catch(e){return W.warn(`vector search failed`,h(e)),[]}return this.rowsToSearchResults(i,r,n)}async coarseSearch(e,t){if(!this.vectorEnabled||this.coarseDim>=this.embeddingDim)return this.search(e,t);let n=t?.limit??m.maxResults,r=t?.minScore??m.minScore,i=e.subarray(0,this.coarseDim),a;try{a=this.runAdaptiveVectorSearch(`vec_knowledge_coarse`,U(i),t)}catch(n){return W.warn(`coarse vector search failed, falling back to full search`,h(n)),this.search(e,t)}return a.length===0?this.search(e,t):this.rowsToSearchResults(a,r,n)}async ftsSearch(e,t){if(!e||e.trim().length===0||!this.ftsEnabled)return[];let n=this.getAdapter(),r=t?.limit??m.maxResults,i=this.buildFilterSqlSuffix(t,!0),a=`
      SELECT k.*, bm25(knowledge_fts) AS _bm25
      FROM knowledge_fts
      JOIN knowledge k ON k.id = knowledge_fts.id
      WHERE knowledge_fts MATCH ?
      ${i.sql}
      ORDER BY _bm25 ASC
      LIMIT ?
    `,o;try{let t=Me(e);o=n.queryAll(a,[t,...i.params,r])}catch(e){return W.warn(`fts search failed`,h(e)),[]}return o.map(e=>({record:this.fromRow(e),score:Ne(e._bm25)}))}async getById(e){let t=this.getAdapter().queryAll(`SELECT * FROM knowledge WHERE id = ? LIMIT 1`,[e]);return t.length===0?null:this.fromRow(t[0])}async deleteBySourcePath(e){return this.enqueueWrite(()=>this._deleteBySourcePathImpl(e))}async _deleteBySourcePathImpl(e){let t=this.getAdapter(),n=t.queryAll(`SELECT id FROM knowledge WHERE sourcePath = ?`,[e]);if(n.length===0)return 0;t.exec(`BEGIN`);try{for(let{id:e}of n)this.vectorEnabled&&(t.run(`DELETE FROM vec_knowledge WHERE knowledge_id = ?`,[e]),this.coarseDim<this.embeddingDim&&t.run(`DELETE FROM vec_knowledge_coarse WHERE knowledge_id = ?`,[e])),t.run(`DELETE FROM knowledge_tags WHERE knowledge_id = ?`,[e]),this.ftsEnabled&&t.run(`DELETE FROM knowledge_fts WHERE id = ?`,[e]);t.run(`DELETE FROM knowledge WHERE sourcePath = ?`,[e]),t.exec(`COMMIT`)}catch(e){try{t.exec(`ROLLBACK`)}catch{}throw e}return t.flush(),n.length}async deleteById(e){return this.enqueueWrite(()=>this._deleteByIdImpl(e))}async deleteByIdInteractive(e){return this.enqueueWrite(()=>this._deleteByIdImpl(e),!0)}async _deleteByIdImpl(e){let t=this.getAdapter();if(t.queryAll(`SELECT id FROM knowledge WHERE id = ? LIMIT 1`,[e]).length===0)return!1;t.exec(`BEGIN`);try{this.vectorEnabled&&(t.run(`DELETE FROM vec_knowledge WHERE knowledge_id = ?`,[e]),this.coarseDim<this.embeddingDim&&t.run(`DELETE FROM vec_knowledge_coarse WHERE knowledge_id = ?`,[e])),t.run(`DELETE FROM knowledge_tags WHERE knowledge_id = ?`,[e]),this.ftsEnabled&&t.run(`DELETE FROM knowledge_fts WHERE id = ?`,[e]),t.run(`DELETE FROM knowledge WHERE id = ?`,[e]),t.exec(`COMMIT`)}catch(e){try{t.exec(`ROLLBACK`)}catch{}throw e}return t.flush(),!0}async getBySourcePath(e){return this.getAdapter().queryAll(`SELECT * FROM knowledge WHERE sourcePath = ? ORDER BY chunkIndex ASC`,[e]).map(e=>this.fromRow(e))}async getStats(){let e=this.getAdapter(),t=e.queryAll(`SELECT COUNT(*) AS n FROM knowledge`)[0]?.n??0;if(t===0)return{totalRecords:0,totalFiles:0,contentTypeBreakdown:{},lastIndexedAt:null,storeBackend:`sqlite-vec`,embeddingModel:this.embeddingProfile.model};let n=e.queryAll(`SELECT COUNT(DISTINCT sourcePath) AS n FROM knowledge`),r=e.queryAll(`SELECT contentType, COUNT(*) AS n FROM knowledge GROUP BY contentType`),i=e.queryAll(`SELECT MAX(indexedAt) AS ts FROM knowledge`),a={};for(let e of r)a[e.contentType]=e.n;return{totalRecords:t,totalFiles:n[0]?.n??0,contentTypeBreakdown:a,lastIndexedAt:i[0]?.ts??null,storeBackend:`sqlite-vec`,embeddingModel:this.embeddingProfile.model}}async listSourcePaths(){return this.getAdapter().queryAll(`SELECT DISTINCT sourcePath FROM knowledge ORDER BY sourcePath`).map(e=>e.sourcePath)}async createFtsIndex(){this.createFtsTable()}async dropTable(){return this.enqueueWrite(()=>this._dropTableImpl())}async _dropTableImpl(){let e=this.getAdapter();this.ftsEnabled&&e.exec(`DROP TABLE IF EXISTS knowledge_fts`),this.vectorEnabled&&this.dropVectorTables(),e.exec(`DROP TABLE IF EXISTS ${K}`),e.exec(`DROP TABLE IF EXISTS knowledge_tags`),e.exec(`DROP TABLE IF EXISTS knowledge`),e.flush(),this.createKnowledgeTable(),this.createKnowledgeTagsTable(),this.createFtsTable(),this.vectorEnabled&&this.ensureVecTable()}releaseMemory(){if(this.adapter)try{this.adapter.exec(`PRAGMA shrink_memory`),this.adapter.exec(`PRAGMA wal_checkpoint(TRUNCATE)`)}catch{}}onBeforeClose(e){this._onCloseHooks.push(e)}async close(e=5e3){for(let e of this._onCloseHooks)try{e()}catch{}this._onCloseHooks.length=0,(this._priorityQueue.length>0||this._normalQueue.length>0||this._draining)&&(this._drain(),await new Promise(t=>{let n=setTimeout(()=>{W.warn(`SqliteVecStore.close() timed out waiting for queue drain — force closing`),t(!0)},e);this._closeWaiter={resolve:()=>{clearTimeout(n),t(!1)},reject:()=>{clearTimeout(n),t(!1)}}})&&(this._priorityQueue.length=0,this._normalQueue.length=0)),this.adapter&&!this.externalAdapter&&this.adapter.close(),this.adapter=null}getAdapter(){if(!this.adapter)throw Error(`SqliteVecStore: not initialized — call initialize() first`);return this.adapter}runAdaptiveVectorSearch(e,t,n){let r=n?.limit??m.maxResults;if(r<=0)return[];let i=this.buildFilterSqlSuffix(n),a=this.buildVectorSearchPlan(r,i.profile),o=a.initialCandidateLimit,s=this.queryVectorRows(e,t,i,o,r);for(;a.hasFilters&&s.length<r&&o<a.maxCandidateLimit;)o=Math.min(a.maxCandidateLimit,Math.max(o+r,o*J.filteredRetryMultiplier)),s=this.queryVectorRows(e,t,i,o,r);return s}queryVectorRows(e,t,n,r,i){let a=this.getAdapter(),o=`
      SELECT k.*, v.distance AS _distance
      FROM (
        SELECT knowledge_id, distance
        FROM ${e}
        WHERE embedding MATCH vec_int8(?)
        ORDER BY distance
        LIMIT ?
      ) v
      JOIN knowledge k ON k.id = v.knowledge_id
      ${n.sql}
      ORDER BY v.distance ASC
      LIMIT ?
    `;return a.queryAll(o,[t,r,...n.params,i])}buildVectorSearchPlan(e,t){let n=Math.max(1,e*J.baseOverfetchMultiplier);if(!t.hasFilters)return{hasFilters:!1,initialCandidateLimit:n,maxCandidateLimit:n};let r=Math.max(0,t.filterCount-1),i=J.filteredOverfetchMultiplier+r*J.additionalFilterMultiplier+(t.tagCount>0?J.tagFilterMultiplier:0),a=Math.min(J.maxCandidateLimit,Math.max(e*i,J.minFilteredCandidateLimit));return{hasFilters:!0,initialCandidateLimit:a,maxCandidateLimit:Math.min(J.maxCandidateLimit,Math.max(a*J.maxExpansionFactor,e*J.filteredOverfetchMultiplier))}}rowsToSearchResults(e,t,n){return e.map(e=>({record:this.fromRow(e),score:1-(e._distance??1)})).filter(e=>e.score>=t).slice(0,n)}buildFilterSqlSuffix(e,t=!1){if(!e)return{sql:``,params:[],profile:{filterCount:0,hasFilters:!1,tagCount:0}};let n=[],r=[],i=0,a=0;if(e.contentType&&(n.push(`k.contentType = ?`),r.push(e.contentType),i++),e.sourceType){let t=ne(e.sourceType);t.length>0&&(n.push(`k.contentType IN (${t.map(()=>`?`).join(`, `)})`),r.push(...t),i++)}if(e.origin&&(n.push(`k.origin = ?`),r.push(e.origin),i++),e.category&&(n.push(`k.category = ?`),r.push(e.category),i++),e.tags&&e.tags.length>0){let t=e.tags.map(()=>`?`).join(`, `);n.push(`EXISTS (SELECT 1 FROM knowledge_tags kt WHERE kt.knowledge_id = k.id AND kt.tag IN (${t}))`),r.push(...e.tags),i++,a=e.tags.length}if(n.length===0)return{sql:``,params:[],profile:{filterCount:0,hasFilters:!1,tagCount:0}};let o=n.join(` AND `);return{sql:t?`AND ${o}`:`WHERE ${o}`,params:r,profile:{filterCount:i,hasFilters:!0,tagCount:a}}}fromRow(e){return{id:e.id,content:e.content,sourcePath:e.sourcePath,contentType:e.contentType,headingPath:e.headingPath||void 0,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,startLine:e.startLine,endLine:e.endLine,fileHash:e.fileHash,contentHash:e.content_hash||void 0,indexedAt:e.indexedAt,origin:e.origin,tags:je(e.tags),category:e.category||void 0,version:e.version}}};function Me(e){let t=e.replace(/["'()*:^-]/g,` `).trim();return t?t.split(/\s+/).filter(e=>e.length>0).map(e=>`"${e}"`).join(` OR `):`""`}function Ne(e){return e==null||Number.isNaN(e)?0:1-Math.exp(-Math.abs(e)/5)}function Q(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`,n=new Date(t);return Number.isNaN(n.getTime())?t:n.toISOString()}function $(e){return`queryAll`in e&&`run`in e}function Pe(e){return{get(t){return e.queryAll(`SELECT key, value, updated_at AS updatedAt FROM stash WHERE key = ?`,[t])[0]},set(t,n){e.run(`INSERT INTO stash (key, value)
         VALUES (?, ?)
         ON CONFLICT(key) DO UPDATE SET
           value = excluded.value,
           updated_at = datetime('now')`,[t,n])},list(){return e.queryAll(`SELECT key, value, updated_at AS updatedAt FROM stash ORDER BY key`)},has(t){return e.queryAll(`SELECT 1 AS present FROM stash WHERE key = ?`,[t]).length>0},delete(t){e.run(`DELETE FROM stash WHERE key = ?`,[t])},clear(){e.run(`DELETE FROM stash`)}}}function Fe(e){return{save(t,n,r,i){e.run(`INSERT INTO checkpoints (id, label, data, notes)
         VALUES (?, ?, ?, ?)
         ON CONFLICT(id) DO UPDATE SET
           label = excluded.label,
           data = excluded.data,
           notes = excluded.notes,
           created_at = datetime('now')`,[t,n,r,i??null])},get(t){return e.queryAll(`SELECT id, label, data, notes, created_at AS createdAt FROM checkpoints WHERE id = ?`,[t])[0]},list(t,n){return t!==void 0&&n!==void 0?e.queryAll(`SELECT id, label, notes, created_at AS createdAt
           FROM checkpoints
           WHERE label = ?
           ORDER BY created_at DESC, id DESC
           LIMIT ?`,[t,n]):t===void 0?n===void 0?e.queryAll(`SELECT id, label, notes, created_at AS createdAt
         FROM checkpoints
         ORDER BY created_at DESC, id DESC`):e.queryAll(`SELECT id, label, notes, created_at AS createdAt
           FROM checkpoints
           ORDER BY created_at DESC, id DESC
           LIMIT ?`,[n]):e.queryAll(`SELECT id, label, notes, created_at AS createdAt
           FROM checkpoints
           WHERE label = ?
           ORDER BY created_at DESC, id DESC`,[t])},latest(t){let n=t===void 0?[]:[t],r=t===void 0?`SELECT id, label, data, notes, created_at AS createdAt
             FROM checkpoints
             ORDER BY created_at DESC, id DESC
             LIMIT 1`:`SELECT id, label, data, notes, created_at AS createdAt
             FROM checkpoints
             WHERE label = ?
             ORDER BY created_at DESC, id DESC
             LIMIT 1`;return e.queryAll(r,n)[0]},has(t){return e.queryAll(`SELECT 1 AS present FROM checkpoints WHERE id = ?`,[t]).length>0},delete(t){e.run(`DELETE FROM checkpoints WHERE id = ?`,[t])},gc(t=10,n){let r=e.queryAll(`SELECT id, label, notes, created_at AS createdAt
         FROM checkpoints
         ORDER BY label, created_at DESC, id DESC`),i=n===void 0?void 0:Date.now()-n*864e5,a=new Map;for(let e of r){let t=a.get(e.label);t?t.push(e):a.set(e.label,[e])}let o=[];for(let e of a.values())e.forEach((e,n)=>{let r=Date.parse(e.createdAt);n<t&&!(i!==void 0&&!Number.isNaN(r)&&r<i)||o.push(e.id)});for(let t of o)e.run(`DELETE FROM checkpoints WHERE id = ?`,[t]);return o.length}}}function Ie(e){return{create(t,n){e.run(`INSERT INTO sessions (session_id, metadata)
         VALUES (?, ?)
         ON CONFLICT(session_id) DO UPDATE SET
           last_activity = datetime('now'),
           metadata = excluded.metadata`,[t,n??null])},touch(t){e.run(`UPDATE sessions SET last_activity = datetime('now') WHERE session_id = ?`,[t])},get(t){return e.queryAll(`SELECT session_id AS sessionId,
                created_at AS createdAt,
                last_activity AS lastActivity,
                metadata
         FROM sessions
         WHERE session_id = ?`,[t])[0]},list(){return e.queryAll(`SELECT session_id AS sessionId,
                created_at AS createdAt,
                last_activity AS lastActivity
         FROM sessions
         ORDER BY created_at, session_id`)},has(t){return e.queryAll(`SELECT 1 AS present FROM sessions WHERE session_id = ?`,[t]).length>0},delete(t){e.run(`DELETE FROM sessions WHERE session_id = ?`,[t])},deleteStale(t){let n=`-${Math.max(0,t)} minutes`,r=e.queryAll(`SELECT COUNT(*) AS count
         FROM sessions
         WHERE last_activity < datetime('now', ?)`,[n])[0]?.count??0;return r>0&&e.run(`DELETE FROM sessions
           WHERE last_activity < datetime('now', ?)`,[n]),r}}}function Le(e){return{post(t,n,r,i,a=300){return e.run(`INSERT INTO signals (workspace, key, value, agent, ttl_seconds, expires_at)
         VALUES (?, ?, ?, ?, ?, datetime('now', '+' || ? || ' seconds'))`,[t,n,r,i??null,a,a]),e.queryAll(`SELECT last_insert_rowid() AS id`)[0]?.id??0},get(t,n){return e.queryAll(`SELECT id,
                workspace,
                key,
                value,
                agent,
                created_at AS createdAt,
                expires_at AS expiresAt
         FROM signals
         WHERE workspace = ?
           AND key = ?
         ORDER BY created_at ASC, id ASC`,[t,n])},list(t){return e.queryAll(`SELECT id,
                workspace,
                key,
                value,
                agent,
                created_at AS createdAt,
                expires_at AS expiresAt
         FROM signals
         WHERE workspace = ?
         ORDER BY created_at ASC, id ASC`,[t])},clear(t,n){let r=n===void 0?e.queryAll(`SELECT COUNT(*) AS count FROM signals WHERE workspace = ?`,[t])[0]?.count??0:e.queryAll(`SELECT COUNT(*) AS count FROM signals WHERE workspace = ? AND key = ?`,[t,n])[0]?.count??0;return r>0&&(n===void 0?e.run(`DELETE FROM signals WHERE workspace = ?`,[t]):e.run(`DELETE FROM signals WHERE workspace = ? AND key = ?`,[t,n])),r},cleanExpired(){let t=e.queryAll(`SELECT COUNT(*) AS count
           FROM signals
           WHERE expires_at <= datetime('now')`)[0]?.count??0;return t>0&&e.run(`DELETE FROM signals WHERE expires_at <= datetime('now')`),t}}}function Re(e){return{upsert(t,n,r,i,a=10){e.run(`INSERT INTO leases (resource, holder, intent, workspace, ttl_minutes, expires_at)
         VALUES (?, ?, ?, ?, ?, datetime('now', '+' || ? || ' minutes'))
         ON CONFLICT(workspace, resource) DO UPDATE SET
           holder = excluded.holder,
           intent = excluded.intent,
           ttl_minutes = excluded.ttl_minutes,
           acquired_at = datetime('now'),
           expires_at = excluded.expires_at`,[t,n,i??null,r,a,a])},get(t,n){return e.queryAll(`SELECT resource,
                holder,
                intent,
                workspace,
                acquired_at AS acquiredAt,
                expires_at AS expiresAt
         FROM leases
         WHERE resource = ?
           AND workspace = ?`,[t,n])[0]},list(t){return e.queryAll(`SELECT resource,
                holder,
                intent,
                workspace,
                acquired_at AS acquiredAt,
                expires_at AS expiresAt
         FROM leases
         WHERE workspace = ?
         ORDER BY acquired_at ASC, resource ASC`,[t])},delete(t,n){e.run(`DELETE FROM leases WHERE resource = ? AND workspace = ?`,[t,n])},cleanExpired(){let t=e.queryAll(`SELECT COUNT(*) AS count
           FROM leases
           WHERE expires_at <= datetime('now')`)[0]?.count??0;return t>0&&e.run(`DELETE FROM leases WHERE expires_at <= datetime('now')`),t}}}function ze(e){return{create(t,n){e.run(`INSERT INTO memory_meta (entry_id, tier)
         VALUES (?, ?)
         ON CONFLICT(entry_id) DO NOTHING`,[t,n??`working`])},get(t){return e.queryAll(`SELECT entry_id AS entryId,
                tier,
                retention_score AS retentionScore,
                access_count AS accessCount,
                last_accessed_at AS lastAccessedAt,
                created_at AS createdAt,
                promoted_at AS promotedAt,
                superseded_by AS supersededBy,
                confidence
         FROM memory_meta
         WHERE entry_id = ?`,[t])[0]},touch(t){e.run(`UPDATE memory_meta
         SET access_count = access_count + 1,
             last_accessed_at = datetime('now')
         WHERE entry_id = ?`,[t])},updateScore(t,n){e.run(`UPDATE memory_meta SET retention_score = ? WHERE entry_id = ?`,[n,t])},updateConfidence(t,n){e.run(`UPDATE memory_meta SET confidence = ? WHERE entry_id = ?`,[n,t])},updateTier(t,n){e.run(`UPDATE memory_meta
         SET tier = ?,
             promoted_at = CASE
               WHEN ? = tier THEN promoted_at
               WHEN ? = 'working' THEN promoted_at
               ELSE COALESCE(promoted_at, datetime('now'))
             END
         WHERE entry_id = ?`,[n,n,n,t])},setSuperseded(t,n){e.run(`UPDATE memory_meta SET superseded_by = ? WHERE entry_id = ?`,[n,t])},list(t){let n=[],r=[];t?.tier!==void 0&&(n.push(`tier = ?`),r.push(t.tier)),t?.belowScore!==void 0&&(n.push(`retention_score < ?`),r.push(t.belowScore));let i=n.length>0?`WHERE ${n.join(` AND `)}`:``,a=t?.limit===void 0?``:`LIMIT ?`;return t?.limit!==void 0&&r.push(t.limit),e.queryAll(`SELECT entry_id AS entryId,
                tier,
                retention_score AS retentionScore,
                access_count AS accessCount,
                last_accessed_at AS lastAccessedAt,
                created_at AS createdAt,
                promoted_at AS promotedAt,
                superseded_by AS supersededBy,
                confidence
         FROM memory_meta
         ${i}
         ORDER BY retention_score ASC,
                  COALESCE(last_accessed_at, created_at) ASC,
                  entry_id ASC
         ${a}`,r)}}}function Be(e){let t=e.prepare(`SELECT key, value, updated_at AS updatedAt FROM stash WHERE key = ?`),n=e.prepare(`INSERT INTO stash (key, value)
     VALUES (?, ?)
     ON CONFLICT(key) DO UPDATE SET
       value = excluded.value,
       updated_at = datetime('now')`),r=e.prepare(`SELECT key, value, updated_at AS updatedAt FROM stash ORDER BY key`),i=e.prepare(`SELECT 1 AS present FROM stash WHERE key = ?`),a=e.prepare(`DELETE FROM stash WHERE key = ?`),o=e.prepare(`DELETE FROM stash`);return{get(e){return t.get(e)},set(e,t){n.run(e,t)},list(){return r.all()},has(e){return i.get(e)!==void 0},delete(e){a.run(e)},clear(){o.run()}}}function Ve(e){let t=e.prepare(`INSERT INTO checkpoints (id, label, data, notes)
     VALUES (?, ?, ?, ?)
     ON CONFLICT(id) DO UPDATE SET
       label = excluded.label,
       data = excluded.data,
       notes = excluded.notes,
       created_at = datetime('now')`),n=e.prepare(`SELECT id, label, data, notes, created_at AS createdAt FROM checkpoints WHERE id = ?`),r=e.prepare(`SELECT id, label, notes, created_at AS createdAt
     FROM checkpoints
     ORDER BY created_at DESC, id DESC`),i=e.prepare(`SELECT id, label, notes, created_at AS createdAt
     FROM checkpoints
     ORDER BY created_at DESC, id DESC
     LIMIT ?`),a=e.prepare(`SELECT id, label, notes, created_at AS createdAt
     FROM checkpoints
     WHERE label = ?
     ORDER BY created_at DESC, id DESC`),o=e.prepare(`SELECT id, label, notes, created_at AS createdAt
     FROM checkpoints
     WHERE label = ?
     ORDER BY created_at DESC, id DESC
     LIMIT ?`),s=e.prepare(`SELECT id, label, data, notes, created_at AS createdAt
     FROM checkpoints
     ORDER BY created_at DESC, id DESC
     LIMIT 1`),c=e.prepare(`SELECT id, label, data, notes, created_at AS createdAt
     FROM checkpoints
     WHERE label = ?
     ORDER BY created_at DESC, id DESC
     LIMIT 1`),l=e.prepare(`SELECT 1 AS present FROM checkpoints WHERE id = ?`),u=e.prepare(`DELETE FROM checkpoints WHERE id = ?`),d=e.prepare(`SELECT id, label, notes, created_at AS createdAt
     FROM checkpoints
     ORDER BY label, created_at DESC, id DESC`);return{save(e,n,r,i){t.run(e,n,r,i??null)},get(e){return n.get(e)},list(e,t){return e!==void 0&&t!==void 0?o.all(e,t):e===void 0?t===void 0?r.all():i.all(t):a.all(e)},latest(e){return e===void 0?s.get():c.get(e)},has(e){return l.get(e)!==void 0},delete(e){u.run(e)},gc(e=10,t){let n=d.all(),r=t===void 0?void 0:Date.now()-t*864e5,i=new Map;for(let e of n){let t=i.get(e.label);t?t.push(e):i.set(e.label,[e])}let a=[];for(let t of i.values())t.forEach((t,n)=>{let i=Date.parse(t.createdAt);n<e&&!(r!==void 0&&!Number.isNaN(i)&&i<r)||a.push(t.id)});for(let e of a)u.run(e);return a.length}}}function He(e){let t=e.prepare(`INSERT INTO sessions (session_id, metadata)
     VALUES (?, ?)
     ON CONFLICT(session_id) DO UPDATE SET
       last_activity = datetime('now'),
       metadata = excluded.metadata`),n=e.prepare(`UPDATE sessions SET last_activity = datetime('now') WHERE session_id = ?`),r=e.prepare(`SELECT session_id AS sessionId,
            created_at AS createdAt,
            last_activity AS lastActivity,
            metadata
     FROM sessions
     WHERE session_id = ?`),i=e.prepare(`SELECT session_id AS sessionId,
            created_at AS createdAt,
            last_activity AS lastActivity
     FROM sessions
     ORDER BY created_at, session_id`),a=e.prepare(`SELECT 1 AS present FROM sessions WHERE session_id = ?`),o=e.prepare(`DELETE FROM sessions WHERE session_id = ?`),s=e.prepare(`SELECT COUNT(*) AS count
     FROM sessions
     WHERE last_activity < datetime('now', ?)`),c=e.prepare(`DELETE FROM sessions
     WHERE last_activity < datetime('now', ?)`);return{create(e,n){t.run(e,n??null)},touch(e){n.run(e)},get(e){return r.get(e)},list(){return i.all()},has(e){return a.get(e)!==void 0},delete(e){o.run(e)},deleteStale(e){let t=`-${Math.max(0,e)} minutes`,n=s.get(t)?.count??0;return n>0&&c.run(t),n}}}function Ue(e){let t=e.prepare(`INSERT INTO signals (workspace, key, value, agent, ttl_seconds, expires_at)
     VALUES (?, ?, ?, ?, ?, datetime('now', '+' || ? || ' seconds'))`),n=e.prepare(`SELECT id,
            workspace,
            key,
            value,
            agent,
            created_at AS createdAt,
            expires_at AS expiresAt
     FROM signals
     WHERE workspace = ?
       AND key = ?
     ORDER BY created_at ASC, id ASC`),r=e.prepare(`SELECT id,
            workspace,
            key,
            value,
            agent,
            created_at AS createdAt,
            expires_at AS expiresAt
     FROM signals
     WHERE workspace = ?
     ORDER BY created_at ASC, id ASC`),i=e.prepare(`SELECT COUNT(*) AS count FROM signals WHERE workspace = ?`),a=e.prepare(`SELECT COUNT(*) AS count FROM signals WHERE workspace = ? AND key = ?`),o=e.prepare(`DELETE FROM signals WHERE workspace = ?`),s=e.prepare(`DELETE FROM signals WHERE workspace = ? AND key = ?`),c=e.prepare(`SELECT COUNT(*) AS count
     FROM signals
     WHERE expires_at <= datetime('now')`),l=e.prepare(`DELETE FROM signals WHERE expires_at <= datetime('now')`);return{post(e,n,r,i,a=300){let o=t.run(e,n,r,i??null,a,a);return Number(o.lastInsertRowid)},get(e,t){return n.all(e,t)},list(e){return r.all(e)},clear(e,t){let n=t===void 0?i.get(e)?.count??0:a.get(e,t)?.count??0;return n>0&&(t===void 0?o.run(e):s.run(e,t)),n},cleanExpired(){let e=c.get()?.count??0;return e>0&&l.run(),e}}}function We(e){let t=e.prepare(`INSERT INTO leases (resource, holder, intent, workspace, ttl_minutes, expires_at)
     VALUES (?, ?, ?, ?, ?, datetime('now', '+' || ? || ' minutes'))
     ON CONFLICT(workspace, resource) DO UPDATE SET
       holder = excluded.holder,
       intent = excluded.intent,
       ttl_minutes = excluded.ttl_minutes,
       acquired_at = datetime('now'),
       expires_at = excluded.expires_at`),n=e.prepare(`SELECT resource,
            holder,
            intent,
            workspace,
            acquired_at AS acquiredAt,
            expires_at AS expiresAt
     FROM leases
     WHERE resource = ?
       AND workspace = ?`),r=e.prepare(`SELECT resource,
            holder,
            intent,
            workspace,
            acquired_at AS acquiredAt,
            expires_at AS expiresAt
     FROM leases
     WHERE workspace = ?
     ORDER BY acquired_at ASC, resource ASC`),i=e.prepare(`DELETE FROM leases WHERE resource = ? AND workspace = ?`),a=e.prepare(`SELECT COUNT(*) AS count
     FROM leases
     WHERE expires_at <= datetime('now')`),o=e.prepare(`DELETE FROM leases WHERE expires_at <= datetime('now')`);return{upsert(e,n,r,i,a=10){t.run(e,n,i??null,r,a,a)},get(e,t){return n.get(e,t)},list(e){return r.all(e)},delete(e,t){i.run(e,t)},cleanExpired(){let e=a.get()?.count??0;return e>0&&o.run(),e}}}function Ge(e){let t=e.prepare(`INSERT INTO memory_meta (entry_id, tier)
     VALUES (?, ?)
     ON CONFLICT(entry_id) DO NOTHING`),n=e.prepare(`SELECT entry_id AS entryId,
            tier,
            retention_score AS retentionScore,
            access_count AS accessCount,
            last_accessed_at AS lastAccessedAt,
            created_at AS createdAt,
            promoted_at AS promotedAt,
            superseded_by AS supersededBy,
            confidence
     FROM memory_meta
     WHERE entry_id = ?`),r=e.prepare(`UPDATE memory_meta
     SET access_count = access_count + 1,
         last_accessed_at = datetime('now')
     WHERE entry_id = ?`),i=e.prepare(`UPDATE memory_meta SET retention_score = ? WHERE entry_id = ?`),a=e.prepare(`UPDATE memory_meta SET confidence = ? WHERE entry_id = ?`),o=e.prepare(`UPDATE memory_meta
     SET tier = ?,
         promoted_at = CASE
           WHEN ? = tier THEN promoted_at
           WHEN ? = 'working' THEN promoted_at
           ELSE COALESCE(promoted_at, datetime('now'))
         END
     WHERE entry_id = ?`),s=e.prepare(`UPDATE memory_meta SET superseded_by = ? WHERE entry_id = ?`),c=e.prepare(`SELECT entry_id AS entryId,
            tier,
            retention_score AS retentionScore,
            access_count AS accessCount,
            last_accessed_at AS lastAccessedAt,
            created_at AS createdAt,
            promoted_at AS promotedAt,
            superseded_by AS supersededBy,
            confidence
     FROM memory_meta
     ORDER BY retention_score ASC,
              COALESCE(last_accessed_at, created_at) ASC,
              entry_id ASC`),l=e.prepare(`SELECT entry_id AS entryId,
            tier,
            retention_score AS retentionScore,
            access_count AS accessCount,
            last_accessed_at AS lastAccessedAt,
            created_at AS createdAt,
            promoted_at AS promotedAt,
            superseded_by AS supersededBy,
            confidence
     FROM memory_meta
     ORDER BY retention_score ASC,
              COALESCE(last_accessed_at, created_at) ASC,
              entry_id ASC
     LIMIT ?`),u=e.prepare(`SELECT entry_id AS entryId,
            tier,
            retention_score AS retentionScore,
            access_count AS accessCount,
            last_accessed_at AS lastAccessedAt,
            created_at AS createdAt,
            promoted_at AS promotedAt,
            superseded_by AS supersededBy,
            confidence
     FROM memory_meta
     WHERE tier = ?
     ORDER BY retention_score ASC,
              COALESCE(last_accessed_at, created_at) ASC,
              entry_id ASC`),d=e.prepare(`SELECT entry_id AS entryId,
            tier,
            retention_score AS retentionScore,
            access_count AS accessCount,
            last_accessed_at AS lastAccessedAt,
            created_at AS createdAt,
            promoted_at AS promotedAt,
            superseded_by AS supersededBy,
            confidence
     FROM memory_meta
     WHERE tier = ?
     ORDER BY retention_score ASC,
              COALESCE(last_accessed_at, created_at) ASC,
              entry_id ASC
     LIMIT ?`),f=e.prepare(`SELECT entry_id AS entryId,
            tier,
            retention_score AS retentionScore,
            access_count AS accessCount,
            last_accessed_at AS lastAccessedAt,
            created_at AS createdAt,
            promoted_at AS promotedAt,
            superseded_by AS supersededBy,
            confidence
     FROM memory_meta
     WHERE retention_score < ?
     ORDER BY retention_score ASC,
              COALESCE(last_accessed_at, created_at) ASC,
              entry_id ASC`),p=e.prepare(`SELECT entry_id AS entryId,
            tier,
            retention_score AS retentionScore,
            access_count AS accessCount,
            last_accessed_at AS lastAccessedAt,
            created_at AS createdAt,
            promoted_at AS promotedAt,
            superseded_by AS supersededBy,
            confidence
     FROM memory_meta
     WHERE retention_score < ?
     ORDER BY retention_score ASC,
              COALESCE(last_accessed_at, created_at) ASC,
              entry_id ASC
     LIMIT ?`),m=e.prepare(`SELECT entry_id AS entryId,
            tier,
            retention_score AS retentionScore,
            access_count AS accessCount,
            last_accessed_at AS lastAccessedAt,
            created_at AS createdAt,
            promoted_at AS promotedAt,
            superseded_by AS supersededBy,
            confidence
     FROM memory_meta
     WHERE tier = ?
       AND retention_score < ?
     ORDER BY retention_score ASC,
              COALESCE(last_accessed_at, created_at) ASC,
              entry_id ASC`),ee=e.prepare(`SELECT entry_id AS entryId,
            tier,
            retention_score AS retentionScore,
            access_count AS accessCount,
            last_accessed_at AS lastAccessedAt,
            created_at AS createdAt,
            promoted_at AS promotedAt,
            superseded_by AS supersededBy,
            confidence
     FROM memory_meta
     WHERE tier = ?
       AND retention_score < ?
     ORDER BY retention_score ASC,
              COALESCE(last_accessed_at, created_at) ASC,
              entry_id ASC
     LIMIT ?`);return{create(e,n){t.run(e,n??`working`)},get(e){return n.get(e)},touch(e){r.run(e)},updateScore(e,t){i.run(t,e)},updateConfidence(e,t){a.run(t,e)},updateTier(e,t){o.run(t,t,t,e)},setSuperseded(e,t){s.run(t,e)},list(e){return e?.tier!==void 0&&e?.belowScore!==void 0&&e?.limit!==void 0?ee.all(e.tier,e.belowScore,e.limit):e?.tier!==void 0&&e?.belowScore!==void 0?m.all(e.tier,e.belowScore):e?.tier!==void 0&&e?.limit!==void 0?d.all(e.tier,e.limit):e?.tier===void 0?e?.belowScore!==void 0&&e?.limit!==void 0?p.all(e.belowScore,e.limit):e?.belowScore===void 0?e?.limit===void 0?c.all():l.all(e.limit):f.all(e.belowScore):u.all(e.tier)}}}function Ke(e){let t=$(e)?Pe(e):Be(e),n=$(e)?Le(e):Ue(e),r=$(e)?Re(e):We(e),i=$(e)?Ie(e):He(e),a=$(e)?Fe(e):Ve(e),o=$(e)?ze(e):Ge(e);return{stashGet(e){return t.get(e)?.value},stashSet(e,n){t.set(e,n)},stashList(){return t.list()},stashDelete(e){return t.has(e)?(t.delete(e),!0):!1},stashClear(){t.clear()},signalPost(e,t,r,i,a){return n.post(e,t,r,i,a)},signalGet(e,t){return n.cleanExpired(),n.get(e,t).map(e=>({id:e.id,value:e.value,createdAt:Q(e.createdAt),expiresAt:Q(e.expiresAt),...e.agent?{agent:e.agent}:{}}))},signalList(e){return n.cleanExpired(),n.list(e).map(e=>({id:e.id,key:e.key,value:e.value,createdAt:Q(e.createdAt),...e.agent?{agent:e.agent}:{}}))},signalClear(e,t){return n.cleanExpired(),n.clear(e,t)},signalCleanExpired(){return n.cleanExpired()},leaseAcquire(e,t,n,i,a){r.cleanExpired();let o=r.get(e,n);return o&&o.holder!==t?!1:(r.upsert(e,t,n,i??o?.intent??void 0,a),!0)},leaseRelease(e,t,n){r.cleanExpired();let i=r.get(e,n);return!i||i.holder!==t?!1:(r.delete(e,n),!0)},leaseGet(e,t){r.cleanExpired();let n=r.get(e,t);if(n)return{resource:n.resource,holder:n.holder,workspace:n.workspace,acquiredAt:Q(n.acquiredAt),expiresAt:Q(n.expiresAt),...n.intent?{intent:n.intent}:{}}},leaseList(e){return r.cleanExpired(),r.list(e).map(e=>({resource:e.resource,holder:e.holder,acquiredAt:Q(e.acquiredAt),expiresAt:Q(e.expiresAt),...e.intent?{intent:e.intent}:{}}))},leaseCleanExpired(){return r.cleanExpired()},sessionCreate(e,t){i.create(e,t?JSON.stringify(t):void 0)},sessionTouch(e){i.touch(e)},sessionGet(e){let t=i.get(e);if(t)return{sessionId:t.sessionId,createdAt:t.createdAt,lastActivity:t.lastActivity,...t.metadata?{metadata:t.metadata}:{}}},sessionList(){return i.list().map(e=>({sessionId:e.sessionId,createdAt:e.createdAt,lastActivity:e.lastActivity}))},sessionDelete(e){return i.has(e)?(i.delete(e),!0):!1},sessionDeleteStale(e){return i.deleteStale(e)},checkpointSave(e,t,n,r){a.save(e,t,n,r)},checkpointLoad(e){let t=a.get(e);if(t)return{id:t.id,label:t.label,data:t.data,createdAt:t.createdAt,...t.notes?{notes:t.notes}:{}}},checkpointList(e,t){return a.list(e,t).map(e=>({id:e.id,label:e.label,createdAt:e.createdAt,...e.notes?{notes:e.notes}:{}}))},checkpointLatest(e){let t=a.latest(e);if(t)return{id:t.id,label:t.label,data:t.data,createdAt:t.createdAt,...t.notes?{notes:t.notes}:{}}},checkpointDelete(e){return a.has(e)?(a.delete(e),!0):!1},checkpointDiff(e,t){let n=a.get(e),r=a.get(t);if(!(!n||!r))return{from:n.data,to:r.data}},checkpointHistory(e,t){return a.list(e,t).map(e=>({id:e.id,label:e.label,createdAt:e.createdAt,...e.notes?{notes:e.notes}:{}}))},checkpointGc(e,t){return a.gc(e,t)},memoryMetaCreate(e,t){o.create(e,t)},memoryMetaGet(e){return o.get(e)},memoryMetaTouch(e){o.touch(e)},memoryMetaUpdateScore(e,t){o.updateScore(e,t)},memoryMetaUpdateConfidence(e,t){o.updateConfidence(e,t)},memoryMetaUpdateTier(e,t){o.updateTier(e,t)},memoryMetaSetSuperseded(e,t){o.setSuperseded(e,t)},memoryMetaList(e){return o.list(e)}}}async function qe(e){switch(e.backend){case`lancedb`:{let{LanceStore:t}=await import(`./lance-store-B1Gim3h9.js`);return new t({path:e.path})}case`sqlite-vec`:return new Z({path:e.path,adapter:e.adapter,embeddingDim:e.embeddingDim,embeddingProfile:e.embeddingProfile,partition:e.partition});default:{let t=e.backend;throw Error(`Unknown store backend: "${t}". Supported: lancedb, sqlite-vec`)}}}export{N as CONTROL_TABLES,ke as SqliteGraphStore,Z as SqliteVecStore,_ as allMigrations,_e as createSqlJsAdapter,j as createSqliteAdapter,Ke as createStateStore,qe as createStore,ye as getTablePartition,Oe as migrateToSplitState,be as readStatePartitionConfigFromEnv,P as resolveStatePartitionConfig,g as runMigrations};