@vpxa/aikit 0.1.248 → 0.1.250

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -355,7 +355,7 @@ interface SearchOptions {
355
355
  origin?: KnowledgeOrigin;
356
356
  /** Filter by category */
357
357
  category?: string;
358
- /** Filter by tags (any match) */
358
+ /** Filter by exact tag membership (any supplied tag may match) */
359
359
  tags?: string[];
360
360
  }
361
361
  interface IKnowledgeStore {
@@ -453,6 +453,7 @@ declare class SqliteVecStore implements IKnowledgeStore {
453
453
  embeddingProfile: EmbeddingProfile$1;
454
454
  };
455
455
  private createKnowledgeTable;
456
+ private createKnowledgeTagsTable;
456
457
  private createFtsTable;
457
458
  private createEmbeddingProfileTable;
458
459
  private getStoredEmbeddingProfile;
@@ -469,6 +470,7 @@ declare class SqliteVecStore implements IKnowledgeStore {
469
470
  */
470
471
  upsertWithoutVector(record: KnowledgeRecord, sourceRecordId: string): Promise<void>;
471
472
  private upsertKnowledgeRow;
473
+ private replaceKnowledgeTags;
472
474
  private _upsertImpl;
473
475
  search(queryVector: Float32Array, options?: SearchOptions): Promise<SearchResult[]>;
474
476
  coarseSearch(queryVector: Float32Array, options?: SearchOptions): Promise<SearchResult[]>;
@@ -1,10 +1,10 @@
1
- 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{AIKIT_PATHS as d,EMBEDDING_DEFAULTS as f,SEARCH_DEFAULTS as p,STORE_DEFAULTS as m,createLogger as h,serializeError as g,sourceTypeContentTypes as ee}from"../../core/dist/index.js";var _=e(import.meta.url);function te(e){e.exec(`
1
+ 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{AIKIT_PATHS as d,EMBEDDING_DEFAULTS as f,SEARCH_DEFAULTS as p,STORE_DEFAULTS as m,createLogger as h,serializeError as g,sourceTypeContentTypes as ee}from"../../core/dist/index.js";var te=e(import.meta.url);function ne(e){e.exec(`
2
2
  CREATE TABLE IF NOT EXISTS _migrations (
3
3
  version INTEGER PRIMARY KEY,
4
4
  name TEXT NOT NULL,
5
5
  applied_at TEXT NOT NULL DEFAULT (datetime('now'))
6
6
  )
7
- `)}function v(e,t){te(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 y=[{version:1,name:`create state store tables`,up(e){e.exec(`
7
+ `)}function _(e,t){ne(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 v=[{version:1,name:`create state store tables`,up(e){e.exec(`
8
8
  CREATE TABLE IF NOT EXISTS stash (
9
9
  key TEXT PRIMARY KEY,
10
10
  value TEXT NOT NULL,
@@ -79,17 +79,17 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
79
79
  FROM leases_legacy;
80
80
 
81
81
  DROP TABLE leases_legacy;
82
- `)}}],b=h(`sqlite-adapter`),x=e(import.meta.url);var S=class{type=`better-sqlite3`;vectorCapable=!1;db=null;stmtCache=new Map;dbPath=``;DatabaseCtor=null;recovering=!1;async open(e){let t;try{t=x(`better-sqlite3`)}catch(e){throw Error(`better-sqlite3 native binding unavailable: ${e instanceof Error?e.message:String(e)}`)}this.db=new t(e),this.dbPath=e,this.DatabaseCtor=t,this.db.pragma(`journal_mode = WAL`),this.db.pragma(`foreign_keys = ON`),this.db.pragma(`synchronous = NORMAL`),this.runIntegrityCheck(e,t)||(this.db?.pragma(`journal_mode = WAL`),this.db?.pragma(`foreign_keys = ON`),this.db?.pragma(`synchronous = NORMAL`));try{x(`sqlite-vec`).load(this.db),this.vectorCapable=!0,b.debug(`sqlite-vec extension loaded`)}catch(e){this.vectorCapable=!1,b.warn(`sqlite-vec extension failed to load; vector search disabled`,g(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(`; `);b.warn(`Database integrity check failed — recreating`,{dbPath:e,issues:n})}catch(t){b.warn(`Integrity check query failed — recreating database`,{dbPath:e,error:g(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),b.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{b.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{x(`sqlite-vec`).load(this.db),this.vectorCapable=!0}catch{this.vectorCapable=!1}b.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 ne(e){return x.resolve(`sql.js/dist/${e}`)}function re(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 C=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=>ne(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=re(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 w(){try{return x.resolve(`better-sqlite3/package.json`).replace(/[\\/]package\.json$/,``)}catch{return null}}function ie(){let e=w();if(!e)return null;let n=u(e,`build`,`Release`,`better_sqlite3.node`);return t(n)?n:null}async function ae(){let e=w();if(!e)return`package-missing`;if(!t(u(e,`build`,`Release`,`better_sqlite3.node`)))return`binding-missing`;try{let{execSync:e}=await import(`node:child_process`);return e(`"${process.execPath}" -e "require('better-sqlite3')"`,{stdio:`pipe`,timeout:15e3}),`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 oe(e=!1){let n=w();if(!n)return b.info(`better-sqlite3 package is not installed — skipping native rebuild`),!1;try{let{execSync:r}=await import(`node:child_process`),i=n.replace(/[\\/]node_modules[\\/]better-sqlite3$/,``);if(e){let e=u(n,`build`,`Release`,`better_sqlite3.node`);if(t(e))try{a(e),b.info(`Deleted stale native binding before rebuild`,{path:e})}catch(t){b.warn(`Cannot delete stale native binding — file may be locked by another process`,{path:e,error:t instanceof Error?t.message:String(t)})}}return b.info(`Attempting native module rebuild for better-sqlite3`,{cwd:i}),r(`npm rebuild better-sqlite3`,{cwd:i,stdio:`pipe`,timeout:6e4}),b.info(`Native module rebuild completed successfully`),!0}catch(e){return b.warn(`Native module rebuild failed — continuing with sql.js fallback`,g(e)),!1}}async function se(){try{let{execSync:e}=await import(`node:child_process`),t=x.resolve(`@vpxa/aikit/package.json`).replace(/[\\/]package\.json$/,``);return b.info(`Attempting to install better-sqlite3 for native adapter recovery`,{cwd:t}),e(`npm install better-sqlite3 --no-save --package-lock=false`,{cwd:t,stdio:`pipe`,timeout:12e4}),b.info(`better-sqlite3 install completed successfully`),!0}catch(e){return b.warn(`better-sqlite3 install failed — continuing with sql.js fallback`,g(e)),!1}}let T=!1;function ce(){return!!process.env.VITEST||process.argv.some(e=>e.includes(`vitest`))}async function E(e){if(!D.isVitestRuntime()){let e=await D.probeNativeModuleAbi();e===`abi-mismatch`?(b.info(`Detected NODE_MODULE_VERSION mismatch via pre-flight probe — rebuilding before load`),await D.tryRebuildNativeModule(!0)&&b.info(`Pre-flight rebuild succeeded — proceeding with native adapter`)):e===`binding-missing`?(b.info(`No native binding found — attempting rebuild before load`),await D.tryRebuildNativeModule(!1)):e===`package-missing`&&(b.info(`better-sqlite3 package is not installed — attempting install before load`),await se())}{let t=D.createNativeAdapter();try{return await t.open(e),t}catch(t){let n=t instanceof Error?t.message:String(t);if(!D.isVitestRuntime()&&/NODE_MODULE_VERSION|Could not locate the bindings file|no native build was found/.test(n)&&await D.tryRebuildNativeModule(!1)){let t=D.createNativeAdapter();try{return await t.open(e),b.info(`better-sqlite3 recovered after native module rebuild`),t}catch{}}T||(T=!0,b.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.`,g(t)))}}let t=D.createFallbackAdapter();try{return await t.open(e),t}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`[aikit] SQLite adapter "sql.js" failed to load: ${t}`)}}async function le(e){let t=new C;return await t.open(e),t}const D={BetterSqlite3Adapter:S,SqlJsAdapter:C,isVitestRuntime:ce,resolveNativeModulePackageDir:w,resolveNativeBindingPath:ie,probeNativeModuleAbi:ae,tryRebuildNativeModule:oe,createNativeAdapter:()=>new S,createFallbackAdapter:()=>new C},O=new Set([`sessions`,`stash`,`checkpoints`,`leases`,`signals`,`audit_log`,`replay_entries`,`session_metadata`]);function ue(e){let t=l(e)||`.db`,n=s(e,t);return u(c(e),`${n}-control${t}`)}function de(e){return O.has(e)?`control`:`content`}function k(e,t={}){let n=t.splitEnabled??!1;return{splitEnabled:n,contentDbPath:t.contentDbPath??e,controlDbPath:t.controlDbPath??(n?ue(e):e)}}function fe(e,t=process.env){let n=t.AIKIT_SPLIT_STATE?.trim().toLowerCase();return k(e,{splitEnabled:n===`1`||n===`true`||n===`yes`||n===`on`})}const A=`_state_partition_meta`;function j(e){return`"${e.replaceAll(`"`,`""`)}"`}function pe(e){let r=c(e);t(r)||n(r,{recursive:!0})}async function M(e){return pe(e),E(e)}function N(e,t){return e.queryAll(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`,[t]).length>0}function me(e,t){return e.queryAll(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?`,[t])[0]?.sql??void 0}function he(e,t){return e.queryAll(`PRAGMA table_info(${j(t)})`).map(e=>e.name)}function P(e,t){return e.queryAll(`SELECT COUNT(*) AS count FROM ${j(t)}`)[0]?.count??0}function F(e,t,n){if(!N(e,n))return;if(!N(t,n)){let r=me(e,n);if(!r)return;t.exec(r)}let r=he(t,n);if(r.length===0)return;let i=r.map(j).join(`, `),a=r.map(()=>`?`).join(`, `),o=e.queryAll(`SELECT ${i} FROM ${j(n)}`);if(o.length===0)return;let s=`INSERT OR REPLACE INTO ${j(n)} (${i}) VALUES (${a})`;for(let e of o)t.run(s,r.map(t=>e[t]??null))}function I(e){e.exec(`
83
- CREATE TABLE IF NOT EXISTS ${A} (
82
+ `)}}],y=h(`sqlite-adapter`),b=e(import.meta.url);var x=class{type=`better-sqlite3`;vectorCapable=!1;db=null;stmtCache=new Map;dbPath=``;DatabaseCtor=null;recovering=!1;async open(e){let t;try{t=b(`better-sqlite3`)}catch(e){throw Error(`better-sqlite3 native binding unavailable: ${e instanceof Error?e.message:String(e)}`)}this.db=new t(e),this.dbPath=e,this.DatabaseCtor=t,this.db.pragma(`journal_mode = WAL`),this.db.pragma(`foreign_keys = ON`),this.db.pragma(`synchronous = NORMAL`),this.runIntegrityCheck(e,t)||(this.db?.pragma(`journal_mode = WAL`),this.db?.pragma(`foreign_keys = ON`),this.db?.pragma(`synchronous = NORMAL`));try{b(`sqlite-vec`).load(this.db),this.vectorCapable=!0,y.debug(`sqlite-vec extension loaded`)}catch(e){this.vectorCapable=!1,y.warn(`sqlite-vec extension failed to load; vector search disabled`,g(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(`; `);y.warn(`Database integrity check failed — recreating`,{dbPath:e,issues:n})}catch(t){y.warn(`Integrity check query failed — recreating database`,{dbPath:e,error:g(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),y.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{y.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{b(`sqlite-vec`).load(this.db),this.vectorCapable=!0}catch{this.vectorCapable=!1}y.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 re(e){return b.resolve(`sql.js/dist/${e}`)}function ie(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 S=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=>re(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=ie(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 C(){try{return b.resolve(`better-sqlite3/package.json`).replace(/[\\/]package\.json$/,``)}catch{return null}}function ae(){let e=C();if(!e)return null;let n=u(e,`build`,`Release`,`better_sqlite3.node`);return t(n)?n:null}async function oe(){let e=C();if(!e)return`package-missing`;if(!t(u(e,`build`,`Release`,`better_sqlite3.node`)))return`binding-missing`;try{let{execSync:e}=await import(`node:child_process`);return e(`"${process.execPath}" -e "require('better-sqlite3')"`,{stdio:`pipe`,timeout:15e3}),`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 se(e=!1){let n=C();if(!n)return y.info(`better-sqlite3 package is not installed — skipping native rebuild`),!1;try{let{execSync:r}=await import(`node:child_process`),i=n.replace(/[\\/]node_modules[\\/]better-sqlite3$/,``);if(e){let e=u(n,`build`,`Release`,`better_sqlite3.node`);if(t(e))try{a(e),y.info(`Deleted stale native binding before rebuild`,{path:e})}catch(t){y.warn(`Cannot delete stale native binding — file may be locked by another process`,{path:e,error:t instanceof Error?t.message:String(t)})}}return y.info(`Attempting native module rebuild for better-sqlite3`,{cwd:i}),r(`npm rebuild better-sqlite3`,{cwd:i,stdio:`pipe`,timeout:6e4}),y.info(`Native module rebuild completed successfully`),!0}catch(e){return y.warn(`Native module rebuild failed — continuing with sql.js fallback`,g(e)),!1}}async function ce(){try{let{execSync:e}=await import(`node:child_process`),t=b.resolve(`@vpxa/aikit/package.json`).replace(/[\\/]package\.json$/,``);return y.info(`Attempting to install better-sqlite3 for native adapter recovery`,{cwd:t}),e(`npm install better-sqlite3 --no-save --package-lock=false`,{cwd:t,stdio:`pipe`,timeout:12e4}),y.info(`better-sqlite3 install completed successfully`),!0}catch(e){return y.warn(`better-sqlite3 install failed — continuing with sql.js fallback`,g(e)),!1}}let w=!1;function le(){return!!process.env.VITEST||process.argv.some(e=>e.includes(`vitest`))}async function T(e){if(!E.isVitestRuntime()){let e=await E.probeNativeModuleAbi();e===`abi-mismatch`?(y.info(`Detected NODE_MODULE_VERSION mismatch via pre-flight probe — rebuilding before load`),await E.tryRebuildNativeModule(!0)&&y.info(`Pre-flight rebuild succeeded — proceeding with native adapter`)):e===`binding-missing`?(y.info(`No native binding found — attempting rebuild before load`),await E.tryRebuildNativeModule(!1)):e===`package-missing`&&(y.info(`better-sqlite3 package is not installed — attempting install before load`),await ce())}{let t=E.createNativeAdapter();try{return await t.open(e),t}catch(t){let n=t instanceof Error?t.message:String(t);if(!E.isVitestRuntime()&&/NODE_MODULE_VERSION|Could not locate the bindings file|no native build was found/.test(n)&&await E.tryRebuildNativeModule(!1)){let t=E.createNativeAdapter();try{return await t.open(e),y.info(`better-sqlite3 recovered after native module rebuild`),t}catch{}}w||(w=!0,y.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.`,g(t)))}}let t=E.createFallbackAdapter();try{return await t.open(e),t}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`[aikit] SQLite adapter "sql.js" failed to load: ${t}`)}}async function ue(e){let t=new S;return await t.open(e),t}const E={BetterSqlite3Adapter:x,SqlJsAdapter:S,isVitestRuntime:le,resolveNativeModulePackageDir:C,resolveNativeBindingPath:ae,probeNativeModuleAbi:oe,tryRebuildNativeModule:se,createNativeAdapter:()=>new x,createFallbackAdapter:()=>new S},D=new Set([`sessions`,`stash`,`checkpoints`,`leases`,`signals`,`audit_log`,`replay_entries`,`session_metadata`]);function de(e){let t=l(e)||`.db`,n=s(e,t);return u(c(e),`${n}-control${t}`)}function fe(e){return D.has(e)?`control`:`content`}function O(e,t={}){let n=t.splitEnabled??!1;return{splitEnabled:n,contentDbPath:t.contentDbPath??e,controlDbPath:t.controlDbPath??(n?de(e):e)}}function pe(e,t=process.env){let n=t.AIKIT_SPLIT_STATE?.trim().toLowerCase();return O(e,{splitEnabled:n===`1`||n===`true`||n===`yes`||n===`on`})}const k=`_state_partition_meta`;function A(e){return`"${e.replaceAll(`"`,`""`)}"`}function me(e){let r=c(e);t(r)||n(r,{recursive:!0})}async function j(e){return me(e),T(e)}function M(e,t){return e.queryAll(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`,[t]).length>0}function he(e,t){return e.queryAll(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?`,[t])[0]?.sql??void 0}function ge(e,t){return e.queryAll(`PRAGMA table_info(${A(t)})`).map(e=>e.name)}function N(e,t){return e.queryAll(`SELECT COUNT(*) AS count FROM ${A(t)}`)[0]?.count??0}function P(e,t,n){if(!M(e,n))return;if(!M(t,n)){let r=he(e,n);if(!r)return;t.exec(r)}let r=ge(t,n);if(r.length===0)return;let i=r.map(A).join(`, `),a=r.map(()=>`?`).join(`, `),o=e.queryAll(`SELECT ${i} FROM ${A(n)}`);if(o.length===0)return;let s=`INSERT OR REPLACE INTO ${A(n)} (${i}) VALUES (${a})`;for(let e of o)t.run(s,r.map(t=>e[t]??null))}function F(e){e.exec(`
83
+ CREATE TABLE IF NOT EXISTS ${k} (
84
84
  key TEXT PRIMARY KEY,
85
85
  value TEXT NOT NULL,
86
86
  updated_at TEXT NOT NULL DEFAULT (datetime('now'))
87
87
  )
88
- `)}function L(e,t,n){I(e),e.run(`INSERT INTO ${A} (key, value, updated_at)
88
+ `)}function I(e,t,n){F(e),e.run(`INSERT INTO ${k} (key, value, updated_at)
89
89
  VALUES (?, ?, datetime('now'))
90
90
  ON CONFLICT(key) DO UPDATE SET
91
91
  value = excluded.value,
92
- updated_at = datetime('now')`,[`split-state`,JSON.stringify({splitEnabled:t.splitEnabled,contentDbPath:t.contentDbPath,controlDbPath:t.controlDbPath,migratedTables:n})])}async function R(e){let t=e.contentDbPath??e.controlDbPath;if(!t)throw Error(`migrateToSplitState requires at least one database path in config`);let n=k(t,e);if(!n.splitEnabled||n.controlDbPath===n.contentDbPath)return;let r=await M(n.contentDbPath),i=await M(n.controlDbPath);try{v(i,y);let e=[];for(let t of O){if(!N(r,t))continue;F(r,i,t);let n=P(r,t),a=P(i,t);if(a<n)throw Error(`Split-state migration verification failed for ${t}: source=${n} target=${a}`);e.push(t)}L(i,n,e)}finally{r.close(),i.close()}}var ge=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??d.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 E(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(`
92
+ updated_at = datetime('now')`,[`split-state`,JSON.stringify({splitEnabled:t.splitEnabled,contentDbPath:t.contentDbPath,controlDbPath:t.controlDbPath,migratedTables:n})])}async function L(e){let t=e.contentDbPath??e.controlDbPath;if(!t)throw Error(`migrateToSplitState requires at least one database path in config`);let n=O(t,e);if(!n.splitEnabled||n.controlDbPath===n.contentDbPath)return;let r=await j(n.contentDbPath),i=await j(n.controlDbPath);try{_(i,v);let e=[];for(let t of D){if(!M(r,t))continue;P(r,i,t);let n=N(r,t),a=N(i,t);if(a<n)throw Error(`Split-state migration verification failed for ${t}: source=${n} target=${a}`);e.push(t)}I(i,n,e)}finally{r.close(),i.close()}}var _e=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??d.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 T(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(`
93
93
  CREATE TABLE IF NOT EXISTS nodes (
94
94
  id TEXT PRIMARY KEY,
95
95
  type TEXT NOT NULL,
@@ -130,7 +130,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
130
130
  FOREIGN KEY (process_id) REFERENCES processes(id) ON DELETE CASCADE,
131
131
  FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
132
132
  )
133
- `),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 E(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)
133
+ `),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 T(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)
134
134
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
135
135
  ON CONFLICT(id) DO UPDATE SET
136
136
  type = excluded.type, name = excluded.name, properties = excluded.properties,
@@ -148,19 +148,19 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
148
148
  VALUES (?, ?, ?, ?, ?, ?, ?)
149
149
  ON CONFLICT(id) DO UPDATE SET
150
150
  from_id = excluded.from_id, to_id = excluded.to_id,
151
- 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=`
151
+ 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?z(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=`
152
152
  SELECT e.id AS edge_id, e.from_id, e.to_id, e.type AS edge_type, e.weight,
153
153
  e.confidence AS edge_confidence, e.properties AS edge_props,
154
154
  n.id AS node_id, n.type AS node_type, n.name AS node_name, n.properties AS node_props,
155
155
  n.source_record_id AS node_src_rec, n.source_path AS node_src_path,
156
156
  n.created_at AS node_created, n.community AS node_community
157
- 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=`
157
+ 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(B(e)),s.has(e.node_id)||(s.add(e.node_id),a.push(V(e)))}if(n===`incoming`||n===`both`){let t=`
158
158
  SELECT e.id AS edge_id, e.from_id, e.to_id, e.type AS edge_type, e.weight,
159
159
  e.confidence AS edge_confidence, e.properties AS edge_props,
160
160
  n.id AS node_id, n.type AS node_type, n.name AS node_name, n.properties AS node_props,
161
161
  n.source_record_id AS node_src_rec, n.source_path AS node_src_path,
162
162
  n.created_at AS node_created, n.community AS node_community
163
- 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=>_e(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,
163
+ 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(B(e)),s.has(e.node_id)||(s.add(e.node_id),a.push(V(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=>z(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=>ve(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,
164
164
  CASE
165
165
  WHEN n1.id IS NULL THEN e.from_id
166
166
  WHEN n2.id IS NULL THEN e.to_id
@@ -178,7 +178,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
178
178
  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
179
179
  FROM processes p
180
180
  JOIN process_steps ps ON p.id = ps.process_id
181
- 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 _e(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=h(`sqlite-vec-store`);function ve(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}const G=`knowledge_meta`,K=`embedding_profile`,q=Object.freeze({additionalFilterMultiplier:4,baseOverfetchMultiplier:4,filteredOverfetchMultiplier:8,filteredRetryMultiplier:2,maxCandidateLimit:512,maxExpansionFactor:4,minFilteredCandidateLimit:16,tagFilterMultiplier:4});function J(e){return{model:e.model,nativeDim:e.nativeDim,dimensions:e.dimensions,queryPrefix:e.queryPrefix}}function Y(e){return JSON.stringify(J(e))}var X=class{adapter=null;externalAdapter;dbPath;embeddingDim;embeddingProfile;coarseDim;vectorEnabled=!1;ftsEnabled=!1;warnedVectorDisabled=!1;_draining=!1;_priorityQueue=[];_normalQueue=[];_onCloseHooks=[];constructor(e={}){let t=e.embeddingProfile?.dimensions??e.embeddingDim??f.dimensions;if(this.embeddingDim=t,this.embeddingProfile=J(e.embeddingProfile??{model:f.model,nativeDim:f.nativeDim,dimensions:t,queryPrefix:f.queryPrefix}),this.coarseDim=Math.min(128,this.embeddingDim),e.adapter)this.adapter=e.adapter,this.externalAdapter=!0,this.dbPath=``;else{let t=k(e.path??`${m.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 E(this.dbPath)}this.configureConnectionPragmas(),this.vectorEnabled=this.adapter.vectorCapable,v(this.adapter,y),this.createKnowledgeTable(),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}=_(`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(`
181
+ 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:R(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 R(e){if(!e)return{};try{return JSON.parse(e)}catch{return{}}}function z(e){return{id:e.id,type:e.type,name:e.name,properties:R(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 ve(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:R(e.properties)}}function B(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:R(e.edge_props??`{}`)}}function V(e){return{id:e.node_id,type:e.node_type,name:e.node_name,properties:R(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 H(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 U=h(`sqlite-vec-store`);function ye(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function W(e){return!e||e.length===0?[]:[...new Set(e.filter(e=>typeof e==`string`&&e.length>0))]}const G=`knowledge_meta`,K=`embedding_profile`,q=Object.freeze({additionalFilterMultiplier:4,baseOverfetchMultiplier:4,filteredOverfetchMultiplier:8,filteredRetryMultiplier:2,maxCandidateLimit:512,maxExpansionFactor:4,minFilteredCandidateLimit:16,tagFilterMultiplier:4});function J(e){return{model:e.model,nativeDim:e.nativeDim,dimensions:e.dimensions,queryPrefix:e.queryPrefix}}function Y(e){return JSON.stringify(J(e))}var X=class{adapter=null;externalAdapter;dbPath;embeddingDim;embeddingProfile;coarseDim;vectorEnabled=!1;ftsEnabled=!1;warnedVectorDisabled=!1;_draining=!1;_priorityQueue=[];_normalQueue=[];_onCloseHooks=[];constructor(e={}){let t=e.embeddingProfile?.dimensions??e.embeddingDim??f.dimensions;if(this.embeddingDim=t,this.embeddingProfile=J(e.embeddingProfile??{model:f.model,nativeDim:f.nativeDim,dimensions:t,queryPrefix:f.queryPrefix}),this.coarseDim=Math.min(128,this.embeddingDim),e.adapter)this.adapter=e.adapter,this.externalAdapter=!0,this.dbPath=``;else{let t=O(e.path??`${m.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 T(this.dbPath)}this.configureConnectionPragmas(),this.vectorEnabled=this.adapter.vectorCapable,_(this.adapter,v),this.createKnowledgeTable(),this.createKnowledgeTagsTable(),this.createFtsTable(),this.vectorEnabled?this.ensureVecTable():this.warnedVectorDisabled||(this.warnedVectorDisabled=!0,U.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}=te(`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(`
182
182
  CREATE TABLE IF NOT EXISTS knowledge (
183
183
  id TEXT PRIMARY KEY,
184
184
  content TEXT NOT NULL,
@@ -197,20 +197,26 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
197
197
  category TEXT NOT NULL DEFAULT '',
198
198
  version INTEGER NOT NULL DEFAULT 1
199
199
  )
200
- `),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)`)}createFtsTable(){let e=this.getAdapter();try{e.exec(`
200
+ `),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(`
201
+ CREATE TABLE IF NOT EXISTS knowledge_tags (
202
+ knowledge_id TEXT NOT NULL,
203
+ tag TEXT NOT NULL,
204
+ PRIMARY KEY (knowledge_id, tag)
205
+ )
206
+ `),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(`
201
207
  CREATE VIRTUAL TABLE IF NOT EXISTS knowledge_fts USING fts5(
202
208
  id UNINDEXED,
203
209
  content,
204
210
  tokenize = 'unicode61 remove_diacritics 2'
205
211
  )
206
- `),this.ftsEnabled=!0}catch(e){this.ftsEnabled=!1,W.warn(`FTS5 unavailable — keyword search disabled`,g(e))}}createEmbeddingProfileTable(){this.getAdapter().exec(`
212
+ `),this.ftsEnabled=!0}catch(e){this.ftsEnabled=!1,U.warn(`FTS5 unavailable — keyword search disabled`,g(e))}}createEmbeddingProfileTable(){this.getAdapter().exec(`
207
213
  CREATE TABLE IF NOT EXISTS ${G} (
208
214
  key TEXT PRIMARY KEY,
209
215
  value TEXT NOT NULL
210
216
  )
211
217
  `)}getStoredEmbeddingProfile(){return this.getAdapter().queryAll(`SELECT value FROM ${G} WHERE key = ? LIMIT 1`,[K])[0]?.value??null}saveEmbeddingProfile(){this.getAdapter().run(`INSERT INTO ${G} (key, value)
212
218
  VALUES (?, ?)
213
- ON CONFLICT(key) DO UPDATE SET value = excluded.value`,[K,Y(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=Y(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(`
219
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value`,[K,Y(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=Y(this.embeddingProfile),n=this.getStoredEmbeddingProfile(),r=!1;n!==null&&n!==t&&(r=!0,U.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,U.warn(`Vec table schema mismatch — dropping for recreation`,{existingDim:n,newDim:this.embeddingDim,wasInt8:a}))}r&&this.dropVectorTables(),e.exec(`
214
220
  CREATE VIRTUAL TABLE IF NOT EXISTS vec_knowledge USING vec0(
215
221
  embedding int8[${this.embeddingDim}] distance_metric=cosine,
216
222
  +knowledge_id TEXT
@@ -220,7 +226,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
220
226
  embedding int8[${this.coarseDim}] distance_metric=cosine,
221
227
  +knowledge_id TEXT
222
228
  )
223
- `),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{this._draining=!1}}}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,
229
+ `),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{this._draining=!1}}}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 U.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,
224
230
  totalChunks, startLine, endLine, fileHash, content_hash, indexedAt, origin, tags, category, version)
225
231
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
226
232
  ON CONFLICT(id) DO UPDATE SET
@@ -238,7 +244,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
238
244
  origin = excluded.origin,
239
245
  tags = excluded.tags,
240
246
  category = excluded.category,
241
- 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(e.tags??[]),e.category??``,e.version])}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.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??p.maxResults,r=t?.minScore??p.minScore,i;try{i=this.runAdaptiveVectorSearch(`vec_knowledge`,U(e),t)}catch(e){return W.warn(`vector search failed`,g(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??p.maxResults,r=t?.minScore??p.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`,g(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??p.maxResults,i=this.buildFilterSqlSuffix(t,!0),a=`
247
+ 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(W(e.tags)),e.category??``,e.version])}replaceKnowledgeTags(e,t){let n=this.getAdapter(),r=W(t);if(n.run(`DELETE FROM knowledge_tags WHERE knowledge_id = ?`,[e]),r.length!==0)for(let t of r)n.run(`INSERT INTO knowledge_tags (knowledge_id, tag) VALUES (?, ?)`,[e,t])}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(?), ?)`,[H(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(?), ?)`,[H(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,U.warn(`search() called but vector backend is disabled — returning []`)),[];let n=t?.limit??p.maxResults,r=t?.minScore??p.minScore,i;try{i=this.runAdaptiveVectorSearch(`vec_knowledge`,H(e),t)}catch(e){return U.warn(`vector search failed`,g(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??p.maxResults,r=t?.minScore??p.minScore,i=e.subarray(0,this.coarseDim),a;try{a=this.runAdaptiveVectorSearch(`vec_knowledge_coarse`,H(i),t)}catch(n){return U.warn(`coarse vector search failed, falling back to full search`,g(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??p.maxResults,i=this.buildFilterSqlSuffix(t,!0),a=`
242
248
  SELECT k.*, bm25(knowledge_fts) AS _bm25
243
249
  FROM knowledge_fts
244
250
  JOIN knowledge k ON k.id = knowledge_fts.id
@@ -246,7 +252,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
246
252
  ${i.sql}
247
253
  ORDER BY _bm25 ASC
248
254
  LIMIT ?
249
- `,o;try{let t=ye(e);o=n.queryAll(a,[t,...i.params,r])}catch(e){return W.warn(`fts search failed`,g(e)),[]}return o.map(e=>({record:this.fromRow(e),score:be(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])),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])),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 ${G}`),e.exec(`DROP TABLE IF EXISTS knowledge`),e.flush(),this.createKnowledgeTable(),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(){for(let e of this._onCloseHooks)try{e()}catch{}for(this._onCloseHooks.length=0;this._priorityQueue.length>0||this._normalQueue.length>0||this._draining;)await new Promise(e=>setTimeout(e,5));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??p.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*q.filteredRetryMultiplier)),s=this.queryVectorRows(e,t,i,o,r);return s}queryVectorRows(e,t,n,r,i){let a=this.getAdapter(),o=`
255
+ `,o;try{let t=be(e);o=n.queryAll(a,[t,...i.params,r])}catch(e){return U.warn(`fts search failed`,g(e)),[]}return o.map(e=>({record:this.fromRow(e),score:xe(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 ${G}`),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(){for(let e of this._onCloseHooks)try{e()}catch{}for(this._onCloseHooks.length=0;this._priorityQueue.length>0||this._normalQueue.length>0||this._draining;)await new Promise(e=>setTimeout(e,5));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??p.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*q.filteredRetryMultiplier)),s=this.queryVectorRows(e,t,i,o,r);return s}queryVectorRows(e,t,n,r,i){let a=this.getAdapter(),o=`
250
256
  SELECT k.*, v.distance AS _distance
251
257
  FROM (
252
258
  SELECT knowledge_id, distance
@@ -259,11 +265,11 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
259
265
  ${n.sql}
260
266
  ORDER BY v.distance ASC
261
267
  LIMIT ?
262
- `;return a.queryAll(o,[t,r,...n.params,i])}buildVectorSearchPlan(e,t){let n=Math.max(1,e*q.baseOverfetchMultiplier);if(!t.hasFilters)return{hasFilters:!1,initialCandidateLimit:n,maxCandidateLimit:n};let r=Math.max(0,t.filterCount-1),i=q.filteredOverfetchMultiplier+r*q.additionalFilterMultiplier+(t.tagCount>0?q.tagFilterMultiplier:0),a=Math.min(q.maxCandidateLimit,Math.max(e*i,q.minFilteredCandidateLimit));return{hasFilters:!0,initialCandidateLimit:a,maxCandidateLimit:Math.min(q.maxCandidateLimit,Math.max(a*q.maxExpansionFactor,e*q.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=ee(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(()=>`k.tags LIKE ?`);n.push(`(${t.join(` OR `)})`),r.push(...e.tags.map(e=>`%${e}%`)),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:ve(e.tags),category:e.category||void 0,version:e.version}}};function ye(e){let t=e.replace(/["'()*:^-]/g,` `).trim();return t?t.split(/\s+/).filter(e=>e.length>0).map(e=>`"${e}"`).join(` OR `):`""`}function be(e){return e==null||Number.isNaN(e)?0:1-Math.exp(-Math.abs(e)/5)}function Z(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`,n=new Date(t);return Number.isNaN(n.getTime())?t:n.toISOString()}function Q(e){return`queryAll`in e&&`run`in e}function xe(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)
268
+ `;return a.queryAll(o,[t,r,...n.params,i])}buildVectorSearchPlan(e,t){let n=Math.max(1,e*q.baseOverfetchMultiplier);if(!t.hasFilters)return{hasFilters:!1,initialCandidateLimit:n,maxCandidateLimit:n};let r=Math.max(0,t.filterCount-1),i=q.filteredOverfetchMultiplier+r*q.additionalFilterMultiplier+(t.tagCount>0?q.tagFilterMultiplier:0),a=Math.min(q.maxCandidateLimit,Math.max(e*i,q.minFilteredCandidateLimit));return{hasFilters:!0,initialCandidateLimit:a,maxCandidateLimit:Math.min(q.maxCandidateLimit,Math.max(a*q.maxExpansionFactor,e*q.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=ee(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:ye(e.tags),category:e.category||void 0,version:e.version}}};function be(e){let t=e.replace(/["'()*:^-]/g,` `).trim();return t?t.split(/\s+/).filter(e=>e.length>0).map(e=>`"${e}"`).join(` OR `):`""`}function xe(e){return e==null||Number.isNaN(e)?0:1-Math.exp(-Math.abs(e)/5)}function Z(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`,n=new Date(t);return Number.isNaN(n.getTime())?t:n.toISOString()}function Q(e){return`queryAll`in e&&`run`in e}function Se(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)
263
269
  VALUES (?, ?)
264
270
  ON CONFLICT(key) DO UPDATE SET
265
271
  value = excluded.value,
266
- 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 Se(e){return{save(t,n,r,i){e.run(`INSERT INTO checkpoints (id, label, data, notes)
272
+ 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 Ce(e){return{save(t,n,r,i){e.run(`INSERT INTO checkpoints (id, label, data, notes)
267
273
  VALUES (?, ?, ?, ?)
268
274
  ON CONFLICT(id) DO UPDATE SET
269
275
  label = excluded.label,
@@ -290,7 +296,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
290
296
  ORDER BY created_at DESC, id DESC
291
297
  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
292
298
  FROM checkpoints
293
- 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 Ce(e){return{create(t,n){e.run(`INSERT INTO sessions (session_id, metadata)
299
+ 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 we(e){return{create(t,n){e.run(`INSERT INTO sessions (session_id, metadata)
294
300
  VALUES (?, ?)
295
301
  ON CONFLICT(session_id) DO UPDATE SET
296
302
  last_activity = datetime('now'),
@@ -306,7 +312,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
306
312
  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
307
313
  FROM sessions
308
314
  WHERE last_activity < datetime('now', ?)`,[n])[0]?.count??0;return r>0&&e.run(`DELETE FROM sessions
309
- WHERE last_activity < datetime('now', ?)`,[n]),r}}}function we(e){return{post(t,n,r,i,a=300){return e.run(`INSERT INTO signals (workspace, key, value, agent, ttl_seconds, expires_at)
315
+ WHERE last_activity < datetime('now', ?)`,[n]),r}}}function Te(e){return{post(t,n,r,i,a=300){return e.run(`INSERT INTO signals (workspace, key, value, agent, ttl_seconds, expires_at)
310
316
  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,
311
317
  workspace,
312
318
  key,
@@ -328,7 +334,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
328
334
  WHERE workspace = ?
329
335
  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
330
336
  FROM signals
331
- WHERE expires_at <= datetime('now')`)[0]?.count??0;return t>0&&e.run(`DELETE FROM signals WHERE expires_at <= datetime('now')`),t}}}function Te(e){return{upsert(t,n,r,i,a=10){e.run(`INSERT INTO leases (resource, holder, intent, workspace, ttl_minutes, expires_at)
337
+ WHERE expires_at <= datetime('now')`)[0]?.count??0;return t>0&&e.run(`DELETE FROM signals WHERE expires_at <= datetime('now')`),t}}}function Ee(e){return{upsert(t,n,r,i,a=10){e.run(`INSERT INTO leases (resource, holder, intent, workspace, ttl_minutes, expires_at)
332
338
  VALUES (?, ?, ?, ?, ?, datetime('now', '+' || ? || ' minutes'))
333
339
  ON CONFLICT(workspace, resource) DO UPDATE SET
334
340
  holder = excluded.holder,
@@ -353,7 +359,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
353
359
  WHERE workspace = ?
354
360
  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
355
361
  FROM leases
356
- WHERE expires_at <= datetime('now')`)[0]?.count??0;return t>0&&e.run(`DELETE FROM leases WHERE expires_at <= datetime('now')`),t}}}function Ee(e){return{create(t,n){e.run(`INSERT INTO memory_meta (entry_id, tier)
362
+ WHERE expires_at <= datetime('now')`)[0]?.count??0;return t>0&&e.run(`DELETE FROM leases WHERE expires_at <= datetime('now')`),t}}}function De(e){return{create(t,n){e.run(`INSERT INTO memory_meta (entry_id, tier)
357
363
  VALUES (?, ?)
358
364
  ON CONFLICT(entry_id) DO NOTHING`,[t,n??`working`])},get(t){return e.queryAll(`SELECT entry_id AS entryId,
359
365
  tier,
@@ -389,11 +395,11 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
389
395
  ORDER BY retention_score ASC,
390
396
  COALESCE(last_accessed_at, created_at) ASC,
391
397
  entry_id ASC
392
- ${a}`,r)}}}function De(e){let t=e.prepare(`SELECT key, value, updated_at AS updatedAt FROM stash WHERE key = ?`),n=e.prepare(`INSERT INTO stash (key, value)
398
+ ${a}`,r)}}}function $(e){let t=e.prepare(`SELECT key, value, updated_at AS updatedAt FROM stash WHERE key = ?`),n=e.prepare(`INSERT INTO stash (key, value)
393
399
  VALUES (?, ?)
394
400
  ON CONFLICT(key) DO UPDATE SET
395
401
  value = excluded.value,
396
- 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 $(e){let t=e.prepare(`INSERT INTO checkpoints (id, label, data, notes)
402
+ 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 Oe(e){let t=e.prepare(`INSERT INTO checkpoints (id, label, data, notes)
397
403
  VALUES (?, ?, ?, ?)
398
404
  ON CONFLICT(id) DO UPDATE SET
399
405
  label = excluded.label,
@@ -420,7 +426,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
420
426
  ORDER BY created_at DESC, id DESC
421
427
  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
422
428
  FROM checkpoints
423
- 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 Oe(e){let t=e.prepare(`INSERT INTO sessions (session_id, metadata)
429
+ 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 ke(e){let t=e.prepare(`INSERT INTO sessions (session_id, metadata)
424
430
  VALUES (?, ?)
425
431
  ON CONFLICT(session_id) DO UPDATE SET
426
432
  last_activity = datetime('now'),
@@ -436,7 +442,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
436
442
  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
437
443
  FROM sessions
438
444
  WHERE last_activity < datetime('now', ?)`),c=e.prepare(`DELETE FROM sessions
439
- 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 ke(e){let t=e.prepare(`INSERT INTO signals (workspace, key, value, agent, ttl_seconds, expires_at)
445
+ 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 Ae(e){let t=e.prepare(`INSERT INTO signals (workspace, key, value, agent, ttl_seconds, expires_at)
440
446
  VALUES (?, ?, ?, ?, ?, datetime('now', '+' || ? || ' seconds'))`),n=e.prepare(`SELECT id,
441
447
  workspace,
442
448
  key,
@@ -458,7 +464,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
458
464
  WHERE workspace = ?
459
465
  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
460
466
  FROM signals
461
- 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 Ae(e){let t=e.prepare(`INSERT INTO leases (resource, holder, intent, workspace, ttl_minutes, expires_at)
467
+ 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 je(e){let t=e.prepare(`INSERT INTO leases (resource, holder, intent, workspace, ttl_minutes, expires_at)
462
468
  VALUES (?, ?, ?, ?, ?, datetime('now', '+' || ? || ' minutes'))
463
469
  ON CONFLICT(workspace, resource) DO UPDATE SET
464
470
  holder = excluded.holder,
@@ -483,7 +489,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
483
489
  WHERE workspace = ?
484
490
  ORDER BY acquired_at ASC, resource ASC`),i=e.prepare(`DELETE FROM leases WHERE resource = ? AND workspace = ?`),a=e.prepare(`SELECT COUNT(*) AS count
485
491
  FROM leases
486
- 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 je(e){let t=e.prepare(`INSERT INTO memory_meta (entry_id, tier)
492
+ 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 Me(e){let t=e.prepare(`INSERT INTO memory_meta (entry_id, tier)
487
493
  VALUES (?, ?)
488
494
  ON CONFLICT(entry_id) DO NOTHING`),n=e.prepare(`SELECT entry_id AS entryId,
489
495
  tier,
@@ -613,4 +619,4 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
613
619
  ORDER BY retention_score ASC,
614
620
  COALESCE(last_accessed_at, created_at) ASC,
615
621
  entry_id ASC
616
- 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?h.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 Me(e){let t=Q(e)?xe(e):De(e),n=Q(e)?we(e):ke(e),r=Q(e)?Te(e):Ae(e),i=Q(e)?Ce(e):Oe(e),a=Q(e)?Se(e):$(e),o=Q(e)?Ee(e):je(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:Z(e.createdAt),expiresAt:Z(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:Z(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:Z(n.acquiredAt),expiresAt:Z(n.expiresAt),...n.intent?{intent:n.intent}:{}}},leaseList(e){return r.cleanExpired(),r.list(e).map(e=>({resource:e.resource,holder:e.holder,acquiredAt:Z(e.acquiredAt),expiresAt:Z(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 Ne(e){switch(e.backend){case`lancedb`:{let{LanceStore:t}=await import(`./lance-store-BRKcJXVO.js`);return new t({path:e.path})}case`sqlite-vec`:return new X({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{O as CONTROL_TABLES,ge as SqliteGraphStore,X as SqliteVecStore,y as allMigrations,le as createSqlJsAdapter,E as createSqliteAdapter,Me as createStateStore,Ne as createStore,de as getTablePartition,R as migrateToSplitState,fe as readStatePartitionConfigFromEnv,k as resolveStatePartitionConfig,v as runMigrations};
622
+ 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?h.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 Ne(e){let t=Q(e)?Se(e):$(e),n=Q(e)?Te(e):Ae(e),r=Q(e)?Ee(e):je(e),i=Q(e)?we(e):ke(e),a=Q(e)?Ce(e):Oe(e),o=Q(e)?De(e):Me(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:Z(e.createdAt),expiresAt:Z(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:Z(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:Z(n.acquiredAt),expiresAt:Z(n.expiresAt),...n.intent?{intent:n.intent}:{}}},leaseList(e){return r.cleanExpired(),r.list(e).map(e=>({resource:e.resource,holder:e.holder,acquiredAt:Z(e.acquiredAt),expiresAt:Z(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 Pe(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 X({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{D as CONTROL_TABLES,_e as SqliteGraphStore,X as SqliteVecStore,v as allMigrations,ue as createSqlJsAdapter,T as createSqliteAdapter,Ne as createStateStore,Pe as createStore,fe as getTablePartition,L as migrateToSplitState,pe as readStatePartitionConfigFromEnv,O as resolveStatePartitionConfig,_ as runMigrations};
@@ -0,0 +1 @@
1
+ import{EMBEDDING_DEFAULTS as e,SEARCH_DEFAULTS as t,STORE_DEFAULTS as n,createLogger as r,serializeError as i,sourceTypeContentTypes as a}from"../../core/dist/index.js";import{Index as o,connect as s,makeArrowTable as c}from"@lancedb/lancedb";function l(e){if(!e)return[];if(Array.isArray(e))return e.filter(e=>typeof e==`string`);try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}catch{return[]}}function u(e){return c([{...e,tags:Array.isArray(e.tags)&&e.tags.length===0?[`__schema_seed__`]:e.tags}]).schema}const d=/^[\w.\-/ ]+$/,f=r(`store`);function p(e,t){if(!d.test(e))throw Error(`Invalid ${t} filter value: contains disallowed characters`);return e.replace(/'/g,`''`)}var m=class r{db=null;table=null;dbPath;tableName;_draining=!1;_priorityQueue=[];_normalQueue=[];_ftsReady=!1;_ftsRecoveryAttemptAt=0;static FTS_RECOVERY_COOLDOWN_MS=300*1e3;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{this._draining=!1}}}constructor(e){this.dbPath=e?.path??n.path,this.tableName=e?.tableName??n.tableName}async initialize(){this.db=await s(this.dbPath),(await this.db.tableNames()).includes(this.tableName)&&(this.table=await this.db.openTable(this.tableName),await this.createFtsIndex())}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 _upsertImpl(e,t){let n=e.map((e,n)=>({id:e.id,vector:Array.from(t[n]),content:e.content,sourcePath:e.sourcePath,contentType:e.contentType,headingPath:e.headingPath??``,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,startLine:e.startLine,endLine:e.endLine,fileHash:e.fileHash,indexedAt:e.indexedAt,origin:e.origin,tags:e.tags,category:e.category??``,version:e.version})),r=c(n,{schema:this.table?await this.table.schema():u(n[0])});if(this.table){let t=[...new Set(e.map(e=>e.sourcePath))];for(let e of t)try{await this.table.delete(`sourcePath = '${p(e,`sourcePath`)}'`)}catch{}await this.table.add(r)}else try{this.table=await this.db?.createTable(this.tableName,r)??null}catch(e){if(String(e).includes(`already exists`)&&this.db)this.table=await this.db.openTable(this.tableName),await this.table.add(r);else throw e}}async search(e,n){if(e.length===0||!this.table)return[];let r=n?.limit??t.maxResults,i=n?.minScore??t.minScore,a=this.table.search(e).limit(r*2),o=this.buildFilterString(n);return o&&(a=a.where(o)),(await a.toArray()).map(e=>({record:this.fromLanceRecord(e),score:1-(e._distance??1)})).filter(e=>e.score>=i).slice(0,r)}async createFtsIndex(){return this.enqueueWrite(()=>this._createFtsIndexImpl())}async _createFtsIndexImpl(){if(this.table)try{await this.table.createIndex(`content`,{config:o.fts({withPosition:!0}),replace:!0}),this._ftsReady=!0,this._ftsRecoveryAttemptAt=0,f.info(`FTS index created/updated`,{column:`content`})}catch(e){f.warn(`FTS index creation failed`,i(e))}}async ftsSearch(e,n){if(!this.table)return[];if(!this._ftsReady){let e=Date.now();if(e-this._ftsRecoveryAttemptAt<r.FTS_RECOVERY_COOLDOWN_MS)return[];this._ftsRecoveryAttemptAt=e;try{await this.createFtsIndex()}catch{return[]}if(!this._ftsReady)return[]}let a=n?.limit??t.maxResults;try{let t=this.table.search(e).limit(a*2),r=this.buildFilterString(n);return r&&(t=t.where(r)),(await t.toArray()).map(e=>({record:this.fromLanceRecord(e),score:e._score??e._relevance_score??0}))}catch(e){return(e instanceof Error?e.message:String(e)).includes(`INVERTED index`)?(f.debug(`FTS search skipped — index not yet available`),this._ftsReady=!1):f.warn(`FTS search failed`,i(e)),[]}}async getById(e){if(!this.table)return null;let t=await this.table.query().where(`id = '${p(e,`id`)}'`).limit(1).toArray();return t.length===0?null:this.fromLanceRecord(t[0])}async deleteBySourcePath(e){return this.enqueueWrite(()=>this._deleteBySourcePathImpl(e))}async _deleteBySourcePathImpl(e){if(!this.table)return 0;let t=await this.getBySourcePath(e);return t.length===0?0:(await this.table.delete(`sourcePath = '${p(e,`sourcePath`)}'`),t.length)}async deleteById(e){return this.enqueueWrite(()=>this._deleteByIdImpl(e))}async deleteByIdInteractive(e){return this.enqueueWrite(()=>this._deleteByIdImpl(e),!0)}async _deleteByIdImpl(e){return!this.table||!await this.getById(e)?!1:(await this.table.delete(`id = '${p(e,`id`)}'`),!0)}async getBySourcePath(e){return this.table?(await this.table.query().where(`sourcePath = '${p(e,`sourcePath`)}'`).limit(1e3).toArray()).map(e=>this.fromLanceRecord(e)):[]}async getStats(){if(!this.table)return{totalRecords:0,totalFiles:0,contentTypeBreakdown:{},lastIndexedAt:null,storeBackend:`lancedb`,embeddingModel:e.model};let t=await this.table.countRows(),n=await this.table.query().select([`sourcePath`,`contentType`,`indexedAt`]).limit(1e5).toArray(),r={},i=new Set,a=null;for(let e of n){let t=e;r[t.contentType]=(r[t.contentType]??0)+1,i.add(t.sourcePath),(!a||t.indexedAt>a)&&(a=t.indexedAt)}return{totalRecords:t,totalFiles:i.size,contentTypeBreakdown:r,lastIndexedAt:a,storeBackend:`lancedb`,embeddingModel:e.model}}async listSourcePaths(){if(!this.table)return[];let e=await this.table.query().select([`sourcePath`]).limit(1e5).toArray();return[...new Set(e.map(e=>e.sourcePath))]}async dropTable(){return this.enqueueWrite(()=>this._dropTableImpl())}async _dropTableImpl(){if(this.db&&(await this.db.tableNames()).includes(this.tableName))for(let e=1;e<=3;e++)try{await this.db.dropTable(this.tableName);break}catch(t){if(e===3)throw t;let n=e*500;f.warn(`dropTable attempt failed, retrying`,{attempt:e,delayMs:n}),await new Promise(e=>setTimeout(e,n))}this.table=null}async close(){try{this.db&&typeof this.db.close==`function`&&await this.db.close()}catch{}this.table=null,this.db=null}buildFilterString(e){let t=[];if(e?.contentType&&t.push(`contentType = '${p(e.contentType,`contentType`)}'`),e?.sourceType){let n=a(e.sourceType);if(n.length>0){let e=n.map(e=>`'${p(e,`sourceType`)}'`).join(`, `);t.push(`contentType IN (${e})`)}}if(e?.origin&&t.push(`origin = '${p(e.origin,`origin`)}'`),e?.category&&t.push(`category = '${p(e.category,`category`)}'`),e?.tags&&e.tags.length>0){let n=e.tags.map(e=>`'${p(e,`tag`)}'`).join(`, `);t.push(`array_has_any(tags, [${n}])`)}return t.length>0?t.join(` AND `):null}fromLanceRecord(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,indexedAt:e.indexedAt,origin:e.origin,tags:l(e.tags),category:e.category||void 0,version:e.version}}};export{m as LanceStore};
@@ -1678,6 +1678,7 @@ declare function markPromoteRun(): void;
1678
1678
  interface MeasureOptions {
1679
1679
  path: string;
1680
1680
  extensions?: string[];
1681
+ includeHidden?: boolean;
1681
1682
  }
1682
1683
  interface FileMetrics {
1683
1684
  path: string;
@@ -70,8 +70,8 @@ import{mkdir as e,readFile as t,readdir as n,rm as r,stat as i,writeFile as a}fr
70
70
  `)});continue}if(!s||!o)continue;let c=P(t,`utf-8`),l=P(n,`utf-8`);c===l?a.push({file:e,status:`unchanged`}):a.push({file:e,status:`modified`,diff:bo(c,l)})}return{name:e,entries:a,modified:a.filter(e=>e.status===`modified`).length,added:a.filter(e=>e.status===`added`).length,deleted:a.filter(e=>e.status===`deleted`).length}}function _o(e,t){let n=fo(e,t),r=uo(e,t),i=n.rootPath,a=[],o=new Set(n.sourceFiles);for(let e of yo(r))o.add(e);for(let e of o){let t=u(r,e);if(!M(t))continue;let n=f(i,e);N(u(n,`..`),{recursive:!0}),re(t,n),a.push(e)}return ie(r,{recursive:!0,force:!0}),{name:e,filesMerged:a.length,files:a}}function vo(e,t){let n=uo(e,t);return M(n)?(ie(n,{recursive:!0,force:!0}),!0):!1}function yo(e){let t=[];function n(r){for(let i of F(r)){if(i===co)continue;let a=u(r,i);L(a).isDirectory()?n(a):t.push(d(e,a).replace(/\\/g,`/`))}}return M(e)&&n(e),t.sort()}function bo(e,t){let n=e.split(`
71
71
  `),r=t.split(`
72
72
  `),i=[],a=Math.max(n.length,r.length);for(let e=0;e<a;e++){let t=n[e],a=r[e];t===a?i.push(` ${t??``}`):(t!==void 0&&i.push(`-${t}`),a!==void 0&&i.push(`+${a}`))}return i.join(`
73
- `)}function xo(e){return[...new Set(e)]}function So(e){return e.status===`active`}function Co(e){return u(B(e??process.cwd()),`leases.json`)}function wo(e,t){let n=Co(t);N(s(n),{recursive:!0});let r=`${n}.tmp`;R(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),I(r,n)}function To(e){let t=Date.now(),n=!1;for(let r of e.leases)r.status===`active`&&new Date(r.expiresAt).getTime()<t&&(r.status=`expired`,n=!0);return n}function Eo(e){let t=Co(e);if(!M(t))return{leases:[],hotspots:{}};try{let n=P(t,`utf-8`),r=JSON.parse(n),i={leases:r.leases??[],hotspots:r.hotspots??{}};return To(i)&&wo(i,e),i}catch(e){return e?.code===`ENOENT`||console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),{leases:[],hotspots:{}}}}function Do(e,t){let n=new Set(e.files),r=e.symbols?new Set(e.symbols):null,i=[];for(let a of t){if(!So(a)||a.agent===e.agent)continue;let t=xo(a.files.filter(e=>n.has(e)));if(t.length!==0){if(r&&a.symbols&&a.symbols.length>0){let e=xo(a.symbols.filter(e=>r.has(e)));if(e.length===0)continue;i.push({leaseId:a.id,agent:a.agent,overlappingFiles:t,overlappingSymbols:e,intent:a.intent});continue}i.push({leaseId:a.id,agent:a.agent,overlappingFiles:t,intent:a.intent})}}return i}function Oo(e,t,n){let r=new Date().toISOString();for(let i of xo(t)){let t=e.hotspots[i]??{path:i,leaseCount:0,conflictCount:0,lastContested:r};t.leaseCount+=1,n>0&&(t.conflictCount+=n,t.lastContested=r),e.hotspots[i]=t}}function ko(e){let t=Eo(e.cwd),n={id:xe(),agent:e.agent,files:xo(e.files),symbols:e.symbols?xo(e.symbols):void 0,intent:e.intent,status:`active`,acquiredAt:new Date().toISOString(),expiresAt:new Date(Date.now()+(e.ttl_minutes??10)*60*1e3).toISOString()},r=Do(n,t.leases.filter(So)),i=new Set;for(let e of r)for(let t of e.overlappingFiles)i.add(t);for(let e of n.files)Oo(t,[e],+!!i.has(e));return t.leases.push(n),wo(t,e.cwd),{lease:n,conflicts:r}}function Ao(e){let t=Eo(e.cwd),n=t.leases.find(t=>t.id===e.id);return n?(n.status=`released`,n.releasedAt=new Date().toISOString(),wo(t,e.cwd),{released:!0,lease:n}):{released:!1}}function jo(e){let t=Eo(e?.cwd);return{leases:t.leases.filter(t=>So(t)&&(!e?.agent||t.agent===e.agent)),hotspots:t.hotspots}}const K=_e(`maintenance`),Mo=`last-prune.txt`,No=`last-promote-run`,Po=new Set([`queues`,`worksets`,`stash`]);function Fo(e){if(!M(e))return[];try{return F(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch(t){return K.warn(`Failed to list directories`,{dirPath:e,error:String(t)}),[]}}function Io(e,t){t||ie(e,{recursive:!0,force:!0})}function Lo(e){return/^aikit-forge-ground-[a-z0-9]{6}-[a-f0-9]{8}$/.test(e)}function Ro(e,t){let n=Date.parse(e);return Number.isNaN(n)?!1:Date.now()-n>t*24*60*60*1e3}function zo(e){let t=0;try{let n=F(e,{withFileTypes:!0});for(let r of n){let n=u(e,r.name);r.isDirectory()?t+=zo(n):t+=L(n).size}}catch{}return t}function Bo(e){if(e<1024)return`${e} B`;let t=[`KB`,`MB`,`GB`,`TB`],n=e,r=-1;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n.toFixed(1)} ${t[r]}`}function Vo(e,t=!1){let n=0,r=0;for(let i of Fo(e)){if(!Lo(i))continue;let a=u(e,i);try{let e=zo(a);Io(a,t),n+=1,r+=e,K.info(t?`Would remove forge-ground orphan`:`Removed forge-ground orphan`,{dirPath:a,size:e})}catch(e){K.warn(`Failed to remove forge-ground orphan`,{dirPath:a,error:String(e)})}}return{count:n,bytesFreed:r}}function Ho(e,t=!1){let n=0,r=0;for(let i of Fo(e)){if(Lo(i))continue;let a=u(e,i,`knowledge.lance`);if(M(a))try{let e=zo(a);Io(a,t),n+=1,r+=e,K.info(t?`Would remove legacy LanceDB directory`:`Removed legacy LanceDB directory`,{lanceDir:a,size:e})}catch(e){K.warn(`Failed to remove legacy LanceDB directory`,{lanceDir:a,error:String(e)})}}return{count:n,bytesFreed:r}}function Uo(e,t=!1){let n=0;for(let r of Fo(e)){if(Lo(r))continue;let i=u(e,r,`state`);if(M(i))for(let e of Fo(i)){if(!Po.has(e))continue;let r=u(i,e);try{if(F(r).length>0)continue;Io(r,t),n+=1,K.info(t?`Would remove empty ephemeral directory`:`Removed empty ephemeral directory`,{ephemeralDir:r})}catch(e){K.warn(`Failed to remove empty ephemeral directory`,{ephemeralDir:r,error:String(e)})}}}return{count:n}}function Wo(e,t=90,n=!1){let r=0,i=0,a=!1,o=ye(),s=ge(process.cwd());for(let[c,l]of Object.entries(o.workspaces)){if(l.partition===s||c===s||!Ro(l.lastAccessedAt,t))continue;let d=u(e,l.partition);try{let e=M(d)?zo(d):0;!n&&M(d)&&ie(d,{recursive:!0,force:!0}),n||(delete o.workspaces[c],a=!0),r+=1,i+=e,K.info(n?`Would remove stale partition`:`Removed stale partition`,{partition:l.partition,workspacePath:l.workspacePath,size:e})}catch(e){K.warn(`Failed to remove stale partition`,{partition:l.partition,workspacePath:l.workspacePath,error:String(e)})}}if(a)try{be(o)}catch(e){K.warn(`Failed to save registry after stale partition cleanup`,{error:String(e)})}return{count:r,bytesFreed:i}}function Go(e=5,t=!1){let n=0,r=0,i=f(ue(),`.aikit`,`profiles`);if(!M(i))return{count:n,bytesFreed:r};let a=Fo(i).map(e=>{let t=u(i,e),n=0;try{n=L(t).mtimeMs}catch(e){K.warn(`Failed to stat browser profile directory`,{dirPath:t,error:String(e)})}return{dirPath:t,mtimeMs:n}}).sort((e,t)=>t.mtimeMs-e.mtimeMs),o=Math.max(e,0);for(let e of a.slice(o))try{let i=zo(e.dirPath);Io(e.dirPath,t),n+=1,r+=i,K.info(t?`Would remove browser profile`:`Removed browser profile`,{dirPath:e.dirPath,size:i})}catch(t){K.warn(`Failed to remove browser profile`,{dirPath:e.dirPath,error:String(t)})}return{count:n,bytesFreed:r}}function Ko(e={}){let t=e.dryRun??!1,n=e.maxAgeDays??90,r=e.maxBrowserProfiles??5,i=ve();K.info(`Starting storage prune`,{dryRun:t,maxAgeDays:n,maxBrowserProfiles:r,globalDir:i}),K.info(`Pruning forge-ground orphan directories`);let a=Vo(i,t);K.info(`Pruning legacy LanceDB directories`);let o=Ho(i,t);K.info(`Pruning empty ephemeral directories`);let s=Uo(i,t);K.info(`Pruning stale partitions`);let c=Wo(i,n,t);K.info(`Pruning browser profiles`);let l=Go(r,t);return{forgeGroundOrphans:a,legacyLance:o,emptyEphemeral:s,stalePartitions:c,browserProfiles:l,totalBytesFreed:a.bytesFreed+o.bytesFreed+c.bytesFreed+l.bytesFreed,dryRun:t}}function qo(){let e=f(ve(),Mo);if(!M(e))return!0;try{let t=Number.parseInt(P(e,`utf-8`).trim(),10);return Date.now()-t>1440*60*1e3}catch{return!0}}function Jo(){let e=ve(),t=f(e,Mo);N(e,{recursive:!0}),R(t,String(Date.now()),`utf-8`)}function Yo(){let e=f(ve(),No);if(!M(e))return!0;try{let t=Number.parseInt(P(e,`utf-8`).trim(),10);return Date.now()-t>10080*60*1e3}catch{return!0}}function Xo(){let e=ve(),t=f(e,No);N(e,{recursive:!0}),R(t,String(Date.now()),`utf-8`)}const Zo=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`cdk.out`,`.cache`]),Qo=[/\bif\s*\(/g,/\belse\s+if\b/g,/\bfor\s*\(/g,/\bwhile\s*\(/g,/\bcase\s+/g,/\bcatch\s*\(/g,/&&/g,/\|\|/g,/\?\?/g];async function $o(e){let{path:t,extensions:n=[`.ts`,`.tsx`,`.js`,`.jsx`]}=e,r=is(t,n),i=[];for(let e of r){let t=P(e,`utf8`),n=es(d(process.cwd(),e),t),r=await rs(t,c(e));r!==void 0&&(n.cognitiveComplexity=r),i.push(n)}i.sort((e,t)=>t.complexity-e.complexity);let a=i.reduce((e,t)=>e+t.lines.total,0),o=i.reduce((e,t)=>e+t.lines.code,0),s=i.reduce((e,t)=>e+t.complexity,0),l=i.reduce((e,t)=>e+t.functions,0),u=i[0]??{path:``,complexity:0};return{files:i,summary:{totalFiles:i.length,totalLines:a,totalCodeLines:o,avgComplexity:i.length>0?Math.round(s/i.length*10)/10:0,maxComplexity:{file:u.path,value:u.complexity},totalFunctions:l}}}function es(e,t){let n=t.split(`
74
- `),r=0,i=0,a=!1;for(let e of n){let t=e.trim();if(t===``){r++;continue}if(a){i++,t.includes(`*/`)&&(a=!1);continue}if(t.startsWith(`//`)){i++;continue}t.startsWith(`/*`)&&(i++,a=!t.includes(`*/`))}let o=1;for(let e of Qo){let n=t.match(e);n&&(o+=n.length)}let s=(t.match(/\bfunction\b/g)?.length??0)+(t.match(/=>\s*[{(]/g)?.length??0),c=t.match(/^\s*import\s/gm)?.length??0,l=t.match(/^\s*export\s/gm)?.length??0;return{path:e,lines:{total:n.length,code:n.length-r-i,blank:r,comment:i},complexity:o,functions:s,imports:c,exports:l}}const ts=new Set(`if_statement.for_statement.for_in_statement.while_statement.do_statement.switch_case.catch_clause.ternary_expression.if_statement.for_statement.while_statement.except_clause.list_comprehension.if_statement.for_statement.enhanced_for_statement.while_statement.catch_clause.ternary_expression.if_statement.for_statement.select_statement.if_expression.for_expression.while_expression.match_arm`.split(`.`)),ns=new Set([`if_statement`,`if_expression`,`for_statement`,`for_in_statement`,`enhanced_for_statement`,`for_expression`,`while_statement`,`while_expression`,`do_statement`,`switch_statement`,`match_expression`,`try_statement`,`catch_clause`,`except_clause`,`lambda`,`lambda_expression`,`arrow_function`]);async function rs(e,t){let n=D.get();if(!(!n||!E.has(t)))try{let r=await n.parse(e,t);if(!r)return;let i=0;function a(e,t){let n=ts.has(e.type),r=ns.has(e.type);n&&(i+=1+t);let o=r?t+1:t;for(let t=0;t<e.childCount;t++){let n=e.child(t);n&&a(n,o)}}return a(r.rootNode,0),i}catch{return}}function is(e,t){try{if(L(e).isFile())return[e]}catch{throw Error(`Path not found: ${e}`)}let n=[];function r(e){for(let i of F(e)){if(Zo.has(i))continue;let a=u(e,i);L(a).isDirectory()?r(a):t.includes(c(i).toLowerCase())&&n.push(a)}}return r(e),n.sort(),n}const as=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,`__pycache__`,`.venv`,`target`,`obj`,`.gradle`]),os=[{glob:/\.env(?:\.\w+)?$/,type:`env`},{glob:/\.env\.example$/,type:`env`},{glob:/package\.json$/,type:`package-json`},{glob:/^(?:app|config|settings|default)\.(?:json|ya?ml|toml)$/i,type:`config`},{glob:/docker-compose\.ya?ml$/,type:`docker`},{glob:/cdk\.json$/,type:`cdk`},{glob:/turbo\.json$/,type:`tooling`},{glob:/application\.(?:properties|ya?ml)$/i,type:`spring`},{glob:/settings\.py$/,type:`django`},{glob:/\.flaskenv$/,type:`env`},{glob:/appsettings\.(?:\w+\.)?json$/i,type:`dotnet`}];async function ss(e,n){let r=[],i=await cs(e),a=/aikit\.config\.json$/;for(let n of i)try{let i=d(e,n).replace(/\\/g,`/`);if(a.test(i))continue;let o=await t(n,`utf-8`),s=ls(n);if(i.split(`/`).length-1>1&&s===`tooling`)continue;let c=ds(o,s);c.length>0&&r.push({file:i,type:s,values:c})}catch{}return ps(r,n)}async function cs(e){let t=[],r=async(e,i)=>{if(!(i>3))try{let a=await n(e,{withFileTypes:!0});for(let n of a){if(as.has(n.name))continue;let a=u(e,n.name);n.isDirectory()&&!n.name.startsWith(`.`)?await r(a,i+1):n.isFile()&&os.some(e=>e.glob.test(n.name))&&t.push(a)}}catch{}};return await r(e,0),t}function ls(e){let t=o(e);for(let e of os)if(e.glob.test(t))return e.type;return`unknown`}const us=/(?:secret|password|token|key|api.?key|auth|credential|private)/i;function ds(e,t){let n=[];if(t===`env`)for(let t of e.split(`
73
+ `)}function xo(e){return[...new Set(e)]}function So(e){return e.status===`active`}function Co(e){return u(B(e??process.cwd()),`leases.json`)}function wo(e,t){let n=Co(t);N(s(n),{recursive:!0});let r=`${n}.tmp`;R(r,`${JSON.stringify(e,null,2)}\n`,`utf-8`),I(r,n)}function To(e){let t=Date.now(),n=!1;for(let r of e.leases)r.status===`active`&&new Date(r.expiresAt).getTime()<t&&(r.status=`expired`,n=!0);return n}function Eo(e){let t=Co(e);if(!M(t))return{leases:[],hotspots:{}};try{let n=P(t,`utf-8`),r=JSON.parse(n),i={leases:r.leases??[],hotspots:r.hotspots??{}};return To(i)&&wo(i,e),i}catch(e){return e?.code===`ENOENT`||console.warn(`Corrupt state file ${t}: ${e instanceof Error?e.message:String(e)}`),{leases:[],hotspots:{}}}}function Do(e,t){let n=new Set(e.files),r=e.symbols?new Set(e.symbols):null,i=[];for(let a of t){if(!So(a)||a.agent===e.agent)continue;let t=xo(a.files.filter(e=>n.has(e)));if(t.length!==0){if(r&&a.symbols&&a.symbols.length>0){let e=xo(a.symbols.filter(e=>r.has(e)));if(e.length===0)continue;i.push({leaseId:a.id,agent:a.agent,overlappingFiles:t,overlappingSymbols:e,intent:a.intent});continue}i.push({leaseId:a.id,agent:a.agent,overlappingFiles:t,intent:a.intent})}}return i}function Oo(e,t,n){let r=new Date().toISOString();for(let i of xo(t)){let t=e.hotspots[i]??{path:i,leaseCount:0,conflictCount:0,lastContested:r};t.leaseCount+=1,n>0&&(t.conflictCount+=n,t.lastContested=r),e.hotspots[i]=t}}function ko(e){let t=Eo(e.cwd),n={id:xe(),agent:e.agent,files:xo(e.files),symbols:e.symbols?xo(e.symbols):void 0,intent:e.intent,status:`active`,acquiredAt:new Date().toISOString(),expiresAt:new Date(Date.now()+(e.ttl_minutes??10)*60*1e3).toISOString()},r=Do(n,t.leases.filter(So)),i=new Set;for(let e of r)for(let t of e.overlappingFiles)i.add(t);for(let e of n.files)Oo(t,[e],+!!i.has(e));return t.leases.push(n),wo(t,e.cwd),{lease:n,conflicts:r}}function Ao(e){let t=Eo(e.cwd),n=t.leases.find(t=>t.id===e.id);return n?(n.status=`released`,n.releasedAt=new Date().toISOString(),wo(t,e.cwd),{released:!0,lease:n}):{released:!1}}function jo(e){let t=Eo(e?.cwd);return{leases:t.leases.filter(t=>So(t)&&(!e?.agent||t.agent===e.agent)),hotspots:t.hotspots}}const K=_e(`maintenance`),Mo=`last-prune.txt`,No=`last-promote-run`,Po=new Set([`queues`,`worksets`,`stash`]);function Fo(e){if(!M(e))return[];try{return F(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch(t){return K.warn(`Failed to list directories`,{dirPath:e,error:String(t)}),[]}}function Io(e,t){t||ie(e,{recursive:!0,force:!0})}function Lo(e){return/^aikit-forge-ground-[a-z0-9]{6}-[a-f0-9]{8}$/.test(e)}function Ro(e,t){let n=Date.parse(e);return Number.isNaN(n)?!1:Date.now()-n>t*24*60*60*1e3}function zo(e){let t=0;try{let n=F(e,{withFileTypes:!0});for(let r of n){let n=u(e,r.name);r.isDirectory()?t+=zo(n):t+=L(n).size}}catch{}return t}function Bo(e){if(e<1024)return`${e} B`;let t=[`KB`,`MB`,`GB`,`TB`],n=e,r=-1;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n.toFixed(1)} ${t[r]}`}function Vo(e,t=!1){let n=0,r=0;for(let i of Fo(e)){if(!Lo(i))continue;let a=u(e,i);try{let e=zo(a);Io(a,t),n+=1,r+=e,K.info(t?`Would remove forge-ground orphan`:`Removed forge-ground orphan`,{dirPath:a,size:e})}catch(e){K.warn(`Failed to remove forge-ground orphan`,{dirPath:a,error:String(e)})}}return{count:n,bytesFreed:r}}function Ho(e,t=!1){let n=0,r=0;for(let i of Fo(e)){if(Lo(i))continue;let a=u(e,i,`knowledge.lance`);if(M(a))try{let e=zo(a);Io(a,t),n+=1,r+=e,K.info(t?`Would remove legacy LanceDB directory`:`Removed legacy LanceDB directory`,{lanceDir:a,size:e})}catch(e){K.warn(`Failed to remove legacy LanceDB directory`,{lanceDir:a,error:String(e)})}}return{count:n,bytesFreed:r}}function Uo(e,t=!1){let n=0;for(let r of Fo(e)){if(Lo(r))continue;let i=u(e,r,`state`);if(M(i))for(let e of Fo(i)){if(!Po.has(e))continue;let r=u(i,e);try{if(F(r).length>0)continue;Io(r,t),n+=1,K.info(t?`Would remove empty ephemeral directory`:`Removed empty ephemeral directory`,{ephemeralDir:r})}catch(e){K.warn(`Failed to remove empty ephemeral directory`,{ephemeralDir:r,error:String(e)})}}}return{count:n}}function Wo(e,t=90,n=!1){let r=0,i=0,a=!1,o=ye(),s=ge(process.cwd());for(let[c,l]of Object.entries(o.workspaces)){if(l.partition===s||c===s||!Ro(l.lastAccessedAt,t))continue;let d=u(e,l.partition);try{let e=M(d)?zo(d):0;!n&&M(d)&&ie(d,{recursive:!0,force:!0}),n||(delete o.workspaces[c],a=!0),r+=1,i+=e,K.info(n?`Would remove stale partition`:`Removed stale partition`,{partition:l.partition,workspacePath:l.workspacePath,size:e})}catch(e){K.warn(`Failed to remove stale partition`,{partition:l.partition,workspacePath:l.workspacePath,error:String(e)})}}if(a)try{be(o)}catch(e){K.warn(`Failed to save registry after stale partition cleanup`,{error:String(e)})}return{count:r,bytesFreed:i}}function Go(e=5,t=!1){let n=0,r=0,i=f(ue(),`.aikit`,`profiles`);if(!M(i))return{count:n,bytesFreed:r};let a=Fo(i).map(e=>{let t=u(i,e),n=0;try{n=L(t).mtimeMs}catch(e){K.warn(`Failed to stat browser profile directory`,{dirPath:t,error:String(e)})}return{dirPath:t,mtimeMs:n}}).sort((e,t)=>t.mtimeMs-e.mtimeMs),o=Math.max(e,0);for(let e of a.slice(o))try{let i=zo(e.dirPath);Io(e.dirPath,t),n+=1,r+=i,K.info(t?`Would remove browser profile`:`Removed browser profile`,{dirPath:e.dirPath,size:i})}catch(t){K.warn(`Failed to remove browser profile`,{dirPath:e.dirPath,error:String(t)})}return{count:n,bytesFreed:r}}function Ko(e={}){let t=e.dryRun??!1,n=e.maxAgeDays??90,r=e.maxBrowserProfiles??5,i=ve();K.info(`Starting storage prune`,{dryRun:t,maxAgeDays:n,maxBrowserProfiles:r,globalDir:i}),K.info(`Pruning forge-ground orphan directories`);let a=Vo(i,t);K.info(`Pruning legacy LanceDB directories`);let o=Ho(i,t);K.info(`Pruning empty ephemeral directories`);let s=Uo(i,t);K.info(`Pruning stale partitions`);let c=Wo(i,n,t);K.info(`Pruning browser profiles`);let l=Go(r,t);return{forgeGroundOrphans:a,legacyLance:o,emptyEphemeral:s,stalePartitions:c,browserProfiles:l,totalBytesFreed:a.bytesFreed+o.bytesFreed+c.bytesFreed+l.bytesFreed,dryRun:t}}function qo(){let e=f(ve(),Mo);if(!M(e))return!0;try{let t=Number.parseInt(P(e,`utf-8`).trim(),10);return Date.now()-t>1440*60*1e3}catch{return!0}}function Jo(){let e=ve(),t=f(e,Mo);N(e,{recursive:!0}),R(t,String(Date.now()),`utf-8`)}function Yo(){let e=f(ve(),No);if(!M(e))return!0;try{let t=Number.parseInt(P(e,`utf-8`).trim(),10);return Date.now()-t>10080*60*1e3}catch{return!0}}function Xo(){let e=ve(),t=f(e,No);N(e,{recursive:!0}),R(t,String(Date.now()),`utf-8`)}const Zo=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`cdk.out`,`.cache`]),Qo=[/\bif\s*\(/g,/\belse\s+if\b/g,/\bfor\s*\(/g,/\bwhile\s*\(/g,/\bcase\s+/g,/\bcatch\s*\(/g,/&&/g,/\|\|/g,/\?\?/g];async function $o(e){let{path:t,extensions:n=[`.ts`,`.tsx`,`.js`,`.jsx`],includeHidden:r=!1}=e,i=is(t,n,r),a=[];for(let e of i){let t=P(e,`utf8`),n=es(d(process.cwd(),e),t),r=await rs(t,c(e));r!==void 0&&(n.cognitiveComplexity=r),a.push(n)}a.sort((e,t)=>t.complexity-e.complexity);let o=a.reduce((e,t)=>e+t.lines.total,0),s=a.reduce((e,t)=>e+t.lines.code,0),l=a.reduce((e,t)=>e+t.complexity,0),u=a.reduce((e,t)=>e+t.functions,0),f=a[0]??{path:``,complexity:0};return{files:a,summary:{totalFiles:a.length,totalLines:o,totalCodeLines:s,avgComplexity:a.length>0?Math.round(l/a.length*10)/10:0,maxComplexity:{file:f.path,value:f.complexity},totalFunctions:u}}}function es(e,t){let n=t.split(`
74
+ `),r=0,i=0,a=!1;for(let e of n){let t=e.trim();if(t===``){r++;continue}if(a){i++,t.includes(`*/`)&&(a=!1);continue}if(t.startsWith(`//`)){i++;continue}t.startsWith(`/*`)&&(i++,a=!t.includes(`*/`))}let o=1;for(let e of Qo){let n=t.match(e);n&&(o+=n.length)}let s=(t.match(/\bfunction\b/g)?.length??0)+(t.match(/=>\s*[{(]/g)?.length??0),c=t.match(/^\s*import\s/gm)?.length??0,l=t.match(/^\s*export\s/gm)?.length??0;return{path:e,lines:{total:n.length,code:n.length-r-i,blank:r,comment:i},complexity:o,functions:s,imports:c,exports:l}}const ts=new Set(`if_statement.for_statement.for_in_statement.while_statement.do_statement.switch_case.catch_clause.ternary_expression.if_statement.for_statement.while_statement.except_clause.list_comprehension.if_statement.for_statement.enhanced_for_statement.while_statement.catch_clause.ternary_expression.if_statement.for_statement.select_statement.if_expression.for_expression.while_expression.match_arm`.split(`.`)),ns=new Set([`if_statement`,`if_expression`,`for_statement`,`for_in_statement`,`enhanced_for_statement`,`for_expression`,`while_statement`,`while_expression`,`do_statement`,`switch_statement`,`match_expression`,`try_statement`,`catch_clause`,`except_clause`,`lambda`,`lambda_expression`,`arrow_function`]);async function rs(e,t){let n=D.get();if(!(!n||!E.has(t)))try{let r=await n.parse(e,t);if(!r)return;let i=0;function a(e,t){let n=ts.has(e.type),r=ns.has(e.type);n&&(i+=1+t);let o=r?t+1:t;for(let t=0;t<e.childCount;t++){let n=e.child(t);n&&a(n,o)}}return a(r.rootNode,0),i}catch{return}}function is(e,t,n){try{if(L(e).isFile())return[e]}catch{throw Error(`Path not found: ${e}`)}let r=[];function i(e){for(let a of F(e)){if(!n&&a.startsWith(`.`)||Zo.has(a))continue;let o=u(e,a);L(o).isDirectory()?i(o):t.includes(c(a).toLowerCase())&&r.push(o)}}return i(e),r.sort(),r}const as=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,`__pycache__`,`.venv`,`target`,`obj`,`.gradle`]),os=[{glob:/\.env(?:\.\w+)?$/,type:`env`},{glob:/\.env\.example$/,type:`env`},{glob:/package\.json$/,type:`package-json`},{glob:/^(?:app|config|settings|default)\.(?:json|ya?ml|toml)$/i,type:`config`},{glob:/docker-compose\.ya?ml$/,type:`docker`},{glob:/cdk\.json$/,type:`cdk`},{glob:/turbo\.json$/,type:`tooling`},{glob:/application\.(?:properties|ya?ml)$/i,type:`spring`},{glob:/settings\.py$/,type:`django`},{glob:/\.flaskenv$/,type:`env`},{glob:/appsettings\.(?:\w+\.)?json$/i,type:`dotnet`}];async function ss(e,n){let r=[],i=await cs(e),a=/aikit\.config\.json$/;for(let n of i)try{let i=d(e,n).replace(/\\/g,`/`);if(a.test(i))continue;let o=await t(n,`utf-8`),s=ls(n);if(i.split(`/`).length-1>1&&s===`tooling`)continue;let c=ds(o,s);c.length>0&&r.push({file:i,type:s,values:c})}catch{}return ps(r,n)}async function cs(e){let t=[],r=async(e,i)=>{if(!(i>3))try{let a=await n(e,{withFileTypes:!0});for(let n of a){if(as.has(n.name))continue;let a=u(e,n.name);n.isDirectory()&&!n.name.startsWith(`.`)?await r(a,i+1):n.isFile()&&os.some(e=>e.glob.test(n.name))&&t.push(a)}}catch{}};return await r(e,0),t}function ls(e){let t=o(e);for(let e of os)if(e.glob.test(t))return e.type;return`unknown`}const us=/(?:secret|password|token|key|api.?key|auth|credential|private)/i;function ds(e,t){let n=[];if(t===`env`)for(let t of e.split(`
75
75
  `)){let e=t.trim();if(!e||e.startsWith(`#`))continue;let r=e.indexOf(`=`);if(r===-1)continue;let i=e.slice(0,r).trim(),a=e.slice(r+1).trim(),o=us.test(i);n.push({key:i,value:o?`***`:a,sensitive:o})}else if(t===`package-json`)try{let t=JSON.parse(e);if(t.scripts)for(let[e,r]of Object.entries(t.scripts))n.push({key:`scripts.${e}`,value:String(r),sensitive:!1});if(t.engines)for(let[e,r]of Object.entries(t.engines))n.push({key:`engines.${e}`,value:String(r),sensitive:!1})}catch{}else if(t===`spring`)for(let t of e.split(`
76
76
  `)){let e=t.trim();if(!e||e.startsWith(`#`)||e.startsWith(`---`))continue;let r=e.match(/^([\w.[\]-]+)\s*[=:]\s*(.*)$/);if(r){let e=r[1],t=r[2].trim(),i=us.test(e);n.push({key:e,value:i?`***`:t,sensitive:i})}}else if(t===`json`||t===`config`||t===`cdk`||t===`tooling`||t===`dotnet`)try{fs(JSON.parse(e),``,n,0)}catch{}else if(t===`django`)for(let t of e.split(`
77
77
  `)){let e=t.match(/^([A-Z_][A-Z0-9_]*)\s*=\s*(.+)$/);if(e){let t=e[1],r=e[2].trim(),i=us.test(t);n.push({key:t,value:i?`***`:r.slice(0,100),sensitive:i})}}return n}function fs(e,t,n,r){if(!(r>3)&&typeof e==`object`&&e&&!Array.isArray(e))for(let[i,a]of Object.entries(e)){let e=t?`${t}.${i}`:i;if(typeof a==`object`&&a&&!Array.isArray(a))fs(a,e,n,r+1);else{let t=us.test(i),r=Array.isArray(a)?`[${a.length} items]`:String(a);n.push({key:e,value:t?`***`:r.slice(0,120),sensitive:t})}}}function ps(e,t){let n=[];if(n.push(`## Configuration Values: ${t}\n`),e.length===0)return n.push(`No configuration files detected.`),n.join(`
@@ -93,6 +93,7 @@ Important distinction:
93
93
  - Root `*-viewer.html` files are Vite entry templates
94
94
  - `dist/*.html` files are the final self-contained artifacts
95
95
  - `embed.mjs` reads from `dist/`, not from the root entry templates
96
+ - `package.json` `exports` points at the built viewer HTML assets, which keeps workspace health satisfied without changing the standalone build flow
96
97
 
97
98
  ## Architecture
98
99
 
@@ -7,6 +7,7 @@ function e(e){return e&&e[0].toLowerCase()+e.slice(1)}function t(e){return!e||e.
7
7
  `)).join(`
8
8
  `).trimEnd()}function o(e){return[[`Session Start`,e.sessionStart],[`Before Code Change`,e.beforeCodeChange],[`Before Commit`,e.beforeCommit],[`Session End`,e.sessionEnd]].map(([e,t])=>{let n=(t?.actions||[]).map(e=>`- \`${e}\``);return[`### ${e}`,``,...n,``].join(`
9
9
  `)}).join(`
10
- `).trimEnd()}function s(e,t){let n=[];for(let[t,r]of Object.entries(e))if(r.variants)for(let[e,i]of Object.entries(r.variants)){let a=`${t}-${e}`;n.push(`| **${a}** | ${i.description} | ${r.category||`—`} |`)}else n.push(`| **${t}** | ${r.description} | ${r.category||`—`} |`);return`| Agent | Purpose | Category |\n|-------|---------|----------|\n${n.join(`
11
- `)}`}function c(e){let t=[];for(let[n,r]of Object.entries(e)){if(n===`Orchestrator`)continue;let e=r.compactRole||r.description;if(r.variants){let i=Object.keys(r.variants);t.push(`| **${n}-${i.join(`/`)}** | ${e} |`)}else t.push(`| **${n}** | ${e} |`)}return`| Agent | Role |\n|-------|------|\n${t.join(`
12
- `)}`}function l({serverName:e,mcpEntry:t,configKey:n,extraServerFields:r}){let i={...t};return r&&Object.assign(i,r),JSON.stringify({[n]:{[e]:i}},null,2)}export{n as buildAgentPrompt,s as buildAgentTable,c as buildCompactAgentTable,o as buildHooksSection,r as buildInlineAgentSection,l as buildMcpConfigJson,i as buildPromptFile,a as buildPromptSections,t as buildSkillsSection,e as lowerFirst};
10
+ `).trimEnd()}function s(e,t){if(!e)return null;let n=typeof e==`function`?e(t):e[t];return n?typeof n==`string`?n:n.primary||n.model||null:null}function c(e,t){let n=!!t,r=[];for(let[i,a]of Object.entries(e))if(a.variants)for(let[e,o]of Object.entries(a.variants)){let c=`${i}-${e}`,l=[`| **${c}** | ${o.description} |`];n&&l.push(` ${s(t,c)||`—`} |`),l.push(` ${a.category||`—`} |`),r.push(l.join(``))}else{let e=[`| **${i}** | ${a.description} |`];n&&e.push(` ${s(t,i)||`—`} |`),e.push(` ${a.category||`—`} |`),r.push(e.join(``))}return n?`| Agent | Purpose | Model | Category |\n|-------|---------|-------|----------|\n${r.join(`
11
+ `)}`:`| Agent | Purpose | Category |\n|-------|---------|----------|\n${r.join(`
12
+ `)}`}function l(e){let t=[];for(let[n,r]of Object.entries(e)){if(n===`Orchestrator`)continue;let e=r.compactRole||r.description;if(r.variants){let i=Object.keys(r.variants);t.push(`| **${n}-${i.join(`/`)}** | ${e} |`)}else t.push(`| **${n}** | ${e} |`)}return`| Agent | Role |\n|-------|------|\n${t.join(`
13
+ `)}`}function u({serverName:e,mcpEntry:t,configKey:n,extraServerFields:r}){let i={...t};return r&&Object.assign(i,r),JSON.stringify({[n]:{[e]:i}},null,2)}export{n as buildAgentPrompt,c as buildAgentTable,l as buildCompactAgentTable,o as buildHooksSection,r as buildInlineAgentSection,u as buildMcpConfigJson,i as buildPromptFile,a as buildPromptSections,t as buildSkillsSection,e as lowerFirst};