@vpxa/aikit 0.1.270 → 0.1.272
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.
- package/package.json +1 -1
- package/packages/blocks-core/dist/index.mjs +3 -3
- package/packages/cli/dist/index.js +3 -3
- package/packages/cli/dist/{init-o6szsZIP.js → init-DCs4TWh6.js} +1 -1
- package/packages/cli/dist/{templates-guQ2153Z.js → templates-C92mODRl.js} +5 -2
- package/packages/present/dist/index.html +1 -1
- package/packages/server/dist/bin.js +3 -3
- package/packages/server/dist/{curated-manager-xTfPLFMR.js → curated-manager-CfwN96rp.js} +2 -2
- package/packages/server/dist/index.d.ts +9 -0
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/{promotion-PdKQQktE.js → promotion-BNEScZVD.js} +1 -1
- package/packages/server/dist/{server-CIPdEf8F.js → server-4h0Cclv3.js} +82 -82
- package/packages/server/dist/{server-CIf0Ejd4.js → server-DIz2FGOX.js} +83 -83
- package/packages/server/viewers/report-template.html +3 -3
- package/packages/store/dist/index.d.ts +0 -13
- package/packages/store/dist/index.js +32 -32
- package/packages/tools/dist/index.js +1 -1
- package/scaffold/definitions/mcp-entry.json +1 -1
- package/scaffold/dist/definitions/agents.mjs +1 -1
- package/scaffold/dist/definitions/mcp-entry.json +1 -1
- package/scaffold/dist/definitions/skills/aikit.mjs +3 -1
|
@@ -1455,10 +1455,10 @@ ${ft}
|
|
|
1455
1455
|
}
|
|
1456
1456
|
`;function yn(e){let t=[vn],n=new Set;for(let r of e)!n.has(r)&&A[r]&&(n.add(r),t.push(A[r]));return t.join(`
|
|
1457
1457
|
`)}function bn(){return yn(Object.keys(A))}var j={header:`aikit-header`,brand:`aikit-header-brand`,title:`aikit-header-title`,titleText:`aikit-header-title-text`,subtitle:`aikit-header-subtitle`,actions:`aikit-header-actions`,themeToggle:`aikit-theme-toggle`,themeToggleIcon:`aikit-theme-toggle-icon`,themeToggleIconSun:`aikit-theme-toggle-icon--sun`,themeToggleIconMoon:`aikit-theme-toggle-icon--moon`,toolbox:`aikit-toolbox`,toolboxToggle:`aikit-toolbox-toggle`,toolboxMenu:`aikit-toolbox-menu`,toolboxItem:`aikit-toolbox-item`,footer:`aikit-footer`,footerMeta:`aikit-footer-meta`,footerText:`aikit-footer-text`,footerBrand:`aikit-footer-brand`,footerTimestamp:`aikit-footer-timestamp`,footerSlot:`aikit-footer-slot`,footerBadge:`aikit-footer-badge`},xn=`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>`,Sn=`<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>`,Cn=`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>`,wn=`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>`,Tn=[{kind:`shared-chrome-action`,id:`copy-image`,label:`Copy as Image`,icon:Sn,onclick:`screenshotPage()`}];function En(t){let n=t.onclick?` onclick="${e(t.onclick)}"`:``;return[` <button type="button" class="${j.toolboxItem}" role="menuitem" data-shared-chrome-action="${e(t.id)}" aria-label="${e(t.label)}"${n}>`,` <span aria-hidden="true">${t.icon}</span>`,` <span>${e(t.label)}</span>`,` </button>`].join(`
|
|
1458
|
-
`)}function Dn(e){if(e!==`browser`&&e!==`mcp-app`)return``;let t
|
|
1459
|
-
`)}function On(e){return e?.trim()?e.trim():``}function kn(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?{display:e}:{dateTime:t.toISOString(),display:new Intl.DateTimeFormat(void 0,{month:`long`,day:`numeric`,year:`numeric`,hour:`numeric`,minute:`2-digit`}).format(t)}}function An(t){let n=t.brand??`AI KIT`,r=[On(t.actionsHtml),Dn(t.transport),t.showThemeToggle===!1?``:[` <button type="button" class="${j.themeToggle}" aria-label="Switch to dark theme" aria-pressed="false" onclick="toggleTheme()">`,` <span class="${j.themeToggleIcon} ${j.themeToggleIconSun}" aria-hidden="true">${Cn}</span>`,` <span class="${j.themeToggleIcon} ${j.themeToggleIconMoon}" aria-hidden="true">${wn}</span>`,` </button>`].join(`
|
|
1458
|
+
`)}function Dn(e,t=[]){if(e!==`browser`&&e!==`mcp-app`)return``;let n=t.filter(e=>e.kind===`shared-chrome-action`);return n.length===0?``:[` <div class="${j.toolbox}">`,` <button type="button" class="${j.toolboxToggle}" aria-label="Open tools menu" aria-haspopup="menu" aria-expanded="false" aria-controls="aikit-toolbox-menu" onclick="toggleToolbox()">`,` ${xn}`,` </button>`,` <div id="aikit-toolbox-menu" class="${j.toolboxMenu}" role="menu" hidden>`,...n.map(e=>En(e)),` </div>`,` </div>`].join(`
|
|
1459
|
+
`)}function On(e){return e?.trim()?e.trim():``}function kn(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?{display:e}:{dateTime:t.toISOString(),display:new Intl.DateTimeFormat(void 0,{month:`long`,day:`numeric`,year:`numeric`,hour:`numeric`,minute:`2-digit`}).format(t)}}function An(t){let n=t.brand??`AI KIT`,r=t.sharedChromeActions??(t.transport===`browser`?Tn:[]),i=[On(t.actionsHtml),Dn(t.transport,r),t.showThemeToggle===!1?``:[` <button type="button" class="${j.themeToggle}" aria-label="Switch to dark theme" aria-pressed="false" onclick="toggleTheme()">`,` <span class="${j.themeToggleIcon} ${j.themeToggleIconSun}" aria-hidden="true">${Cn}</span>`,` <span class="${j.themeToggleIcon} ${j.themeToggleIconMoon}" aria-hidden="true">${wn}</span>`,` </button>`].join(`
|
|
1460
1460
|
`)].filter(Boolean).join(`
|
|
1461
|
-
`);return[` <header class="${j.header}">`,` <div class="${j.brand}">${e(n)}</div>`,` <div class="${j.title}">`,` <span class="${j.titleText}">${e(t.title)}</span>`,...t.subtitle?[` <span class="${j.subtitle}">${e(t.subtitle)}</span>`]:[],` </div>`,` <div class="${j.actions}">`,
|
|
1461
|
+
`);return[` <header class="${j.header}">`,` <div class="${j.brand}">${e(n)}</div>`,` <div class="${j.title}">`,` <span class="${j.titleText}">${e(t.title)}</span>`,...t.subtitle?[` <span class="${j.subtitle}">${e(t.subtitle)}</span>`]:[],` </div>`,` <div class="${j.actions}">`,i,` </div>`,` </header>`].join(`
|
|
1462
1462
|
`)}function jn(t={}){let n=kn(t.generatedAt),r=n?[`Generated by `,`<span class="${j.footerBrand}">AI KIT</span>`,` at `,n.dateTime?`<time class="${j.footerTimestamp}" datetime="${e(n.dateTime)}">${e(n.display)}</time>`:`<span class="${j.footerTimestamp}">${e(n.display)}</span>`].join(``):`Generated by <span class="${j.footerBrand}">AI KIT</span>`,i=On(t.contentHtml);return[` <footer class="${j.footer}">`,` <div class="${j.footerMeta}">`,` <span class="${j.footerText}">${r}</span>`,...i?[` <span class="${j.footerSlot}">${i}</span>`]:[],` </div>`,` </footer>`].join(`
|
|
1463
1463
|
`)}var Mn={actions:f,cards:m,chart:ne,checklist:Oe,code:Ae,comparison:Ne,diff:Ze,"component-detail":Ve,"data-table-schema":qe,"docs-browser":et,"docs-hub":at,finding:ct,graph:dt,heading:pt,kv:gt,"lifecycle-flow":jt,list:Nt,markdown:Rt,mermaid:Bt,metrics:Ut,paragraph:Gt,progress:Jt,prompt:Zt,separator:$t,"status-board":nn,table:cn,tags:dn,text:pn,timeline:hn,tree:_n};function Nn(t,n){let r={...t,value:i(t.value)},a=Mn[r.type],o=a?a(r,n):Fn(r);return r.title&&![`heading`,`finding`].includes(r.type)?`<section class="bk-section bk-section--${e(r.type)}"><h3 class="bk-section-title">${e(r.title)}</h3>${o}</section>`:o}function Pn(e,t){return e.map(e=>Nn(e,t)).join(`
|
|
1464
1464
|
`)}function Fn(t){if(t.value===void 0||t.value===null)return``;if(typeof t.value==`string`)return`<p class="bk-paragraph">${e(t.value)}</p>`;try{return`<pre class="bk-fallback">${e(JSON.stringify(t.value,null,2))}</pre>`}catch{return`<pre class="bk-fallback">${e(String(t.value))}</pre>`}}var In=class{templates=new Map;register(e){this.templates.set(e.id,e)}get(e){let t=this.templates.get(e);if(t)return t;let n=e.includes(`@`)?e:`${e}@`,r,i=-1;for(let[e,t]of this.templates){if(!e.startsWith(n))continue;let a=Number.parseInt(e.split(`@`)[1]??`0`,10);a>i&&(i=a,r=t)}return r}has(e){return this.get(e)!==void 0}list(){return[...this.templates.values()]}},Ln=[`mcp-app`,`browser`];function M(e){return typeof e==`object`&&!!e}function Rn(e){return Array.isArray(e)?e.flatMap(e=>!M(e)||typeof e.label!=`string`?[]:[{label:e.label,checked:!!e.checked}]):[]}var zn={id:`checklist@1`,label:`Checklist`,description:`Checklist with optional title and checklist hydration metadata.`,inputSchema:{type:`object`,properties:{title:{type:`string`},items:{type:`array`,items:{type:`object`,required:[`label`,`checked`],properties:{label:{type:`string`},checked:{type:`boolean`}},additionalProperties:!1}}},required:[`items`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=[],n=M(e)&&typeof e.title==`string`?e.title:void 0,r=M(e)?Rn(e.items):[];return n&&t.push({type:`heading`,value:n}),t.push({type:`checklist`,value:r}),t},hydration:[`checklist`],supportedTransports:Ln},Bn=[`mcp-app`,`browser`,`export`];function N(e){return typeof e==`object`&&!!e}function Vn(e){return N(e)&&typeof e.label==`string`&&(typeof e.value==`string`||typeof e.value==`number`)}function Hn(e){return N(e)&&typeof e.key==`string`&&typeof e.label==`string`}function Un(e){return Array.isArray(e)?e.filter(N):[]}function Wn(e,t){if(Array.isArray(e)){let t=e.filter(Hn);if(t.length>0)return t}return Object.keys(t[0]??{}).map(e=>({key:e,label:e}))}var Gn={id:`data-table@1`,label:`Data Table`,description:`Static data table with optional metrics and sortable table hydration.`,inputSchema:{type:`object`,properties:{columns:{type:`array`,items:{type:`object`,required:[`key`,`label`],properties:{key:{type:`string`},label:{type:`string`}},additionalProperties:!1}},rows:{type:`array`,items:{type:`object`}},stats:{type:`array`,items:{type:`object`,required:[`label`,`value`],properties:{label:{type:`string`},value:{type:[`string`,`number`]},trend:{type:[`string`,`number`]},status:{type:`string`}},additionalProperties:!1}}},required:[`rows`],additionalProperties:!1},defaultLayout:{},blocksFromData:e=>{let t=N(e)?Un(e.rows):[],n=N(e)?Wn(e.columns,t):[],r=n.map(e=>e.label),i=t.map(e=>n.map(t=>e[t.key])),a=[];if(N(e)&&Array.isArray(e.stats)){let t=e.stats.filter(Vn);t.length>0&&a.push({type:`metrics`,value:t})}return a.push({type:`table`,columns:n,headers:r,rows:i,value:{headers:r,rows:i}}),a},hydration:[`table`],supportedTransports:Bn},Kn=[`mcp-app`,`browser`,`export`];function P(e){return typeof e==`object`&&!!e}function qn(e){return Array.isArray(e)?e.flatMap(e=>!P(e)||typeof e.type!=`string`||typeof e.content!=`string`?[]:[{type:e.type,content:e.content}]):[]}function Jn(e){return Array.isArray(e)?e.flatMap(e=>!P(e)||typeof e.header!=`string`?[]:[{header:e.header,changes:qn(e.changes)}]):[]}function Yn(e){return!P(e)||!Array.isArray(e.files)?[]:e.files.flatMap(e=>!P(e)||typeof e.path!=`string`||typeof e.status!=`string`?[]:[{path:e.path,status:e.status,additions:typeof e.additions==`number`?e.additions:0,deletions:typeof e.deletions==`number`?e.deletions:0,hunks:Jn(e.hunks)}])}function Xn(e){return e===`add`?`+`:e===`delete`?`-`:` `}function Zn(e){let t=e.hunks.flatMap(e=>[e.header,...e.changes.map(e=>`${Xn(e.type)}${e.content}`)]).join(`
|
|
@@ -162,19 +162,6 @@ interface IGraphStore {
|
|
|
162
162
|
}
|
|
163
163
|
//#endregion
|
|
164
164
|
//#region packages/store/src/sqlite-adapter.d.ts
|
|
165
|
-
/**
|
|
166
|
-
* SQLite adapter — selects between native better-sqlite3 (preferred) and
|
|
167
|
-
* sql.js let skipNativeAdapter = false;
|
|
168
|
-
|
|
169
|
-
(WASM fallback). The fallback exists because better-sqlite3 is a
|
|
170
|
-
* native module whose prebuilt binary is not available in every environment
|
|
171
|
-
* (Codespaces, restricted CI, mismatched Node ABI).
|
|
172
|
-
*
|
|
173
|
-
* better-sqlite3 also lets us load the sqlite-vec extension, which sql.js
|
|
174
|
-
* (running inside a WASM sandbox) cannot dlopen. When we fall back, vector
|
|
175
|
-
* search is unavailable and the consumer (SqliteVecStore) downgrades to
|
|
176
|
-
* FTS-only mode loudly.
|
|
177
|
-
*/
|
|
178
165
|
type SqliteAdapterType = 'better-sqlite3' | 'sql.js';
|
|
179
166
|
interface ISqliteAdapter {
|
|
180
167
|
/** Which adapter implementation is active */
|
|
@@ -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
|
|
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{homedir as d}from"node:os";import{AIKIT_PATHS as f,EMBEDDING_DEFAULTS as p,SEARCH_DEFAULTS as m,STORE_DEFAULTS as ee,createLogger as te,serializeError as h,sourceTypeContentTypes as ne}from"../../core/dist/index.js";var re=e(import.meta.url);function ie(e){e.exec(`
|
|
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
|
|
7
|
+
`)}function g(e,t){ie(e);let n=new Set(e.queryAll(`SELECT version FROM _migrations`).map(e=>e.version)),r=[...t].sort((e,t)=>e.version-t.version).filter(e=>!n.has(e.version));for(let t of r){e.exec(`BEGIN`);try{t.up(e),e.run(`INSERT INTO _migrations (version, name) VALUES (?, ?)`,[t.version,t.name]),e.exec(`COMMIT`)}catch(t){try{e.exec(`ROLLBACK`)}catch{}throw t}}}const _=[{version:1,name:`create state store tables`,up(e){e.exec(`
|
|
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
|
-
`)}}],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 ${
|
|
82
|
+
`)}}],v=te(`sqlite-adapter`),y=e(import.meta.url),b=`better-sqlite3`;function ae(e){return e.replace(/\\/g,`/`)}function x(){return y.resolve(`@vpxa/aikit/package.json`).replace(/[\\/]package\.json$/,``)}function S(){return x().replace(/[\\/]node_modules[\\/]@vpxa[\\/]aikit$/,``)}function oe(e){return ae(e).includes(`/_npx/`)}function C(){try{return JSON.parse(r(u(x(),`package.json`),`utf8`)).optionalDependencies?.[b]??`latest`}catch{return`latest`}}function se(e){return e.replace(/[^a-zA-Z0-9._-]+/g,`_`)}function ce(){let e=`${se(C())}-${process.platform}-${process.arch}-abi${process.versions.modules}`;return u(d(),`.aikit`,`cache`,`native-modules`,b,e)}function w(e){n(e,{recursive:!0});let r=u(e,`package.json`);t(r)||o(r,`${JSON.stringify({name:`aikit-native-runtime-cache`,private:!0},null,2)}\n`,`utf8`)}function T(e){let t=k(e);if(!t)return null;try{return JSON.parse(r(u(t,`package.json`),`utf8`)).version??null}catch{return null}}function E(e,t){try{let n={packageName:b,packageSpec:C(),packageVersion:T(e),platform:process.platform,arch:process.arch,nodeAbi:process.versions.modules,installedAt:new Date().toISOString(),source:t};o(u(e,`.aikit-native-module.json`),`${JSON.stringify(n,null,2)}\n`,`utf8`)}catch(e){v.debug(`Failed to write better-sqlite3 runtime marker`,h(e))}}var D=class{runtimeRoot;type=`better-sqlite3`;vectorCapable=!1;db=null;stmtCache=new Map;dbPath=``;DatabaseCtor=null;recovering=!1;constructor(e){this.runtimeRoot=e}async open(t){let n;try{let t=y;this.runtimeRoot!=null&&(w(this.runtimeRoot),t=e(u(this.runtimeRoot,`package.json`))),n=t(b)}catch(e){throw Error(`better-sqlite3 native binding unavailable: ${e instanceof Error?e.message:String(e)}`)}this.db=new n(t),this.dbPath=t,this.DatabaseCtor=n,this.db.pragma(`journal_mode = WAL`),this.db.pragma(`foreign_keys = ON`),this.db.pragma(`synchronous = NORMAL`),this.runIntegrityCheck(t,n)||(this.db?.pragma(`journal_mode = WAL`),this.db?.pragma(`foreign_keys = ON`),this.db?.pragma(`synchronous = NORMAL`));try{y(`sqlite-vec`).load(this.db),this.vectorCapable=!0,v.debug(`sqlite-vec extension loaded`)}catch(e){this.vectorCapable=!1,v.warn(`sqlite-vec extension failed to load; vector search disabled`,h(e))}}exec(e){try{this.getDb().exec(e)}catch(t){if(this.isCorruptionError(t)){this.recover(),this.getDb().exec(e);return}throw t}}pragma(e){this.getDb().pragma(e)}queryAll(e,t=[]){try{let n=this.prepareCached(e);return t.length>0?n.all(...t):n.all()}catch(n){if(this.isCorruptionError(n))return this.recover(),this.queryAll(e,t);throw n}}run(e,t=[]){try{let n=this.prepareCached(e);t.length>0?n.run(...t):n.run()}catch(n){if(this.isCorruptionError(n)){this.recover(),this.run(e,t);return}throw n}}flush(){}close(){this.db&&=(this.stmtCache.clear(),this.db.close(),null)}runIntegrityCheck(e,t){try{let t=this.db?.pragma(`integrity_check`);if(t.length===1&&t[0]?.integrity_check===`ok`)return!0;let n=t.map(e=>e.integrity_check).slice(0,5).join(`; `);v.warn(`Database integrity check failed — recreating`,{dbPath:e,issues:n})}catch(t){v.warn(`Integrity check query failed — recreating database`,{dbPath:e,error:h(t)})}try{this.db?.close()}catch{}this.db=null,this.stmtCache.clear();try{a(e)}catch{}try{a(`${e}-wal`)}catch{}try{a(`${e}-shm`)}catch{}return this.db=new t(e),v.info(`Database recreated successfully — full reindex required`,{dbPath:e}),!1}isCorruptionError(e){if(this.recovering)return!1;let t=e instanceof Error?e.message:String(e);return/database disk image is malformed|file is not a database|database or disk is full/.test(t)}recover(){if(this.recovering)throw Error(`BetterSqlite3Adapter: recovery already in progress`);this.recovering=!0;try{v.warn(`Runtime corruption detected — recovering database`,{dbPath:this.dbPath});try{this.db?.close()}catch{}this.db=null,this.stmtCache.clear();try{a(this.dbPath)}catch{}try{a(`${this.dbPath}-wal`)}catch{}try{a(`${this.dbPath}-shm`)}catch{}if(!this.DatabaseCtor)throw Error(`DatabaseCtor is not initialized`);this.db=this.DatabaseCtor(this.dbPath),this.db.pragma(`journal_mode = WAL`),this.db.pragma(`foreign_keys = ON`),this.db.pragma(`synchronous = NORMAL`);try{y(`sqlite-vec`).load(this.db),this.vectorCapable=!0}catch{this.vectorCapable=!1}v.info(`Database recovered — full reindex required`,{dbPath:this.dbPath})}finally{this.recovering=!1}}getDb(){if(!this.db)throw Error(`BetterSqlite3Adapter: database not opened`);return this.db}prepareCached(e){let t=this.stmtCache.get(e);if(t)return t;let n=this.getDb().prepare(e);return this.stmtCache.set(e,n),n}};function le(e){return y.resolve(`sql.js/dist/${e}`)}function ue(e){return e.match(/^\s*(?:INSERT(?:\s+OR\s+\w+)?\s+INTO|UPDATE)\s+([A-Za-z_][A-Za-z0-9_]*)/i)?.[1]??null}var O=class{type=`sql.js`;vectorCapable=!1;db=null;dbPath=``;dirty=!1;inTransaction=!1;foreignKeysEnabled=!1;async open(e){this.dbPath=e;let n=(await import(`sql.js`)).default,i=await n({locateFile:e=>le(e)});if(t(e)){let t=r(e);this.db=new i.Database(t)}else this.db=new i.Database}exec(e){let t=e.trimStart().toUpperCase();this.getDb().run(e),t.startsWith(`BEGIN`)?this.inTransaction=!0:(t.startsWith(`COMMIT`)||t.startsWith(`ROLLBACK`))&&(this.inTransaction=!1),this.dirty=!0}pragma(e){let t=e.trim().toLowerCase();t===`foreign_keys = on`||t===`foreign_keys=on`?this.foreignKeysEnabled=!0:(t===`foreign_keys = off`||t===`foreign_keys=off`)&&(this.foreignKeysEnabled=!1),this.getDb().exec(`PRAGMA ${e}`)}queryAll(e,t=[]){let n=this.getDb().prepare(e);try{t.length>0&&n.bind(t);let e=[];for(;n.step();)e.push(n.getAsObject());return e}finally{n.free()}}run(e,t=[]){let n=this.getDb(),r=e.trimStart().toUpperCase(),i=ue(e),a=this.foreignKeysEnabled&&!this.inTransaction&&i!==null&&(r.startsWith(`INSERT`)||r.startsWith(`UPDATE`));a&&n.run(`SAVEPOINT fk_check`);try{if(t.length>0){let r=n.prepare(e);try{r.bind(t),r.step()}finally{r.free()}}else n.run(e);if(a){if(n.exec(`PRAGMA foreign_key_check(${i})`).length>0)throw n.run(`ROLLBACK TO fk_check`),n.run(`RELEASE fk_check`),Error(`FOREIGN KEY constraint failed`);n.run(`RELEASE fk_check`)}}catch(e){if(a)try{n.run(`ROLLBACK TO fk_check`),n.run(`RELEASE fk_check`)}catch{}throw e}this.dirty=!0}flush(){if(!this.dirty||!this.db)return;let e=this.db.export(),r=`${this.dbPath}.tmp`,a=c(this.dbPath);a&&!t(a)&&n(a,{recursive:!0}),o(r,Buffer.from(e)),i(r,this.dbPath),this.dirty=!1}close(){if(this.db){let e=this.db,t;try{this.flush()}catch(e){t=e;try{a(`${this.dbPath}.tmp`)}catch{}}try{e.close()}finally{this.db=null}if(t)throw t}}getDb(){if(!this.db)throw Error(`SqlJsAdapter: database not opened`);return this.db}};function k(e){if(e){let n=u(e,`node_modules`,b);return t(u(n,`package.json`))?n:null}try{return y.resolve(`${b}/package.json`).replace(/[\\/]package\.json$/,``)}catch{return null}}function de(e){let n=k(e);if(!n)return null;let r=u(n,`build`,`Release`,`better_sqlite3.node`);return t(r)?r:null}async function fe(e){let n=k(e);if(!n)return`package-missing`;if(!t(u(n,`build`,`Release`,`better_sqlite3.node`)))return`binding-missing`;try{let{execFileSync:t}=await import(`node:child_process`),n=e??S();return e&&w(e),t(process.execPath,[`-e`,`require('${b}')`],{cwd:n,stdio:`pipe`,timeout:15e3,windowsHide:!0}),`ok`}catch(e){let t=e instanceof Error&&`stderr`in e?String(e.stderr):``;return/NODE_MODULE_VERSION/.test(t)?`abi-mismatch`:/Could not locate the bindings file|no native build was found/.test(t)?`binding-missing`:`error`}}async function pe(e,n=!1){let r=k(e);if(!r)return v.info(`better-sqlite3 package is not installed — skipping native rebuild`),!1;try{let{execFileSync:i}=await import(`node:child_process`),o=e??r.replace(/[\\/]node_modules[\\/]better-sqlite3$/,``),s=process.platform===`win32`?`npm.cmd`:`npm`;if(e&&w(e),n){let e=u(r,`build`,`Release`,`better_sqlite3.node`);if(t(e))try{a(e),v.info(`Deleted stale native binding before rebuild`,{path:e})}catch(t){v.warn(`Cannot delete stale native binding — file may be locked by another process`,{path:e,error:t instanceof Error?t.message:String(t)})}}return v.info(`Attempting native module rebuild for better-sqlite3`,{cwd:o}),i(s,[`rebuild`,b],{cwd:o,stdio:`pipe`,timeout:6e4,windowsHide:!0}),v.info(`Native module rebuild completed successfully`),E(o,`rebuild`),!0}catch(e){return v.warn(`Native module rebuild failed — continuing with sql.js fallback`,h(e)),!1}}async function me(e){try{let{execFileSync:t}=await import(`node:child_process`),n=e??S(),r=process.platform===`win32`?`npm.cmd`:`npm`,i=C();return w(n),v.info(`Attempting to install better-sqlite3 for native adapter recovery`,{cwd:n,packageSpec:i}),t(r,[`install`,`--no-save`,`--package-lock=false`,`--no-audit`,`--no-fund`,`--omit=dev`,`${b}@${i}`],{cwd:n,stdio:`pipe`,timeout:12e4,windowsHide:!0}),v.info(`better-sqlite3 install completed successfully`),E(n,`install`),!0}catch(e){return v.warn(`better-sqlite3 install failed — continuing with sql.js fallback`,h(e)),!1}}let A=!1;function he(){return!!process.env.VITEST||process.argv.some(e=>e.includes(`vitest`))}async function ge(){let e=M.resolveAikitRuntimeRoot(),t=await M.probeNativeModuleAbi(e);if(t===`ok`)return e;if(M.isNpxRuntimeRoot(e)){let e=M.resolvePersistentNativeRuntimeRoot(),t=await M.probeNativeModuleAbi(e);if(t===`ok`)return v.info(`Using cached better-sqlite3 native runtime`,{runtimeRoot:e,version:M.resolveNativeModuleVersion(e)}),e;let n=!1;if(t===`abi-mismatch`?(v.info(`Persistent better-sqlite3 cache ABI mismatch — rebuilding cached binding`),n=await M.tryRebuildNativeModule(e,!0)):t===`binding-missing`?(v.info(`Persistent better-sqlite3 cache missing binding — rebuilding cache`),n=await M.tryRebuildNativeModule(e,!1)):(v.info(`Persistent better-sqlite3 cache missing — installing cached runtime`,{runtimeRoot:e,packageSpec:M.readAikitPackageSpec()}),n=await M.tryInstallNativeModule(e)),n&&await M.probeNativeModuleAbi(e)===`ok`)return v.info(`Persistent better-sqlite3 cache ready`,{runtimeRoot:e,version:M.resolveNativeModuleVersion(e)}),e}if(t===`abi-mismatch`){if(v.info(`Detected NODE_MODULE_VERSION mismatch via pre-flight probe — rebuilding before load`),await M.tryRebuildNativeModule(e,!0)&&await M.probeNativeModuleAbi(e)===`ok`)return v.info(`Pre-flight rebuild succeeded — proceeding with native adapter`),e}else if(t===`binding-missing`){if(v.info(`No native binding found — attempting rebuild before load`),await M.tryRebuildNativeModule(e,!1)&&await M.probeNativeModuleAbi(e)===`ok`)return e}else if(t===`package-missing`&&(v.info(`better-sqlite3 package is not installed — attempting install before load`),await M.tryInstallNativeModule(e)&&await M.probeNativeModuleAbi(e)===`ok`))return e;return null}async function j(e){let t=null;M.isVitestRuntime()||(t=await M.preparePreferredNativeRuntime());{let n=M.createNativeAdapter(t??void 0);try{return await n.open(e),n}catch(n){let r=n instanceof Error?n.message:String(n);if(!M.isVitestRuntime()&&/NODE_MODULE_VERSION|Could not locate the bindings file|no native build was found/.test(r)){let n=t??M.resolveAikitRuntimeRoot();if(await M.tryRebuildNativeModule(n,!1)){let t=M.createNativeAdapter(n);try{return await t.open(e),v.info(`better-sqlite3 recovered after native module rebuild`),t}catch{}}}A||(A=!0,v.warn(`[aikit] better-sqlite3 unavailable — falling back to sql.js (vector search disabled). Reinstall with prebuild support or rebuild from source to enable vector search.`,h(n)))}}let n=M.createFallbackAdapter();try{return await n.open(e),n}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`[aikit] SQLite adapter "sql.js" failed to load: ${t}`)}}async function _e(e){let t=new O;return await t.open(e),t}const M={BetterSqlite3Adapter:D,SqlJsAdapter:O,isVitestRuntime:he,resolveAikitPackageRoot:x,resolveAikitRuntimeRoot:S,isNpxRuntimeRoot:oe,readAikitPackageSpec:C,resolvePersistentNativeRuntimeRoot:ce,ensureRuntimeRootPackageJson:w,resolveNativeModulePackageDir:k,resolveNativeBindingPath:de,resolveNativeModuleVersion:T,probeNativeModuleAbi:fe,tryRebuildNativeModule:pe,tryInstallNativeModule:me,preparePreferredNativeRuntime:ge,createNativeAdapter:e=>new D(e),createFallbackAdapter:()=>new O},N=new Set([`sessions`,`stash`,`checkpoints`,`leases`,`signals`,`audit_log`,`replay_entries`,`session_metadata`]);function ve(e){let t=l(e)||`.db`,n=s(e,t);return u(c(e),`${n}-control${t}`)}function ye(e){return N.has(e)?`control`:`content`}function P(e,t={}){let n=t.splitEnabled??!1;return{splitEnabled:n,contentDbPath:t.contentDbPath??e,controlDbPath:t.controlDbPath??(n?ve(e):e)}}function be(e,t=process.env){let n=t.AIKIT_SPLIT_STATE?.trim().toLowerCase();return P(e,{splitEnabled:n===`1`||n===`true`||n===`yes`||n===`on`})}const F=`_state_partition_meta`;function I(e){return`"${e.replaceAll(`"`,`""`)}"`}function xe(e){let r=c(e);t(r)||n(r,{recursive:!0})}async function Se(e){return xe(e),j(e)}function L(e,t){return e.queryAll(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`,[t]).length>0}function Ce(e,t){return e.queryAll(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?`,[t])[0]?.sql??void 0}function we(e,t){return e.queryAll(`PRAGMA table_info(${I(t)})`).map(e=>e.name)}function R(e,t){return e.queryAll(`SELECT COUNT(*) AS count FROM ${I(t)}`)[0]?.count??0}function Te(e,t,n){if(!L(e,n))return;if(!L(t,n)){let r=Ce(e,n);if(!r)return;t.exec(r)}let r=we(t,n);if(r.length===0)return;let i=r.map(I).join(`, `),a=r.map(()=>`?`).join(`, `),o=e.queryAll(`SELECT ${i} FROM ${I(n)}`);if(o.length===0)return;let s=`INSERT OR REPLACE INTO ${I(n)} (${i}) VALUES (${a})`;for(let e of o)t.run(s,r.map(t=>e[t]??null))}function Ee(e){e.exec(`
|
|
83
|
+
CREATE TABLE IF NOT EXISTS ${F} (
|
|
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
|
|
88
|
+
`)}function De(e,t,n){Ee(e),e.run(`INSERT INTO ${F} (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
|
|
92
|
+
updated_at = datetime('now')`,[`split-state`,JSON.stringify({splitEnabled:t.splitEnabled,contentDbPath:t.contentDbPath,controlDbPath:t.controlDbPath,migratedTables:n})])}async function Oe(e){let t=e.contentDbPath??e.controlDbPath;if(!t)throw Error(`migrateToSplitState requires at least one database path in config`);let n=P(t,e);if(!n.splitEnabled||n.controlDbPath===n.contentDbPath)return;let r=await Se(n.contentDbPath),i=await Se(n.controlDbPath);try{g(i,_);let e=[];for(let t of N){if(!L(r,t))continue;Te(r,i,t);let n=R(r,t),a=R(i,t);if(a<n)throw Error(`Split-state migration verification failed for ${t}: source=${n} target=${a}`);e.push(t)}De(i,n,e)}finally{r.close(),i.close()}}var ke=class{adapter=null;reopenPromise=null;dbPath;externalAdapter;constructor(e={}){if(e.adapter)this.adapter=e.adapter,this.externalAdapter=!0,this.dbPath=``;else{let t=e.path??f.data;this.dbPath=u(t,`graph.db`),this.externalAdapter=!1}}async initialize(){if(this.externalAdapter){let e=this.getAdapter();this.createTables(e),this.migrateSchema(e),e.flush();return}let e=c(this.dbPath);t(e)||n(e,{recursive:!0}),this.adapter=await j(this.dbPath),this.configureAdapter(this.adapter),this.createTables(this.adapter),this.migrateSchema(this.adapter),this.adapter.flush()}configureAdapter(e){e.pragma(`journal_mode = WAL`),e.pragma(`foreign_keys = ON`)}createTables(e){e.exec(`
|
|
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
|
|
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 j(this.dbPath);this.configureAdapter(e),this.adapter=e}query(e,t=[]){return this.getAdapter().queryAll(e,t)}run(e,t=[]){this.getAdapter().run(e,t)}async upsertNode(e){await this.ensureOpen(),this.run(`INSERT INTO nodes (id, type, name, properties, source_record_id, source_path, created_at, community)
|
|
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?
|
|
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=`
|
|
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(
|
|
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=`
|
|
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(
|
|
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=>Ae(e))}async deleteNode(e){await this.ensureOpen();let t=this.getAdapter();t.exec(`BEGIN TRANSACTION`);try{this.run(`DELETE FROM edges WHERE from_id = ? OR to_id = ?`,[e,e]),this.run(`DELETE FROM nodes WHERE id = ?`,[e]),t.exec(`COMMIT`),t.flush()}catch(e){throw t.exec(`ROLLBACK`),e}}async deleteBySourcePath(e){await this.ensureOpen();let t=this.query(`SELECT id FROM nodes WHERE source_path = ?`,[e]);if(t.length===0)return 0;let n=this.getAdapter();n.exec(`BEGIN TRANSACTION`);try{for(let e of t)this.run(`DELETE FROM edges WHERE from_id = ? OR to_id = ?`,[e.id,e.id]);this.run(`DELETE FROM nodes WHERE source_path = ?`,[e]),n.exec(`COMMIT`),n.flush()}catch(e){throw n.exec(`ROLLBACK`),e}return t.length}async clear(){await this.ensureOpen();let e=this.getAdapter();e.exec(`BEGIN TRANSACTION`);try{this.run(`DELETE FROM process_steps`),this.run(`DELETE FROM processes`),this.run(`DELETE FROM edges`),this.run(`DELETE FROM nodes`),e.exec(`COMMIT`)}catch(t){throw e.exec(`ROLLBACK`),t}e.flush()}async getStats(){await this.ensureOpen();let e=this.query(`SELECT COUNT(*) as count FROM nodes`)[0]?.count??0,t=this.query(`SELECT COUNT(*) as count FROM edges`)[0]?.count??0,n=this.query(`SELECT type, COUNT(*) as count FROM nodes GROUP BY type`),r={};for(let e of n)r[e.type]=e.count;let i=this.query(`SELECT type, COUNT(*) as count FROM edges GROUP BY type`),a={};for(let e of i)a[e.type]=e.count;return{nodeCount:e,edgeCount:t,nodeTypes:r,edgeTypes:a}}async validate(){await this.ensureOpen();let e=await this.getStats(),t=this.query(`SELECT e.id AS edgeId,
|
|
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:
|
|
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 Ae(e){return{id:e.id,fromId:e.from_id,toId:e.to_id,type:e.type,weight:e.weight??1,confidence:e.confidence??1,properties:z(e.properties)}}function V(e){return{id:e.edge_id,fromId:e.from_id,toId:e.to_id,type:e.edge_type,weight:e.weight??1,confidence:e.edge_confidence??1,properties:z(e.edge_props??`{}`)}}function H(e){return{id:e.node_id,type:e.node_type,name:e.node_name,properties:z(e.node_props??`{}`),sourceRecordId:e.node_src_rec??void 0,sourcePath:e.node_src_path??void 0,createdAt:e.node_created,community:e.node_community??void 0}}function U(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n]<0?-e[n]:e[n];r>t&&(t=r)}let n=new Int8Array(e.length);if(t===0)return Buffer.from(n.buffer,n.byteOffset,n.byteLength);let r=127/t;for(let t=0;t<e.length;t++){let i=Math.round(e[t]*r);n[t]=i<-127?-127:i>127?127:i}return Buffer.from(n.buffer,n.byteOffset,n.byteLength)}const W=te(`sqlite-vec-store`);function je(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function G(e){return!e||e.length===0?[]:[...new Set(e.filter(e=>typeof e==`string`&&e.length>0))]}const K=`knowledge_meta`,q=`embedding_profile`,J=Object.freeze({additionalFilterMultiplier:4,baseOverfetchMultiplier:4,filteredOverfetchMultiplier:8,filteredRetryMultiplier:2,maxCandidateLimit:512,maxExpansionFactor:4,minFilteredCandidateLimit:16,tagFilterMultiplier:4});function Y(e){return{model:e.model,nativeDim:e.nativeDim,dimensions:e.dimensions,queryPrefix:e.queryPrefix}}function X(e){return JSON.stringify(Y(e))}var Z=class{adapter=null;externalAdapter;dbPath;embeddingDim;embeddingProfile;coarseDim;vectorEnabled=!1;ftsEnabled=!1;warnedVectorDisabled=!1;_draining=!1;_priorityQueue=[];_normalQueue=[];_onCloseHooks=[];constructor(e={}){let t=e.embeddingProfile?.dimensions??e.embeddingDim??p.dimensions;if(this.embeddingDim=t,this.embeddingProfile=Y(e.embeddingProfile??{model:p.model,nativeDim:p.nativeDim,dimensions:t,queryPrefix:p.queryPrefix}),this.coarseDim=Math.min(128,this.embeddingDim),e.adapter)this.adapter=e.adapter,this.externalAdapter=!0,this.dbPath=``;else{let t=P(e.path??`${ee.path}/aikit.db`,e.partition);this.dbPath=t.contentDbPath,this.externalAdapter=!1}}async initialize(){if(!this.adapter){let e=c(this.dbPath);t(e)||n(e,{recursive:!0}),this.adapter=await j(this.dbPath)}this.configureConnectionPragmas(),this.vectorEnabled=this.adapter.vectorCapable,g(this.adapter,_),this.createKnowledgeTable(),this.createKnowledgeTagsTable(),this.createFtsTable(),this.vectorEnabled?this.ensureVecTable():this.warnedVectorDisabled||(this.warnedVectorDisabled=!0,W.warn(`SqliteVecStore: vector search disabled (sqlite-vec extension not loaded). Hybrid search will return FTS-only results.`))}configureConnectionPragmas(){let e=this.getAdapter();e.pragma(`journal_mode = WAL`),e.pragma(`busy_timeout = 5000`)}getDiagnostics(){let e=this.adapter,t=e?e.constructor.name:`unknown`,n=null,r=this.externalAdapter?``:this.dbPath;if(r)try{let{statSync:e}=re(`node:fs`);n=e(r).size}catch{n=null}return{adapterType:t,vectorSearchEnabled:this.vectorEnabled,ftsEnabled:this.ftsEnabled,degradedMode:!this.vectorEnabled,dbPath:r,dbSizeBytes:n,embeddingDim:this.embeddingDim,vectorDtype:`int8`,embeddingModel:this.embeddingProfile.model,embeddingProfile:this.embeddingProfile}}createKnowledgeTable(){let e=this.getAdapter();e.exec(`
|
|
182
182
|
CREATE TABLE IF NOT EXISTS knowledge (
|
|
183
183
|
id TEXT PRIMARY KEY,
|
|
184
184
|
content TEXT NOT NULL,
|
|
@@ -209,14 +209,14 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
|
|
|
209
209
|
content,
|
|
210
210
|
tokenize = 'unicode61 remove_diacritics 2'
|
|
211
211
|
)
|
|
212
|
-
`),this.ftsEnabled=!0}catch(e){this.ftsEnabled=!1,
|
|
213
|
-
CREATE TABLE IF NOT EXISTS ${
|
|
212
|
+
`),this.ftsEnabled=!0}catch(e){this.ftsEnabled=!1,W.warn(`FTS5 unavailable — keyword search disabled`,h(e))}}createEmbeddingProfileTable(){this.getAdapter().exec(`
|
|
213
|
+
CREATE TABLE IF NOT EXISTS ${K} (
|
|
214
214
|
key TEXT PRIMARY KEY,
|
|
215
215
|
value TEXT NOT NULL
|
|
216
216
|
)
|
|
217
|
-
`)}getStoredEmbeddingProfile(){return this.getAdapter().queryAll(`SELECT value FROM ${
|
|
217
|
+
`)}getStoredEmbeddingProfile(){return this.getAdapter().queryAll(`SELECT value FROM ${K} WHERE key = ? LIMIT 1`,[q])[0]?.value??null}saveEmbeddingProfile(){this.getAdapter().run(`INSERT INTO ${K} (key, value)
|
|
218
218
|
VALUES (?, ?)
|
|
219
|
-
ON CONFLICT(key) DO UPDATE SET value = excluded.value`,[
|
|
219
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value`,[q,X(this.embeddingProfile)])}dropVectorTables(){let e=this.getAdapter();e.exec(`DROP TABLE IF EXISTS vec_knowledge_coarse`),e.exec(`DROP TABLE IF EXISTS vec_knowledge`)}ensureVecTable(){let e=this.getAdapter();this.createEmbeddingProfileTable();let t=X(this.embeddingProfile),n=this.getStoredEmbeddingProfile(),r=!1;n!==null&&n!==t&&(r=!0,W.warn(`Vec profile mismatch — dropping vector tables for recreation`,{storedProfile:n,activeProfile:t}));let i=e.queryAll(`SELECT name, sql FROM sqlite_master WHERE type='table' AND name='vec_knowledge'`);if(!r&&i.length>0){let e=i[0].sql??``,t=e.match(/(?:float|int8)\[(\d+)\]/i),n=t?Number(t[1]):null,a=/int8\[/i.test(e);(n!==null&&n!==this.embeddingDim||!a)&&(r=!0,W.warn(`Vec table schema mismatch — dropping for recreation`,{existingDim:n,newDim:this.embeddingDim,wasInt8:a}))}r&&this.dropVectorTables(),e.exec(`
|
|
220
220
|
CREATE VIRTUAL TABLE IF NOT EXISTS vec_knowledge USING vec0(
|
|
221
221
|
embedding int8[${this.embeddingDim}] distance_metric=cosine,
|
|
222
222
|
+knowledge_id TEXT
|
|
@@ -226,7 +226,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
|
|
|
226
226
|
embedding int8[${this.coarseDim}] distance_metric=cosine,
|
|
227
227
|
+knowledge_id TEXT
|
|
228
228
|
)
|
|
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
|
|
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 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,
|
|
230
230
|
totalChunks, startLine, endLine, fileHash, content_hash, indexedAt, origin, tags, category, version)
|
|
231
231
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
232
232
|
ON CONFLICT(id) DO UPDATE SET
|
|
@@ -244,7 +244,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
|
|
|
244
244
|
origin = excluded.origin,
|
|
245
245
|
tags = excluded.tags,
|
|
246
246
|
category = excluded.category,
|
|
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(
|
|
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(G(e.tags)),e.category??``,e.version])}replaceKnowledgeTags(e,t){let n=this.getAdapter(),r=G(t);if(n.run(`DELETE FROM knowledge_tags WHERE knowledge_id = ?`,[e]),r.length!==0)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(?), ?)`,[U(t[r]),i.id]),this.coarseDim<this.embeddingDim)){let e=t[r].subarray(0,this.coarseDim);n.run(`DELETE FROM vec_knowledge_coarse WHERE knowledge_id = ?`,[i.id]),n.run(`INSERT INTO vec_knowledge_coarse (embedding, knowledge_id) VALUES (vec_int8(?), ?)`,[U(e),i.id])}}n.exec(`COMMIT`)}catch(e){try{n.exec(`ROLLBACK`)}catch{}throw e}n.flush()}async search(e,t){if(e.length===0)return[];if(!this.vectorEnabled)return this.warnedVectorDisabled||(this.warnedVectorDisabled=!0,W.warn(`search() called but vector backend is disabled — returning []`)),[];let n=t?.limit??m.maxResults,r=t?.minScore??m.minScore,i;try{i=this.runAdaptiveVectorSearch(`vec_knowledge`,U(e),t)}catch(e){return W.warn(`vector search failed`,h(e)),[]}return this.rowsToSearchResults(i,r,n)}async coarseSearch(e,t){if(!this.vectorEnabled||this.coarseDim>=this.embeddingDim)return this.search(e,t);let n=t?.limit??m.maxResults,r=t?.minScore??m.minScore,i=e.subarray(0,this.coarseDim),a;try{a=this.runAdaptiveVectorSearch(`vec_knowledge_coarse`,U(i),t)}catch(n){return W.warn(`coarse vector search failed, falling back to full search`,h(n)),this.search(e,t)}return a.length===0?this.search(e,t):this.rowsToSearchResults(a,r,n)}async ftsSearch(e,t){if(!e||e.trim().length===0||!this.ftsEnabled)return[];let n=this.getAdapter(),r=t?.limit??m.maxResults,i=this.buildFilterSqlSuffix(t,!0),a=`
|
|
248
248
|
SELECT k.*, bm25(knowledge_fts) AS _bm25
|
|
249
249
|
FROM knowledge_fts
|
|
250
250
|
JOIN knowledge k ON k.id = knowledge_fts.id
|
|
@@ -252,7 +252,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
|
|
|
252
252
|
${i.sql}
|
|
253
253
|
ORDER BY _bm25 ASC
|
|
254
254
|
LIMIT ?
|
|
255
|
-
`,o;try{let t=
|
|
255
|
+
`,o;try{let t=Me(e);o=n.queryAll(a,[t,...i.params,r])}catch(e){return W.warn(`fts search failed`,h(e)),[]}return o.map(e=>({record:this.fromRow(e),score:Ne(e._bm25)}))}async getById(e){let t=this.getAdapter().queryAll(`SELECT * FROM knowledge WHERE id = ? LIMIT 1`,[e]);return t.length===0?null:this.fromRow(t[0])}async deleteBySourcePath(e){return this.enqueueWrite(()=>this._deleteBySourcePathImpl(e))}async _deleteBySourcePathImpl(e){let t=this.getAdapter(),n=t.queryAll(`SELECT id FROM knowledge WHERE sourcePath = ?`,[e]);if(n.length===0)return 0;t.exec(`BEGIN`);try{for(let{id:e}of n)this.vectorEnabled&&(t.run(`DELETE FROM vec_knowledge WHERE knowledge_id = ?`,[e]),this.coarseDim<this.embeddingDim&&t.run(`DELETE FROM vec_knowledge_coarse WHERE knowledge_id = ?`,[e])),t.run(`DELETE FROM knowledge_tags WHERE knowledge_id = ?`,[e]),this.ftsEnabled&&t.run(`DELETE FROM knowledge_fts WHERE id = ?`,[e]);t.run(`DELETE FROM knowledge WHERE sourcePath = ?`,[e]),t.exec(`COMMIT`)}catch(e){try{t.exec(`ROLLBACK`)}catch{}throw e}return t.flush(),n.length}async deleteById(e){return this.enqueueWrite(()=>this._deleteByIdImpl(e))}async deleteByIdInteractive(e){return this.enqueueWrite(()=>this._deleteByIdImpl(e),!0)}async _deleteByIdImpl(e){let t=this.getAdapter();if(t.queryAll(`SELECT id FROM knowledge WHERE id = ? LIMIT 1`,[e]).length===0)return!1;t.exec(`BEGIN`);try{this.vectorEnabled&&(t.run(`DELETE FROM vec_knowledge WHERE knowledge_id = ?`,[e]),this.coarseDim<this.embeddingDim&&t.run(`DELETE FROM vec_knowledge_coarse WHERE knowledge_id = ?`,[e])),t.run(`DELETE FROM knowledge_tags WHERE knowledge_id = ?`,[e]),this.ftsEnabled&&t.run(`DELETE FROM knowledge_fts WHERE id = ?`,[e]),t.run(`DELETE FROM knowledge WHERE id = ?`,[e]),t.exec(`COMMIT`)}catch(e){try{t.exec(`ROLLBACK`)}catch{}throw e}return t.flush(),!0}async getBySourcePath(e){return this.getAdapter().queryAll(`SELECT * FROM knowledge WHERE sourcePath = ? ORDER BY chunkIndex ASC`,[e]).map(e=>this.fromRow(e))}async getStats(){let e=this.getAdapter(),t=e.queryAll(`SELECT COUNT(*) AS n FROM knowledge`)[0]?.n??0;if(t===0)return{totalRecords:0,totalFiles:0,contentTypeBreakdown:{},lastIndexedAt:null,storeBackend:`sqlite-vec`,embeddingModel:this.embeddingProfile.model};let n=e.queryAll(`SELECT COUNT(DISTINCT sourcePath) AS n FROM knowledge`),r=e.queryAll(`SELECT contentType, COUNT(*) AS n FROM knowledge GROUP BY contentType`),i=e.queryAll(`SELECT MAX(indexedAt) AS ts FROM knowledge`),a={};for(let e of r)a[e.contentType]=e.n;return{totalRecords:t,totalFiles:n[0]?.n??0,contentTypeBreakdown:a,lastIndexedAt:i[0]?.ts??null,storeBackend:`sqlite-vec`,embeddingModel:this.embeddingProfile.model}}async listSourcePaths(){return this.getAdapter().queryAll(`SELECT DISTINCT sourcePath FROM knowledge ORDER BY sourcePath`).map(e=>e.sourcePath)}async createFtsIndex(){this.createFtsTable()}async dropTable(){return this.enqueueWrite(()=>this._dropTableImpl())}async _dropTableImpl(){let e=this.getAdapter();this.ftsEnabled&&e.exec(`DROP TABLE IF EXISTS knowledge_fts`),this.vectorEnabled&&this.dropVectorTables(),e.exec(`DROP TABLE IF EXISTS ${K}`),e.exec(`DROP TABLE IF EXISTS knowledge_tags`),e.exec(`DROP TABLE IF EXISTS knowledge`),e.flush(),this.createKnowledgeTable(),this.createKnowledgeTagsTable(),this.createFtsTable(),this.vectorEnabled&&this.ensureVecTable()}releaseMemory(){if(this.adapter)try{this.adapter.exec(`PRAGMA shrink_memory`),this.adapter.exec(`PRAGMA wal_checkpoint(TRUNCATE)`)}catch{}}onBeforeClose(e){this._onCloseHooks.push(e)}async close(){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??m.maxResults;if(r<=0)return[];let i=this.buildFilterSqlSuffix(n),a=this.buildVectorSearchPlan(r,i.profile),o=a.initialCandidateLimit,s=this.queryVectorRows(e,t,i,o,r);for(;a.hasFilters&&s.length<r&&o<a.maxCandidateLimit;)o=Math.min(a.maxCandidateLimit,Math.max(o+r,o*J.filteredRetryMultiplier)),s=this.queryVectorRows(e,t,i,o,r);return s}queryVectorRows(e,t,n,r,i){let a=this.getAdapter(),o=`
|
|
256
256
|
SELECT k.*, v.distance AS _distance
|
|
257
257
|
FROM (
|
|
258
258
|
SELECT knowledge_id, distance
|
|
@@ -265,11 +265,11 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
|
|
|
265
265
|
${n.sql}
|
|
266
266
|
ORDER BY v.distance ASC
|
|
267
267
|
LIMIT ?
|
|
268
|
-
`;return a.queryAll(o,[t,r,...n.params,i])}buildVectorSearchPlan(e,t){let n=Math.max(1,e*
|
|
268
|
+
`;return a.queryAll(o,[t,r,...n.params,i])}buildVectorSearchPlan(e,t){let n=Math.max(1,e*J.baseOverfetchMultiplier);if(!t.hasFilters)return{hasFilters:!1,initialCandidateLimit:n,maxCandidateLimit:n};let r=Math.max(0,t.filterCount-1),i=J.filteredOverfetchMultiplier+r*J.additionalFilterMultiplier+(t.tagCount>0?J.tagFilterMultiplier:0),a=Math.min(J.maxCandidateLimit,Math.max(e*i,J.minFilteredCandidateLimit));return{hasFilters:!0,initialCandidateLimit:a,maxCandidateLimit:Math.min(J.maxCandidateLimit,Math.max(a*J.maxExpansionFactor,e*J.filteredOverfetchMultiplier))}}rowsToSearchResults(e,t,n){return e.map(e=>({record:this.fromRow(e),score:1-(e._distance??1)})).filter(e=>e.score>=t).slice(0,n)}buildFilterSqlSuffix(e,t=!1){if(!e)return{sql:``,params:[],profile:{filterCount:0,hasFilters:!1,tagCount:0}};let n=[],r=[],i=0,a=0;if(e.contentType&&(n.push(`k.contentType = ?`),r.push(e.contentType),i++),e.sourceType){let t=ne(e.sourceType);t.length>0&&(n.push(`k.contentType IN (${t.map(()=>`?`).join(`, `)})`),r.push(...t),i++)}if(e.origin&&(n.push(`k.origin = ?`),r.push(e.origin),i++),e.category&&(n.push(`k.category = ?`),r.push(e.category),i++),e.tags&&e.tags.length>0){let t=e.tags.map(()=>`?`).join(`, `);n.push(`EXISTS (SELECT 1 FROM knowledge_tags kt WHERE kt.knowledge_id = k.id AND kt.tag IN (${t}))`),r.push(...e.tags),i++,a=e.tags.length}if(n.length===0)return{sql:``,params:[],profile:{filterCount:0,hasFilters:!1,tagCount:0}};let o=n.join(` AND `);return{sql:t?`AND ${o}`:`WHERE ${o}`,params:r,profile:{filterCount:i,hasFilters:!0,tagCount:a}}}fromRow(e){return{id:e.id,content:e.content,sourcePath:e.sourcePath,contentType:e.contentType,headingPath:e.headingPath||void 0,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,startLine:e.startLine,endLine:e.endLine,fileHash:e.fileHash,contentHash:e.content_hash||void 0,indexedAt:e.indexedAt,origin:e.origin,tags:je(e.tags),category:e.category||void 0,version:e.version}}};function Me(e){let t=e.replace(/["'()*:^-]/g,` `).trim();return t?t.split(/\s+/).filter(e=>e.length>0).map(e=>`"${e}"`).join(` OR `):`""`}function Ne(e){return e==null||Number.isNaN(e)?0:1-Math.exp(-Math.abs(e)/5)}function Q(e){let t=e.includes(`T`)?e:`${e.replace(` `,`T`)}Z`,n=new Date(t);return Number.isNaN(n.getTime())?t:n.toISOString()}function $(e){return`queryAll`in e&&`run`in e}function Pe(e){return{get(t){return e.queryAll(`SELECT key, value, updated_at AS updatedAt FROM stash WHERE key = ?`,[t])[0]},set(t,n){e.run(`INSERT INTO stash (key, value)
|
|
269
269
|
VALUES (?, ?)
|
|
270
270
|
ON CONFLICT(key) DO UPDATE SET
|
|
271
271
|
value = excluded.value,
|
|
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
|
|
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 Fe(e){return{save(t,n,r,i){e.run(`INSERT INTO checkpoints (id, label, data, notes)
|
|
273
273
|
VALUES (?, ?, ?, ?)
|
|
274
274
|
ON CONFLICT(id) DO UPDATE SET
|
|
275
275
|
label = excluded.label,
|
|
@@ -296,7 +296,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
|
|
|
296
296
|
ORDER BY created_at DESC, id DESC
|
|
297
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
|
|
298
298
|
FROM checkpoints
|
|
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
|
|
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 Ie(e){return{create(t,n){e.run(`INSERT INTO sessions (session_id, metadata)
|
|
300
300
|
VALUES (?, ?)
|
|
301
301
|
ON CONFLICT(session_id) DO UPDATE SET
|
|
302
302
|
last_activity = datetime('now'),
|
|
@@ -312,7 +312,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
|
|
|
312
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
|
|
313
313
|
FROM sessions
|
|
314
314
|
WHERE last_activity < datetime('now', ?)`,[n])[0]?.count??0;return r>0&&e.run(`DELETE FROM sessions
|
|
315
|
-
WHERE last_activity < datetime('now', ?)`,[n]),r}}}function
|
|
315
|
+
WHERE last_activity < datetime('now', ?)`,[n]),r}}}function Le(e){return{post(t,n,r,i,a=300){return e.run(`INSERT INTO signals (workspace, key, value, agent, ttl_seconds, expires_at)
|
|
316
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,
|
|
317
317
|
workspace,
|
|
318
318
|
key,
|
|
@@ -334,7 +334,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
|
|
|
334
334
|
WHERE workspace = ?
|
|
335
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
|
|
336
336
|
FROM signals
|
|
337
|
-
WHERE expires_at <= datetime('now')`)[0]?.count??0;return t>0&&e.run(`DELETE FROM signals WHERE expires_at <= datetime('now')`),t}}}function
|
|
337
|
+
WHERE expires_at <= datetime('now')`)[0]?.count??0;return t>0&&e.run(`DELETE FROM signals WHERE expires_at <= datetime('now')`),t}}}function Re(e){return{upsert(t,n,r,i,a=10){e.run(`INSERT INTO leases (resource, holder, intent, workspace, ttl_minutes, expires_at)
|
|
338
338
|
VALUES (?, ?, ?, ?, ?, datetime('now', '+' || ? || ' minutes'))
|
|
339
339
|
ON CONFLICT(workspace, resource) DO UPDATE SET
|
|
340
340
|
holder = excluded.holder,
|
|
@@ -359,7 +359,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
|
|
|
359
359
|
WHERE workspace = ?
|
|
360
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
|
|
361
361
|
FROM leases
|
|
362
|
-
WHERE expires_at <= datetime('now')`)[0]?.count??0;return t>0&&e.run(`DELETE FROM leases WHERE expires_at <= datetime('now')`),t}}}function
|
|
362
|
+
WHERE expires_at <= datetime('now')`)[0]?.count??0;return t>0&&e.run(`DELETE FROM leases WHERE expires_at <= datetime('now')`),t}}}function ze(e){return{create(t,n){e.run(`INSERT INTO memory_meta (entry_id, tier)
|
|
363
363
|
VALUES (?, ?)
|
|
364
364
|
ON CONFLICT(entry_id) DO NOTHING`,[t,n??`working`])},get(t){return e.queryAll(`SELECT entry_id AS entryId,
|
|
365
365
|
tier,
|
|
@@ -395,11 +395,11 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
|
|
|
395
395
|
ORDER BY retention_score ASC,
|
|
396
396
|
COALESCE(last_accessed_at, created_at) ASC,
|
|
397
397
|
entry_id ASC
|
|
398
|
-
${a}`,r)}}}function
|
|
398
|
+
${a}`,r)}}}function Be(e){let t=e.prepare(`SELECT key, value, updated_at AS updatedAt FROM stash WHERE key = ?`),n=e.prepare(`INSERT INTO stash (key, value)
|
|
399
399
|
VALUES (?, ?)
|
|
400
400
|
ON CONFLICT(key) DO UPDATE SET
|
|
401
401
|
value = excluded.value,
|
|
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
|
|
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 Ve(e){let t=e.prepare(`INSERT INTO checkpoints (id, label, data, notes)
|
|
403
403
|
VALUES (?, ?, ?, ?)
|
|
404
404
|
ON CONFLICT(id) DO UPDATE SET
|
|
405
405
|
label = excluded.label,
|
|
@@ -426,7 +426,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
|
|
|
426
426
|
ORDER BY created_at DESC, id DESC
|
|
427
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
|
|
428
428
|
FROM checkpoints
|
|
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
|
|
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 He(e){let t=e.prepare(`INSERT INTO sessions (session_id, metadata)
|
|
430
430
|
VALUES (?, ?)
|
|
431
431
|
ON CONFLICT(session_id) DO UPDATE SET
|
|
432
432
|
last_activity = datetime('now'),
|
|
@@ -442,7 +442,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
|
|
|
442
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
|
|
443
443
|
FROM sessions
|
|
444
444
|
WHERE last_activity < datetime('now', ?)`),c=e.prepare(`DELETE FROM sessions
|
|
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
|
|
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 Ue(e){let t=e.prepare(`INSERT INTO signals (workspace, key, value, agent, ttl_seconds, expires_at)
|
|
446
446
|
VALUES (?, ?, ?, ?, ?, datetime('now', '+' || ? || ' seconds'))`),n=e.prepare(`SELECT id,
|
|
447
447
|
workspace,
|
|
448
448
|
key,
|
|
@@ -464,7 +464,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
|
|
|
464
464
|
WHERE workspace = ?
|
|
465
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
|
|
466
466
|
FROM signals
|
|
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
|
|
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 We(e){let t=e.prepare(`INSERT INTO leases (resource, holder, intent, workspace, ttl_minutes, expires_at)
|
|
468
468
|
VALUES (?, ?, ?, ?, ?, datetime('now', '+' || ? || ' minutes'))
|
|
469
469
|
ON CONFLICT(workspace, resource) DO UPDATE SET
|
|
470
470
|
holder = excluded.holder,
|
|
@@ -489,7 +489,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
|
|
|
489
489
|
WHERE workspace = ?
|
|
490
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
|
|
491
491
|
FROM leases
|
|
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
|
|
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 Ge(e){let t=e.prepare(`INSERT INTO memory_meta (entry_id, tier)
|
|
493
493
|
VALUES (?, ?)
|
|
494
494
|
ON CONFLICT(entry_id) DO NOTHING`),n=e.prepare(`SELECT entry_id AS entryId,
|
|
495
495
|
tier,
|
|
@@ -604,7 +604,7 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
|
|
|
604
604
|
AND retention_score < ?
|
|
605
605
|
ORDER BY retention_score ASC,
|
|
606
606
|
COALESCE(last_accessed_at, created_at) ASC,
|
|
607
|
-
entry_id ASC`),
|
|
607
|
+
entry_id ASC`),ee=e.prepare(`SELECT entry_id AS entryId,
|
|
608
608
|
tier,
|
|
609
609
|
retention_score AS retentionScore,
|
|
610
610
|
access_count AS accessCount,
|
|
@@ -619,4 +619,4 @@ import{createRequire as e}from"node:module";import{existsSync as t,mkdirSync as
|
|
|
619
619
|
ORDER BY retention_score ASC,
|
|
620
620
|
COALESCE(last_accessed_at, created_at) ASC,
|
|
621
621
|
entry_id ASC
|
|
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?
|
|
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?ee.all(e.tier,e.belowScore,e.limit):e?.tier!==void 0&&e?.belowScore!==void 0?m.all(e.tier,e.belowScore):e?.tier!==void 0&&e?.limit!==void 0?d.all(e.tier,e.limit):e?.tier===void 0?e?.belowScore!==void 0&&e?.limit!==void 0?p.all(e.belowScore,e.limit):e?.belowScore===void 0?e?.limit===void 0?c.all():l.all(e.limit):f.all(e.belowScore):u.all(e.tier)}}}function Ke(e){let t=$(e)?Pe(e):Be(e),n=$(e)?Le(e):Ue(e),r=$(e)?Re(e):We(e),i=$(e)?Ie(e):He(e),a=$(e)?Fe(e):Ve(e),o=$(e)?ze(e):Ge(e);return{stashGet(e){return t.get(e)?.value},stashSet(e,n){t.set(e,n)},stashList(){return t.list()},stashDelete(e){return t.has(e)?(t.delete(e),!0):!1},stashClear(){t.clear()},signalPost(e,t,r,i,a){return n.post(e,t,r,i,a)},signalGet(e,t){return n.cleanExpired(),n.get(e,t).map(e=>({id:e.id,value:e.value,createdAt:Q(e.createdAt),expiresAt:Q(e.expiresAt),...e.agent?{agent:e.agent}:{}}))},signalList(e){return n.cleanExpired(),n.list(e).map(e=>({id:e.id,key:e.key,value:e.value,createdAt:Q(e.createdAt),...e.agent?{agent:e.agent}:{}}))},signalClear(e,t){return n.cleanExpired(),n.clear(e,t)},signalCleanExpired(){return n.cleanExpired()},leaseAcquire(e,t,n,i,a){r.cleanExpired();let o=r.get(e,n);return o&&o.holder!==t?!1:(r.upsert(e,t,n,i??o?.intent??void 0,a),!0)},leaseRelease(e,t,n){r.cleanExpired();let i=r.get(e,n);return!i||i.holder!==t?!1:(r.delete(e,n),!0)},leaseGet(e,t){r.cleanExpired();let n=r.get(e,t);if(n)return{resource:n.resource,holder:n.holder,workspace:n.workspace,acquiredAt:Q(n.acquiredAt),expiresAt:Q(n.expiresAt),...n.intent?{intent:n.intent}:{}}},leaseList(e){return r.cleanExpired(),r.list(e).map(e=>({resource:e.resource,holder:e.holder,acquiredAt:Q(e.acquiredAt),expiresAt:Q(e.expiresAt),...e.intent?{intent:e.intent}:{}}))},leaseCleanExpired(){return r.cleanExpired()},sessionCreate(e,t){i.create(e,t?JSON.stringify(t):void 0)},sessionTouch(e){i.touch(e)},sessionGet(e){let t=i.get(e);if(t)return{sessionId:t.sessionId,createdAt:t.createdAt,lastActivity:t.lastActivity,...t.metadata?{metadata:t.metadata}:{}}},sessionList(){return i.list().map(e=>({sessionId:e.sessionId,createdAt:e.createdAt,lastActivity:e.lastActivity}))},sessionDelete(e){return i.has(e)?(i.delete(e),!0):!1},sessionDeleteStale(e){return i.deleteStale(e)},checkpointSave(e,t,n,r){a.save(e,t,n,r)},checkpointLoad(e){let t=a.get(e);if(t)return{id:t.id,label:t.label,data:t.data,createdAt:t.createdAt,...t.notes?{notes:t.notes}:{}}},checkpointList(e,t){return a.list(e,t).map(e=>({id:e.id,label:e.label,createdAt:e.createdAt,...e.notes?{notes:e.notes}:{}}))},checkpointLatest(e){let t=a.latest(e);if(t)return{id:t.id,label:t.label,data:t.data,createdAt:t.createdAt,...t.notes?{notes:t.notes}:{}}},checkpointDelete(e){return a.has(e)?(a.delete(e),!0):!1},checkpointDiff(e,t){let n=a.get(e),r=a.get(t);if(!(!n||!r))return{from:n.data,to:r.data}},checkpointHistory(e,t){return a.list(e,t).map(e=>({id:e.id,label:e.label,createdAt:e.createdAt,...e.notes?{notes:e.notes}:{}}))},checkpointGc(e,t){return a.gc(e,t)},memoryMetaCreate(e,t){o.create(e,t)},memoryMetaGet(e){return o.get(e)},memoryMetaTouch(e){o.touch(e)},memoryMetaUpdateScore(e,t){o.updateScore(e,t)},memoryMetaUpdateConfidence(e,t){o.updateConfidence(e,t)},memoryMetaUpdateTier(e,t){o.updateTier(e,t)},memoryMetaSetSuperseded(e,t){o.setSuperseded(e,t)},memoryMetaList(e){return o.list(e)}}}async function qe(e){switch(e.backend){case`lancedb`:{let{LanceStore:t}=await import(`./lance-store-B1Gim3h9.js`);return new t({path:e.path})}case`sqlite-vec`:return new Z({path:e.path,adapter:e.adapter,embeddingDim:e.embeddingDim,embeddingProfile:e.embeddingProfile,partition:e.partition});default:{let t=e.backend;throw Error(`Unknown store backend: "${t}". Supported: lancedb, sqlite-vec`)}}}export{N as CONTROL_TABLES,ke as SqliteGraphStore,Z as SqliteVecStore,_ as allMigrations,_e as createSqlJsAdapter,j as createSqliteAdapter,Ke as createStateStore,qe as createStore,ye as getTablePartition,Oe as migrateToSplitState,be as readStatePartitionConfigFromEnv,P as resolveStatePartitionConfig,g as runMigrations};
|
|
@@ -12,7 +12,7 @@ import{mkdir as e,readFile as t,readdir as n,rm as r,stat as i,writeFile as a}fr
|
|
|
12
12
|
### Patterns Detected
|
|
13
13
|
`),n.push(`| Pattern | Confidence | Count |`),n.push(`|---------|-----------|-------|`);for(let t of e.patterns)n.push(`| ${t.name} | ${t.confidence} | ${t.count} |`)}else t===`normal`&&n.push(`\n**Patterns:** ${e.patterns.map(e=>e.name).join(`, `)}`);return n.join(`
|
|
14
14
|
`)}const bt=/^[a-zA-Z0-9_./\-~^@{}]+$/;function xt(e){let{from:t,to:n=`HEAD`,format:r=`grouped`,includeBreaking:i=!0,cwd:a=process.cwd()}=e;if(!bt.test(t))throw Error(`Invalid git ref: ${t}`);if(!bt.test(n))throw Error(`Invalid git ref: ${n}`);let o;try{o=w(`git`,[`log`,`${t}..${n}`,`--format=%H%s%b%an%ai`],{cwd:a,encoding:`utf8`,maxBuffer:10*1024*1024,timeout:3e4})}catch{throw Error(`Git log failed. Ensure "${t}" and "${n}" are valid refs.`)}let s=o.split(``).map(e=>e.trim()).filter(Boolean).map(e=>{let[t=``,n=``,r=``,i=``,a=``]=e.split(``),o=n.match(/^(\w+)(?:\(([^)]*)\))?(!)?:\s*(.+)/);return{hash:t.slice(0,8),type:o?.[1]??`other`,scope:o?.[2]??``,subject:o?.[4]??n,body:r.trim(),author:i.trim(),date:a.trim().split(` `)[0],breaking:!!(o?.[3]||/BREAKING[\s-]CHANGE/i.test(r))}}),c={},l=0;for(let e of s)c[e.type]=(c[e.type]??0)+1,e.breaking&&l++;return{entries:s,markdown:St(s,r,i),stats:{total:s.length,breaking:l,types:c}}}function St(e,t,n){let r=[`# Changelog`,``];if(n){let t=e.filter(e=>e.breaking);if(t.length>0){r.push(`## Breaking Changes`,``);for(let e of t)r.push(`- ${e.subject} (${e.hash})`);r.push(``)}}if(t===`grouped`){let t={};for(let n of e)t[n.type]||(t[n.type]=[]),t[n.type].push(n);let n=[`feat`,`fix`,`refactor`,`perf`,`test`,`docs`,`chore`],i={feat:`Features`,fix:`Bug Fixes`,refactor:`Refactoring`,perf:`Performance`,test:`Tests`,docs:`Documentation`,chore:`Chores`,other:`Other`};for(let e of[...n,...Object.keys(t).filter(e=>!n.includes(e))])if(t[e]?.length){r.push(`## ${i[e]??e}`,``);for(let n of t[e]){let e=n.scope?`**${n.scope}:** `:``;r.push(`- ${e}${n.subject} (${n.hash})`)}r.push(``)}}else if(t===`chronological`)for(let t of e){let e=t.scope?`(${t.scope}) `:``;r.push(`- \`${t.date}\` ${t.type}: ${e}${t.subject} (${t.hash})`)}else{let t={};for(let n of e){let e=n.scope||`general`;t[e]||(t[e]=[]),t[e].push(n)}for(let[e,n]of Object.entries(t)){r.push(`## ${e}`,``);for(let e of n)r.push(`- ${e.type}: ${e.subject} (${e.hash})`);r.push(``)}}return r.join(`
|
|
15
|
-
`)}const Ct=/^[a-z0-9][a-z0-9-]*$/,wt=new Map;function Tt(e){let t=f(e),n=wt.get(t);if(n!==void 0)return n;try{return w(`git`,[`rev-parse`,`--git-dir`],{cwd:t,timeout:1e4,encoding:`utf8`}),wt.set(t,!0),!0}catch{return wt.set(t,!1),!1}}function Et(e,t,n,r){try{return w(`git`,e,{cwd:t,timeout:1e4,input:n,encoding:`utf8`,stdio:[`pipe`,`pipe`,`pipe`]}).trim()}catch(t){r||console.warn(`Git operation failed (${e.join(` `)}): ${t instanceof Error?t.message:String(t)}`);return}}function Dt(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,60)||`untitled`}function Ot(e,t,n,r,i){let a=Et([`hash-object`,`-w`,`--stdin`],i,n);if(!a)return;let o=Et([`mktree`],i,`100644 blob ${a}\t${t}\n`);if(!o)return;let s=Et([`rev-parse`,e],i,void 0,!0),c=[`commit-tree`,o];s&&c.push(`-p`,s),c.push(`-m`,r);let l=Et(c,i);if(l)return Et([`update-ref`,e,l],i)===void 0?void 0:l}function kt(){wt.clear()}const At=new Set;function jt(e){let t=Dt(e);return t===`untitled`?`checkpoint`:t}function Mt(e={}){let t=e.cwd??process.cwd();return f(e.stateDir??B(t),`checkpoints`)}function Nt(e){return`${e}.bak`}function Pt(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Ft(e,t,n){if(typeof e!=`string`||e.length<1||e.length>120)throw Error(`Checkpoint label must be 1-120 characters.`);if(!Pt(t))throw Error(`Checkpoint data must be a JSON-serializable object.`);let r;try{r=JSON.stringify(t)}catch{throw Error(`Checkpoint data must be a JSON-serializable object.`)}if(Buffer.byteLength(r,`utf8`)>5e5)throw Error(`Checkpoint data must be 500KB or less when serialized.`);if(n?.notes!==void 0&&Buffer.byteLength(n.notes,`utf8`)>1e4)throw Error(`Checkpoint notes must be 10KB or less.`);return r}function It(e,t){try{let t=JSON.parse(e);if(!Pt(t))throw Error(`Checkpoint data must deserialize to an object.`);return t}catch(e){console.warn(`Corrupt checkpoint payload ${t}: ${e instanceof Error?e.message:String(e)}`);return}}function Lt(e){let t=It(e.data,e.id);if(t)return{id:e.id,label:e.label,createdAt:e.createdAt,data:t,...e.notes?{notes:e.notes}:{}}}function Rt(e){return{id:e.id,label:e.label,createdAt:e.createdAt,...e.notes?{notes:e.notes}:{}}}function zt(e,t={}){let n=Mt(t);if(At.has(n)||!M(n)){At.add(n);return}try{let t=F(n).filter(e=>e.endsWith(`.json`));for(let r of t){let t=f(n,r);try{let n=P(t,`utf-8`),i=JSON.parse(n),a=typeof i.id==`string`&&i.id.length>0?i.id:o(r,`.json`);if(typeof i.label!=`string`)throw Error(`Missing checkpoint label.`);if(!Pt(i.data))throw Error(`Checkpoint data must be a JSON object.`);let s=Ft(i.label,i.data,{notes:i.notes});e.checkpointSave(a,i.label,s,i.notes)}catch(e){console.warn(`Legacy checkpoint import failed for ${t}: ${e instanceof Error?e.message:String(e)}`)}}let r=Nt(n);M(r)&&ie(r,{recursive:!0,force:!0}),I(n,r),At.add(n)}catch(e){console.warn(`Legacy checkpoint import failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}}function Bt(e,t,n,r){zt(e,{cwd:r?.cwd});let i=Ft(t,n,{notes:r?.notes}),a=`${Date.now()}-${jt(t)}`;e.checkpointSave(a,t,i,r?.notes);let o=Vt(e,a,{cwd:r?.cwd});if(!o)throw Error(`Failed to load saved checkpoint "${a}".`);return o}function Vt(e,t,n={}){zt(e,n);let r=e.checkpointLoad(t);if(r)return Lt(r)}function Ht(e,t={}){return zt(e,t),e.checkpointList(t.label,t.limit).map(Rt)}function Ut(e,t={}){zt(e,t);let n=e.checkpointLatest(t.label);if(n)return Lt(n)}function Wt(e,t,n,r={}){zt(e,r);let i=e.checkpointDiff(t,n);if(!i)return;let a=It(i.from,t),o=It(i.to,n);if(!a||!o)return;let s=new Set(Object.keys(a)),c=new Set(Object.keys(o));return{fromId:t,toId:n,added:[...c].filter(e=>!s.has(e)),removed:[...s].filter(e=>!c.has(e)),modified:[...s].filter(e=>c.has(e)).filter(e=>JSON.stringify(a[e])!==JSON.stringify(o[e]))}}function Gt(e,t,n){return zt(e,{cwd:n?.cwd}),e.checkpointHistory(t,n?.limit??20).map(Rt)}function Kt(e,t){zt(e,{cwd:t?.cwd});let n=t?.keepLast??10,r=t?.dryRun??!0,i=t?.maxAgeDays===void 0?void 0:Date.now()-t.maxAgeDays*864e5,a=t?.label?jt(t.label):void 0,o=t?.label?e.checkpointHistory(t.label):e.checkpointList(),s=new Map;for(let e of o){let t=jt(e.label);if(a&&t!==a)continue;let n=s.get(t);n?n.push(e):s.set(t,[e])}let c=[],l=0;for(let e of s.values())e.forEach((e,t)=>{let r=Date.parse(e.createdAt);if(t<n&&!(i!==void 0&&!Number.isNaN(r)&&r<i)){l+=1;return}c.push(e.id)});if(!r)for(let t of c)e.checkpointDelete(t);return{deleted:c.length,kept:l,labels:[...s.keys()],deletedIds:c}}const qt=[`.ts`,`.tsx`,`.js`,`.jsx`],Jt=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,z.state]);function Yt(e){return e.replace(/\\/g,`/`)}function Xt(e){return e.replace(/[.+^${}()|[\]\\]/g,`\\$&`)}function Zt(e,t){let n=Yt(e),r=Yt(t).trim();if(!r)return!1;let i=Xt(r).replace(/\*\*/g,`::DOUBLE_STAR::`).replace(/\*/g,`[^/]*`).replace(/\?/g,`[^/]`).replace(/::DOUBLE_STAR::/g,`.*`);return RegExp(`^${i}$`).test(n)}function Qt(e,t,n){return t.some(t=>Zt(e,t)?!0:n?Zt(`${e}/`,t):!1)}async function $t(e,t,r,a){let o=[],s=t.map(e=>e.toLowerCase()),l=Math.max(0,Math.min(a?.maxFiles??1e4,5e4)),f=Math.max(0,Math.min(a?.maxDepth??20,50));async function p(t,a){if(a>f||o.length>=l)return;let m=await n(t);for(let n of m){if(o.length>=l)return;if(Jt.has(n))continue;let f=u(t,n),m=await i(f),h=Yt(d(e,f));if(m.isDirectory()){Qt(h,r,!0)||await p(f,a+1);continue}Qt(h,r,!1)||s.includes(c(n).toLowerCase())&&o.push(f)}}return await p(e,0),o.sort((e,t)=>e.localeCompare(t)),o}const en=z.restorePoints;function tn(){let e=u(process.cwd(),en);return M(e)||N(e,{recursive:!0}),e}function nn(e,t,n){let r=tn(),i=`${Date.now()}-${e}`,a={id:i,timestamp:new Date().toISOString(),operation:e,files:t,description:n};R(u(r,`${i}.json`),`${JSON.stringify(a,null,2)}\n`,`utf-8`);let o=F(r).filter(e=>e.endsWith(`.json`)).sort();for(;o.length>50;){let e=o.shift();if(!e)break;try{ae(u(r,e))}catch{}}return i}function rn(){let e=u(process.cwd(),en);return M(e)?F(e).filter(e=>e.endsWith(`.json`)).sort().reverse().map(t=>{try{return JSON.parse(P(u(e,t),`utf-8`))}catch(n){return console.debug(`Skipping corrupt restore point ${u(e,t)}: ${n instanceof Error?n.message:String(n)}`),null}}).filter(e=>e!==null):[]}async function an(e){let t=u(u(process.cwd(),en),`${e}.json`);if(!M(t))throw Error(`Restore point not found: ${e}`);let n=JSON.parse(P(t,`utf-8`)),r=[];for(let e of n.files){let t=s(e.path);M(t)||N(t,{recursive:!0}),await a(e.path,e.content,`utf-8`),r.push(e.path)}return r}function on(e){return e.replace(/\\/g,`/`)}async function sn(e){let{rootPath:n,rules:r,extensions:i=qt,exclude:o=[],dryRun:s=!1}=e,c=r.map(e=>({...e,regex:new RegExp(e.pattern,`g`)})),l=await $t(n,i,o),u=[],f=new Set,p=0,m=[];for(let e of l){let r=on(d(n,e)),i=await t(e,`utf-8`),o=i.split(/\r?\n/),l=!1;for(let[e,t]of c.entries())if(!(t.fileFilter&&!Zt(r,t.fileFilter)))for(let n=0;n<o.length;n++){let i=o[n];t.regex.lastIndex=0;let a=i.replace(t.regex,t.replacement);i!==a&&(o[n]=a,l=!0,f.add(e),u.push({rule:t.description,path:r,line:n+1,before:i,after:a}))}l&&(p+=1,s||(m.push({path:e,content:i}),await a(e,o.join(`
|
|
15
|
+
`)}const Ct=/^[a-z0-9][a-z0-9-]*$/,wt=new Map;function Tt(e){let t=f(e),n=wt.get(t);if(n!==void 0)return n;try{return w(`git`,[`rev-parse`,`--git-dir`],{cwd:t,timeout:1e4,encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0}),wt.set(t,!0),!0}catch{return wt.set(t,!1),!1}}function Et(e,t,n,r){try{return w(`git`,e,{cwd:t,timeout:1e4,input:n,encoding:`utf8`,stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0}).trim()}catch(t){r||console.warn(`Git operation failed (${e.join(` `)}): ${t instanceof Error?t.message:String(t)}`);return}}function Dt(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,60)||`untitled`}function Ot(e,t,n,r,i){let a=Et([`hash-object`,`-w`,`--stdin`],i,n);if(!a)return;let o=Et([`mktree`],i,`100644 blob ${a}\t${t}\n`);if(!o)return;let s=Et([`rev-parse`,e],i,void 0,!0),c=[`commit-tree`,o];s&&c.push(`-p`,s),c.push(`-m`,r);let l=Et(c,i);if(l)return Et([`update-ref`,e,l],i)===void 0?void 0:l}function kt(){wt.clear()}const At=new Set;function jt(e){let t=Dt(e);return t===`untitled`?`checkpoint`:t}function Mt(e={}){let t=e.cwd??process.cwd();return f(e.stateDir??B(t),`checkpoints`)}function Nt(e){return`${e}.bak`}function Pt(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Ft(e,t,n){if(typeof e!=`string`||e.length<1||e.length>120)throw Error(`Checkpoint label must be 1-120 characters.`);if(!Pt(t))throw Error(`Checkpoint data must be a JSON-serializable object.`);let r;try{r=JSON.stringify(t)}catch{throw Error(`Checkpoint data must be a JSON-serializable object.`)}if(Buffer.byteLength(r,`utf8`)>5e5)throw Error(`Checkpoint data must be 500KB or less when serialized.`);if(n?.notes!==void 0&&Buffer.byteLength(n.notes,`utf8`)>1e4)throw Error(`Checkpoint notes must be 10KB or less.`);return r}function It(e,t){try{let t=JSON.parse(e);if(!Pt(t))throw Error(`Checkpoint data must deserialize to an object.`);return t}catch(e){console.warn(`Corrupt checkpoint payload ${t}: ${e instanceof Error?e.message:String(e)}`);return}}function Lt(e){let t=It(e.data,e.id);if(t)return{id:e.id,label:e.label,createdAt:e.createdAt,data:t,...e.notes?{notes:e.notes}:{}}}function Rt(e){return{id:e.id,label:e.label,createdAt:e.createdAt,...e.notes?{notes:e.notes}:{}}}function zt(e,t={}){let n=Mt(t);if(At.has(n)||!M(n)){At.add(n);return}try{let t=F(n).filter(e=>e.endsWith(`.json`));for(let r of t){let t=f(n,r);try{let n=P(t,`utf-8`),i=JSON.parse(n),a=typeof i.id==`string`&&i.id.length>0?i.id:o(r,`.json`);if(typeof i.label!=`string`)throw Error(`Missing checkpoint label.`);if(!Pt(i.data))throw Error(`Checkpoint data must be a JSON object.`);let s=Ft(i.label,i.data,{notes:i.notes});e.checkpointSave(a,i.label,s,i.notes)}catch(e){console.warn(`Legacy checkpoint import failed for ${t}: ${e instanceof Error?e.message:String(e)}`)}}let r=Nt(n);M(r)&&ie(r,{recursive:!0,force:!0}),I(n,r),At.add(n)}catch(e){console.warn(`Legacy checkpoint import failed for ${n}: ${e instanceof Error?e.message:String(e)}`)}}function Bt(e,t,n,r){zt(e,{cwd:r?.cwd});let i=Ft(t,n,{notes:r?.notes}),a=`${Date.now()}-${jt(t)}`;e.checkpointSave(a,t,i,r?.notes);let o=Vt(e,a,{cwd:r?.cwd});if(!o)throw Error(`Failed to load saved checkpoint "${a}".`);return o}function Vt(e,t,n={}){zt(e,n);let r=e.checkpointLoad(t);if(r)return Lt(r)}function Ht(e,t={}){return zt(e,t),e.checkpointList(t.label,t.limit).map(Rt)}function Ut(e,t={}){zt(e,t);let n=e.checkpointLatest(t.label);if(n)return Lt(n)}function Wt(e,t,n,r={}){zt(e,r);let i=e.checkpointDiff(t,n);if(!i)return;let a=It(i.from,t),o=It(i.to,n);if(!a||!o)return;let s=new Set(Object.keys(a)),c=new Set(Object.keys(o));return{fromId:t,toId:n,added:[...c].filter(e=>!s.has(e)),removed:[...s].filter(e=>!c.has(e)),modified:[...s].filter(e=>c.has(e)).filter(e=>JSON.stringify(a[e])!==JSON.stringify(o[e]))}}function Gt(e,t,n){return zt(e,{cwd:n?.cwd}),e.checkpointHistory(t,n?.limit??20).map(Rt)}function Kt(e,t){zt(e,{cwd:t?.cwd});let n=t?.keepLast??10,r=t?.dryRun??!0,i=t?.maxAgeDays===void 0?void 0:Date.now()-t.maxAgeDays*864e5,a=t?.label?jt(t.label):void 0,o=t?.label?e.checkpointHistory(t.label):e.checkpointList(),s=new Map;for(let e of o){let t=jt(e.label);if(a&&t!==a)continue;let n=s.get(t);n?n.push(e):s.set(t,[e])}let c=[],l=0;for(let e of s.values())e.forEach((e,t)=>{let r=Date.parse(e.createdAt);if(t<n&&!(i!==void 0&&!Number.isNaN(r)&&r<i)){l+=1;return}c.push(e.id)});if(!r)for(let t of c)e.checkpointDelete(t);return{deleted:c.length,kept:l,labels:[...s.keys()],deletedIds:c}}const qt=[`.ts`,`.tsx`,`.js`,`.jsx`],Jt=new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,z.state]);function Yt(e){return e.replace(/\\/g,`/`)}function Xt(e){return e.replace(/[.+^${}()|[\]\\]/g,`\\$&`)}function Zt(e,t){let n=Yt(e),r=Yt(t).trim();if(!r)return!1;let i=Xt(r).replace(/\*\*/g,`::DOUBLE_STAR::`).replace(/\*/g,`[^/]*`).replace(/\?/g,`[^/]`).replace(/::DOUBLE_STAR::/g,`.*`);return RegExp(`^${i}$`).test(n)}function Qt(e,t,n){return t.some(t=>Zt(e,t)?!0:n?Zt(`${e}/`,t):!1)}async function $t(e,t,r,a){let o=[],s=t.map(e=>e.toLowerCase()),l=Math.max(0,Math.min(a?.maxFiles??1e4,5e4)),f=Math.max(0,Math.min(a?.maxDepth??20,50));async function p(t,a){if(a>f||o.length>=l)return;let m=await n(t);for(let n of m){if(o.length>=l)return;if(Jt.has(n))continue;let f=u(t,n),m=await i(f),h=Yt(d(e,f));if(m.isDirectory()){Qt(h,r,!0)||await p(f,a+1);continue}Qt(h,r,!1)||s.includes(c(n).toLowerCase())&&o.push(f)}}return await p(e,0),o.sort((e,t)=>e.localeCompare(t)),o}const en=z.restorePoints;function tn(){let e=u(process.cwd(),en);return M(e)||N(e,{recursive:!0}),e}function nn(e,t,n){let r=tn(),i=`${Date.now()}-${e}`,a={id:i,timestamp:new Date().toISOString(),operation:e,files:t,description:n};R(u(r,`${i}.json`),`${JSON.stringify(a,null,2)}\n`,`utf-8`);let o=F(r).filter(e=>e.endsWith(`.json`)).sort();for(;o.length>50;){let e=o.shift();if(!e)break;try{ae(u(r,e))}catch{}}return i}function rn(){let e=u(process.cwd(),en);return M(e)?F(e).filter(e=>e.endsWith(`.json`)).sort().reverse().map(t=>{try{return JSON.parse(P(u(e,t),`utf-8`))}catch(n){return console.debug(`Skipping corrupt restore point ${u(e,t)}: ${n instanceof Error?n.message:String(n)}`),null}}).filter(e=>e!==null):[]}async function an(e){let t=u(u(process.cwd(),en),`${e}.json`);if(!M(t))throw Error(`Restore point not found: ${e}`);let n=JSON.parse(P(t,`utf-8`)),r=[];for(let e of n.files){let t=s(e.path);M(t)||N(t,{recursive:!0}),await a(e.path,e.content,`utf-8`),r.push(e.path)}return r}function on(e){return e.replace(/\\/g,`/`)}async function sn(e){let{rootPath:n,rules:r,extensions:i=qt,exclude:o=[],dryRun:s=!1}=e,c=r.map(e=>({...e,regex:new RegExp(e.pattern,`g`)})),l=await $t(n,i,o),u=[],f=new Set,p=0,m=[];for(let e of l){let r=on(d(n,e)),i=await t(e,`utf-8`),o=i.split(/\r?\n/),l=!1;for(let[e,t]of c.entries())if(!(t.fileFilter&&!Zt(r,t.fileFilter)))for(let n=0;n<o.length;n++){let i=o[n];t.regex.lastIndex=0;let a=i.replace(t.regex,t.replacement);i!==a&&(o[n]=a,l=!0,f.add(e),u.push({rule:t.description,path:r,line:n+1,before:i,after:a}))}l&&(p+=1,s||(m.push({path:e,content:i}),await a(e,o.join(`
|
|
16
16
|
`),`utf-8`)))}return!s&&m.length>0&&nn(`codemod`,m,`codemod: ${r.length} rules, ${p} files`),{changes:u,rulesApplied:f.size,filesModified:p,dryRun:s}}const cn=new Se({max:1e4,ttl:1e3*60*30});function ln(e){return V(`sha256`).update(e).digest(`hex`).slice(0,24)}function un(e,t){return`${e.modelId}:${e.dimensions}:${ln(t)}`}async function dn(e,t,n){if(t.length===0)return[];let r=Array(t.length),i=[],a=[];for(let n=0;n<t.length;n++){let o=t[n],s=cn.get(un(e,o));if(s){r[n]=s;continue}i.push(o),a.push(n)}if(i.length>0){let t=await e.embedBatch(i,n);for(let n=0;n<a.length;n++){let o=a[n],s=t[n]??new Float32Array;r[o]=s,s.length>0&&cn.set(un(e,i[n]),s)}}return r.map(e=>e??new Float32Array)}const fn=.6;function pn(e){if(!e||e.length===0)return 0;let t=Ce(e),n=e.length;return n===0?0:Math.min(t.length/n,fn)/fn}function mn(e){if(e.length===0)return[];let t=new Map,n=[];for(let r of e){let e=Ce(r);n.push(e);for(let n of e)t.set(n,(t.get(n)??0)+1)}let r=[];for(let i=0;i<e.length;i++){let a=e[i],o=n[i];if(!a||o.length===0){r.push(0);continue}let s=Math.min(o.length/a.length,fn)/fn,c=0;for(let e of o)(t.get(e)??0)===1&&c++;let l=c/o.length,u=.6*s+.4*l;r.push(Math.min(u,1))}return r}function hn(e){if(!e||e.length===0)return 0;let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);let n=0,r=e.length;for(let e of t.values()){let t=e/r;t>0&&(n-=t*Math.log2(t))}return Math.min(n/6.6,1)}function gn(e){try{return pn(e)}catch{return hn(e)}}const _n=new Set(`a.an.and.are.as.at.be.by.for.from.how.in.is.it.of.on.or.that.the.this.to.was.what.when.where.with`.split(`.`));function vn(e){let t=e.toLowerCase().split(/[^a-z0-9_]+/i).map(e=>e.trim()).filter(e=>e.length>=2&&!_n.has(e));return[...new Set(t)]}function yn(e,t){let n=0,r=e.indexOf(t);for(;r!==-1;)n++,r=e.indexOf(t,r+t.length);return n}function bn(e,t,n){if(e.length===0||t.length===0)return 0;let r=e.toLowerCase(),i=0,a=0;for(let e of t){let t=yn(r,e);t>0&&(i++,a+=t)}if(i===0)return 0;let o=i/t.length,s=Math.min(1,a/Math.max(1,r.length/32)),c=n.length>=3&&r.includes(n)?1:0;return .65*o+.2*s+.15*c}function xn(e,t,n){if(e.size>=n||t.length===0)return;let r=Math.max(1,Math.floor(t.length/Math.max(1,n-e.size)));for(let i=0;i<t.length&&e.size<n;i+=r){let n=t[i];e.has(n.index)||e.set(n.index,n)}if(e.size>=n)return;let i=[0,Math.floor((t.length-1)/2),t.length-1];for(let r of i){let i=t[r];if(i&&!e.has(i.index)&&e.set(i.index,i),e.size>=n)return}for(let r of t)if(e.has(r.index)||e.set(r.index,r),e.size>=n)return}function Sn(e){return e<=24?e:Math.min(e,Math.min(96,Math.max(24,Math.ceil(Math.sqrt(e)*6))))}function Cn(e,t){if(e.length===0)return[];let n=Sn(e.length),r=t.trim().toLowerCase(),i=vn(t),a=e.map((e,t)=>{let n=bn(e,i,r),a=hn(e);return{index:t,text:e,lexicalScore:n,semanticBonus:a,prefilterScore:i.length===0?a:n>0?n*.85+a*.15:a*.35}});if(a.length<=n){let e=mn(a.map(e=>e.text));return a.map((t,n)=>({...t,semanticBonus:e[n]??t.semanticBonus}))}let o=[...a].sort((e,t)=>t.prefilterScore-e.prefilterScore||t.lexicalScore-e.lexicalScore||e.text.length-t.text.length||e.index-t.index),s=new Map,c=Math.min(n,Math.max(1,Math.ceil(n*.75)));for(let e of o){if(s.size>=c)break;s.set(e.index,e)}xn(s,a,n);let l=[...s.values()].sort((e,t)=>e.index-t.index),u=mn(l.map(e=>e.text));return l.map((e,t)=>({...e,semanticBonus:u[t]??e.semanticBonus}))}const wn=new Se({max:200,ttl:1e3*60*30});function Tn(e){return V(`sha256`).update(e).digest(`hex`).slice(0,16)}function En(e,t){let n=Tn(t),r=wn.get(e);if(wn.set(e,{hash:n,text:t,timestamp:Date.now()}),!r||r.hash===n)return{text:r?.hash===n?`[No changes since last read]`:t,isDelta:r?.hash===n,hash:n};let i=we(e,e,r.text,t,`previous`,`current`,{context:3});return i.length>=t.length*.8?{text:t,isDelta:!1,hash:n}:{text:i,isDelta:!0,hash:n}}const Dn=/^ctx[cd]_[a-z0-9]+$/,On=new Se({max:250,ttl:1e3*60*30});function kn(e,t){let n=V(`sha256`).update(e).update(`\0`).update(t).digest(`hex`);return`${e===`compact`?`ctxc`:`ctxd`}_${n.slice(0,12)}`}function An(e){return Dn.test(e)}function jn(e){if(e.text.length===0||e.text.length>1e5)return;let t={...e,ref:kn(e.kind,e.text),createdAt:Date.now()};return On.set(t.ref,t),t}function Mn(e){return On.get(e)}function Nn(e,t=15){try{let n=F(s(e),{withFileTypes:!0});if(n.length===0)return``;let r=n.slice(0,t).map(e=>e.isDirectory()?`${e.name}/`:e.name),i=n.length>t?`, … (${n.length} total)`:``;return` Available in directory: ${r.join(`, `)}${i}`}catch{return``}}function Pn(e){return{text:e.text,ref:e.ref,originalChars:e.originalChars,compressedChars:e.compressedChars,ratio:e.originalChars===0?0:e.compressedChars/e.originalChars,segmentsKept:1,segmentsTotal:1}}async function Fn(e,n){let{query:r,ref:a,maxChars:o=3e3,minScore:s=.3,segmentation:c=`paragraph`}=n,l=r?.trim(),u=n.tokenBudget?n.tokenBudget*4:o;function d(e){if(n.storeReference===!1||e.text.length===0)return e;let t=jn({kind:`compact`,text:e.text,originalChars:e.originalChars,compressedChars:e.compressedChars});return t?{...e,ref:t.ref}:e}if(a&&(n.text||n.path))throw Error(`Provide "ref" by itself, not together with "text" or "path".`);let f=a?Mn(a):void 0;if(a){if(!f)throw Error(`Cached ref not found: ${a}. It may have expired.`);if(!l)return Pn(f)}if(!l)throw Error(`Either "query" or "ref" must be provided`);let p;if(n.text)p=n.text;else if(f)p=f.text;else if(n.path){if(An(n.path))throw Error(`Cached reversible refs must be passed as "ref", not "path".`);let e;try{e=await i(n.path)}catch(e){let t=e.code;if(t===`ENOENT`){let e=Nn(n.path);throw Error(`File not found: ${n.path}. Check the path and try again.${e}`)}throw t===`EACCES`||t===`EPERM`?Error(`Permission denied reading ${n.path}. The file exists but is not accessible.`):e}if(e.isDirectory())throw Error(`Path is a directory: ${n.path}. compact requires a file path, not a directory. Use analyze({ aspect: "structure", path }) or find to explore directories.`);if(e.size>1e7)throw Error(`File too large (${(e.size/1e6).toFixed(1)}MB). compact supports files up to 10MB. Consider splitting or using search instead.`);p=n.cache?(await n.cache.get(n.path)).content:await t(n.path,`utf-8`)}else throw Error(`Either "text", "path", or "ref" must be provided`);if(n.mode===`delta`&&n.path){let e=En(n.path,p);if(e.isDelta)return d({text:e.text,originalChars:p.length,compressedChars:e.text.length,ratio:e.text.length/p.length,segmentsKept:1,segmentsTotal:1})}if(p.length<=u)return d({text:p,originalChars:p.length,compressedChars:p.length,ratio:1,segmentsKept:1,segmentsTotal:1});let m=ct(p,c);if(m.length===0)return d({text:``,originalChars:p.length,compressedChars:0,ratio:0,segmentsKept:0,segmentsTotal:0});let h;try{h=await e.embedQuery(l)}catch{h=new Float32Array}if(h.length===0){let e=p.slice(0,u);return d({text:`/* warning: embeddings unavailable — returning unscored text */\n${e}`,originalChars:p.length,compressedChars:e.length,ratio:e.length/p.length,segmentsKept:m.length,segmentsTotal:m.length})}let g=Cn(m,l),_=await dn(e,g.map(e=>e.text),8),v=g.map((e,t)=>{let n=_[t]??new Float32Array,r=.85*ft(h,n)+.15*e.semanticBonus;return{text:e.text,score:r,index:e.index}}).filter(e=>e.score>=s).sort((e,t)=>t.score-e.score),y=[],b=0;for(let e of v){if(b+e.text.length>u){b===0&&(y.push({...e,text:e.text.slice(0,u)}),b=u);break}y.push(e),b+=e.text.length+2}let x=pt(y.sort((e,t)=>t.score-e.score)).map(e=>e.text).join(`
|
|
17
17
|
|
|
18
18
|
`);return d({text:x,originalChars:p.length,compressedChars:x.length,ratio:x.length/p.length,segmentsKept:y.length,segmentsTotal:m.length})}const In=/vitest|jest|mocha|pnpm test|npm test/i,Ln=/\btsc\b|pnpm check|pnpm typecheck|pnpm lint|biome/i,Rn=/\bgrep\b|\bfind\b|\brg\b|Select-String/i,zn=new Set([`apply_patch`,`codemod`,`create_file`,`rename`,`restore`,`replace_string_in_file`,`vscode_renameSymbol`]),U=[{id:`no-grep-search`,description:`grep_search → use search`,toolMatch:`grep_search`,commandPatterns:null,heuristic:null},{id:`no-semantic-search`,description:`semantic_search → use search`,toolMatch:`semantic_search`,commandPatterns:null,heuristic:null},{id:`no-read-file-understanding`,description:`read_file (for understanding) → use file_summary or compact`,toolMatch:null,commandPatterns:null,heuristic:`read_file with range > 50 lines and no subsequent edit`},{id:`no-terminal-test`,description:`run_in_terminal (for test) → use test_run`,toolMatch:null,commandPatterns:[`vitest`,`jest`,`mocha`,`pnpm test`,`npm test`],heuristic:null},{id:`no-terminal-typecheck`,description:`run_in_terminal (for tsc/lint) → use check`,toolMatch:null,commandPatterns:[`\\btsc\\b`,`pnpm check`,`pnpm typecheck`,`pnpm lint`,`biome`],heuristic:null},{id:`no-terminal-grep`,description:`run_in_terminal (for find/grep) → use find or search`,toolMatch:null,commandPatterns:[`\\bgrep\\b`,`\\bfind\\b`,`\\brg\\b`,`Select-String`],heuristic:null},{id:`no-fetch-webpage`,description:`fetch_webpage → use web_fetch`,toolMatch:`fetch_webpage`,commandPatterns:null,heuristic:null},{id:`no-subagent-present`,description:`present (from subagent) → use Return findings as structured text`,toolMatch:null,commandPatterns:null,heuristic:`present called in subagent context`}];function Bn(e){return typeof e==`object`&&!!e}function Vn(e){try{return JSON.parse(e)}catch{return e}}function Hn(e){let t=Vn(e.input);return Bn(t)?t:null}function Un(e){let t=Hn(e);return t&&typeof t.command==`string`?t.command:e.input}function Wn(e,t){return t.test(e)}function Gn(e){let t=Hn(e),n=typeof t?.startLine==`number`?t.startLine:null,r=typeof t?.endLine==`number`?t.endLine:null;if(n!==null&&r!==null)return Math.max(0,r-n+1);let i=e.input.match(/"startLine"\s*:\s*(\d+)/),a=e.input.match(/"endLine"\s*:\s*(\d+)/);if(!i||!a)return null;let o=Number(i[1]),s=Number(a[1]);return!Number.isFinite(o)||!Number.isFinite(s)?null:Math.max(0,s-o+1)}function Kn(e){return zn.has(e.tool)?!0:/(?:^|_)rename|codemod|apply_patch|create_file|replace_string_in_file|restore/i.test(e.tool)}function qn(e){if(e.tool!==`knowledge`)return!1;let t=Hn(e);return t?t.scope===`flow`&&typeof t.profile==`string`:!1}function W(e,t,n,r){return{rule:n,ruleId:t,tool:e.tool,timestamp:e.ts,suggestion:r}}function Jn(e){let t=new WeakMap;return e.forEach((e,n)=>{t.set(e,n)}),[{id:`no-grep-search`,description:U[0].description,check:e=>e.tool===`grep_search`?W(e,`no-grep-search`,`Avoid grep_search for code discovery.`,"Use `search` instead."):null},{id:`no-semantic-search`,description:U[1].description,check:e=>e.tool===`semantic_search`?W(e,`no-semantic-search`,`Avoid semantic_search for code discovery.`,"Use `search` instead."):null},{id:`no-read-file-understanding`,description:U[2].description,check:n=>{if(n.tool!==`read_file`)return null;let r=Gn(n);if(r===null||r<=50)return null;let i=t.get(n);return i===void 0||e.slice(i+1,i+3).some(Kn)?null:W(n,`no-read-file-understanding`,`Avoid large read_file ranges for understanding code.`,"Use `file_summary` or `compact` for understanding.")}},{id:`no-terminal-test`,description:U[3].description,check:e=>e.tool===`run_in_terminal`&&Wn(Un(e),In)?W(e,`no-terminal-test`,`Avoid terminal-driven test execution.`,"Use `test_run` instead."):null},{id:`no-terminal-typecheck`,description:U[4].description,check:e=>e.tool===`run_in_terminal`&&Wn(Un(e),Ln)?W(e,`no-terminal-typecheck`,`Avoid terminal-driven typecheck or lint execution.`,"Use `check` instead."):null},{id:`no-terminal-grep`,description:U[5].description,check:e=>e.tool===`run_in_terminal`&&Wn(Un(e),Rn)?W(e,`no-terminal-grep`,`Avoid terminal-driven grep or file search.`,"Use `find` or `search` instead."):null},{id:`no-fetch-webpage`,description:U[6].description,check:e=>e.tool===`fetch_webpage`?W(e,`no-fetch-webpage`,`Avoid fetch_webpage when AI Kit web fetching is available.`,"Use `web_fetch` instead."):null},{id:`no-subagent-present`,description:U[7].description,check:n=>{if(n.tool!==`present`)return null;let r=t.get(n);return r===void 0?null:e.slice(Math.max(0,r-5),r).some(qn)?W(n,`no-subagent-present`,`Subagent execution should stay text-only.`,"Subagents should not use `present`."):null}}]}function Yn(e,t={}){let n=typeof t.lastN==`number`?e.slice(-Math.max(0,t.lastN)):[...e],r=Jn(n),i=[];for(let e of n)for(let t of r){let n=t.check(e);n&&i.push(n)}let a=Math.max(0,100-i.length*10),o=i.length===0?`No routing violations detected across ${n.length} replay calls.`:`Compliance score ${a}/100. Found ${i.length} violation(s) across ${n.length} replay calls.`;return{score:a,violations:i,totalCalls:n.length,summary:o}}const Xn=/\b(error|fatal|exception|failed|failure|fail|passed|warn|warning|panic|abort|timeout|critical)\b/i,Zn=[];function Qn(e){Zn.push(e),Zn.sort((e,t)=>t.priority-e.priority)}function $n(e){for(let t of e)Qn(t)}function er(){return Zn}function tr(e){return/^(diff --git|commit [0-9a-f]{7,40}|On branch |Your branch )/m.test(e)?`git`:/^\s*[MADRCU?!]{1,2}\s+\S/m.test(e)&&/^##\s/m.test(e)?`git-status`:/^(npm (warn|ERR!|notice)|added \d+ packages?|up to date)/m.test(e)?`npm`:/^(Packages|Progress):/m.test(e)||/pnpm/.test(e)?`pnpm`:/✓|✗|PASS|FAIL|Tests?\s+\d+\s+(passed|failed)/m.test(e)||/^(PASS|FAIL)\s+\S/m.test(e)?`test-runner`:/^(error TS\d+|warning TS\d+|\S+\.tsx?[(:]\d+)/m.test(e)?`tsc`:/^\S+\.\w+:\d+:\d+\s+(error|warning|info)/m.test(e)||/Found \d+ (error|warning)/m.test(e)?`lint`:/^(CONTAINER ID|IMAGE|REPOSITORY|Step \d+\/\d+|--->)/m.test(e)||/docker|Dockerfile/i.test(e)?`docker`:/^(NAME\s+READY|NAMESPACE\s|kubectl)/m.test(e)?`kubectl`:`unknown`}function nr(e,t,n){return[`\n... [${e} chars / ~${t} tokens omitted]\n`,`\n... [${e} chars omitted]\n`,`
|
|
@@ -3,6 +3,6 @@
|
|
|
3
3
|
"command": "node",
|
|
4
4
|
"args": [
|
|
5
5
|
"-e",
|
|
6
|
-
"const{execSync:x}=require('child_process');const{
|
|
6
|
+
"const{execSync:x}=require('child_process');const{existsSync:e,renameSync:m}=require('fs');const{join:j}=require('path');const c=j(process.env.LOCALAPPDATA||process.env.HOME||'','npm-cache');const s={stdio:'inherit'};try{x('npx -y @vpxa/aikit@latest serve',s)}catch{try{const d=j(c,'_npx');if(e(d))m(d,j(c,'_npx_'+Date.now()))}catch{};try{x('npm cache verify',{stdio:'ignore',timeout:30000})}catch{};try{x('npx -y @vpxa/aikit@latest serve',s)}catch(e){process.stderr.write('aikit: all recovery attempts failed. Run: npm cache clean --force && npx -y @vpxa/aikit@latest serve');process.exit(1)}}"
|
|
7
7
|
]
|
|
8
8
|
}
|