ko-qmd 2.8.3-ko.10

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.
Files changed (76) hide show
  1. package/CHANGELOG.md +1937 -0
  2. package/LICENSE +21 -0
  3. package/README.en.md +184 -0
  4. package/README.md +292 -0
  5. package/bin/qmd +192 -0
  6. package/dist/ast.d.ts +65 -0
  7. package/dist/ast.js +51 -0
  8. package/dist/bench/bench.d.ts +41 -0
  9. package/dist/bench/bench.js +12 -0
  10. package/dist/bench/score.d.ts +33 -0
  11. package/dist/bench/score.js +1 -0
  12. package/dist/bench/types.d.ts +101 -0
  13. package/dist/bench/types.js +1 -0
  14. package/dist/cli/build-info.json +4 -0
  15. package/dist/cli/embed-lock.d.ts +24 -0
  16. package/dist/cli/embed-lock.js +2 -0
  17. package/dist/cli/formatter.d.ts +120 -0
  18. package/dist/cli/formatter.js +60 -0
  19. package/dist/cli/mcp-pid.d.ts +33 -0
  20. package/dist/cli/mcp-pid.js +1 -0
  21. package/dist/cli/qmd.d.ts +101 -0
  22. package/dist/cli/qmd.js +165 -0
  23. package/dist/cli/version.d.ts +42 -0
  24. package/dist/cli/version.js +1 -0
  25. package/dist/collections.d.ts +162 -0
  26. package/dist/collections.js +1 -0
  27. package/dist/db.d.ts +63 -0
  28. package/dist/db.js +2 -0
  29. package/dist/filters.d.ts +46 -0
  30. package/dist/filters.js +1 -0
  31. package/dist/grep.d.ts +85 -0
  32. package/dist/grep.js +9 -0
  33. package/dist/hangul.d.ts +102 -0
  34. package/dist/hangul.js +1 -0
  35. package/dist/index.d.ts +270 -0
  36. package/dist/index.js +1 -0
  37. package/dist/llm.d.ts +584 -0
  38. package/dist/llm.js +40 -0
  39. package/dist/maintenance.d.ts +33 -0
  40. package/dist/maintenance.js +1 -0
  41. package/dist/mcp/daemon-health.d.ts +17 -0
  42. package/dist/mcp/daemon-health.js +1 -0
  43. package/dist/mcp/origin-guard.d.ts +67 -0
  44. package/dist/mcp/origin-guard.js +1 -0
  45. package/dist/mcp/server.d.ts +131 -0
  46. package/dist/mcp/server.js +35 -0
  47. package/dist/memory.d.ts +74 -0
  48. package/dist/memory.js +13 -0
  49. package/dist/metadata-filter.d.ts +74 -0
  50. package/dist/metadata-filter.js +1 -0
  51. package/dist/metadata-store.d.ts +45 -0
  52. package/dist/metadata-store.js +68 -0
  53. package/dist/metadata.d.ts +61 -0
  54. package/dist/metadata.js +1 -0
  55. package/dist/paths.d.ts +1 -0
  56. package/dist/paths.js +1 -0
  57. package/dist/query-log.d.ts +156 -0
  58. package/dist/query-log.js +2 -0
  59. package/dist/refresh.d.ts +60 -0
  60. package/dist/refresh.js +1 -0
  61. package/dist/rerank-input.d.ts +46 -0
  62. package/dist/rerank-input.js +5 -0
  63. package/dist/store.d.ts +1267 -0
  64. package/dist/store.js +421 -0
  65. package/dist/trust.d.ts +152 -0
  66. package/dist/trust.js +2 -0
  67. package/package.json +124 -0
  68. package/scripts/build.mjs +130 -0
  69. package/scripts/check-package-grammars.mjs +29 -0
  70. package/scripts/package-smoke.mjs +65 -0
  71. package/scripts/test-all.mjs +42 -0
  72. package/skills/qmd/SKILL.md +333 -0
  73. package/skills/qmd/references/mcp-setup.md +122 -0
  74. package/skills/release/SKILL.md +141 -0
  75. package/skills/release/scripts/install-hooks.sh +38 -0
  76. package/skills/release/scripts/release-context.sh +129 -0
package/dist/store.js ADDED
@@ -0,0 +1,421 @@
1
+ var qn=Object.defineProperty;var c=(e,n)=>qn(e,"name",{value:n,configurable:!0});import{openDatabase as ht,loadSqliteVec as Un}from"./db.js";import ft from"picomatch";import{isNarrowing as pt,matchesPaths as Ne}from"./filters.js";import{createHash as Ce}from"crypto";import{readFileSync as Bn,realpathSync as Et,statSync as mt,mkdirSync as $n}from"node:fs";import Vn from"fast-glob";import{qmdHomedir as Xn}from"./paths.js";import{containsHangul as Gn,estimateCharsPerToken as zn,hangulBigramTail as Kn,hangulMixedQuery as jn,hangulTermQuery as Jn,stripHangulNegation as gt}from"./hangul.js";import{formatRerankDoc as Yn,formatRerankQuery as Qn,INTENT_WEIGHT_CHUNK as Zn,selectRerankChunk as eo}from"./rerank-input.js";import{getDefaultLlamaCpp as _e,formatQueryForEmbedding as xe,formatDocForEmbedding as le,withLLMSessionForLlm as Tt,DEFAULT_EMBED_MODEL_URI as to,DEFAULT_RERANK_MODEL_URI as no,DEFAULT_GENERATE_MODEL_URI as oo,normalizeRerankMaxDocTokens as so}from"./llm.js";import{METADATA_EXTRACTION_VERSION as We}from"./metadata.js";import{compileMetadataFilter as qe}from"./metadata-filter.js";import{initializeMetadataSchema as ro,syncDocumentMetadata as co,countDocumentsPendingMetadata as ao,getMetadataByFilepath as io,parseMetadataJson as _t}from"./metadata-store.js";const te=to,xt=no,De=oo,lr="**/*.md";function lo(e){const n=[];let t="",o=0,r=0;for(const a of e)if(a==="{")o++,t+=a;else if(a==="}"&&o>0)o--,t+=a;else if(a==="[")r++,t+=a;else if(a==="]"&&r>0)r--,t+=a;else if(a===","&&o===0&&r===0){const i=t.trim();i&&n.push(i),t=""}else t+=a;const s=t.trim();return s&&n.push(s),n.length>0?n:[e]}c(lo,"splitGlobMask");const uo=64*1024,ho=64,fo=64*1024*1024,po=1800*1e3,Eo="__qmd_embedding_query_probe__",mo="__qmd_embedding_title_probe__",go="__qmd_embedding_document_probe__",re=900,he=Math.floor(re*.15),Se=re*4,Ue=he*4,Re=200,Oe=Re*4;function fe(e=te){const n=[`model:${e}`,`query:${xe(Eo,e)}`,`doc:${le(go,mo,e)}`,`chunk_tokens:${re}`,`chunk_overlap_tokens:${he}`,"chunk_chars_estimator:2"].join(`
2
+ `);return Ce("sha256").update(n).digest("hex").slice(0,6)}c(fe,"getEmbeddingFingerprint");function ue(e){return e.llm??_e()}c(ue,"getLlm");const To=[[/\n#{1}(?!#)/g,100,"h1"],[/\n#{2}(?!#)/g,90,"h2"],[/\n#{3}(?!#)/g,80,"h3"],[/\n#{4}(?!#)/g,70,"h4"],[/\n#{5}(?!#)/g,60,"h5"],[/\n#{6}(?!#)/g,50,"h6"],[/\n```/g,80,"codeblock"],[/\n(?:---|\*\*\*|___)\s*\n/g,60,"hr"],[/\n\n+/g,20,"blank"],[/\n[-*]\s/g,5,"list"],[/\n\d+\.\s/g,5,"numlist"],[/\n/g,1,"newline"]];function St(e){const n=[],t=new Map;for(const[o,r,s]of To)for(const a of e.matchAll(o)){const i=a.index,u=t.get(i);if(!u||r>u.score){const l={pos:i,score:r,type:s};t.set(i,l)}}for(const o of t.values())n.push(o);return n.sort((o,r)=>o.pos-r.pos)}c(St,"scanBreakPoints");function Rt(e){const n=[],t=/\n```/g;let o=!1,r=0;for(const s of e.matchAll(t))o?(n.push({start:r,end:s.index+s[0].length}),o=!1):(r=s.index,o=!0);return o&&n.push({start:r,end:e.length}),n}c(Rt,"findCodeFences");function _o(e,n){return n.some(t=>e>t.start&&e<t.end)}c(_o,"isInsideCodeFence");function xo(e,n,t=Oe,o=.7,r=[]){const s=n-t;let a=-1,i=n;for(const u of e){if(u.pos<s)continue;if(u.pos>n)break;if(_o(u.pos,r))continue;const d=(n-u.pos)/t,f=1-d*d*o,h=u.score*f;h>a&&(a=h,i=u.pos)}return i}c(xo,"findBestCutoff");function So(e,n){const t=new Map;for(const o of e){const r=t.get(o.pos);(!r||o.score>r.score)&&t.set(o.pos,o)}for(const o of n){const r=t.get(o.pos);(!r||o.score>r.score)&&t.set(o.pos,o)}return Array.from(t.values()).sort((o,r)=>o.pos-r.pos)}c(So,"mergeBreakPoints");function Ro(e,n){if(n<=0||n>=e.length)return!1;const t=e.charCodeAt(n-1),o=e.charCodeAt(n);return t>=55296&&t<=56319&&o>=56320&&o<=57343}c(Ro,"isSurrogatePairBoundary");function yt(e,n,t){if(!Ro(e,n))return n;const o=n-1;return o>t?o:n+1}c(yt,"adjustSurrogateBoundary");function Nt(e,n,t,o=Se,r=Ue,s=Oe){if(e.length<=o)return[{text:e,pos:0}];const a=[];let i=0;for(;i<e.length;){const u=Math.min(i+o,e.length);let l=u;if(l<e.length){const f=xo(n,u,s,.7,t);f>i&&f<=u&&(l=f)}if(l<=i&&(l=Math.min(i+o,e.length)),l=yt(e,l,i),a.push({text:e.slice(i,l),pos:i}),l>=e.length)break;i=l-r;const d=a.at(-1).pos;i<=d&&(i=l),i=yt(e,i,d)}return a}c(Nt,"chunkDocumentWithBreakPoints");const yo=.85,No=.15,Be=40;function $e(){return Xn()}c($e,"homedir");function Ct(e){if(!e)return!1;if(e.startsWith("/")){if(!Ve()&&e.length>=3&&e[2]==="/"){const n=e[1];if(n&&/[c-zC-Z]/.test(n))return!0}return!0}return!!(e.length>=2&&/[a-zA-Z]/.test(e[0])&&e[1]===":")}c(Ct,"isAbsolutePath");function pe(e){return e.replace(/\\/g,"/")}c(pe,"normalizePathSeparators");function Ve(){return!!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP)}c(Ve,"isWSL");function Dt(e,n){if(!n)return null;const t=pe(e),o=pe(n),r=o.endsWith("/")?o:o+"/";return t===o?"":t.startsWith(r)?t.slice(r.length):null}c(Dt,"getRelativePathFromPrefix");function ce(...e){if(e.length===0)throw new Error("resolve: at least one path segment is required");const n=e.map(pe);let t="",o="";const r=n[0];if(Ct(r)){if(t=r,r.length>=2&&/[a-zA-Z]/.test(r[0])&&r[1]===":")o=r.slice(0,2),t=r.slice(2);else if(!Ve()&&r.startsWith("/")&&r.length>=3&&r[2]==="/"){const u=r[1];u&&/[c-zC-Z]/.test(u)&&(o=u.toUpperCase()+":",t=r.slice(2))}}else{const u=pe(process.env.PWD||process.cwd());u.length>=2&&/[a-zA-Z]/.test(u[0])&&u[1]===":"?(o=u.slice(0,2),t=u.slice(2)+"/"+r):t=u+"/"+r}for(let u=1;u<n.length;u++){const l=n[u];if(Ct(l))if(t=l,l.length>=2&&/[a-zA-Z]/.test(l[0])&&l[1]===":")o=l.slice(0,2),t=l.slice(2);else if(!Ve()&&l.startsWith("/")&&l.length>=3&&l[2]==="/"){const d=l[1];d&&/[c-zC-Z]/.test(d)?(o=d.toUpperCase()+":",t=l.slice(2)):o=""}else o="";else t=t+"/"+l}const s=t.split("/").filter(Boolean),a=[];for(const u of s)u===".."?a.pop():u!=="."&&a.push(u);const i="/"+a.join("/");return o?o+i:i}c(ce,"resolve");let Xe=!1;function ur(){Xe=!0}c(ur,"enableProductionMode");function dr(){Xe=!1}c(dr,"_resetProductionModeForTesting");function Co(e="index"){if(process.env.INDEX_PATH)return process.env.INDEX_PATH;if(!Xe)throw new Error("Database path not set. Tests must set INDEX_PATH env var or use createStore() with explicit path. This prevents tests from accidentally writing to the global index.");const n=process.env.XDG_CACHE_HOME||ce($e(),".cache"),t=ce(n,"qmd");try{$n(t,{recursive:!0})}catch{}return ce(t,`${e}.sqlite`)}c(Co,"getDefaultDbPath");function hr(){return process.env.PWD||process.cwd()}c(hr,"getPwd");function Ot(e){try{return Et(e)}catch{return ce(e)}}c(Ot,"getRealPath");function Lt(e,n){const t=Ot(e);try{return Dt(Et(n),t)!==null}catch{return Dt(ce(n),ce(e))!==null}}c(Lt,"isPathInsideDir");function Do(e){let n=e.trim();return n.startsWith("qmd:")?(n=n.slice(4),n=n.replace(/^\/+/,""),`qmd://${n}`):n.startsWith("//")?(n=n.replace(/^\/+/,""),`qmd://${n}`):n}c(Do,"normalizeVirtualPath");function Ee(e){const n=Do(e),[t=n,o=""]=n.split("?"),r=t.match(/^qmd:\/\/([^\/]+)\/?(.*)$/);if(!r?.[1])return null;const s=new URLSearchParams(o).get("index")?.trim()||void 0;return{collectionName:r[1],path:r[2]??"",...s?{indexName:s}:{}}}c(Ee,"parseVirtualPath");function At(e,n,t){const o=`qmd://${e}/${n}`;return t?`${o}?index=${encodeURIComponent(t)}`:o}c(At,"buildVirtualPath");function Ge(e){const n=e.trim();return!!(n.startsWith("qmd:")||n.startsWith("//"))}c(Ge,"isVirtualPath");function Oo(e,n){const t=Ee(n);if(!t)return null;const o=fn(e,t.collectionName);if(!o)return null;const r=ce(o.pwd,t.path);return Lt(o.pwd,r)?r:null}c(Oo,"resolveVirtualPath");function Lo(e,n){const t=oe(e);for(const o of t)if(n.startsWith(o.path+"/")||n===o.path){const r=n.startsWith(o.path+"/")?n.slice(o.path.length+1):"";if(e.prepare(`
3
+ SELECT d.path
4
+ FROM documents d
5
+ WHERE d.collection = ? AND d.path = ? AND d.active = 1
6
+ LIMIT 1
7
+ `).get(o.name,r))return At(o.name,r)}return null}c(Lo,"toVirtualPath");function vt(e){return new Error(`sqlite-vec extension is unavailable. ${e}. Install Homebrew SQLite so the sqlite-vec extension can be loaded, and set BREW_PREFIX if Homebrew is installed in a non-standard location.`)}c(vt,"createSqliteVecUnavailableError");let Le=null;function ze(e){return e instanceof Error?e.message:String(e)}c(ze,"getErrorMessage");function Ao(e){try{const n=e.prepare("SELECT vec_version() AS version").get();if(!n?.version||typeof n.version!="string")throw new Error("vec_version() returned no version")}catch(n){const t=ze(n);throw vt(`sqlite-vec probe failed (${t})`)}}c(Ao,"verifySqliteVecLoaded");let Ae=null;const vo=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u,Io=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+/gu,Ke="2",ve=2;function de(e){const n=Kn(e);return n?`${je(e)} ${n}`:je(e)}c(de,"normalizeCjkForFTS");function je(e){return e.replace(Io,n=>` ${Array.from(n).join(" ")} `)}c(je,"spaceCjkRuns");function Mo(e){return vo.test(e)}c(Mo,"containsCjk");function It(e){return je(e).split(/\s+/).flatMap(n=>pn(n)).join(" ")}c(It,"sanitizeFTS5Phrase");function Je(e){const n=e.prepare("PRAGMA user_version").get(),t=n?Object.values(n)[0]:0;return typeof t=="number"?t:Number(t)||0}c(Je,"getUserVersion");function Mt(e){e.exec("DROP TRIGGER IF EXISTS documents_ai"),e.exec(`
8
+ CREATE TRIGGER documents_ai AFTER INSERT ON documents
9
+ WHEN new.active = 1
10
+ BEGIN
11
+ INSERT INTO documents_fts(rowid, filepath, title, body)
12
+ SELECT
13
+ new.id,
14
+ new.collection || '/' || new.path,
15
+ new.title,
16
+ (SELECT doc FROM content WHERE hash = new.hash)
17
+ WHERE new.active = 1;
18
+ END
19
+ `),e.exec("DROP TRIGGER IF EXISTS documents_ad"),e.exec(`
20
+ CREATE TRIGGER documents_ad AFTER DELETE ON documents BEGIN
21
+ DELETE FROM documents_fts WHERE rowid = old.id;
22
+ END
23
+ `),e.exec("DROP TRIGGER IF EXISTS documents_au"),e.exec(`
24
+ CREATE TRIGGER documents_au AFTER UPDATE OF collection, path, hash, active ON documents
25
+ BEGIN
26
+ -- Delete from FTS if no longer active
27
+ DELETE FROM documents_fts WHERE rowid = old.id AND new.active = 0;
28
+
29
+ -- Update FTS if still/newly active
30
+ INSERT OR REPLACE INTO documents_fts(rowid, filepath, title, body)
31
+ SELECT
32
+ new.id,
33
+ new.collection || '/' || new.path,
34
+ new.title,
35
+ (SELECT doc FROM content WHERE hash = new.hash)
36
+ WHERE new.active = 1;
37
+ END
38
+ `)}c(Mt,"installFtsSyncTriggers");function wo(e){if(!(Je(e)>=ve)){e.exec("BEGIN IMMEDIATE");try{Je(e)<ve&&(Mt(e),e.exec(`PRAGMA user_version = ${ve}`)),e.exec("COMMIT")}catch(n){throw e.exec("ROLLBACK"),n}}}c(wo,"applyFtsSyncTriggers");function bo(e){try{return e.prepare("PRAGMA table_info(documents_fts)").all().map(t=>(t.name??"").toLowerCase()).filter(Boolean)}catch{return[]}}c(bo,"documentsFtsColumnNames");function wt(e){const t=(e.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'documents_fts'").get()?.sql??"").toLowerCase().replace(/\s+/g,"");if(!t.includes("filepath")||!t.includes("title")||t.includes("content="))return!1;const o=new Set(bo(e));return o.has("filepath")&&o.has("title")&&o.has("body")&&!o.has("name")}c(wt,"documentsFtsSchemaIsCurrent");function Fo(e){return/already exists/i.test(ze(e))}c(Fo,"isAlreadyExistsError");function bt(e){return!!e.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'documents_fts'").get()?.name}c(bt,"documentsFtsExists");const ko=`
39
+ CREATE VIRTUAL TABLE IF NOT EXISTS documents_fts USING fts5(
40
+ filepath, title, body,
41
+ tokenize='porter unicode61'
42
+ )
43
+ `;function Ft(e){try{e.exec(ko)}catch(n){if(!Fo(n)||!bt(e))throw n}}c(Ft,"createDocumentsFtsTable");function Po(e){e.exec("DROP TRIGGER IF EXISTS documents_ai"),e.exec("DROP TRIGGER IF EXISTS documents_ad"),e.exec("DROP TRIGGER IF EXISTS documents_au"),e.exec("DROP TABLE IF EXISTS documents_fts"),Ft(e),e.exec("DELETE FROM store_config WHERE key = 'fts_cjk_normalized_version'")}c(Po,"recreateDocumentsFts");function kt(e){if(!wt(e)){e.exec("BEGIN IMMEDIATE");try{wt(e)||(bt(e)?(Po(e),Je(e)>=ve&&Mt(e)):Ft(e)),e.exec("COMMIT")}catch(n){throw e.exec("ROLLBACK"),n}}}c(kt,"ensureDocumentsFtsSchema");function Pt(e){return e.prepare("SELECT value FROM store_config WHERE key = 'fts_cjk_normalized_version'").get()?.value}c(Pt,"cjkRebuildVersion");function Ht(e){return`"${e.replace(/"/g,'""')}"`}c(Ht,"quoteSqlIdentifier");function Wt(e,n){e.exec(`DROP TABLE IF EXISTS ${Ht(n)}`)}c(Wt,"dropTableIfExists");function Ho(e){if(kt(e),Pt(e)===Ke)return;Wt(e,"documents_fts_rebuild");const n=500,t=`documents_fts_rebuild_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2)}`,o=Ht(t);try{e.exec(`
44
+ CREATE VIRTUAL TABLE ${o} USING fts5(
45
+ filepath, title, body,
46
+ tokenize='porter unicode61'
47
+ )
48
+ `);const r=e.prepare(`INSERT INTO ${o}(rowid, filepath, title, body) VALUES (?, ?, ?, ?)`);let s=[];const a=e.transaction(()=>{for(const l of s)r.run(l.id,de(`${l.collection}/${l.path}`),de(l.title),de(l.body))}),i=e.prepare(`
49
+ SELECT d.id, d.collection, d.path, d.title, content.doc as body
50
+ FROM documents d
51
+ JOIN content ON content.hash = d.hash
52
+ WHERE d.active = 1
53
+ AND d.id > ?
54
+ ORDER BY d.id
55
+ LIMIT ?
56
+ `);let u=0;for(;s=i.all(u,n),s.length!==0;)a(),u=s[s.length-1].id;e.exec("BEGIN IMMEDIATE");try{Pt(e)!==Ke&&(e.exec("DELETE FROM documents_fts"),e.exec(`INSERT INTO documents_fts(rowid, filepath, title, body)
57
+ SELECT rowid, filepath, title, body FROM ${o}`),e.prepare(`
58
+ INSERT OR REPLACE INTO store_config(key, value)
59
+ VALUES ('fts_cjk_normalized_version', ?)
60
+ `).run(Ke)),e.exec("COMMIT")}catch(l){throw e.exec("ROLLBACK"),l}}finally{Wt(e,t)}}c(Ho,"rebuildFTSForCjkNormalization");function Wo(e){try{Un(e),Ao(e),Ae=!0,Le=null}catch(n){Ae=!1,Le=ze(n),console.warn(Le)}e.exec("PRAGMA foreign_keys = ON"),e.exec("DROP TABLE IF EXISTS path_contexts"),e.exec("DROP TABLE IF EXISTS collections"),e.exec(`
61
+ CREATE TABLE IF NOT EXISTS content (
62
+ hash TEXT PRIMARY KEY,
63
+ doc TEXT NOT NULL,
64
+ created_at TEXT NOT NULL
65
+ )
66
+ `),e.exec(`
67
+ CREATE TABLE IF NOT EXISTS documents (
68
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
69
+ collection TEXT NOT NULL,
70
+ path TEXT NOT NULL,
71
+ title TEXT NOT NULL,
72
+ hash TEXT NOT NULL,
73
+ created_at TEXT NOT NULL,
74
+ modified_at TEXT NOT NULL,
75
+ active INTEGER NOT NULL DEFAULT 1,
76
+ FOREIGN KEY (hash) REFERENCES content(hash) ON DELETE CASCADE,
77
+ UNIQUE(collection, path)
78
+ )
79
+ `),e.exec("CREATE INDEX IF NOT EXISTS idx_documents_collection ON documents(collection, active)"),e.exec("CREATE INDEX IF NOT EXISTS idx_documents_hash ON documents(hash)"),e.exec("CREATE INDEX IF NOT EXISTS idx_documents_path ON documents(path, active)"),e.exec(`
80
+ CREATE TABLE IF NOT EXISTS llm_cache (
81
+ hash TEXT PRIMARY KEY,
82
+ result TEXT NOT NULL,
83
+ created_at TEXT NOT NULL
84
+ )
85
+ `),e.exec(`
86
+ CREATE TABLE IF NOT EXISTS content_vectors (
87
+ hash TEXT NOT NULL,
88
+ seq INTEGER NOT NULL DEFAULT 0,
89
+ pos INTEGER NOT NULL DEFAULT 0,
90
+ model TEXT NOT NULL,
91
+ embed_fingerprint TEXT NOT NULL DEFAULT '',
92
+ total_chunks INTEGER NOT NULL DEFAULT 1,
93
+ embedded_at TEXT NOT NULL,
94
+ PRIMARY KEY (hash, seq)
95
+ )
96
+ `),Xt(e),ro(e),e.exec(`
97
+ CREATE TABLE IF NOT EXISTS store_collections (
98
+ name TEXT PRIMARY KEY,
99
+ path TEXT NOT NULL,
100
+ pattern TEXT NOT NULL DEFAULT '**/*.md',
101
+ ignore_patterns TEXT,
102
+ include_by_default INTEGER DEFAULT 1,
103
+ update_command TEXT,
104
+ context TEXT
105
+ )
106
+ `),e.exec(`
107
+ CREATE TABLE IF NOT EXISTS store_config (
108
+ key TEXT PRIMARY KEY,
109
+ value TEXT
110
+ )
111
+ `),kt(e),wo(e),Ho(e)}c(Wo,"initializeDatabase");function qt(e){return{name:e.name,path:e.path,pattern:e.pattern,...e.ignore_patterns?{ignore:JSON.parse(e.ignore_patterns)}:{},...e.include_by_default===0?{includeByDefault:!1}:{},...e.update_command?{update:e.update_command}:{},...e.context?{context:JSON.parse(e.context)}:{}}}c(qt,"rowToNamedCollection");function oe(e){return e.prepare("SELECT * FROM store_collections").all().map(qt)}c(oe,"getStoreCollections");function Ie(e,n){const t=e.prepare("SELECT * FROM store_collections WHERE name = ?").get(n);return t==null?null:qt(t)}c(Ie,"getStoreCollection");function Me(e){const n=e.prepare("SELECT value FROM store_config WHERE key = 'global_context'").get();if(n!=null)return n.value||void 0}c(Me,"getStoreGlobalContext");function fr(e){const n=[],t=Me(e);t&&n.push({collection:"*",path:"/",context:t});const o=e.prepare("SELECT name, context FROM store_collections WHERE context IS NOT NULL").all();for(const r of o){const s=JSON.parse(r.context);for(const[a,i]of Object.entries(s))n.push({collection:r.name,path:a,context:i})}return n}c(fr,"getStoreContexts");function qo(e,n,t){e.prepare(`
112
+ INSERT INTO store_collections (name, path, pattern, ignore_patterns, include_by_default, update_command, context)
113
+ VALUES (?, ?, ?, ?, ?, ?, ?)
114
+ ON CONFLICT(name) DO UPDATE SET
115
+ path = excluded.path,
116
+ pattern = excluded.pattern,
117
+ ignore_patterns = excluded.ignore_patterns,
118
+ include_by_default = excluded.include_by_default,
119
+ update_command = excluded.update_command,
120
+ context = excluded.context
121
+ `).run(n,t.path,t.pattern||"**/*.md",t.ignore?JSON.stringify(t.ignore):null,t.includeByDefault===!1?0:1,t.update||null,t.context?JSON.stringify(t.context):null)}c(qo,"upsertStoreCollection");function Uo(e,n){return e.prepare("DELETE FROM store_collections WHERE name = ?").run(n).changes>0}c(Uo,"deleteStoreCollection");function Bo(e,n,t){if(e.prepare("SELECT name FROM store_collections WHERE name = ?").get(t)!=null)throw new Error(`Collection '${t}' already exists`);return e.prepare("UPDATE store_collections SET name = ? WHERE name = ?").run(t,n).changes>0}c(Bo,"renameStoreCollection");function $o(e,n,t,o){const r=e.prepare("SELECT context FROM store_collections WHERE name = ?").get(n);if(r==null)return!1;const s=r.context?JSON.parse(r.context):{};return s[t]=o,e.prepare("UPDATE store_collections SET context = ? WHERE name = ?").run(JSON.stringify(s),n),!0}c($o,"updateStoreContext");function pr(e,n,t){const o=e.prepare("SELECT context FROM store_collections WHERE name = ?").get(n);if(o==null||!o.context)return!1;const r=JSON.parse(o.context);if(!(t in r))return!1;delete r[t];const s=Object.keys(r).length>0?JSON.stringify(r):null;return e.prepare("UPDATE store_collections SET context = ? WHERE name = ?").run(s,n),!0}c(pr,"removeStoreContext");function Ut(e,n){n===void 0?e.prepare("DELETE FROM store_config WHERE key = 'global_context'").run():e.prepare("INSERT INTO store_config (key, value) VALUES ('global_context', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(n)}c(Ut,"setStoreGlobalContext");function Er(e,n){const t=JSON.stringify(n),o=Ce("sha256").update(t).digest("hex"),r=e.prepare("SELECT value FROM store_config WHERE key = 'config_hash'").get();if(r!=null&&r.value===o)return;const s=new Set(Object.keys(n.collections));for(const[i,u]of Object.entries(n.collections))qo(e,i,u);const a=e.prepare("SELECT name FROM store_collections").all();for(const i of a)s.has(i.name)||e.prepare("DELETE FROM store_collections WHERE name = ?").run(i.name);n.global_context!==void 0?Ut(e,n.global_context):Ut(e,void 0),e.prepare("INSERT INTO store_config (key, value) VALUES ('config_hash', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(o)}c(Er,"syncConfigToDb");function mr(){return Ae===!0}c(mr,"isSqliteVecAvailable");function Vo(e,n){if(!Ae)throw vt(Le??"vector operations require a SQLite build with extension loading support");const t=e.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name='vectors_vec'").get();if(t){const o=t.sql.match(/float\[(\d+)\]/),r=t.sql.includes("hash_seq"),s=t.sql.includes("distance_metric=cosine"),a=o?.[1]?parseInt(o[1],10):null;if(a===n&&r&&s)return;if(a!==null&&a!==n)throw new Error(`Embedding dimension mismatch: existing vectors are ${a}d but the current model produces ${n}d. Run 'qmd embed -f' to re-embed with the new model.`);e.exec("DROP TABLE IF EXISTS vectors_vec")}e.exec(`CREATE VIRTUAL TABLE vectors_vec USING vec0(hash_seq TEXT PRIMARY KEY, embedding float[${n}] distance_metric=cosine)`)}c(Vo,"ensureVecTableInternal");function Ye(e){if(e&&typeof e=="object"&&"code"in e){const n=e.code;if(typeof n=="string"&&n.length>0)return n}return"ERROR"}c(Ye,"fsErrorCode");async function Xo(e,n,t){const r=[...["node_modules",".git",".cache","vendor","dist","build"].map(a=>`**/${a}/**`),...t||[]];return(await Vn(lo(n),{cwd:e,onlyFiles:!0,followSymbolicLinks:!1,dot:!1,ignore:r})).filter(a=>!a.split("/").some(u=>u.startsWith(".")))}c(Xo,"listCollectionFiles");async function gr(e,n,t,o,r){const s=e.db,a=new Date().toISOString(),i=await Xo(n,t,r?.ignorePatterns),u=i.length;let l=0,d=0,f=0,h=0,m=0;const T=[],p=new Set,_=new Set(i.map(y=>pe(y)));for(const y of i){const w=Ot(ce(n,y)),W=pe(y);if(!Lt(n,w)){h++,T.push({file:y,code:"OUTSIDE_COLLECTION"}),r?.onProgress?.({file:y,current:h,total:u});continue}p.add(W);let k;try{k=Bn(w,"utf-8")}catch($){h++,T.push({file:y,code:Ye($)}),r?.onProgress?.({file:y,current:h,total:u});continue}if(!k.trim()){p.delete(W),h++;continue}const q=await rs(k),b=et(k,y),g=en(s,o,W,_);let O,H=!0;if(g)if(O=g.id,g.hash===q)H=!1,g.title!==b?(tn(s,g.id,b,a),d++):f++;else{tt(s,q,k,a);let $;try{$=mt(w)}catch(Q){h++,T.push({file:y,code:Ye(Q)}),r?.onProgress?.({file:y,current:h,total:u});continue}nn(s,g.id,b,q,$?new Date($.mtime).toISOString():a),d++}else{tt(s,q,k,a);let $;try{$=mt(w)}catch(Q){h++,T.push({file:y,code:Ye(Q)}),r?.onProgress?.({file:y,current:h,total:u});continue}O=Zt(s,o,W,b,q,$?new Date($.birthtime).toISOString():a,$?new Date($.mtime).toISOString():a),l++}co(s,O,k,W,H?void 0:{onlyIfStale:!0})?.error&&m++,h++,r?.onProgress?.({file:y,current:h,total:u})}const L=sn(s,o);let N=0;for(const y of L)p.has(y)||(on(s,o,y),N++);const S=Fe(s);return{indexed:l,updated:d,unchanged:f,removed:N,orphanedCleaned:S,skipped:T.length,skippedFiles:T,metadataErrors:m}}c(gr,"reindexCollection");function Bt(e,n,t){if(n===void 0)return t;if(!Number.isInteger(n)||n<1)throw new Error(`${e} must be a positive integer`);return n}c(Bt,"validatePositiveIntegerOption");function Go(e){return{maxDocsPerBatch:Bt("maxDocsPerBatch",e?.maxDocsPerBatch,ho),maxBatchBytes:Bt("maxBatchBytes",e?.maxBatchBytes,fo)}}c(Go,"resolveEmbedOptions");const $t=[{name:"seq",definition:"INTEGER NOT NULL DEFAULT 0"},{name:"pos",definition:"INTEGER NOT NULL DEFAULT 0"},{name:"model",definition:"TEXT NOT NULL DEFAULT ''"},{name:"embed_fingerprint",definition:"TEXT NOT NULL DEFAULT ''"},{name:"total_chunks",definition:"INTEGER NOT NULL DEFAULT 1"},{name:"embedded_at",definition:"TEXT NOT NULL DEFAULT ''"}];function Vt(e){const n=e instanceof Error?e.message:String(e);return/(no such column|has no column named)/i.test(n)?$t.some(t=>n.includes(t.name)):!1}c(Vt,"isContentVectorColumnError");function Xt(e){try{e.exec(`
122
+ CREATE INDEX IF NOT EXISTS idx_content_vectors_model_fingerprint
123
+ ON content_vectors(model, embed_fingerprint, hash, total_chunks)
124
+ `)}catch(n){if(!Vt(n))throw n}}c(Xt,"ensureContentVectorsStatusIndex");function zo(e){for(const n of $t)try{e.exec(`ALTER TABLE content_vectors ADD COLUMN ${n.name} ${n.definition}`)}catch(t){if(!(t instanceof Error?t.message:String(t)).includes("duplicate column name"))throw t}Xt(e)}c(zo,"runContentVectorColumnRepairs");function Z(e,n){let t=!1;for(;;)try{return n()}catch(o){if(t||!Vt(o))throw o;zo(e),t=!0}}c(Z,"withLazyContentVectorMigration");function Ko(e,n,t=te){const o=n?"AND d.collection = ?":"",r=fe(t);return Z(e,()=>{const s=e.prepare(`
125
+ SELECT d.hash, MIN(d.path) as path, length(CAST(c.doc AS BLOB)) as bytes
126
+ FROM documents d
127
+ JOIN content c ON d.hash = c.hash
128
+ LEFT JOIN (
129
+ SELECT hash, model, COUNT(*) AS chunk_count, MAX(total_chunks) AS expected_chunks
130
+ FROM content_vectors
131
+ WHERE model = ? AND embed_fingerprint = ?
132
+ GROUP BY hash, model, embed_fingerprint
133
+ ) v ON d.hash = v.hash
134
+ WHERE d.active = 1
135
+ AND (v.hash IS NULL OR v.chunk_count < v.expected_chunks)
136
+ ${o}
137
+ GROUP BY d.hash
138
+ ORDER BY MIN(d.path)
139
+ `);return n?s.all(t,r,n):s.all(t,r)})}c(Ko,"getPendingEmbeddingDocs");function jo(e,n,t){const o=[];let r=[],s=0;for(const a of e){const i=Math.max(0,a.bytes),u=r.length>=n,l=r.length>0&&s+i>t;(u||l)&&(o.push(r),r=[],s=0),r.push(a),s+=i}return r.length>0&&o.push(r),o}c(jo,"buildEmbeddingBatches");function Jo(e,n){if(n.length===0)return[];const t=n.map(()=>"?").join(","),o=e.prepare(`
140
+ SELECT hash, doc as body
141
+ FROM content
142
+ WHERE hash IN (${t})
143
+ `).all(...n.map(s=>s.hash)),r=new Map(o.map(s=>[s.hash,s.body]));return n.map(s=>({...s,body:r.get(s.hash)??""}))}c(Jo,"getEmbeddingDocsForBatch");async function Tr(e,n){const t=e.db,o=ue(e),r=n?.model??o.embedModelName??te,s=fe(r),a=new Date().toISOString(),{maxDocsPerBatch:i,maxBatchBytes:u}=Go(n),l=new TextEncoder;n?.force&&yn(t,n?.collection);const d=Ko(t,n?.collection,r);if(d.length===0)return{docsProcessed:0,chunksEmbedded:0,errors:0,durationMs:0};const f=d.reduce((p,_)=>p+Math.max(0,_.bytes),0),h=Date.now(),m=r,T=await Tt(o,async p=>{let _=0,L=0,N=0,S=0,y=!1;const w=32,W=64,k=3,q=new Map,b=new Map;let g=0,O=!1;const H=c(()=>[...q.values()],"failureList"),G=c(()=>q.size,"activeErrorCount"),$=c(E=>`${E.hash}:${E.seq}`,"chunkKey"),Q=c(E=>{const C=E instanceof Error?E.message:String(E);return C.length>180?`${C.slice(0,177)}...`:C},"reasonFromError"),z=c((E,C)=>{const R=$(E),K=q.get(R);q.set(R,{path:E.path,hash:E.hash,seq:E.seq,attempts:(K?.attempts??0)+1,reason:C}),b.set(R,E)},"recordFailure"),J=c(E=>{const C=$(E);q.delete(C),b.delete(C)},"clearFailure"),se=c(async E=>{try{const C=le(E.text,E.title,m),R=await p.embed(C,{model:r});return R?(ut(t,E.hash,E.seq,E.pos,new Float32Array(R.embedding),r,a,E.expectedTotalChunks,s),_++,g++,J(E),!0):(z(E,"embedding returned no vector"),!1)}catch(C){return z(E,Q(C)),!1}},"tryEmbedChunk"),ne=c(async(E=!1)=>{if(!(!p.isValid||b.size===0)&&!(!E&&g<W)){g=0;do{let C=0;for(const[R,K]of[...b]){const P=q.get(R);!P||P.attempts>=k||(C++,await se(K))}if(!E||C===0)break}while(p.isValid&&[...b].some(([C])=>{const R=q.get(C);return!!R&&R.attempts<k}))}},"retryFailedChunks"),ie=jo(d,i,u);for(const E of ie){if(!p.isValid){console.warn("\u26A0 Session expired \u2014 skipping remaining document batches");break}if(O)break;const C=Jo(t,E),R=[],K=new Map,P=E.reduce((D,M)=>D+Math.max(0,M.bytes),0);for(const D of C){if(!D.body.trim())continue;const M=et(D.body,D.path),F=await ot(o,D.body,void 0,void 0,void 0,D.path,n?.chunkStrategy,p.signal);for(let v=0;v<F.length;v++)R.push({hash:D.hash,path:D.path,title:M,text:F[v].text,seq:v,pos:F[v].pos,tokens:F[v].tokens,bytes:l.encode(F[v].text).length,expectedTotalChunks:F.length});K.set(D.hash,F.length),xs(t,D.hash,r,F.length)}if(N+=R.length,R.length===0){L+=P,n?.onProgress?.({chunksEmbedded:_,totalChunks:N,bytesProcessed:L,totalBytes:f,errors:G(),failures:H()});continue}if(!y){const D=R[0],M=le(D.text,D.title,m),F=await p.embed(M,{model:r});if(!F)throw new Error("Failed to get embedding dimensions from first chunk");e.ensureVecTable(F.embedding.length),y=!0}const j=R.reduce((D,M)=>D+M.bytes,0);let x=0,I=!0;for(let D=0;D<R.length;D+=w){if(!p.isValid){const U=R.slice(D);for(const B of U)z(B,"LLM session expired before embedding chunk");console.warn(`\u26A0 Session expired \u2014 skipping ${U.length} remaining chunks`),I=!1;break}const M=_+G();if(M>=w&&G()>M*.8){const U=R.slice(D);for(const B of U)z(B,"embedding aborted because error rate was too high");console.warn(`\u26A0 Error rate too high (${G()}/${M}) \u2014 aborting embedding`),I=!1,O=!0;break}const F=Math.min(D+w,R.length),v=R.slice(D,F),V=v.map(U=>le(U.text,U.title,m));try{const U=await p.embedBatch(V,{model:r});for(let B=0;B<v.length;B++){const X=v[B],ee=U[B];ee?(ut(t,X.hash,X.seq,X.pos,new Float32Array(ee.embedding),r,a,X.expectedTotalChunks,s),_++,g++,J(X)):z(X,"batch embedding returned no vector"),x+=X.bytes}await ne()}catch(U){const B=Q(U);if(p.isValid)for(const X of v)await se(X),x+=X.bytes,await ne();else{for(const X of v)z(X,`batch failed and session expired: ${B}`);x+=v.reduce((X,ee)=>X+ee.bytes,0)}}const Y=j===0?P:Math.min(P,Math.round(x/j*P));n?.onProgress?.({chunksEmbedded:_,totalChunks:N,bytesProcessed:L+Y,totalBytes:f,errors:G(),failures:H()})}O||await ne(!0);const A=Ss(t,K,r);A>0&&(_=Math.max(0,_-A)),I&&(S+=K.size),L+=P,n?.onProgress?.({chunksEmbedded:_,totalChunks:N,bytesProcessed:L,totalBytes:f,errors:G(),failures:H()})}return{chunksEmbedded:_,docsProcessed:S,errors:G(),failures:H()}},{maxDuration:n?.maxDurationMs??po,name:"generateEmbeddings"});return{docsProcessed:T.docsProcessed,chunksEmbedded:T.chunksEmbedded,errors:T.errors,failures:T.failures,durationMs:Date.now()-h}}c(Tr,"generateEmbeddings");function _r(e){const n=e||Co(),t=ht(n);Wo(t);const o=es(process.env.QMD_RERANK_CACHE),r={db:t,dbPath:n,close:c(()=>{o?.close(),t.close()},"close"),ensureVecTable:c(s=>Vo(t,s),"ensureVecTable"),getHashesNeedingEmbedding:c(s=>Qe(t,void 0,s??r.llm?.embedModelName??te),"getHashesNeedingEmbedding"),getIndexHealth:c(s=>Zo(t,s??r.llm?.embedModelName??te),"getIndexHealth"),getStatus:c(s=>Fs(t,s??r.llm?.embedModelName??te),"getStatus"),getCacheKey:me,getCachedResult:c(s=>be(t,s),"getCachedResult"),setCachedResult:c((s,a)=>Ze(t,s,a),"setCachedResult"),clearCache:c(()=>ts(t),"clearCache"),deleteLLMCache:c(()=>zt(t),"deleteLLMCache"),deleteInactiveDocuments:c(()=>Kt(t),"deleteInactiveDocuments"),cleanupOrphanedContent:c(()=>Fe(t),"cleanupOrphanedContent"),cleanupOrphanedVectors:c(()=>Yt(t),"cleanupOrphanedVectors"),vacuumDatabase:c(()=>Qt(t),"vacuumDatabase"),getContextForFile:c(s=>hn(t,s),"getContextForFile"),getContextForPath:c((s,a)=>ls(t,s,a),"getContextForPath"),getCollectionByName:c(s=>fn(t,s),"getCollectionByName"),getCollectionsWithoutContext:c(()=>us(t),"getCollectionsWithoutContext"),getTopLevelPathsWithoutContext:c(s=>ds(t,s),"getTopLevelPathsWithoutContext"),parseVirtualPath:Ee,buildVirtualPath:At,isVirtualPath:Ge,resolveVirtualPath:c(s=>Oo(t,s),"resolveVirtualPath"),toVirtualPath:c(s=>Lo(t,s),"toVirtualPath"),searchFTS:c((s,a,i,u,l,d)=>_n(t,s,a,i,u,l,d),"searchFTS"),searchVec:c((s,a,i,u,l,d,f,h)=>Rn(t,s,a,i,u,l,d,ue(r),f,h),"searchVec"),expandQuery:c((s,a,i)=>Rs(s,a??r.llm?.generateModelName??De,t,r.llm,i),"expandQuery"),invalidateExpansionCache:c(s=>ys(t,s,r.llm?.generateModelName??De),"invalidateExpansionCache"),rerank:c((s,a,i,u,l)=>{const d=ue(r);return Ns(s,a,i??d.rerankModelName??xt,o??t,u,d,l)},"rerank"),findDocument:c((s,a)=>Is(t,s,a),"findDocument"),getDocumentBody:c((s,a,i)=>Ms(t,s,a,i),"getDocumentBody"),findDocuments:c((s,a)=>bs(t,s,a),"findDocuments"),findSimilarFiles:c((s,a,i)=>ct(t,s,a,i),"findSimilarFiles"),matchFilesByGlob:c(s=>dn(t,s),"matchFilesByGlob"),findDocumentByDocid:c(s=>rt(t,s),"findDocumentByDocid"),insertContent:c((s,a,i)=>tt(t,s,a,i),"insertContent"),insertDocument:c((s,a,i,u,l,d)=>Zt(t,s,a,i,u,l,d),"insertDocument"),findActiveDocument:c((s,a)=>nt(t,s,a),"findActiveDocument"),findOrMigrateLegacyDocument:c((s,a)=>en(t,s,a),"findOrMigrateLegacyDocument"),updateDocumentTitle:c((s,a,i)=>tn(t,s,a,i),"updateDocumentTitle"),updateDocument:c((s,a,i,u)=>nn(t,s,a,i,u),"updateDocument"),deactivateDocument:c((s,a)=>on(t,s,a),"deactivateDocument"),getActiveDocumentPaths:c(s=>sn(t,s),"getActiveDocumentPaths"),getHashesForEmbedding:c(()=>_s(t),"getHashesForEmbedding"),clearAllEmbeddings:c(()=>yn(t),"clearAllEmbeddings"),insertEmbedding:c((s,a,i,u,l,d,f,h)=>ut(t,s,a,i,u,l,d,f,h),"insertEmbedding")};return r}c(_r,"createStore");function we(e){return e.slice(0,6)}c(we,"getDocid");function Yo(e){return e.replace(/(?:\p{So}\p{Mn}?|\p{Sk})+/gu,n=>[...n].filter(t=>/\p{So}|\p{Sk}/u.test(t)).map(t=>t.codePointAt(0).toString(16)).join("-"))}c(Yo,"emojiToHex");function Qo(e){if(!e||e.trim()==="")throw new Error("handelize: path cannot be empty");const n=e.split("/").filter(Boolean),o=(n[n.length-1]||"").replace(/\.[^.]+$/,"");if(!/[\p{L}\p{N}\p{So}\p{Sk}$]/u.test(o))throw new Error(`handelize: path "${e}" has no valid filename content`);const s=e.replace(/___/g,"/").split("/").map((a,i,u)=>{const l=i===u.length-1;if(a=Yo(a),l){const d=a.match(/(\.[a-z0-9]+)$/i),f=d?d[1]:"";return(f?a.slice(0,-f.length):a).replace(/[^\p{L}\p{N}$]+/gu,"-").replace(/^-+|-+$/g,"")+f}else return a.replace(/[^\p{L}\p{N}$]+/gu,"-").replace(/^-+|-+$/g,"")}).filter(Boolean).join("/");if(!s)throw new Error(`handelize: path "${e}" resulted in empty string after processing`);return s}c(Qo,"handelize");function Qe(e,n,t=te){const o=n?"AND d.collection = ?":"",r=fe(t);return Z(e,()=>{const s=e.prepare(`
144
+ SELECT COUNT(DISTINCT d.hash) as count
145
+ FROM documents d
146
+ LEFT JOIN (
147
+ SELECT hash, model, COUNT(*) AS chunk_count, MAX(total_chunks) AS expected_chunks
148
+ FROM content_vectors
149
+ WHERE model = ? AND embed_fingerprint = ?
150
+ GROUP BY hash, model, embed_fingerprint
151
+ ) v ON d.hash = v.hash
152
+ WHERE d.active = 1
153
+ AND (v.hash IS NULL OR v.chunk_count < v.expected_chunks)
154
+ ${o}
155
+ `);return(n?s.get(t,r,n):s.get(t,r)).count})}c(Qe,"getHashesNeedingEmbedding");async function xr(e,n=te){const t=e.db,o=fe(n),r=Z(t,()=>t.prepare("SELECT COUNT(DISTINCT hash) AS count FROM content_vectors WHERE model = ? AND embed_fingerprint = ''").get(n).count);if(r===0)return{checked:!1,adopted:0,reason:"no legacy empty-fingerprint embeddings"};const s=Z(t,()=>t.prepare(`
156
+ SELECT cv.hash, cv.seq, cv.pos, cv.total_chunks, c.doc AS body, MIN(d.path) AS path
157
+ FROM content_vectors cv
158
+ JOIN documents d ON d.hash = cv.hash AND d.active = 1
159
+ JOIN content c ON c.hash = cv.hash
160
+ WHERE cv.model = ? AND cv.embed_fingerprint = ''
161
+ GROUP BY cv.hash, cv.seq, cv.pos, cv.total_chunks, c.doc
162
+ ORDER BY cv.hash, cv.seq
163
+ LIMIT 1
164
+ `).get(n));if(!s)return{checked:!1,adopted:0,reason:`${r} legacy docs have no active sample`};if(!t.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'").get())return{checked:!1,adopted:0,reason:"vectors_vec table is missing"};const i=`${s.hash}_${s.seq}`,u=et(s.body,s.path),l=ue(e);return await Tt(l,async d=>{const h=(await ot(l,s.body,void 0,void 0,void 0,s.path,void 0,d.signal))[s.seq];if(!h)return{checked:!0,adopted:0,reason:`sample chunk ${i} no longer exists`};const m=await d.embed(le(h.text,u,n),{model:n});if(!m)return{checked:!0,adopted:0,reason:"failed to embed legacy sample"};const T=t.prepare(`
165
+ SELECT hash_seq, distance
166
+ FROM vectors_vec
167
+ WHERE embedding MATCH ? AND k = 1
168
+ `).get(new Float32Array(m.embedding));return T?T.hash_seq!==i||T.distance>1e-4?{checked:!0,adopted:0,reason:`legacy sample differs from current fingerprint (nearest ${T.hash_seq}, distance ${T.distance.toFixed(6)})`}:{checked:!0,adopted:Z(t,()=>t.prepare("UPDATE content_vectors SET embed_fingerprint = ? WHERE model = ? AND embed_fingerprint = ''").run(o,n)).changes,reason:`sample ${i} matched current fingerprint at distance ${T.distance.toFixed(6)}`}:{checked:!0,adopted:0,reason:"legacy sample vector not found"}})}c(xr,"maybeAdoptLegacyEmbeddingFingerprint");function Zo(e,n=te){const t=Qe(e,void 0,n),o=e.prepare("SELECT COUNT(*) as count FROM documents WHERE active = 1").get().count,r=e.prepare("SELECT MAX(modified_at) as latest FROM documents WHERE active = 1").get();let s=null;if(r?.latest){const a=new Date(r.latest);s=Math.floor((Date.now()-a.getTime())/(1440*60*1e3))}return{needsEmbedding:t,totalDocs:o,daysStale:s}}c(Zo,"getIndexHealth");function me(e,n){const t=Ce("sha256");return t.update(e),t.update(JSON.stringify(n)),t.digest("hex")}c(me,"getCacheKey");function be(e,n){return e.prepare("SELECT result FROM llm_cache WHERE hash = ?").get(n)?.result??null}c(be,"getCachedResult");const Gt=new WeakSet,es=c(e=>{if(!e)return;const n=ht(e);return n.exec("CREATE TABLE IF NOT EXISTS llm_cache (hash TEXT PRIMARY KEY, result TEXT NOT NULL, created_at TEXT NOT NULL)"),Gt.add(n),n},"openRerankCache");function Ze(e,n,t){const o=new Date().toISOString();e.prepare("INSERT OR REPLACE INTO llm_cache (hash, result, created_at) VALUES (?, ?, ?)").run(n,t,o),!Gt.has(e)&&Math.random()<.01&&e.exec("DELETE FROM llm_cache WHERE hash NOT IN (SELECT hash FROM llm_cache ORDER BY created_at DESC LIMIT 1000)")}c(Ze,"setCachedResult");function ts(e){e.exec("DELETE FROM llm_cache")}c(ts,"clearCache");function zt(e){return e.prepare("DELETE FROM llm_cache").run().changes}c(zt,"deleteLLMCache");function Kt(e){return e.prepare("DELETE FROM documents WHERE active = 0").run().changes}c(Kt,"deleteInactiveDocuments");function Fe(e){return e.prepare(`
169
+ DELETE FROM content
170
+ WHERE hash NOT IN (SELECT DISTINCT hash FROM documents)
171
+ `).run().changes}c(Fe,"cleanupOrphanedContent");function ns(e){return e.prepare(`
172
+ SELECT COUNT(*) as c FROM content
173
+ WHERE hash NOT IN (SELECT DISTINCT hash FROM documents WHERE active = 1)
174
+ `).get().c}c(ns,"countOrphanedContent");const jt=`
175
+ SELECT COUNT(*) as c FROM content_vectors cv
176
+ WHERE NOT EXISTS (
177
+ SELECT 1 FROM documents d WHERE d.hash = cv.hash AND d.active = 1
178
+ )
179
+ `;function os(e){try{return Z(e,()=>e.prepare(jt).get().c)}catch(n){const t=n instanceof Error?n.message:String(n);if(/no such table/i.test(t))return 0;throw n}}c(os,"countOrphanedVectors");function Jt(e){try{e.prepare("SELECT 1 FROM vectors_vec LIMIT 0").get()}catch{return!1}return!0}c(Jt,"isVectorCleanupActionable");function Yt(e){return Jt(e)?Z(e,()=>e.transaction(()=>{const t=e.prepare(jt).get().c;return t===0?0:(e.exec(`
180
+ DELETE FROM vectors_vec WHERE hash_seq IN (
181
+ SELECT cv.hash || '_' || cv.seq FROM content_vectors cv
182
+ WHERE NOT EXISTS (
183
+ SELECT 1 FROM documents d WHERE d.hash = cv.hash AND d.active = 1
184
+ )
185
+ )
186
+ `),e.exec(`
187
+ DELETE FROM content_vectors WHERE hash NOT IN (
188
+ SELECT hash FROM documents WHERE active = 1
189
+ )
190
+ `),t)}).immediate()):0}c(Yt,"cleanupOrphanedVectors");function Qt(e){e.exec("VACUUM")}c(Qt,"vacuumDatabase");function ss(e){try{e.exec("INSERT INTO documents_fts(documents_fts) VALUES('optimize')")}catch(n){const t=n instanceof Error?n.message:String(n);if(/no such table/i.test(t))return;throw n}}c(ss,"optimizeDocumentsFts");function Sr(e){const n=e.prepare("SELECT COUNT(*) as c FROM llm_cache").get().c,t=Jt(e)?os(e):0,o=e.prepare("SELECT COUNT(*) as c FROM documents WHERE active = 0").get().c,r=ns(e);return{cacheCount:n,orphanedVectors:t,inactiveDocs:o,orphanedContent:r}}c(Sr,"previewCleanup");function Rr(e){const n=zt(e),t=Yt(e),o=Kt(e),r=Fe(e);return ss(e),Qt(e),{cacheCount:n,orphanedVectors:t,inactiveDocs:o,orphanedContent:r}}c(Rr,"runCleanup");async function rs(e){const n=Ce("sha256");return n.update(e),n.digest("hex")}c(rs,"hashContent");const cs={".md":c(e=>{const n=e.match(/^##?\s+(.+)$/m);if(n){const t=(n[1]??"").trim();if(t==="\u{1F4DD} Notes"||t==="Notes"){const o=e.match(/^##\s+(.+)$/m);if(o?.[1])return o[1].trim()}return t}return null},".md"),".org":c(e=>{const n=e.match(/^#\+TITLE:\s*(.+)$/im);if(n?.[1])return n[1].trim();const t=e.match(/^\*+\s+(.+)$/m);return t?.[1]?t[1].trim():null},".org")};function et(e,n){const t=n.slice(n.lastIndexOf(".")).toLowerCase(),o=cs[t];if(o){const r=o(e);if(r)return r}return n.replace(/\.[^.]+$/,"").split("/").pop()||n}c(et,"extractTitle");function tt(e,n,t,o){e.prepare("INSERT OR IGNORE INTO content (hash, doc, created_at) VALUES (?, ?, ?)").run(n,t,o)}c(tt,"insertContent");function ke(e,n){const t=e.prepare(`
191
+ SELECT d.id, d.collection, d.path, d.title, content.doc as body
192
+ FROM documents d
193
+ JOIN content ON content.hash = d.hash
194
+ WHERE d.id = ? AND d.active = 1
195
+ `).get(n);e.prepare("DELETE FROM documents_fts WHERE rowid = ?").run(n),t&&e.prepare(`
196
+ INSERT INTO documents_fts(rowid, filepath, title, body)
197
+ VALUES (?, ?, ?, ?)
198
+ `).run(t.id,de(`${t.collection}/${t.path}`),de(t.title),de(t.body))}c(ke,"rebuildDocumentFTS");function Zt(e,n,t,o,r,s,a){e.prepare(`
199
+ INSERT INTO documents (collection, path, title, hash, created_at, modified_at, active)
200
+ VALUES (?, ?, ?, ?, ?, ?, 1)
201
+ ON CONFLICT(collection, path) DO UPDATE SET
202
+ title = excluded.title,
203
+ hash = excluded.hash,
204
+ modified_at = excluded.modified_at,
205
+ active = 1
206
+ `).run(n,t,o,r,s,a);const i=e.prepare("SELECT id FROM documents WHERE collection = ? AND path = ?").get(n,t);if(!i)throw new Error(`Document row missing after insert: ${n}/${t}`);return ke(e,i.id),i.id}c(Zt,"insertDocument");function nt(e,n,t){return e.prepare(`
207
+ SELECT id, hash, title FROM documents
208
+ WHERE collection = ? AND path = ? AND active = 1
209
+ `).get(n,t)??null}c(nt,"findActiveDocument");function en(e,n,t,o){const r=nt(e,n,t);if(r)return r;let s;try{const u=Qo(t);if(u!==t){const l=e.prepare(`
210
+ SELECT id, hash, title, path FROM documents
211
+ WHERE collection = ? AND path = ? AND active = 1
212
+ ORDER BY id
213
+ LIMIT 1
214
+ `).get(n,u);l&&!o?.has(l.path)&&(s=l)}}catch{}const a=s;return!a||!e.transaction(()=>e.prepare("UPDATE OR IGNORE documents SET path = ? WHERE id = ? AND active = 1").run(t,a.id).changes===0?!1:(ke(e,a.id),!0))()?null:nt(e,n,t)}c(en,"findOrMigrateLegacyDocument");function tn(e,n,t,o){e.prepare("UPDATE documents SET title = ?, modified_at = ? WHERE id = ?").run(t,o,n),e.prepare("UPDATE documents_fts SET title = ? WHERE rowid = ?").run(de(t),n).changes===0&&ke(e,n)}c(tn,"updateDocumentTitle");function nn(e,n,t,o,r){e.prepare("UPDATE documents SET title = ?, hash = ?, modified_at = ? WHERE id = ?").run(t,o,r,n),ke(e,n)}c(nn,"updateDocument");function on(e,n,t){e.prepare("UPDATE documents SET active = 0 WHERE collection = ? AND path = ? AND active = 1").run(n,t)}c(on,"deactivateDocument");function sn(e,n){return e.prepare(`
215
+ SELECT path FROM documents WHERE collection = ? AND active = 1
216
+ `).all(n).map(o=>o.path)}c(sn,"getActiveDocumentPaths");function rn(e,n=Se,t=Ue,o=Oe){const r=St(e),s=Rt(e);return Nt(e,r,s,n,t,o)}c(rn,"chunkDocument");async function cn(e,n=Se,t=Ue,o=Oe,r,s="regex"){const a=St(e),i=Rt(e);let u=a;if(s==="auto"&&r){const{getASTBreakPoints:l}=await import("./ast.js"),d=await l(e,r);d.length>0&&(u=So(a,d))}return Nt(e,u,i,n,t,o)}c(cn,"chunkDocumentAsync");function an(e){let n=0,t=e.length;if(t>0){const o=e.charCodeAt(0),r=o>=56320&&o<=57343,s=o>=55296&&o<=56319;if(r)n=1;else if(s){const a=t>1?e.charCodeAt(1):NaN;a>=56320&&a<=57343||(n=1)}}if(t>n){const o=e.charCodeAt(t-1),r=o>=55296&&o<=56319,s=o>=56320&&o<=57343;if(r)t-=1;else if(s){const a=t-1>n?e.charCodeAt(t-2):NaN;a>=55296&&a<=56319||(t-=1)}}return n===0&&t===e.length?e:e.slice(n,t)}c(an,"stripUnpairedSurrogates");function ln(e,n=re,t=he,o=Re,r){const s=zn(e,r);return{maxChars:Math.floor(n*s),overlapChars:Math.floor(t*s),windowChars:Math.floor(o*s)}}c(ln,"scriptAwareCharBudgets");const as=Se/re;async function ot(e,n,t=re,o=he,r=Re,s,a="regex",i){const{maxChars:u,overlapChars:l,windowChars:d}=ln(n,t,o,r);let f=await cn(n,u,l,d,s,a);const h=[],m=c((p,_)=>_<=1?0:Math.max(0,Math.min(_-1,Math.floor(p))),"clampOverlapChars"),T=c(async(p,_)=>{if(i?.aborted)return;const L=await e.tokenize(p);if(L.length<=t||p.length<=1){const k=an(p);if(k.length===0)return;h.push({text:k,pos:_,tokens:L.length});return}const N=p.length/L.length;let S=Math.floor(t*N*.95);(!Number.isFinite(S)||S<1)&&(S=Math.floor(p.length/2)),S=Math.max(1,Math.min(p.length-1,S));let y=m(l*N/2,S),w=Math.max(0,Math.floor(d*N/2)),W=rn(p,S,y,w);if((W.length<=1||W[0]?.text.length===p.length)&&(S=Math.max(1,Math.floor(p.length/2)),y=0,w=0,W=rn(p,S,y,w)),W.length<=1||W[0]?.text.length===p.length){const k=L.slice(0,Math.max(1,t)),q=an(await e.detokenize(k));if(q.length===0)return;h.push({text:q,pos:_,tokens:k.length});return}for(const k of W)await T(p.slice(k.pos,k.pos+k.text.length),_+k.pos)},"pushChunkWithinTokenLimit");for(const p of f)await T(p.text,p.pos);return h}c(ot,"chunkDocumentByTokensWithLlm");async function yr(e,n=re,t=he,o=Re,r,s="regex",a){return await ot(_e(),e,n,t,o,r,s,a)}c(yr,"chunkDocumentByTokens");function is(e,n){const t=e.length,o=n.length;if(t===0)return o;if(o===0)return t;const r=Array.from({length:t+1},()=>Array(o+1).fill(0));for(let s=0;s<=t;s++)r[s][0]=s;for(let s=0;s<=o;s++)r[0][s]=s;for(let s=1;s<=t;s++)for(let a=1;a<=o;a++){const i=e[s-1]===n[a-1]?0:1;r[s][a]=Math.min(r[s-1][a]+1,r[s][a-1]+1,r[s-1][a-1]+i)}return r[t][o]}c(is,"levenshtein");function un(e){let n=e.trim();return(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1)),n.startsWith("#")&&(n=n.slice(1)),n}c(un,"normalizeDocid");function st(e){const n=un(e);return n.length>=6&&/^[a-f0-9]+$/i.test(n)}c(st,"isDocid");function rt(e,n){const t=un(n);return t.length<1?null:e.prepare(`
217
+ SELECT 'qmd://' || d.collection || '/' || d.path as filepath, d.hash
218
+ FROM documents d
219
+ WHERE d.hash LIKE ? AND d.active = 1
220
+ LIMIT 1
221
+ `).get(`${t}%`)}c(rt,"findDocumentByDocid");function ct(e,n,t=3,o=5){const r=e.prepare(`
222
+ SELECT d.path
223
+ FROM documents d
224
+ WHERE d.active = 1
225
+ `).all(),s=n.toLowerCase();return r.map(i=>({path:i.path,dist:is(i.path.toLowerCase(),s)})).filter(i=>i.dist<=t).sort((i,u)=>i.dist-u.dist).slice(0,o).map(i=>i.path)}c(ct,"findSimilarFiles");function dn(e,n){const t=e.prepare(`
226
+ SELECT
227
+ 'qmd://' || d.collection || '/' || d.path as virtual_path,
228
+ octet_length(content.doc) as body_length,
229
+ d.path,
230
+ d.collection
231
+ FROM documents d
232
+ JOIN content ON content.hash = d.hash
233
+ WHERE d.active = 1
234
+ `).all(),o=ft(n);return t.filter(r=>o(r.virtual_path)||o(r.path)||o(r.collection+"/"+r.path)).map(r=>({filepath:r.virtual_path,displayPath:r.path,bodyLength:r.body_length}))}c(dn,"matchFilesByGlob");function ls(e,n,t){const o=Ie(e,n);if(!o)return null;const r=[],s=Me(e);if(s&&r.push(s),o.context){const a=t.startsWith("/")?t:`/${t}`,i=[];for(const[u,l]of Object.entries(o.context)){const d=u.startsWith("/")?u:`/${u}`;a.startsWith(d)&&i.push({prefix:d,context:l})}i.sort((u,l)=>u.prefix.length-l.prefix.length);for(const u of i)r.push(u.context)}return r.length>0?r.join(`
235
+
236
+ `):null}c(ls,"getContextForPath");function hn(e,n){if(!n)return null;const t=oe(e);let o=null,r=null;const s=n.startsWith("qmd://")?Ee(n):null;if(s)o=s.collectionName,r=s.path;else{for(const d of t)if(!(!d||!d.path)&&(n.startsWith(d.path+"/")||n===d.path)){o=d.name,r=n.startsWith(d.path+"/")?n.slice(d.path.length+1):"";break}if(!o||r===null)return null}const a=Ie(e,o);if(!a||!e.prepare(`
237
+ SELECT d.path
238
+ FROM documents d
239
+ WHERE d.collection = ? AND d.path = ? AND d.active = 1
240
+ LIMIT 1
241
+ `).get(o,r))return null;const u=[],l=Me(e);if(l&&u.push(l),a.context){const d=r.startsWith("/")?r:`/${r}`,f=[];for(const[h,m]of Object.entries(a.context)){const T=h.startsWith("/")?h:`/${h}`;d.startsWith(T)&&f.push({prefix:T,context:m})}f.sort((h,m)=>h.prefix.length-m.prefix.length);for(const h of f)u.push(h.context)}return u.length>0?u.join(`
242
+
243
+ `):null}c(hn,"getContextForFile");function ge(e,n){const t=new Map,o=[...new Set(n.filter(Boolean))];if(o.length===0)return t;const r=oe(e),s=new Map(r.map(l=>[l.name,l])),a=Me(e),i=[];for(const l of o){const d=l.startsWith("qmd://")?Ee(l):null;if(d){i.push({fp:l,cn:d.collectionName,rp:d.path});continue}for(const f of r)if(!(!f||!f.path)){if(l===f.path){i.push({fp:l,cn:f.name,rp:""});break}if(l.startsWith(f.path+"/")){i.push({fp:l,cn:f.name,rp:l.slice(f.path.length+1)});break}}}const u=new Set;for(let l=0;l<i.length;l+=500){const d=i.slice(l,l+500),f=e.prepare(`SELECT collection, path FROM documents WHERE active = 1 AND (collection, path) IN (VALUES ${d.map(()=>"(?, ?)").join(", ")})`).all(...d.flatMap(h=>[h.cn,h.rp]));for(const h of f)u.add(`${h.collection}
244
+ ${h.path}`)}for(const l of i){const d=[],f=s.get(l.cn);if(f&&u.has(`${l.cn}
245
+ ${l.rp}`)&&(a&&d.push(a),f.context)){const h=l.rp.startsWith("/")?l.rp:`/${l.rp}`,m=[];for(const[T,p]of Object.entries(f.context)){const _=T.startsWith("/")?T:`/${T}`;h.startsWith(_)&&m.push({prefix:_,context:p})}m.sort((T,p)=>T.prefix.length-p.prefix.length);for(const T of m)d.push(T.context)}t.set(l.fp,d.length>0?d.join(`
246
+
247
+ `):null)}for(const l of o)t.has(l)||t.set(l,null);return t}c(ge,"getContextsForFiles");function fn(e,n){const t=Ie(e,n);return t?{name:t.name,pwd:t.path,glob_pattern:t.pattern}:null}c(fn,"getCollectionByName");function Nr(e){return oe(e).map(o=>{const r=e.prepare(`
248
+ SELECT
249
+ COUNT(d.id) as doc_count,
250
+ SUM(CASE WHEN d.active = 1 THEN 1 ELSE 0 END) as active_count,
251
+ MAX(d.modified_at) as last_modified
252
+ FROM documents d
253
+ WHERE d.collection = ?
254
+ `).get(o.name);return{name:o.name,pwd:o.path,glob_pattern:o.pattern,doc_count:r?.doc_count||0,active_count:r?.active_count||0,last_modified:r?.last_modified||null,includeByDefault:o.includeByDefault!==!1}})}c(Nr,"listCollections");function Cr(e,n){const t=e.prepare("SELECT COUNT(*) as c FROM documents WHERE collection = ?").get(n).c;e.prepare("DELETE FROM documents WHERE collection = ?").run(n);const o=Fe(e);Uo(e,n);const r=e.prepare("SELECT COUNT(*) as c FROM documents WHERE collection = ?").get(n).c;return{deletedDocs:t-r,cleanedHashes:o}}c(Cr,"removeCollection");function Dr(e,n,t){e.prepare("UPDATE documents SET collection = ? WHERE collection = ?").run(t,n),Bo(e,n,t)}c(Dr,"renameCollection");function Or(e,n,t,o){const r=e.prepare("SELECT name FROM store_collections WHERE name = ?").get(n);if(!r)throw new Error(`Collection '${n}' not found`);$o(e,r.name,t,o)}c(Or,"insertContext");function us(e){const n=oe(e),t=[];for(const o of n)if(!o.context||Object.keys(o.context).length===0){const r=e.prepare(`
255
+ SELECT COUNT(d.id) as doc_count
256
+ FROM documents d
257
+ WHERE d.collection = ? AND d.active = 1
258
+ `).get(o.name);t.push({name:o.name,pwd:o.path,doc_count:r?.doc_count||0})}return t.sort((o,r)=>o.name.localeCompare(r.name))}c(us,"getCollectionsWithoutContext");function ds(e,n){const t=e.prepare(`
259
+ SELECT DISTINCT path FROM documents
260
+ WHERE collection = ? AND active = 1
261
+ `).all(n),o=Ie(e,n);if(!o)return[];const r=new Set;if(o.context)for(const i of Object.keys(o.context))r.add(i);const s=new Set;for(const{path:i}of t){const u=i.split("/").filter(Boolean);if(u.length>1){const l=u[0];l&&s.add(l)}}const a=[];for(const i of s){let u=!1;for(const l of r)if(l===""||l===i||i.startsWith(l+"/")){u=!0;break}u||a.push(i)}return a.sort()}c(ds,"getTopLevelPathsWithoutContext");function hs(e){return e.replace(/[^\p{L}\p{N}'_]/gu,"").toLowerCase()}c(hs,"sanitizeFTS5Term");const fs=/[^\p{L}\p{N}'_]+/u;function pn(e){return e.split(fs).map(n=>hs(n)).filter(n=>n)}c(pn,"splitFTS5CompoundTerm");function En(e,n="all"){const t=[],o=[];let r=0;const s=e.trim();for(;r<s.length;){for(;r<s.length&&/\s/.test(s[r]);)r++;if(r>=s.length)break;const i=s[r]==="-";if(i&&r++,s[r]==='"'){const u=r+1;for(r++;r<s.length&&s[r]!=='"';)r++;const l=s.slice(u,r).trim();if(r++,l.length>0){const d=It(l);if(d){const f=`"${d}"`;i?o.push(f):t.push(f)}}}else{const u=r;for(;r<s.length&&!/[\s"]/.test(s[r]);)r++;const l=s.slice(u,r),d=i?null:jn(l);if(d)t.push(d);else if(Mo(l)){const f=i?null:Jn(l),h=f?null:It(l);if(f)t.push(f);else if(h){const m=`"${h}"`;i?o.push(m):t.push(m)}}else{const f=pn(l);if(f.length>0){const h=f.length>1?`"${f.join(" ")}"`:`"${f[0]}"*`;i?o.push(h):t.push(h)}}}}if(t.length===0&&o.length===0||t.length===0||n==="any"&&t.length<3)return null;let a=n==="any"?`(${t.join(" OR ")})`:t.join(" AND ");for(const i of o)a=`${a} NOT ${i}`;return a}c(En,"buildFTS5Query");function ps(e){return/(^|\s)-[\w"]/.test(e)?"Negation (-term) is not supported in vec/hyde queries. Use lex for exclusions.":null}c(ps,"validateSemanticQuery");function Es(e){return/[\r\n]/.test(e)?"Lex queries must be a single line. Remove newline characters or split into separate lex: lines.":(e.match(/"/g)??[]).length%2===1?'Lex query has an unmatched double quote ("). Add the closing quote or remove it.':null}c(Es,"validateLexQuery");function at(e){if(e==null)return;const n=(typeof e=="string"?[e]:Array.from(e)).map(t=>t.trim()).filter(t=>t.length>0);return n.length>0?n:void 0}c(at,"scopedCollectionNames");function mn(e,n){const t=new Map;for(const o of e)for(const r of o){const s=t.get(r.filepath);(!s||r.score>s.score)&&t.set(r.filepath,r)}return Array.from(t.values()).sort((o,r)=>r.score-o.score).slice(0,n)}c(mn,"mergeSearchResultsByScore");const gn=20,it=5e4,Tn=400;function Lr(e,n,t){const o=at(t),r=[];let s="SELECT collection || '/' || path AS display_path, modified_at FROM documents WHERE active = 1";o&&o.length>0&&(s+=` AND collection IN (${o.map(()=>"?").join(",")})`,r.push(...o.map(String)));const a=e.prepare(s).all(...r);return{kept:a.filter(u=>n.sinceIso&&!(u.modified_at&&u.modified_at>=n.sinceIso)||n.untilIso&&!(u.modified_at&&u.modified_at<=n.untilIso)?!1:Ne(u.display_path,n)).length,total:a.length}}c(Lr,"countFilteredDocuments");function _n(e,n,t=20,o,r,s,a){const i=at(o);if(i&&i.length>1)return mn(i.map(T=>_n(e,n,t,T,r,s,a)),t);const u=i?.[0],l=pt(s)||r!==void 0,d=En(n);if(!d)return[];const f=c((T,p)=>{const _=[T],L=Math.max(t,gn);let S=`
262
+ WITH fts_matches AS (
263
+ SELECT rowid, bm25(documents_fts, 1.5, 4.0, 1.0) as bm25_score
264
+ FROM documents_fts
265
+ WHERE documents_fts MATCH ?
266
+ ORDER BY bm25_score ASC
267
+ LIMIT ${l?it:u?L*10:L}
268
+ )
269
+ SELECT
270
+ 'qmd://' || d.collection || '/' || d.path as filepath,
271
+ d.collection || '/' || d.path as display_path,
272
+ d.title,
273
+ d.hash,
274
+ d.modified_at,
275
+ fm.bm25_score,
276
+ dm.metadata_json
277
+ FROM fts_matches fm
278
+ JOIN documents d ON d.id = fm.rowid
279
+ LEFT JOIN document_metadata dm ON dm.document_id = d.id
280
+ WHERE d.active = 1
281
+ `;if(u&&(S+=" AND d.collection = ?",_.push(String(u))),r){const g=qe(r,"d");S+=` AND dm.extraction_version = ${We} AND dm.extraction_error IS NULL AND ${g.sql}`,_.push(...g.params)}s?.sinceIso&&(S+=" AND d.modified_at >= ?",_.push(s.sinceIso)),s?.untilIso&&(S+=" AND d.modified_at <= ?",_.push(s.untilIso));const y=(s?.paths?.length??0)>0;S+=" ORDER BY fm.bm25_score ASC",y||(S+=" LIMIT ?",_.push(t));const w=e.prepare(S).all(..._),W=y?w.filter(g=>Ne(g.display_path,s)).slice(0,t):w;if(a&&l&&t>it&&W.length>0&&e.prepare(`SELECT 1 AS one FROM documents_fts WHERE documents_fts MATCH ? LIMIT 1 OFFSET ${it}`).get(T)&&a(),W.length===0)return[];const k=[...new Set(W.map(g=>g.hash))],q=new Map;for(let g=0;g<k.length;g+=Tn){const O=k.slice(g,g+Tn),H=e.prepare(`SELECT hash, doc FROM content WHERE hash IN (${O.map(()=>"?").join(",")})`).all(...O);for(const G of H)q.set(G.hash,G.doc)}const b=ge(e,W.map(g=>g.filepath));return W.map(g=>{const O=g.filepath.split("//")[1]?.split("/")[0]||"",H=Math.abs(g.bm25_score)/(1+Math.abs(g.bm25_score)),G=q.get(g.hash)??"";return{filepath:g.filepath,displayPath:g.display_path,title:g.title,hash:g.hash,docid:we(g.hash),collectionName:O,modifiedAt:g.modified_at??"",bodyLength:G.length,body:G,context:b.get(g.filepath)??null,metadata:_t(g.metadata_json),score:H,source:"fts",matchMode:p}})},"runMatch"),h=f(d,"all");if(h.length>0)return h;const m=En(n,"any");return m?f(m,"any"):[]}c(_n,"searchFTS");const xn=4096,ms=2e4,Sn=400;function gs(e,n,t,o){if(t.length===0||o<=0)return[];const r=new Float32Array(n),s=Math.max(o*3,o),a=[];for(let i=0;i<t.length;i+=Sn){const u=t.slice(i,i+Sn),l=u.map(()=>"?").join(","),d=e.prepare(`
282
+ SELECT hash_seq, vec_distance_cosine(embedding, ?) AS distance
283
+ FROM vectors_vec
284
+ WHERE hash_seq IN (${l})
285
+ `).all(r,...u);a.push(...d)}return a.sort((i,u)=>i.distance-u.distance),a.slice(0,s)}c(gs,"exactVecScanByHashSeq");function lt(e,n,t){const o=Math.max(1,Math.min(xn,t));return e.prepare(`
286
+ SELECT hash_seq, distance
287
+ FROM vectors_vec
288
+ WHERE embedding MATCH ? AND k = ?
289
+ `).all(new Float32Array(n),o)}c(lt,"annVecScan");async function Rn(e,n,t,o=20,r,s,a,i,u,l){if(!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'").get())return[];const f=a??await Ts(n,t,!0,s,i);if(!f)return[];const h=at(r);if(h&&h.length>1){const g=await Promise.all(h.map(O=>Rn(e,n,t,o,O,s,f,i,u,l)));return mn(g,o)}const m=h?.[0],T=pt(l)||u!==void 0,p=Math.max(o,gn);let _;if(m||T){let g=`
290
+ SELECT DISTINCT cv.hash || '_' || cv.seq AS hash_seq, d.collection || '/' || d.path AS display_path
291
+ FROM content_vectors cv
292
+ JOIN documents d ON d.hash = cv.hash AND d.active = 1
293
+ `;const O=["1 = 1"],H=[];if(m&&(O.push("d.collection = ?"),H.push(m)),l?.sinceIso&&(O.push("d.modified_at >= ?"),H.push(l.sinceIso)),l?.untilIso&&(O.push("d.modified_at <= ?"),H.push(l.untilIso)),u){const J=qe(u,"d");g+=" JOIN document_metadata dm ON dm.document_id = d.id",O.push(`dm.extraction_version = ${We}`),O.push("dm.extraction_error IS NULL"),O.push(J.sql),H.push(...J.params)}g+=` WHERE ${O.join(" AND ")}`;const G=Z(e,()=>e.prepare(g).all(...H)).filter(J=>Ne(J.display_path,l)).map(J=>J.hash_seq),$=[...new Set(G)];if($.length===0)return[];const Q=e.prepare("SELECT count(*) AS n FROM vectors_vec").get().n,z=Q<xn?lt(e,f,Q+1):null;if(z&&z.length<=Q){const J=new Set($);_=z.filter(se=>J.has(se.hash_seq)).slice(0,p*3)}else $.length<=ms?_=gs(e,f,$,p):_=lt(e,f,p*30)}else _=lt(e,f,p*3);if(_.length===0)return[];const L=_.map(g=>g.hash_seq),N=new Map(_.map(g=>[g.hash_seq,g.distance]));let y=`
294
+ SELECT
295
+ cv.hash || '_' || cv.seq as hash_seq,
296
+ cv.hash,
297
+ cv.pos,
298
+ 'qmd://' || d.collection || '/' || d.path as filepath,
299
+ d.collection || '/' || d.path as display_path,
300
+ d.title,
301
+ content.doc as body,
302
+ dm.metadata_json
303
+ FROM content_vectors cv
304
+ JOIN documents d ON d.hash = cv.hash AND d.active = 1
305
+ JOIN content ON content.hash = d.hash
306
+ LEFT JOIN document_metadata dm ON dm.document_id = d.id
307
+ WHERE cv.hash || '_' || cv.seq IN (${L.map(()=>"?").join(",")})
308
+ `;const w=[...L];if(m&&(y+=" AND d.collection = ?",w.push(m)),l?.sinceIso&&(y+=" AND d.modified_at >= ?",w.push(l.sinceIso)),l?.untilIso&&(y+=" AND d.modified_at <= ?",w.push(l.untilIso)),u){const g=qe(u,"d");y+=` AND dm.extraction_version = ${We} AND dm.extraction_error IS NULL AND ${g.sql}`,w.push(...g.params)}const W=Z(e,()=>e.prepare(y).all(...w)),k=new Map;for(const g of W){if(!Ne(g.display_path,l))continue;const O=N.get(g.hash_seq)??1,H=k.get(g.filepath);(!H||O<H.bestDist)&&k.set(g.filepath,{row:g,bestDist:O})}const q=Array.from(k.values()).sort((g,O)=>g.bestDist-O.bestDist).slice(0,o),b=ge(e,q.map(({row:g})=>g.filepath));return q.map(({row:g,bestDist:O})=>{const H=g.filepath.split("//")[1]?.split("/")[0]||"";return{filepath:g.filepath,displayPath:g.display_path,title:g.title,hash:g.hash,docid:we(g.hash),collectionName:H,modifiedAt:"",bodyLength:g.body.length,body:g.body,context:b.get(g.filepath)??null,metadata:_t(g.metadata_json),score:1-O,source:"vec",chunkPos:g.pos}})}c(Rn,"searchVec");async function Ts(e,n,t,o,r){const s=t?xe(e,n):le(e,void 0,n);return(o?await o.embed(s,{model:n,isQuery:t}):await(r??_e()).embed(s,{model:n,isQuery:t}))?.embedding||null}c(Ts,"getEmbedding");function _s(e,n=te){const t=fe(n);return Z(e,()=>e.prepare(`
309
+ SELECT d.hash, c.doc as body, MIN(d.path) as path
310
+ FROM documents d
311
+ JOIN content c ON d.hash = c.hash
312
+ LEFT JOIN (
313
+ SELECT hash, model, COUNT(*) AS chunk_count, MAX(total_chunks) AS expected_chunks
314
+ FROM content_vectors
315
+ WHERE model = ? AND embed_fingerprint = ?
316
+ GROUP BY hash, model, embed_fingerprint
317
+ ) v ON d.hash = v.hash
318
+ WHERE d.active = 1
319
+ AND (v.hash IS NULL OR v.chunk_count < v.expected_chunks)
320
+ GROUP BY d.hash
321
+ `).all(n,t))}c(_s,"getHashesForEmbedding");function yn(e,n){if(!n){e.exec("DELETE FROM content_vectors"),e.exec("DROP TABLE IF EXISTS vectors_vec");return}const t=`
322
+ SELECT DISTINCT d.hash
323
+ FROM documents d
324
+ WHERE d.collection = ? AND d.active = 1
325
+ AND NOT EXISTS (
326
+ SELECT 1 FROM documents d2
327
+ WHERE d2.hash = d.hash
328
+ AND d2.active = 1
329
+ AND d2.collection != d.collection
330
+ )
331
+ `,o=e.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='vectors_vec'").get();Z(e,()=>{if(o){const s=e.prepare(`
332
+ SELECT cv.hash, cv.seq
333
+ FROM content_vectors cv
334
+ WHERE cv.hash IN (${t})
335
+ `).all(n),a=e.prepare("DELETE FROM vectors_vec WHERE hash_seq = ?");for(const i of s)a.run(`${i.hash}_${i.seq}`)}e.prepare(`
336
+ DELETE FROM content_vectors
337
+ WHERE hash IN (${t})
338
+ `).run(n),e.prepare("SELECT COUNT(*) AS n FROM content_vectors").get().n===0&&e.exec("DROP TABLE IF EXISTS vectors_vec")})}c(yn,"clearAllEmbeddings");function ut(e,n,t,o,r,s,a,i=1,u=fe(s)){const l=`${n}_${t}`;Z(e,()=>{e.transaction(()=>{e.prepare("INSERT OR REPLACE INTO content_vectors (hash, seq, pos, model, embed_fingerprint, total_chunks, embedded_at) VALUES (?, ?, ?, ?, ?, ?, ?)").run(n,t,o,s,u,i,a);const h=e.prepare("DELETE FROM vectors_vec WHERE hash_seq = ?"),m=e.prepare("INSERT INTO vectors_vec (hash_seq, embedding) VALUES (?, ?)");h.run(l),m.run(l,r)}).immediate()})}c(ut,"insertEmbedding");function xs(e,n,t,o){Z(e,()=>{const r=e.prepare("SELECT seq FROM content_vectors WHERE hash = ? AND model = ? AND seq >= ?").all(n,t,o);if(r.length===0)return;const s=e.prepare("DELETE FROM vectors_vec WHERE hash_seq = ?"),a=e.prepare("DELETE FROM content_vectors WHERE hash = ? AND model = ? AND seq = ?");for(const i of r)s.run(`${n}_${i.seq}`),a.run(n,t,i.seq)})}c(xs,"pruneStaleChunkVectors");function Ss(e,n,t){return Z(e,()=>{let o=0;const r=e.prepare("SELECT seq FROM content_vectors WHERE hash = ? AND model = ?"),s=e.prepare("DELETE FROM content_vectors WHERE hash = ? AND model = ?"),a=e.prepare("DELETE FROM vectors_vec WHERE hash_seq = ?");for(const[i,u]of n){const l=r.all(i,t);if(!(l.length===0||l.length===u)){for(const d of l)a.run(`${i}_${d.seq}`);s.run(i,t),o+=l.length}}return o})}c(Ss,"removeIncompleteEmbeddings");async function Rs(e,n=De,t,o,r={}){const s=me("expandQuery",{query:e,model:n}),a=be(t,s);if(a)try{const d=JSON.parse(a);if(Array.isArray(d)){const f=d;if(f.length>0&&typeof f[0]?.query=="string")return f.map(h=>({type:h.type,query:String(h.query)}));if(f.length>0&&typeof f[0]?.text=="string")return f.map(h=>({type:h.type,query:String(h.text)}))}}catch{}const l=(await(o??_e()).expandQuery(e,{onModelReady:r.onModelReady})).filter(d=>d.text!==e).map(d=>({type:d.type,query:d.text}));return l.length>0&&Ze(t,s,JSON.stringify(l)),l}c(Rs,"expandQuery");function ys(e,n,t=De){const o=me("expandQuery",{query:n,model:t});e.prepare("DELETE FROM llm_cache WHERE hash = ?").run(o)}c(ys,"deleteExpansionCacheEntry");async function Ns(e,n,t=xt,o,r,s,a={}){const i=Qn(e,r),u=s??_e(),l=u.rerankModelName??t,d=so(a.maxDocTokens),f=d??u.rerankMaxDocTokens,h=f?`${l}#max${f}`:l,m=new Map,T=new Map;for(const p of n){const _=me("rerank",{query:i,model:h,chunk:p.text}),L=me("rerank",{query:e,file:p.file,model:h,chunk:p.text}),N=be(o,_)??be(o,L);N!==null?m.set(p.text,parseFloat(N)):T.set(p.text,{file:p.file,text:p.text})}if(T.size>0){const p=[...T.values()],_=await u.rerank(i,p,{model:l,...d?{maxDocTokens:d}:{},onModelReady:a.onModelReady}),L=_.model!=="fallback",N=new Map(p.map(S=>[S.file,S.text]));for(const S of _.results){const y=N.get(S.file)||"";if(L){const w=me("rerank",{query:i,model:h,chunk:y});Ze(o,w,S.score.toString())}m.set(y,S.score)}}return n.map(p=>({file:p.file,score:m.get(p.text)||0})).sort((p,_)=>_.score-p.score)}c(Ns,"rerank");const Cs=/\p{Script=Hangul}+/gu,Ds=/[a-z0-9]+/gi;function Os(e,n){const t=n.toLowerCase();let o=0,r=0;for(const s of e.toLowerCase().split(/\s+/))if(s){for(const a of s.match(Cs)??[]){const i=Array.from(a);if(!(i.length<2)){if(o++,t.includes(a)){r++;continue}if(i.length>=3){for(let u=0;u+1<i.length;u++)if(t.includes(i[u]+i[u+1])){r++;break}}}}for(const a of s.match(Ds)??[])a.length<=2||(o++,t.includes(a)&&r++)}return o===0?1:r/o}c(Os,"relaxedDocCoverage");function Nn(e,n){return e.map((t,o)=>{const r=n[o];if(!r?.relaxed)return;const s=new Map;for(const a of t)s.set(a.file,.5+.5*Os(r.query,a.body));return s})}c(Nn,"rrfDocMultipliers");function Cn(e,n=[],t=60,o=[]){const r=new Map;for(let s=0;s<e.length;s++){const a=e[s];if(!a)continue;const i=n[s]??1,u=o[s];for(let l=0;l<a.length;l++){const d=a[l];if(!d)continue;const f=u?.get(d.file)??1,h=i*f/(t+l+1),m=r.get(d.file);m?(m.rrfScore+=h,m.topRank=Math.min(m.topRank,l)):r.set(d.file,{result:d,rrfScore:h,topRank:l})}}for(const s of r.values())s.topRank===0?s.rrfScore+=.05:s.topRank<=2&&(s.rrfScore+=.02);return Array.from(r.values()).sort((s,a)=>a.rrfScore-s.rrfScore).map(s=>({...s.result,score:s.rrfScore}))}c(Cn,"reciprocalRankFusion");function Dn(e,n=[],t=[],o=60,r=[]){const s=new Map;for(let a=0;a<e.length;a++){const i=e[a];if(!i)continue;const u=n[a]??1,l=r[a],d=t[a]??{source:"fts",queryType:"original",query:""};for(let f=0;f<i.length;f++){const h=i[f];if(!h)continue;const m=f+1,T=l?.get(h.file)??1,p=u*T/(o+m),_=s.get(h.file),L={listIndex:a,source:d.source,queryType:d.queryType,query:d.query,rank:m,weight:u,multiplier:T,backendScore:h.score,rrfContribution:p};_?(_.baseScore+=p,_.topRank=Math.min(_.topRank,m),_.contributions.push(L)):s.set(h.file,{contributions:[L],baseScore:p,topRank:m,topRankBonus:0,totalScore:0})}}for(const a of s.values()){let i=0;a.topRank===1?i=.05:a.topRank<=3&&(i=.02),a.topRankBonus=i,a.totalScore=a.baseScore+i}return s}c(Dn,"buildRrfTrace");function Ls(e){let n=e.replace(/\\/g,"/").trim();return n.startsWith("~/")&&(n=$e()+n.slice(1)),n}c(Ls,"normalizeLookupPathForIgnore");function As(e,n){const t=e.replace(/\\/g,"/").replace(/^\/+/,""),o=n.replace(/\\/g,"/").replace(/^\/+/,"");return ft(o,{dot:!0})(t)}c(As,"matchesIgnoreRule");function vs(e,n){const t=Ls(n),o=Ge(t)?Ee(t):null,r=oe(e);for(const s of r){if(!s.ignore||s.ignore.length===0)continue;const a=[];if(o){if(o.collectionName!==s.name)continue;a.push(o.path)}else if(t.startsWith(s.path+"/"))a.push(t.slice(s.path.length+1));else if(!t.startsWith("/")){const i=`${s.name}/`;t.startsWith(i)?a.push(t.slice(i.length)):a.push(t)}for(const i of a)for(const u of s.ignore)if(As(i,u))return{error:"excluded_by_ignore",query:n,collection:s.name,path:i,rule:u}}return null}c(vs,"getIgnoredLookupMatch");function Is(e,n,t={}){let o=n;const r=o.match(/:(\d+)$/);if(r&&(o=o.slice(0,-r[0].length)),st(o)){const d=rt(e,o);d&&(o=d.filepath)}o.startsWith("~/")&&(o=$e()+o.slice(1));const a=`
339
+ 'qmd://' || d.collection || '/' || d.path as virtual_path,
340
+ d.collection || '/' || d.path as display_path,
341
+ d.title,
342
+ d.hash,
343
+ d.collection,
344
+ d.modified_at,
345
+ octet_length(content.doc) as body_length
346
+ ${t.includeBody?", content.doc as body":""}
347
+ `;let i=e.prepare(`
348
+ SELECT ${a}
349
+ FROM documents d
350
+ JOIN content ON content.hash = d.hash
351
+ WHERE 'qmd://' || d.collection || '/' || d.path = ? AND d.active = 1
352
+ `).get(o);if(!i&&!o.startsWith("qmd://")){const d=e.prepare(`
353
+ SELECT ${a}
354
+ FROM documents d
355
+ JOIN content ON content.hash = d.hash
356
+ WHERE 'qmd://' || d.collection || '/' || d.path LIKE ? ESCAPE '#' AND d.active = 1
357
+ ORDER BY d.collection, d.path
358
+ `).all(`%/${On(o)}`);if(d.length>1)return{error:"not_found",query:n,similarFiles:d.map(f=>f.virtual_path)};i=d[0]??null}if(!i&&!o.startsWith("qmd://")){const d=oe(e);for(const f of d){let h=null;if(o.startsWith(f.path+"/")?h=o.slice(f.path.length+1):o.startsWith("/")||(h=o),h&&(i=e.prepare(`
359
+ SELECT ${a}
360
+ FROM documents d
361
+ JOIN content ON content.hash = d.hash
362
+ WHERE d.collection = ? AND d.path = ? AND d.active = 1
363
+ `).get(f.name,h),i))break}}if(!i){const d=vs(e,o);if(d)return d;const f=ct(e,o,5,5);return{error:"not_found",query:n,similarFiles:f}}const u=i.virtual_path||`qmd://${i.collection}/${i.display_path}`,l=hn(e,u);return{filepath:u,displayPath:i.display_path,title:i.title,context:l,hash:i.hash,docid:we(i.hash),collectionName:i.collection,modifiedAt:i.modified_at,bodyLength:i.body_length,...t.includeBody&&i.body!==void 0&&{body:i.body}}}c(Is,"findDocument");function Ms(e,n,t,o){const r=n.filepath;let s=null;if(r.startsWith("qmd://")&&(s=e.prepare(`
364
+ SELECT content.doc as body
365
+ FROM documents d
366
+ JOIN content ON content.hash = d.hash
367
+ WHERE 'qmd://' || d.collection || '/' || d.path = ? AND d.active = 1
368
+ `).get(r)),!s){const i=oe(e);for(const u of i)if(r.startsWith(u.path+"/")){const l=r.slice(u.path.length+1);if(s=e.prepare(`
369
+ SELECT content.doc as body
370
+ FROM documents d
371
+ JOIN content ON content.hash = d.hash
372
+ WHERE d.collection = ? AND d.path = ? AND d.active = 1
373
+ `).get(u.name,l),s)break}}if(!s)return null;let a=s.body;if(t!==void 0||o!==void 0){const i=a.split(`
374
+ `),u=Math.max(0,(t||1)-1),l=o!==void 0?u+o:i.length;a=i.slice(u,l).join(`
375
+ `)}return a}c(Ms,"getDocumentBody");function On(e){return e.replace(/#/g,"##").replace(/%/g,"#%").replace(/_/g,"#_")}c(On,"escapeLikePattern");function ye(e,n,t){return e.prepare(`
376
+ SELECT
377
+ d.collection,
378
+ d.path,
379
+ 'qmd://' || d.collection || '/' || d.path as virtual_path,
380
+ octet_length(content.doc) as body_length
381
+ FROM documents d
382
+ JOIN content ON content.hash = d.hash
383
+ WHERE d.active = 1 AND (${n})
384
+ ORDER BY d.collection, d.path
385
+ `).all(...t)}c(ye,"commaListSelect");function Te(e,n,t){if(t.length===1){const s=t[0];return{ok:!0,match:{collection:s.collection,path:s.path,virtualPath:s.virtual_path,bodyLength:s.body_length}}}if(t.length>1)return{ok:!1,error:`Ambiguous path ${n}: ${t.map(s=>s.virtual_path).join(", ")}`};const o=ct(e,n,5,3);let r=`File not found: ${n}`;return o.length>0&&(r+=` (did you mean: ${o.join(", ")}?)`),{ok:!1,error:r}}c(Te,"finishCommaListResolve");function ws(e,n){const t=n.trim();if(!t)return{ok:!1,error:`File not found: ${n}`};if(st(t)){const r=rt(e,t);if(r){const s=ye(e,"'qmd://' || d.collection || '/' || d.path = ?",[r.filepath]);return Te(e,t,s)}}if(Ge(t)){const r=Ee(t);if(!r)return Te(e,t,[]);const s=ye(e,"d.collection = ? AND d.path = ?",[r.collectionName,r.path]);return Te(e,t,s)}let o=ye(e,"d.collection || '/' || d.path = ?",[t]);return o.length>0||(o=ye(e,"d.path = ?",[t]),o.length>0)||(o=ye(e,"d.path LIKE ? ESCAPE '#'",[`%/${On(t)}`])),Te(e,t,o)}c(ws,"resolveCommaListName");function bs(e,n,t={}){const o=n.includes(",")&&!n.includes("*")&&!n.includes("?")&&!n.includes("{"),r=st(n),s=[],a=t.maxBytes??uo,u=`
386
+ 'qmd://' || d.collection || '/' || d.path as virtual_path,
387
+ d.collection || '/' || d.path as display_path,
388
+ d.title,
389
+ d.hash,
390
+ d.collection,
391
+ d.modified_at,
392
+ octet_length(content.doc) as body_length
393
+ ${t.includeBody?", content.doc as body":""}
394
+ `;let l;if(o||r){const h=o?n.split(",").map(m=>m.trim()).filter(Boolean):[n.trim()].filter(Boolean);l=[];for(const m of h){const T=ws(e,m);if(!T.ok){s.push(T.error);continue}const p=e.prepare(`
395
+ SELECT ${u}
396
+ FROM documents d
397
+ JOIN content ON content.hash = d.hash
398
+ WHERE d.collection = ? AND d.path = ? AND d.active = 1
399
+ `).get(T.match.collection,T.match.path);p?l.push(p):s.push(`File not found: ${m}`)}}else{const h=dn(e,n);if(h.length===0)return s.push(`No files matched pattern: ${n}`),{docs:[],errors:s};const m=h.map(p=>p.filepath),T=m.map(()=>"?").join(",");l=e.prepare(`
400
+ SELECT ${u}
401
+ FROM documents d
402
+ JOIN content ON content.hash = d.hash
403
+ WHERE 'qmd://' || d.collection || '/' || d.path IN (${T}) AND d.active = 1
404
+ `).all(...m)}const d=[],f=ge(e,l.map(h=>h.virtual_path||`qmd://${h.collection}/${h.display_path}`));for(const h of l){const m=h.virtual_path||`qmd://${h.collection}/${h.display_path}`,T=f.get(m)??null;if(h.body_length>a){d.push({doc:{filepath:m,displayPath:h.display_path},skipped:!0,skipReason:`File too large (${Math.round(h.body_length/1024)}KB > ${Math.round(a/1024)}KB)`});continue}d.push({doc:{filepath:m,displayPath:h.display_path,title:h.title||h.display_path.split("/").pop()||h.display_path,context:T,hash:h.hash,docid:we(h.hash),collectionName:h.collection,modifiedAt:h.modified_at,bodyLength:h.body_length,...t.includeBody&&h.body!==void 0&&{body:h.body}},skipped:!1})}return{docs:d,errors:s}}c(bs,"findDocuments");function Fs(e,n=te){const t=e.prepare(`
405
+ SELECT
406
+ collection as name,
407
+ COUNT(*) as active_count,
408
+ MAX(modified_at) as last_doc_update
409
+ FROM documents
410
+ WHERE active = 1
411
+ GROUP BY collection
412
+ `).all(),o=oe(e),r=new Map(o.map(l=>[l.name,{path:l.path,pattern:l.pattern}])),s=t.map(l=>{const d=r.get(l.name);return{name:l.name,path:d?.path??null,pattern:d?.pattern??null,documents:l.active_count,lastUpdated:l.last_doc_update||new Date().toISOString()}});s.sort((l,d)=>l.lastUpdated?d.lastUpdated?new Date(d.lastUpdated).getTime()-new Date(l.lastUpdated).getTime():-1:1);const a=e.prepare("SELECT COUNT(*) as c FROM documents WHERE active = 1").get().c,i=Qe(e,void 0,n),u=!!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'").get();return{totalDocuments:a,needsEmbedding:i,hasVectorIndex:u,pendingMetadata:ao(e),collections:s}}c(Fs,"getStatus");const ks=.3,Ps=new Set(["am","an","as","at","be","by","do","he","if","in","is","it","me","my","no","of","on","or","so","to","up","us","we","all","and","any","are","but","can","did","for","get","has","her","him","his","how","its","let","may","not","our","out","the","too","was","who","why","you","also","does","find","from","have","into","more","need","show","some","tell","that","them","this","want","what","when","will","with","your","about","looking","notes","search","where","which"]);function Ln(e){return e.toLowerCase().split(/\s+/).map(n=>n.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu,"")).filter(n=>n.length>1&&!Ps.has(n))}c(Ln,"extractIntentTerms");function An(e,n){let t=0,o=e.indexOf(`
413
+ `);for(;o!==-1&&o<n;)t++,o=e.indexOf(`
414
+ `,o+1);return t}c(An,"countNewlinesBefore");function vn(e,n,t=500,o,r,s){const a=e.split(`
415
+ `),i=a.length;let u=e,l=0,d=a;if(o!==void 0&&o>=0){const b=r||Se,g=Math.max(0,o-100),O=Math.min(e.length,o+b+100);u=e.slice(g,O),g>0&&(l=An(e,g)),d=u.split(`
416
+ `)}const f=n.toLowerCase().split(/\s+/).filter(b=>b.length>0),h=s?Ln(s):[];let m=0,T=-1;for(let b=0;b<d.length;b++){const g=(d[b]??"").toLowerCase();let O=0;for(const H of f)g.includes(H)&&(O+=1);for(const H of h)g.includes(H)&&(O+=ks);O>T&&(T=O,m=b)}if(o!==void 0&&o>=0&&T<=0){if(o===0)return vn(e,n,t,void 0,void 0,s);const b=Math.max(0,o-100);m=o>b?An(u,o-b):0}const p=Math.max(0,m-1),_=Math.min(d.length,m+3),L=d.slice(p,_);let N=L.join(`
417
+ `);if(o&&o>0&&N.trim().length===0)return vn(e,n,t,void 0,void 0,s);N.length>t&&(N=N.substring(0,t-3)+"...");const S=l+p+1,y=L.length,w=S-1,W=i-(S+y-1),q=`${`@@ -${S},${y} @@ (${w} before, ${W} after)`}
418
+ ${N}`;return{line:l+m+1,snippet:q,linesBefore:w,linesAfter:W,snippetLines:y}}c(vn,"extractSnippet");function Ar(e,n=1){return e.split(`
419
+ `).map((o,r)=>`${n+r}: ${o}`).join(`
420
+ `)}c(Ar,"addLineNumbers");function Pe(e,n){const t=io(e,n.map(o=>o.file));return n.map(o=>({...o,metadata:t.get(o.file)??{}}))}c(Pe,"attachResultMetadata");const Hs=.5,In=.5,Ws=.75;function qs(e){return e.map(n=>{const t=n.queryType==="original"?2:Ws,o=n.source==="vec"?t*Hs:t;return n.relaxed?o*In:o})}c(qs,"getHybridRrfWeights");const Us=.25;function Bs(e){const n=e[0]?.searchIndex??0;return e.map((t,o)=>{const r=(t.searchIndex??o)===n;return t.relaxed?r?Us:In:r?2:1})}c(Bs,"getStructuredRrfWeights");const He=.1;function Mn(e,n,t){const o=1-(e-1)/t;return(1-He)*n+He*o}c(Mn,"blendRerankScore");const ae=Symbol("timed out");async function $s(e,n){if(!n||n<=0)return e;let t;const o=new Promise(r=>{t=setTimeout(()=>r(ae),n)});try{return await Promise.race([e,o])}finally{clearTimeout(t)}}c($s,"withDeadline");const wn=new WeakMap,bn=12e4;function Vs(){const e=process.env.QMD_LLM_LOAD_TIMEOUT_MS?.trim();return e===void 0||e===""?bn:/^\d+$/.test(e)?Number(e):bn}c(Vs,"resolveLoadTimeoutMs");async function Fn(e,n,t,o,r){const s=Date.now();let a;const i=c(()=>{a!==void 0&&o?.onModelLoad?.(n,a-s)},"reportLoad"),u=wn.get(e)??{expand:{running:0,warned:!1},rerank:{running:0,warned:!1}};wn.set(e,u);const l=u[n],d=c(()=>{l.running++;const S=c(()=>{l.running--,l.running===0&&(l.warned=!1)},"settle");m.then(S,S)},"abandon");if(t&&t>0&&l.running>0)return l.warned||(l.warned=!0,process.stderr.write(`qmd: a ${n} abandoned at its deadline is still running \u2014 answering without ${n} until it finishes
421
+ `)),o?.onDeadline?.(n),ae;let f=c(()=>{},"markReady");const h=new Promise(S=>{f=c(()=>{a=Date.now(),S()},"markReady")}),m=r(f),T=Vs();let p;const _=new Promise(S=>{T>0&&(p=setTimeout(()=>S("load-timeout"),T),p.unref?.())}),L=await Promise.race([h.then(()=>"ready"),_,m.then(()=>"done",()=>"done")]);if(clearTimeout(p),L==="load-timeout")return d(),o?.onModelLoad?.(n,Date.now()-s),o?.onDeadline?.(n,Date.now()-s),ae;if(i(),L==="done"||!t||t<=0)return m;const N=await $s(m,t);return N===ae&&(d(),o?.onDeadline?.(n,Date.now()-(a??s))),N}c(Fn,"runWithDeadline");const Xs=8,kn=.08;function dt(){const e=Number(process.env.QMD_RERANK_FIRST_BATCH);return Number.isInteger(e)&&e>1?e:Xs}c(dt,"rerankCascadeFirstBatch");function Gs(){const e=process.env.QMD_RERANK_MARGIN?.trim();if(e===void 0||e==="")return kn;const n=Number(e);return Number.isFinite(n)&&n>=0?n:kn}c(Gs,"rerankCascadeMargin");function zs(){const e=process.env.QMD_RERANK_CASCADE?.trim().toLowerCase();return e!=="0"&&e!=="false"&&e!=="off"&&e!=="no"}c(zs,"isRerankCascadeEnabled");function Ks(e,n=Gs()){if(e.length<2)return!1;const[t,o]=[e[0],e[1]];return!Number.isFinite(t)||!Number.isFinite(o)?!0:t-o<n}c(Ks,"cascadeNeedsSecondBatch");async function Pn(e,n,t,o,r){const s=r?.hooks;s?.onRerankStart?.(t.length);const a=Date.now(),i=c((l,d)=>Fn(e,"rerank",d,s,f=>e.rerank(n,l,void 0,o,{maxDocTokens:r?.rerankMaxDocTokens,onModelReady:f})),"scoreBatch");if(zs()&&t.length>dt()){const l=t.slice(0,dt()),d=t.slice(dt()),f=await i(l,r?.rerankDeadlineMs);if(f===ae)return null;const h=[...f].sort((_,L)=>L.score-_.score).map(_=>_.score);if(!Ks(h))return s?.onRerankDone?.(Date.now()-a),[...f,...d.map(_=>({file:_.file,score:0,unscored:!0}))];const m=r?.rerankDeadlineMs,T=m&&m>0?m-(Date.now()-a):void 0;if(T!==void 0&&T<=0)return s?.onDeadline?.("rerank",Date.now()-a),null;const p=await i(d,T);return p===ae?null:(s?.onRerankDone?.(Date.now()-a),[...f,...p])}const u=await i(t,r?.rerankDeadlineMs);return u===ae?null:(s?.onRerankDone?.(Date.now()-a),u)}c(Pn,"rerankWithDeadline");const Hn=c(async(e,n,t,o)=>{const r=t?Ln(t):[],s=new Map;for(const a of e){const{maxChars:i,overlapChars:u,windowChars:l}=ln(a.body,re,he,Re,as),d=await cn(a.body,i,u,l,a.file,o);d.length!==0&&s.set(a.file,{chunks:d,bestIdx:eo(d,n,r)})}return s},"chunkCandidatesForRerank"),Wn=c((e,n)=>e.flatMap(t=>{const o=n.get(t.file);return o?[{file:t.file,text:Yn(o.chunks[o.bestIdx].text,t)}]:[]}),"rerankDocuments");async function vr(e,n,t){const o=gt(n),r=t?.limit??10,s=t?.minScore??0,a=Math.max(1,t?.candidateLimit??Be),i=t?.collection,u=t?.filter,l=t?.explain??!1,d=t?.intent,f=t?.skipRerank??!1,h=t?.scope,m=t?.hooks,T=[],p=[],_=new Map,L=!!e.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'").get();let N=Date.now();const S=e.searchFTS(o,20,i,u,h);let y=Date.now()-N;const w=S[0]?.score??0,W=S[1]?.score??0,k=!d&&S.length>0&&S[0]?.matchMode!=="any"&&w>=yo&&w-W>=No;k&&m?.onStrongSignal?.(w);const q=k||Gn(o);m?.onExpandStart?.();const b=Date.now(),g=q?[]:await Fn(e,"expand",t?.expandDeadlineMs,m,x=>e.expandQuery(o,void 0,{onModelReady:x})),O=g===ae?[]:g;if(m?.onExpand?.(o,O,Date.now()-b),S.length>0){for(const x of S)_.set(x.filepath,x.docid);T.push(S.map(x=>({file:x.filepath,displayPath:x.displayPath,title:x.title,body:x.body||"",score:x.score}))),p.push({source:"fts",queryType:"original",query:o,relaxed:S[0]?.matchMode==="any"})}N=Date.now();for(const x of O)if(x.type==="lex"){const I=e.searchFTS(x.query,20,i,u,h);if(I.length>0){for(const A of I)_.set(A.filepath,A.docid);T.push(I.map(A=>({file:A.filepath,displayPath:A.displayPath,title:A.title,body:A.body||"",score:A.score}))),p.push({source:"fts",queryType:"lex",query:x.query,relaxed:I[0]?.matchMode==="any"})}}if(m?.onFtsDone?.(y+Date.now()-N),L){const x=[{text:o,queryType:"original"}];for(const V of O)(V.type==="vec"||V.type==="hyde")&&x.push({text:V.query,queryType:V.type});const I=ue(e),A=I.embedModelName,D=x.map(V=>xe(V.text,A));m?.onEmbedStart?.(D.length);const M=Date.now(),F=await I.embedBatch(D);m?.onEmbedDone?.(Date.now()-M);const v=Date.now();for(let V=0;V<x.length;V++){const Y=F[V]?.embedding;if(!Y)continue;const U=await e.searchVec(x[V].text,A,20,i,void 0,Y,u,h);if(U.length>0){for(const B of U)_.set(B.filepath,B.docid);T.push(U.map(B=>({file:B.filepath,displayPath:B.displayPath,title:B.title,body:B.body||"",score:B.score}))),p.push({source:"vec",queryType:x[V].queryType,query:x[V].text})}}m?.onVecDone?.(Date.now()-v)}if(O.length>0){const x=O.filter(A=>A.type==="lex"||L),I=p.some(A=>A.queryType!=="original");x.length>0&&!I&&e.invalidateExpansionCache(o)}const H=qs(p),G=Nn(T,p),$=Cn(T,H,60,G),Q=l?Dn(T,H,p,60,G):null,z=$.slice(0,a);if(z.length===0)return[];const J=ge(e.db,z.map(x=>x.file)),se=Date.now(),ne=await Hn(z,o,d,t?.chunkStrategy);m?.onChunkDone?.(Date.now()-se);const ie=f?null:await Pn(e,o,Wn(z,ne),d,t);if(ie===null){const x=new Set,I=z.map((A,D)=>{const M=ne.get(A.file),F=M?.bestIdx??0,v=M?.chunks[F]?.text||A.body||"",V=M?.chunks[F]?.pos||0,Y=D+1,U=1/Y,B=Q?.get(A.file),X=l?{ftsScores:B?.contributions.filter(ee=>ee.source==="fts").map(ee=>ee.backendScore)??[],vectorScores:B?.contributions.filter(ee=>ee.source==="vec").map(ee=>ee.backendScore)??[],rrf:{rank:Y,positionScore:U,weight:1,baseScore:B?.baseScore??0,topRankBonus:B?.topRankBonus??0,totalScore:B?.totalScore??0,contributions:B?.contributions??[]},rerankScore:0,blendedScore:U}:void 0;return{file:A.file,displayPath:A.displayPath,title:A.title,body:A.body,bestChunk:v,bestChunkPos:V,score:U,context:J.get(A.file)??null,docid:_.get(A.file)||"",...X?{explain:X}:{}}}).filter(A=>x.has(A.file)?!1:(x.add(A.file),!0)).filter(A=>!f||A.score>=s).slice(0,r);return Pe(e.db,I)}const E=new Map(z.map(x=>[x.file,{displayPath:x.displayPath,title:x.title,body:x.body}])),C=new Map(z.map((x,I)=>[x.file,I+1])),R=new Set(ie.filter(x=>x.unscored).map(x=>x.file)),K=ie.map(x=>{const I=C.get(x.file)||a,A=1-(I-1)/a,D=Mn(I,x.score,a),M=E.get(x.file),F=ne.get(x.file),v=F?.bestIdx??0,V=F?.chunks[v]?.text||M?.body||"",Y=F?.chunks[v]?.pos||0,U=Q?.get(x.file),B=l?{ftsScores:U?.contributions.filter(X=>X.source==="fts").map(X=>X.backendScore)??[],vectorScores:U?.contributions.filter(X=>X.source==="vec").map(X=>X.backendScore)??[],rrf:{rank:I,positionScore:A,weight:He,baseScore:U?.baseScore??0,topRankBonus:U?.topRankBonus??0,totalScore:U?.totalScore??0,contributions:U?.contributions??[]},rerankScore:x.score,blendedScore:D}:void 0;return{file:x.file,displayPath:M?.displayPath||"",title:M?.title||"",body:M?.body||"",bestChunk:V,bestChunkPos:Y,score:D,context:J.get(x.file)??null,docid:_.get(x.file)||"",...B?{explain:B}:{}}}).sort((x,I)=>I.score-x.score),P=new Set,j=K.filter(x=>P.has(x.file)?!1:(P.add(x.file),!0)).filter(x=>R.has(x.file)||x.score>=s).slice(0,r);return Pe(e.db,j)}c(vr,"hybridQuery");async function Ir(e,n,t){const o=t?.limit??10,r=t?.minScore??.3,s=t?.collection,a=t?.filter,i=t?.intent,u=t?.scope;if(!!!e.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'").get())return[];const d=Date.now(),h=(await e.expandQuery(n)).filter(N=>N.type!=="lex");t?.hooks?.onExpand?.(n,h,Date.now()-d);const m=ue(e).embedModelName,T=[n,...h.map(N=>N.query)],p=new Map;for(const N of T){const S=await e.searchVec(N,m,o,s,void 0,void 0,a,u);for(const y of S){const w=p.get(y.filepath);(!w||y.score>w.score)&&p.set(y.filepath,{file:y.filepath,displayPath:y.displayPath,title:y.title,body:y.body||"",score:y.score,context:null,docid:y.docid,metadata:y.metadata})}}const _=Array.from(p.values()).sort((N,S)=>S.score-N.score).filter(N=>N.score>=r).slice(0,o),L=ge(e.db,_.map(N=>N.file));return _.map(N=>({...N,context:L.get(N.file)??null}))}c(Ir,"vectorSearchQuery");async function Mr(e,n,t){const o=t?.limit??10,r=t?.minScore??0,s=Math.max(1,t?.candidateLimit??Be),a=t?.explain??!1,i=t?.intent,u=t?.skipRerank??!1,l=t?.filter,d=t?.hooks,f=t?.collections,h=t?.scope;if(n.length===0)return[];const m=s>Be?s:20;for(const E of n){const C=E.line?`Line ${E.line}`:"Structured search";if(/[\r\n]/.test(E.query))throw new Error(`${C} (${E.type}): queries must be single-line. Remove newline characters.`);if(E.type==="lex"){const R=Es(E.query);if(R)throw new Error(`${C} (lex): ${R}`)}else if(E.type==="vec"||E.type==="hyde"){const R=ps(E.query);if(R)throw new Error(`${C} (${E.type}): ${R}`)}}const T=n.map(E=>E.type==="hyde"?E:{...E,query:gt(E.query)}),p=[],_=[],L=new Map,N=!!e.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'").get(),S=f??[void 0],y=Date.now();for(let E=0;E<T.length;E++){const C=T[E];if(C.type!=="lex")continue;const R=new Map;for(const P of S){const j=e.searchFTS(C.query,m,P,l,h);for(const x of j){L.set(x.filepath,x.docid);const I=R.get(x.filepath);(!I||x.score>I.score)&&R.set(x.filepath,x)}}if(R.size===0)continue;const K=Array.from(R.values()).sort((P,j)=>j.score-P.score||(P.filepath<j.filepath?-1:P.filepath>j.filepath?1:0));p.push(K.map(P=>({file:P.filepath,displayPath:P.displayPath,title:P.title,body:P.body||"",score:P.score}))),_.push({source:"fts",queryType:"lex",query:C.query,relaxed:K[0]?.matchMode==="any",searchIndex:E})}if(T.some(E=>E.type==="lex")&&d?.onFtsDone?.(Date.now()-y),N){const E=T.map((C,R)=>({s:C,searchIndex:R})).filter(C=>C.s.type==="vec"||C.s.type==="hyde");if(E.length>0){const C=ue(e),R=C.embedModelName,K=E.map(I=>xe(I.s.query,R));d?.onEmbedStart?.(K.length);const P=Date.now(),j=await C.embedBatch(K);d?.onEmbedDone?.(Date.now()-P);const x=Date.now();for(let I=0;I<E.length;I++){const A=j[I]?.embedding;if(!A)continue;const D=E[I],M=new Map;for(const v of S){const V=await e.searchVec(D.s.query,R,m,v,void 0,A,l,h);for(const Y of V){L.set(Y.filepath,Y.docid);const U=M.get(Y.filepath);(!U||Y.score>U.score)&&M.set(Y.filepath,Y)}}if(M.size===0)continue;const F=Array.from(M.values()).sort((v,V)=>V.score-v.score||(v.filepath<V.filepath?-1:v.filepath>V.filepath?1:0));p.push(F.map(v=>({file:v.filepath,displayPath:v.displayPath,title:v.title,body:v.body||"",score:v.score}))),_.push({source:"vec",queryType:D.s.type,query:D.s.query,searchIndex:D.searchIndex})}d?.onVecDone?.(Date.now()-x)}}if(p.length===0)return[];const w=Bs(_),W=Nn(p,_),k=Cn(p,w,60,W),q=a?Dn(p,w,_,60,W):null,b=k.slice(0,s);if(b.length===0)return[];const g=ge(e.db,b.map(E=>E.file));d?.onExpand?.("",[],0);const O=T.find(E=>E.type==="lex")?.query||T.find(E=>E.type==="vec")?.query||T[0]?.query||"",H=Date.now(),G=await Hn(b,O,i,t?.chunkStrategy);d?.onChunkDone?.(Date.now()-H);const $=u?null:await Pn(e,O,Wn(b,G),i,t);if($===null){const E=new Set,C=b.map((R,K)=>{const P=G.get(R.file),j=P?.bestIdx??0,x=P?.chunks[j]?.text||R.body||"",I=P?.chunks[j]?.pos||0,A=K+1,D=1/A,M=q?.get(R.file),F=a?{ftsScores:M?.contributions.filter(v=>v.source==="fts").map(v=>v.backendScore)??[],vectorScores:M?.contributions.filter(v=>v.source==="vec").map(v=>v.backendScore)??[],rrf:{rank:A,positionScore:D,weight:1,baseScore:M?.baseScore??0,topRankBonus:M?.topRankBonus??0,totalScore:M?.totalScore??0,contributions:M?.contributions??[]},rerankScore:0,blendedScore:D}:void 0;return{file:R.file,displayPath:R.displayPath,title:R.title,body:R.body,bestChunk:x,bestChunkPos:I,score:D,context:g.get(R.file)??null,docid:L.get(R.file)||"",...F?{explain:F}:{}}}).filter(R=>E.has(R.file)?!1:(E.add(R.file),!0)).filter(R=>!u||R.score>=r).slice(0,o);return Pe(e.db,C)}const Q=new Map(b.map(E=>[E.file,{displayPath:E.displayPath,title:E.title,body:E.body}])),z=new Map(b.map((E,C)=>[E.file,C+1])),J=new Set($.filter(E=>E.unscored).map(E=>E.file)),se=$.map(E=>{const C=z.get(E.file)||s,R=1-(C-1)/s,K=Mn(C,E.score,s),P=Q.get(E.file),j=G.get(E.file),x=j?.bestIdx??0,I=j?.chunks[x]?.text||P?.body||"",A=j?.chunks[x]?.pos||0,D=q?.get(E.file),M=a?{ftsScores:D?.contributions.filter(F=>F.source==="fts").map(F=>F.backendScore)??[],vectorScores:D?.contributions.filter(F=>F.source==="vec").map(F=>F.backendScore)??[],rrf:{rank:C,positionScore:R,weight:He,baseScore:D?.baseScore??0,topRankBonus:D?.topRankBonus??0,totalScore:D?.totalScore??0,contributions:D?.contributions??[]},rerankScore:E.score,blendedScore:K}:void 0;return{file:E.file,displayPath:P?.displayPath||"",title:P?.title||"",body:P?.body||"",bestChunk:I,bestChunkPos:A,score:K,context:g.get(E.file)??null,docid:L.get(E.file)||"",...M?{explain:M}:{}}}).sort((E,C)=>C.score-E.score),ne=new Set,ie=se.filter(E=>ne.has(E.file)?!1:(ne.add(E.file),!0)).filter(E=>J.has(E.file)||E.score>=r).slice(0,o);return Pe(e.db,ie)}c(Mr,"structuredSearch");export{To as BREAK_PATTERNS,Ue as CHUNK_OVERLAP_CHARS,he as CHUNK_OVERLAP_TOKENS,Se as CHUNK_SIZE_CHARS,re as CHUNK_SIZE_TOKENS,Oe as CHUNK_WINDOW_CHARS,Re as CHUNK_WINDOW_TOKENS,fo as DEFAULT_EMBED_MAX_BATCH_BYTES,ho as DEFAULT_EMBED_MAX_DOCS_PER_BATCH,po as DEFAULT_EMBED_MAX_DURATION_MS,te as DEFAULT_EMBED_MODEL,lr as DEFAULT_GLOB,bn as DEFAULT_LOAD_TIMEOUT_MS,uo as DEFAULT_MULTI_GET_MAX_BYTES,De as DEFAULT_QUERY_MODEL,xt as DEFAULT_RERANK_MODEL,it as FILTERED_FTS_SCAN_MAX,Zn as INTENT_WEIGHT_CHUNK,ks as INTENT_WEIGHT_SNIPPET,Be as RERANK_CANDIDATE_LIMIT,Xs as RERANK_CASCADE_FIRST_BATCH,kn as RERANK_CASCADE_MARGIN,No as STRONG_SIGNAL_MIN_GAP,yo as STRONG_SIGNAL_MIN_SCORE,dr as _resetProductionModeForTesting,Ar as addLineNumbers,Mn as blendRerankScore,Dn as buildRrfTrace,At as buildVirtualPath,Ks as cascadeNeedsSecondBatch,rn as chunkDocument,cn as chunkDocumentAsync,yr as chunkDocumentByTokens,Nt as chunkDocumentWithBreakPoints,Fe as cleanupOrphanedContent,Yt as cleanupOrphanedVectors,yn as clearAllEmbeddings,ts as clearCache,Lr as countFilteredDocuments,ns as countOrphanedContent,os as countOrphanedVectors,_r as createStore,on as deactivateDocument,ys as deleteExpansionCacheEntry,Kt as deleteInactiveDocuments,zt as deleteLLMCache,Uo as deleteStoreCollection,ur as enableProductionMode,On as escapeLikePattern,Rs as expandQuery,Ln as extractIntentTerms,vn as extractSnippet,et as extractTitle,nt as findActiveDocument,xo as findBestCutoff,Rt as findCodeFences,Is as findDocument,rt as findDocumentByDocid,bs as findDocuments,en as findOrMigrateLegacyDocument,ct as findSimilarFiles,le as formatDocForEmbedding,xe as formatQueryForEmbedding,Tr as generateEmbeddings,sn as getActiveDocumentPaths,me as getCacheKey,be as getCachedResult,fn as getCollectionByName,us as getCollectionsWithoutContext,hn as getContextForFile,ls as getContextForPath,ge as getContextsForFiles,Co as getDefaultDbPath,we as getDocid,Ms as getDocumentBody,fe as getEmbeddingFingerprint,_s as getHashesForEmbedding,Qe as getHashesNeedingEmbedding,qs as getHybridRrfWeights,Zo as getIndexHealth,hr as getPwd,Ot as getRealPath,Dt as getRelativePathFromPrefix,Fs as getStatus,Ie as getStoreCollection,oe as getStoreCollections,fr as getStoreContexts,Me as getStoreGlobalContext,Bs as getStructuredRrfWeights,ds as getTopLevelPathsWithoutContext,Qo as handelize,rs as hashContent,$e as homedir,vr as hybridQuery,tt as insertContent,Or as insertContext,Zt as insertDocument,ut as insertEmbedding,Ct as isAbsolutePath,st as isDocid,_o as isInsideCodeFence,Lt as isPathInsideDir,zs as isRerankCascadeEnabled,mr as isSqliteVecAvailable,Ge as isVirtualPath,Xo as listCollectionFiles,Nr as listCollections,dn as matchFilesByGlob,xr as maybeAdoptLegacyEmbeddingFingerprint,So as mergeBreakPoints,de as normalizeCjkForFTS,un as normalizeDocid,pe as normalizePathSeparators,Do as normalizeVirtualPath,ss as optimizeDocumentsFts,Ee as parseVirtualPath,Sr as previewCleanup,Cn as reciprocalRankFusion,gr as reindexCollection,Os as relaxedDocCoverage,Cr as removeCollection,pr as removeStoreContext,Dr as renameCollection,Bo as renameStoreCollection,Ns as rerank,dt as rerankCascadeFirstBatch,Gs as rerankCascadeMargin,Pn as rerankWithDeadline,ce as resolve,ws as resolveCommaListName,Vs as resolveLoadTimeoutMs,Oo as resolveVirtualPath,Nn as rrfDocMultipliers,Rr as runCleanup,hs as sanitizeFTS5Term,St as scanBreakPoints,_n as searchFTS,Rn as searchVec,Ze as setCachedResult,Ut as setStoreGlobalContext,lo as splitGlobMask,Mr as structuredSearch,Er as syncConfigToDb,Lo as toVirtualPath,nn as updateDocument,tn as updateDocumentTitle,$o as updateStoreContext,qo as upsertStoreCollection,Qt as vacuumDatabase,Es as validateLexQuery,ps as validateSemanticQuery,Ir as vectorSearchQuery,Ao as verifySqliteVecLoaded};