@easbot/codebase 0.3.29 → 0.3.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +55 -1
- package/README.md +55 -1
- package/dist/chunks/cache-CSRIBDNY.cjs +1 -0
- package/dist/chunks/cache-EZ3VLUUC.mjs +1 -0
- package/dist/chunks/chunk-3DAM6EZN.cjs +203 -0
- package/dist/chunks/chunk-43WAI4Z7.mjs +1 -0
- package/dist/chunks/chunk-47LKNS74.mjs +1 -0
- package/dist/chunks/chunk-6NYX22KV.cjs +48 -0
- package/dist/chunks/{chunk-YJK7F6NJ.cjs → chunk-AARBEAIB.cjs} +22 -22
- package/dist/chunks/chunk-D5NDNAKA.cjs +1 -0
- package/dist/chunks/chunk-ECMVXJH2.mjs +1 -0
- package/dist/chunks/chunk-EH2QTB6S.cjs +37 -0
- package/dist/chunks/chunk-ESA2CL57.mjs +37 -0
- package/dist/chunks/chunk-ETCTXAXR.mjs +1 -0
- package/dist/chunks/{chunk-4XKCGYFF.mjs → chunk-EU2I2AMK.mjs} +22 -22
- package/dist/chunks/chunk-FZNMPXUO.mjs +62 -0
- package/dist/chunks/chunk-H4VZF3ZQ.mjs +1 -0
- package/dist/chunks/chunk-J7Z3MIR7.cjs +1 -0
- package/dist/chunks/chunk-KTSR5VPT.mjs +1 -0
- package/dist/chunks/chunk-OUJNWRIY.mjs +48 -0
- package/dist/chunks/chunk-QZMJ5EUF.mjs +203 -0
- package/dist/chunks/chunk-R32346OA.cjs +1 -0
- package/dist/chunks/chunk-VXLUR7M5.cjs +62 -0
- package/dist/chunks/chunk-VZCOLSBF.cjs +1 -0
- package/dist/chunks/chunk-W5SMGCKO.cjs +1 -0
- package/dist/chunks/chunk-Y7JDLK56.cjs +1 -0
- package/dist/chunks/cli-handler-7HKSS3UW.mjs +1 -0
- package/dist/chunks/cli-handler-OU2TC2SB.cjs +1 -0
- package/dist/chunks/code-base-OBQSRCQ3.mjs +1 -0
- package/dist/chunks/code-base-WZ3L5IE5.cjs +1 -0
- package/dist/chunks/database-manager-T43UZZ45.cjs +1 -0
- package/dist/chunks/database-manager-ZC46AHSS.mjs +1 -0
- package/dist/chunks/file-watcher-GUS2OVZU.cjs +1 -0
- package/dist/chunks/file-watcher-RAO72GUL.mjs +1 -0
- package/dist/chunks/{interfaces-S7TJGWWS.mjs → interfaces-UUDPRWI6.mjs} +1 -1
- package/dist/chunks/interfaces-YGSG2MI4.cjs +1 -0
- package/dist/chunks/llm-NWYEBR5K.mjs +1 -0
- package/dist/chunks/llm-UYBJKQ3S.cjs +1 -0
- package/dist/chunks/{stdio-server-DFKFFRSM.cjs → stdio-server-37QG6AO2.cjs} +2 -2
- package/dist/chunks/stdio-server-QAEXVFSI.mjs +30 -0
- package/dist/cli.cjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +149 -41
- package/dist/index.d.ts +149 -41
- package/dist/index.mjs +1 -1
- package/package.json +10 -11
- package/dist/chunks/chunk-23YR2LAM.cjs +0 -1
- package/dist/chunks/chunk-2YMB6W5S.mjs +0 -1
- package/dist/chunks/chunk-3RVRPGJC.mjs +0 -1
- package/dist/chunks/chunk-3UGOMK4F.cjs +0 -62
- package/dist/chunks/chunk-5M2N7JFP.cjs +0 -1
- package/dist/chunks/chunk-A4YJ5ZVE.cjs +0 -203
- package/dist/chunks/chunk-J7AIRI5N.mjs +0 -203
- package/dist/chunks/chunk-LLO6DDXU.mjs +0 -48
- package/dist/chunks/chunk-LQVKXVBS.mjs +0 -51
- package/dist/chunks/chunk-LZLPJAB6.mjs +0 -62
- package/dist/chunks/chunk-M2YU5LAI.cjs +0 -1
- package/dist/chunks/chunk-MZHDSOD7.mjs +0 -1
- package/dist/chunks/chunk-OGTQ7MWV.cjs +0 -51
- package/dist/chunks/chunk-V6PHJ4DG.cjs +0 -48
- package/dist/chunks/cli-handler-B7WPIZRE.cjs +0 -1
- package/dist/chunks/cli-handler-EJX27R4Q.mjs +0 -1
- package/dist/chunks/code-base-FSOSU46G.mjs +0 -1
- package/dist/chunks/code-base-OWYMNEQG.cjs +0 -1
- package/dist/chunks/database-manager-7D7NDXJK.mjs +0 -1
- package/dist/chunks/database-manager-X4DMAUWC.cjs +0 -1
- package/dist/chunks/file-watcher-E2JROVI7.cjs +0 -1
- package/dist/chunks/file-watcher-KSLBUUPP.mjs +0 -1
- package/dist/chunks/interfaces-URUTHSR2.cjs +0 -1
- package/dist/chunks/llm-R2ZLKZDO.cjs +0 -1
- package/dist/chunks/llm-U57HNTZO.mjs +0 -1
- package/dist/chunks/stdio-server-NV5YAXJD.mjs +0 -30
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkW5SMGCKO_cjs=require('./chunk-W5SMGCKO.cjs'),chunkR32346OA_cjs=require('./chunk-R32346OA.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database');var A=utils.Log.create({service:"codebase.database.migrations"}),N=1,X=[{id:1,description:"v1 baseline: nodes / edges / file_hashes / nodes_fts / meta / embedding_cache / node_embeddings + unresolved_refs / name_segment_vocab / project_metadata / parse_errors + \u6027\u80FD index (nodes.file_path / edges.source/target)",up:[`CREATE TABLE IF NOT EXISTS nodes (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
name TEXT NOT NULL,
|
|
4
4
|
ast_type TEXT NOT NULL,
|
|
@@ -64,22 +64,22 @@
|
|
|
64
64
|
message TEXT NOT NULL,
|
|
65
65
|
line INTEGER,
|
|
66
66
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
67
|
-
)`,"CREATE INDEX IF NOT EXISTS idx_parse_errors_file_path ON parse_errors(file_path)","CREATE INDEX IF NOT EXISTS idx_nodes_file_path ON nodes(file_path)","CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)"]}];function
|
|
67
|
+
)`,"CREATE INDEX IF NOT EXISTS idx_parse_errors_file_path ON parse_errors(file_path)","CREATE INDEX IF NOT EXISTS idx_nodes_file_path ON nodes(file_path)","CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)"]}];function v(E,e=N,t={}){E.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
68
68
|
id INTEGER PRIMARY KEY,
|
|
69
69
|
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
70
|
-
)`);let s=
|
|
70
|
+
)`);let s=E.prepare("SELECT id FROM schema_migrations").all(),n=new Set(s.map(a=>a.id)),r={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(a=>a.id)),targetVersion:e};for(let a of X){if(a.id>e)break;if(n.has(a.id)){r.pending.push(a.id);continue}if(t.dryRun){r.applied.push(a.id);continue}try{E.execBatch([...a.up]),E.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(a.id),n.add(a.id),r.applied.push(a.id),A.debug("migration applied",{id:a.id,description:a.description});}catch(i){let o=utils.errorMeta(i).message,c=a.up[0]??"";r.errors.push({migrationId:a.id,sql:c,error:o}),A.warn("migration step failed (may be idempotent)",{id:a.id,error:utils.errorMeta(i),sqlCount:a.up.length});}}return r}function w(E){try{let e=E.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(t=>t.id))}catch{return 0}}var l=utils.Filesystem.toUnixPath,d=utils.Log.create({service:"codebase.database"}),S=3,U=class{constructor(e){chunkR32346OA_cjs.a(this,"db");chunkR32346OA_cjs.a(this,"dbPath");chunkR32346OA_cjs.a(this,"closed",false);chunkR32346OA_cjs.a(this,"ftsAvailable",false);this.dbPath=e===":memory:"?e:utils.Filesystem.normalize(e),this.db=database.createSyncSqliteConnection({path:this.dbPath,backend:"better-sqlite3",walMode:true,foreignKeys:true,busyTimeoutMs:3e4}),this.db.initialize();try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("foreign_keys = ON");}catch(t){d.warn("Failed to apply codebase PRAGMAs (synchronous / cache_size / foreign_keys)",{error:utils.errorMeta(t)});}try{this.ensureSchema();let t=w(this.db);t>0&&this.setMeta("schema_version",String(t)),this.ftsAvailable=this.checkFtsAvailability(),this.detectAndMarkStaleOnInit();}catch(t){try{this.db.close();}catch{}throw this.closed=true,t}}ensureSchema(){try{v(this.db,N);let e=[["version","1.0.0"],["createdAt",new Date().toISOString()],["index_state","uninitialized"],["indexed_with_version","unknown"]],t=this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[s,n]of e)t.run(s,n);}catch(e){d.error("ensureSchema failed",{error:utils.errorMeta(e)});let t=utils.errorMeta(e).message,s=e instanceof Error?e.cause:void 0,n=s!==void 0?String(s):"",r=n&&n!==t?` (cause: ${n})`:"";throw new chunkW5SMGCKO_cjs.b.SchemaError({message:`Failed to create database schema: ${t}${r}`,missing:e instanceof Error?[t,n].filter(Boolean):[t]},{cause:e})}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:l(e.file_path)};this.db.prepare(`
|
|
71
71
|
INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
|
|
72
72
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
73
|
-
`).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(r=>({...r,file_path:
|
|
73
|
+
`).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(r=>({...r,file_path:l(r.file_path)})),s=this.db.prepare(`
|
|
74
74
|
INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
|
|
75
75
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
76
|
-
`);this.db.transaction(r=>{for(let a of r)s.run(a.id,a.name,a.ast_type,a.language,a.file_path,a.start_line,a.start_col,a.end_line,a.end_col,a.text,a.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(r);})(t);}updateFtsNodesInternal(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),n=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let r of e)try{let a=s.get(r.id);a&&t.run(a.rowid),n.run(r.id,r.name,r.ast_type,r.language,r.file_path,r.text);}catch(a){
|
|
76
|
+
`);this.db.transaction(r=>{for(let a of r)s.run(a.id,a.name,a.ast_type,a.language,a.file_path,a.start_line,a.start_col,a.end_line,a.end_col,a.text,a.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(r);})(t);}updateFtsNodesInternal(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),n=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let r of e)try{let a=s.get(r.id);a&&t.run(a.rowid),n.run(r.id,r.name,r.ast_type,r.language,r.file_path,r.text);}catch(a){d.warn("FTS update failed for node",{nodeId:r.id,error:utils.errorMeta(a)});}}updateFtsNode(e){try{let t=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?").get(e.id);t&&this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(t.rowid),this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.ast_type,e.language,e.file_path,e.text);}catch(t){d.warn("FTS update failed for node",{nodeId:e.id,error:utils.errorMeta(t)});}}updateFtsNodes(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),n=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(a=>{for(let i of a)try{let o=s.get(i.id);o&&t.run(o.rowid),n.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.text);}catch(o){d.warn("FTS update failed for node",{nodeId:i.id,error:utils.errorMeta(o)});}})(e);}insertEdge(e){this.db.prepare(`
|
|
77
77
|
INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
|
|
78
78
|
VALUES (?, ?, ?, ?, ?)
|
|
79
79
|
`).run(e.id,e.source,e.target,e.relation,e.created_at);}insertEdges(e){if(e.length===0)return;let t=this.db.prepare(`
|
|
80
80
|
INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
|
|
81
81
|
VALUES (?, ?, ?, ?, ?)
|
|
82
|
-
`);this.db.transaction(n=>{for(let r of n)t.run(r.id,r.source,r.target,r.relation,r.created_at);})(e);}queryNodes(e){let t=[],s=[];e.filePath&&(t.push("file_path LIKE ?"),s.push(`%${
|
|
82
|
+
`);this.db.transaction(n=>{for(let r of n)t.run(r.id,r.source,r.target,r.relation,r.created_at);})(e);}queryNodes(e){let t=[],s=[];e.filePath&&(t.push("file_path LIKE ?"),s.push(`%${l(e.filePath)}%`)),e.astType&&(t.push("ast_type = ?"),s.push(e.astType)),e.name&&(t.push("name = ?"),s.push(e.name)),e.language&&(t.push("language = ?"),s.push(e.language));let n="SELECT * FROM nodes";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY file_path, start_line",e.limit&&(n+=" LIMIT ?",s.push(e.limit)),e.offset&&(n+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(n).all(...s)}catch(r){throw new chunkW5SMGCKO_cjs.b.DatabaseError({message:"Failed to query nodes",operation:"queryNodes"},{cause:r})}}findNodesByName(e){if(!e.name)return [];let t=e.limit??50,s=e.kind?`%${e.kind.toLowerCase()}%`:null,n=new Set,r=[],a=(o,c)=>{n.has(o.id)||(n.add(o.id),r.push({node:o,matchKind:c}));},i=(o,c)=>{e.file&&(e.file.includes("/")?(o.push("file_path = ?"),c.push(e.file)):(o.push("file_path LIKE '%/' || ?"),c.push(e.file))),s&&(o.push("LOWER(ast_type) LIKE ?"),c.push(s));};try{let o=["name = ?"],c=[e.name];i(o,c),c.push(t);let p=this.db.prepare(`SELECT * FROM nodes WHERE ${o.join(" AND ")} LIMIT ?`).all(...c);for(let u of p)a(u,"exact");if(p.length>0&&e.file)return r.slice(0,t);if(r.length<t){let u=this.db.prepare("SELECT * FROM nodes WHERE name LIKE ? LIMIT ?").all(`%${e.name}%`,t);for(let g of u)a(g,"qualified");}if(r.length>0&&e.file)return r.slice(0,t);if(r.length===0&&e.name){let u=["name LIKE ?"],g=[`%${e.name}%`];e.file&&(e.file.includes("/")?(u.push("file_path = ?"),g.push(e.file)):(u.push("file_path LIKE '%/' || ?"),g.push(e.file))),s&&(u.push("LOWER(ast_type) LIKE ?"),g.push(s)),u.push("?"),g.push(t);let f=this.db.prepare(`SELECT * FROM nodes WHERE ${u.join(" AND ")}`).all(...g);for(let _ of f)a(_,"substring");}return r.slice(0,t)}catch(o){throw new chunkW5SMGCKO_cjs.b.DatabaseError({message:"Failed to find nodes by name",operation:"findNodesByName"},{cause:o})}}queryEdges(e){let t=[],s=[];if(e.sourceOrTarget&&e.sourceOrTarget.length>0){let r=e.sourceOrTarget.map(()=>"?").join(",");t.push(`(source IN (${r}) OR target IN (${r}))`),s.push(...e.sourceOrTarget,...e.sourceOrTarget);}else e.source&&(t.push("source = ?"),s.push(e.source)),e.target&&(t.push("target = ?"),s.push(e.target));e.relation&&(t.push("relation = ?"),s.push(e.relation));let n="SELECT * FROM edges";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY created_at DESC",e.limit&&(n+=" LIMIT ?",s.push(e.limit)),e.offset&&(n+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(n).all(...s)}catch(r){throw new chunkW5SMGCKO_cjs.b.DatabaseError({message:"Failed to query edges",operation:"queryEdges"},{cause:r})}}queryAll(e,t){try{let s=this.db.prepare(e);return t?s.all(...t):s.all()}catch(s){throw new chunkW5SMGCKO_cjs.b.DatabaseError({message:"Failed to execute query",operation:"queryAll"},{cause:s})}}searchNodesFts(e,t=20){if(d.debug("searchNodesFts start",{query:e,limit:t,ftsAvailable:this.ftsAvailable}),!this.ftsAvailable)return d.debug("searchNodesFts skip - FTS not available"),[];try{let s=e.split(/\s+/).map(i=>`${i}*`).join(" ");d.debug("searchNodesFts query",{ftsQuery:s});let a=this.db.prepare(`
|
|
83
83
|
SELECT
|
|
84
84
|
nodes_fts.id,
|
|
85
85
|
nodes_fts.name,
|
|
@@ -97,62 +97,62 @@
|
|
|
97
97
|
WHERE nodes_fts.text MATCH ?
|
|
98
98
|
ORDER BY score DESC
|
|
99
99
|
LIMIT ?
|
|
100
|
-
`).all(s,t);return
|
|
100
|
+
`).all(s,t);return d.debug("searchNodesFts done",{resultCount:a.length}),a}catch(s){return d.warn("searchNodesFts failed",{error:utils.errorMeta(s)}),[]}}deleteNodesByFile(e){let t=l(e);if(this.ftsAvailable)try{let n=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let r of n)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(r.rowid);}catch(n){d.warn("FTS delete failed for file",{filePath:t,error:utils.errorMeta(n)});}return this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t).changes}deleteEdgesByFile(e){let t=l(e);return this.db.prepare(`
|
|
101
101
|
DELETE FROM edges
|
|
102
102
|
WHERE source IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
103
103
|
OR target IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
104
|
-
`).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(
|
|
104
|
+
`).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(l(e))?.content_hash??null}setFileHash(e,t){this.db.prepare(`
|
|
105
105
|
INSERT OR REPLACE INTO file_hashes (file_path, content_hash, last_modified)
|
|
106
106
|
VALUES (?, ?, ?)
|
|
107
|
-
`).run(
|
|
107
|
+
`).run(l(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(l(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}checkIntegrity(){let e=b=>this.db.prepare(b).get().c,t=b=>e(b),s={nodes:t("SELECT COUNT(*) as c FROM nodes"),edges:t("SELECT COUNT(*) as c FROM edges"),file_hashes:t("SELECT COUNT(*) as c FROM file_hashes"),fts:t("SELECT COUNT(*) as c FROM nodes_fts"),node_embeddings:t("SELECT COUNT(*) as c FROM node_embeddings"),embedding_cache:t("SELECT COUNT(*) as c FROM embedding_cache"),parse_errors:t("SELECT COUNT(*) as c FROM parse_errors"),unresolved_refs:t("SELECT COUNT(*) as c FROM unresolved_refs"),name_segment_vocab:t("SELECT COUNT(*) as c FROM name_segment_vocab"),project_metadata:t("SELECT COUNT(*) as c FROM project_metadata"),schema_migrations:t("SELECT COUNT(*) as c FROM schema_migrations"),meta:t("SELECT COUNT(*) as c FROM meta")},n=[],r=t(`
|
|
108
108
|
SELECT COUNT(*) as c FROM node_embeddings e
|
|
109
109
|
LEFT JOIN nodes n ON n.id = e.node_id WHERE n.id IS NULL
|
|
110
110
|
`);r>0&&n.push({severity:"error",message:`orphan node_embeddings: ${r}`});let a=t(`
|
|
111
111
|
SELECT COUNT(*) as c FROM edges e
|
|
112
112
|
WHERE e.relation != 'IMPORTS'
|
|
113
113
|
AND NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.source)
|
|
114
|
-
`);a>0&&n.push({severity:"error",message:`orphan edges (source): ${a}`});let
|
|
114
|
+
`);a>0&&n.push({severity:"error",message:`orphan edges (source): ${a}`});let i=t(`
|
|
115
115
|
SELECT COUNT(*) as c FROM edges e
|
|
116
116
|
WHERE e.relation NOT IN ('CALLS', 'IMPORTS')
|
|
117
117
|
AND NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.target)
|
|
118
|
-
`);
|
|
118
|
+
`);i>0&&n.push({severity:"error",message:`orphan edges (target): ${i}`});let o=t("SELECT COUNT(*) as c FROM edges WHERE source = target");o>0&&n.push({severity:"error",message:`self-loop edges: ${o} \u2014 re-run \`easbot codebase sync\` to filter (fixed in Wave 4 R3-2)`});t("SELECT COUNT(DISTINCT file_path) as c FROM nodes");let p=t(`
|
|
119
119
|
SELECT COUNT(*) as c FROM file_hashes fh
|
|
120
120
|
WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.file_path = fh.file_path)
|
|
121
|
-
`);
|
|
121
|
+
`);p>0&&n.push({severity:"warn",message:`orphan file_hashes (no nodes): ${p} \u2014 run \`easbot codebase sync\` to cleanup`});let u=t(`
|
|
122
122
|
SELECT COUNT(DISTINCT n.file_path) as c FROM nodes n
|
|
123
123
|
WHERE NOT EXISTS (SELECT 1 FROM file_hashes fh WHERE fh.file_path = n.file_path)
|
|
124
|
-
`);
|
|
124
|
+
`);u>0&&n.push({severity:"warn",message:`node files without hash: ${u}`});let g=t("SELECT COUNT(*) as c FROM nodes WHERE name IS NULL OR name = ''");g>0&&n.push({severity:"error",message:`nodes with null/empty name: ${g}`});let f=t("SELECT COUNT(*) as c FROM nodes WHERE ast_type IS NULL OR ast_type = ''");f>0&&n.push({severity:"error",message:`nodes with null/empty ast_type: ${f}`});let _=t("SELECT COUNT(*) as c FROM nodes WHERE language IS NULL OR language = ''");_>0&&n.push({severity:"error",message:`nodes with null/empty language: ${_}`});let O=t("SELECT COUNT(*) as c FROM nodes WHERE file_path IS NULL OR file_path = ''");O>0&&n.push({severity:"error",message:`nodes with null/empty file_path: ${O}`});let I=this.db.prepare("SELECT id, COUNT(*) as c FROM nodes GROUP BY id HAVING c > 1").all().length;I>0&&n.push({severity:"error",message:`duplicate node ids: ${I}`});let L=t("SELECT COUNT(*) as c FROM nodes WHERE file_path LIKE '%\\\\%'");L>0&&n.push({severity:"warn",message:`nodes with backslash in file_path: ${L}`});let C=t(`
|
|
125
125
|
SELECT COUNT(*) as c FROM nodes
|
|
126
126
|
WHERE start_line IS NOT NULL AND end_line IS NOT NULL AND start_line > end_line
|
|
127
|
-
`);
|
|
127
|
+
`);C>0&&n.push({severity:"error",message:`invalid line ranges: ${C}`});let F=this.db.prepare("SELECT id, COUNT(*) as c FROM edges GROUP BY id HAVING c > 1").all().length;F>0&&n.push({severity:"error",message:`duplicate edge ids: ${F}`});let M=t("SELECT COUNT(*) as c FROM nodes_fts_content");return M!==s.nodes&&n.push({severity:"error",message:`FTS content desync: ${M} vs ${s.nodes} (run \`easbot codebase recreate\` to rebuild)`}),s.parse_errors>100&&n.push({severity:"warn",message:`parse_errors > 100 (${s.parse_errors}) \u2014\u2014 many files failed to parse`}),{issues:n,stats:s}}getStatus(){let e=this.db.prepare("SELECT COUNT(*) as c FROM nodes").get(),t=this.db.prepare("SELECT COUNT(*) as c FROM edges").get(),s=this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get(),n=this.db.prepare("SELECT key, value FROM meta").all(),r={};for(let a of n)r[a.key]=a.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:s?.c??0,dbPath:this.dbPath,meta:r,indexState:this.getIndexState(),extractionVersion:parseInt(this.getMeta("indexed_with_extraction_version")??"0",10),isStale:this.isIndexStale()}}setLastSync(){this.db.prepare(`
|
|
128
128
|
INSERT OR REPLACE INTO meta (key, value)
|
|
129
129
|
VALUES ('lastSync', ?)
|
|
130
|
-
`).run(new Date().toISOString());}getIndexState(){return this.getMeta("index_state")??"uninitialized"}setIndexState(e){this.setMeta("index_state",e),this.setMeta("last_index_state_change",new Date().toISOString());}markIndexed(e){this.setMeta("indexed_with_version",e),this.setMeta("indexed_with_extraction_version",String(
|
|
130
|
+
`).run(new Date().toISOString());}getIndexState(){return this.getMeta("index_state")??"uninitialized"}setIndexState(e){this.setMeta("index_state",e),this.setMeta("last_index_state_change",new Date().toISOString());}markIndexed(e){this.setMeta("indexed_with_version",e),this.setMeta("indexed_with_extraction_version",String(S)),this.setMeta("index_state","complete"),this.setMeta("last_index_state_change",new Date().toISOString());}isIndexStale(){let e=this.getMeta("indexed_with_extraction_version");if(!e)return false;let t=parseInt(e,10);return Number.isNaN(t)||t<S}detectAndMarkStaleOnInit(){if(this.isIndexStale()){let e=this.getMeta("indexed_with_extraction_version");d.warn("codebase db is stale",{recorded:e??"(none)",current:String(S),hint:"run `easbot codebase recreate` or `easbot codebase index --force` to rebuild"});let t=this.getIndexState();(t==="complete"||t==="partial")&&this.setIndexState("stale");}}getNodeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM nodes").get()?.c??0}getEdgeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM edges").get()?.c??0}getFileCount(){return this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get()?.c??0}getNodeById(e){return this.db.prepare("SELECT * FROM nodes WHERE id = ?").get(e)??null}getEdgeById(e){return this.db.prepare("SELECT * FROM edges WHERE id = ?").get(e)??null}clearAll(e={}){this.db.exec("DELETE FROM nodes"),this.db.exec("DELETE FROM edges"),this.db.exec("DELETE FROM file_hashes"),this.db.exec("DELETE FROM meta"),e.keepEmbeddings||(this.db.exec("DELETE FROM node_embeddings"),this.db.exec("DELETE FROM embedding_cache")),this.ftsAvailable&&this.db.exec("DELETE FROM nodes_fts");try{this.db.exec("DELETE FROM sqlite_sequence WHERE name IN ('nodes', 'edges', 'file_hashes', 'meta')");}catch{}}getCachedEmbedding(e){let s=this.db.prepare(`
|
|
131
131
|
SELECT embedding FROM embedding_cache WHERE content_hash = ?
|
|
132
132
|
`).get(e);return s?new Float32Array(s.embedding.buffer,s.embedding.byteOffset,s.embedding.length/4):null}getVectorDims(){let e=this.db.prepare("SELECT value FROM meta WHERE key = ?").get("vectorDims");return e?parseInt(e.value,10):void 0}ensureVectorDims(e){this.db.prepare("SELECT value FROM meta WHERE key = ?").get("vectorDims")||this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)").run("vectorDims",String(e));}cacheEmbedding(e,t){if(this.db.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(e))return;this.ensureVectorDims(t.length),this.db.prepare(`
|
|
133
133
|
INSERT OR REPLACE INTO embedding_cache (content_hash, embedding)
|
|
134
134
|
VALUES (?, ?)
|
|
135
|
-
`).run(e,t);}deleteEmbeddingsByFile(e){let t=
|
|
135
|
+
`).run(e,t);}deleteEmbeddingsByFile(e){let t=l(e);return this.db.prepare(`
|
|
136
136
|
DELETE FROM node_embeddings WHERE node_id IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
137
137
|
`).run(t).changes}getAllNodeEmbeddings(){return this.db.prepare("SELECT node_id, embedding FROM node_embeddings").all()}storeNodeEmbeddings(e){if(e.length===0)return;this.ensureVectorDims(e[0].embedding.length);let t=this.db.prepare(`
|
|
138
138
|
INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
|
|
139
139
|
VALUES (?, ?, ?)
|
|
140
|
-
`);this.db.transaction(n=>{for(let r of n)try{t.run(r.nodeId,r.embeddingText,r.embedding);}catch(a){
|
|
140
|
+
`);this.db.transaction(n=>{for(let r of n)try{t.run(r.nodeId,r.embeddingText,r.embedding);}catch(a){d.warn("Failed to store embedding for node",{nodeId:r.nodeId,error:utils.errorMeta(a)});}})(e);}insertParseError(e){return this.db.prepare(`
|
|
141
141
|
INSERT INTO parse_errors (file_path, language, stage, message, line)
|
|
142
142
|
VALUES (?, ?, ?, ?, ?)
|
|
143
|
-
`).run(
|
|
143
|
+
`).run(l(e.filePath),e.language,e.stage,e.message,e.line??null).changes}insertUnresolvedRef(e){return this.db.prepare(`
|
|
144
144
|
INSERT INTO unresolved_refs
|
|
145
145
|
(from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
|
|
146
146
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
147
|
-
`).run(e.fromNodeId??null,e.referenceName,e.referenceKind,e.line??null,e.col??null,
|
|
147
|
+
`).run(e.fromNodeId??null,e.referenceName,e.referenceKind,e.line??null,e.col??null,l(e.filePath),e.language,e.candidates?JSON.stringify(e.candidates):null).changes}insertUnresolvedRefsBatch(e){if(e.length===0)return 0;let s=`
|
|
148
148
|
INSERT INTO unresolved_refs
|
|
149
149
|
(from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
|
|
150
150
|
VALUES ${e.map(()=>"(?, ?, ?, ?, ?, ?, ?, ?)").join(", ")}
|
|
151
|
-
`,n=[];for(let
|
|
151
|
+
`,n=[];for(let i of e)n.push(i.fromNodeId??null,i.referenceName,i.referenceKind,i.line??null,i.col??null,l(i.filePath),i.language,i.candidates?JSON.stringify(i.candidates):null);return this.db.prepare(s).run(...n).changes}insertNameSegment(e,t){return this.db.prepare(`
|
|
152
152
|
INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES (?, ?)
|
|
153
153
|
`).run(e,t).changes}insertNameSegmentsBatch(e){if(e.length===0)return 0;let s=`
|
|
154
154
|
INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES ${e.map(()=>"(?, ?)").join(", ")}
|
|
155
|
-
`,n=[];for(let
|
|
155
|
+
`,n=[];for(let i of e)n.push(i.segment,i.name);return this.db.prepare(s).run(...n).changes}setProjectMetadata(e,t){let s=e==="worktree"||e==="project"?l(t):t;return this.db.prepare(`
|
|
156
156
|
INSERT OR REPLACE INTO project_metadata (key, value, updated_at)
|
|
157
157
|
VALUES (?, ?, CURRENT_TIMESTAMP)
|
|
158
|
-
`).run(e,s).changes}getNodeIdsByFile(e){let t=e.replace(/\\/g,"/");return this.db.prepare("SELECT id FROM nodes WHERE file_path = ?").all(t).map(n=>n.id)}deleteFtsByFile(e){let t=e.replace(/\\/g,"/"),s=this.getNodeIdsByFile(t);if(s.length===0)return 0;let n=this.db.prepare("DELETE FROM nodes_fts WHERE id = ?");return this.db.transaction(a=>{for(let
|
|
158
|
+
`).run(e,s).changes}getNodeIdsByFile(e){let t=e.replace(/\\/g,"/");return this.db.prepare("SELECT id FROM nodes WHERE file_path = ?").all(t).map(n=>n.id)}deleteFtsByFile(e){let t=e.replace(/\\/g,"/"),s=this.getNodeIdsByFile(t);if(s.length===0)return 0;let n=this.db.prepare("DELETE FROM nodes_fts WHERE id = ?");return this.db.transaction(a=>{for(let i of a)n.run(i);})(s),s.length}initialize(){if(this.closed)throw new chunkW5SMGCKO_cjs.b.DatabaseError({message:"Cannot initialize closed database",operation:"initialize"})}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){d.warn("Database close error",{error:utils.errorMeta(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new utils.NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new utils.NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}countSqliteObjects(){if(!this.db)throw new utils.NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});return this.db.prepare("SELECT COUNT(*) as n FROM sqlite_master WHERE type IN ('table', 'index', 'trigger', 'view')").get()?.n??0}deleteMeta(e){if(!this.db)throw new utils.NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});this.db.prepare("DELETE FROM meta WHERE key = ?").run(e);}};function z(E){return E.isClosed()}function G(E){return E.getDbPath()}function j(E,e){return E.transaction(e)}exports.a=N;exports.b=X;exports.c=v;exports.d=w;exports.e=S;exports.f=U;exports.g=z;exports.h=G;exports.i=j;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkR32346OA_cjs=require('./chunk-R32346OA.cjs'),fs=require('fs'),path=require('path'),module$1=require('module'),utils=require('@easbot/utils');var o=utils.Log.create({service:"codebase.sync.file-watcher"});function A(){return process.env.EASBOT_CACHE_PATH||path.join(process.cwd(),".easbot",".cache")}var C=["node_modules/**",".git/**","dist/**","build/**","__pycache__/**","*.min.js","*.min.ts",".easbot/**",".codebase/**"],s=class s{constructor(){chunkR32346OA_cjs.a(this,"wrapper",null);chunkR32346OA_cjs.a(this,"error",null);}static get(){return s.instance||(s.instance=new s),s.instance}static clearCache(){s.instance&&(s.instance.wrapper=null,s.instance.error=null);}};chunkR32346OA_cjs.a(s,"instance",null);var b=s;function R(){let r=process.platform==="linux"?`-${globalThis.EASBOT_LIBC||"glibc"}`:"";return `@parcel/watcher-${process.platform}-${process.arch}${r}`}async function T(){let r=b.get();if(r.wrapper)return r.wrapper;if(r.error)throw new utils.NameErrors.OperationFailedError({message:r.error,operation:"parcel-watcher-binding-cache"});let e=R(),t=A(),i;try{await $(e,t)?i=path.join(t,"node_modules",e):(o.info("Parcel watcher binding not found, attempting to install",{binding:e,cachePath:t}),i=await q(e,t));}catch(u){let p=utils.errorMeta(u).message,f=`binding "${e}" not found and auto-install failed. Run manually: pnpm install ${e}. Error: ${p}`;throw r.error=f,o.error("failed to install parcel watcher binding",{error:utils.errorMeta(u),binding:e}),new utils.NameErrors.OperationFailedError({message:f,operation:"parcel-watcher-binding-install"})}o.info("Loading Parcel watcher binding",{binding:e,modulePath:i});let{createWrapper:g}=await import('@parcel/watcher/wrapper.js'),l=module$1.createRequire(path.join(i,"package.json"))(e),c=g(l);return r.wrapper=c,c}async function $(r,e){try{return !!await utils.PKG.resolve(r,void 0,{extraPaths:[e]})}catch{return false}}async function q(r,e){return o.info("Installing Parcel watcher binding",{binding:r,cachePath:e}),await utils.Shell.install(r,"latest",e),path.join(e,"node_modules",r)}function P(){return process.platform==="darwin"?"fs-events":process.platform==="linux"?"inotify":process.platform==="win32"?"windows":"brute-force"}var v=class{constructor(e){chunkR32346OA_cjs.a(this,"workspaceDir");chunkR32346OA_cjs.a(this,"backendOpt");chunkR32346OA_cjs.a(this,"ignorePatterns");chunkR32346OA_cjs.a(this,"onLoadFailure");chunkR32346OA_cjs.a(this,"ignoreInstance");chunkR32346OA_cjs.a(this,"listeners",new Set);chunkR32346OA_cjs.a(this,"unsubscribe",null);chunkR32346OA_cjs.a(this,"disposed",false);chunkR32346OA_cjs.a(this,"running",false);this.workspaceDir=path.isAbsolute(e.workspaceDir)?e.workspaceDir:path.normalize(e.workspaceDir),this.backendOpt=e.backend??"auto",this.ignorePatterns=e.ignorePatterns??[...C],this.onLoadFailure=e.onLoadFailure??"throw",this.ignoreInstance=utils.Ignore.create().add(this.ignorePatterns);}getIgnoreInstance(){return this.ignoreInstance}getIgnorePatterns(){return this.ignorePatterns}getActiveBackend(){return this.backendOpt==="auto"?P():this.backendOpt}on(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async start(){if(this.running)return;this.running=true;let e=this.backendOpt==="auto"?P():this.backendOpt;o.info("FileWatcher start",{workspaceDir:this.workspaceDir,backend:e});let t;try{t=await T();}catch(i){if(this.running=false,this.onLoadFailure==="warn")return;throw i}await this.subscribeWithParcel(t,e);}async stop(){if(this.unsubscribe){try{await this.unsubscribe();}catch(e){o.warn("parcel unsubscribe error",{error:utils.errorMeta(e)});}this.unsubscribe=null;}this.running=false;}async dispose(){await this.stop(),this.disposed=true,this.listeners.clear();}isRunning(){return this.running}isDisposed(){return this.disposed}static clearParcelWrapperCache(){b.clearCache();}async subscribeWithParcel(e,t){if(this.disposed)throw new utils.NameErrors.OperationFailedError({message:"FileWatcher disposed before subscribe",operation:"file-watcher-disposed"});let i=(a,l)=>{if(this.disposed)return;let c=this.workspaceDir.replace(/\\/g,"/").replace(/\/$/,""),u=l.replace(/\\/g,"/"),p=l;if(u.startsWith(c+"/")&&(p=u.slice(c.length+1)),this.ignoreInstance.ignores(p,a==="create"&&p.endsWith("/")))return;let f=a==="create"?"add":a==="delete"?"unlink":"change";for(let k of this.listeners)try{k(f,p);}catch(W){o.warn("listener threw",{error:utils.errorMeta(W)});}},g=await e.subscribe(this.workspaceDir,(a,l)=>{if(a){o.error("parcel subscribe callback error",{error:utils.errorMeta(a)});return}for(let c of l)i(c.type,c.path);},{ignore:[...this.ignorePatterns],backend:t});if(this.disposed){await g.unsubscribe().catch(()=>{});return}this.unsubscribe=async()=>{await g.unsubscribe().catch(a=>{o.warn("parcel unsubscribe error",{error:utils.errorMeta(a)});});};}};function m(r){return path.join(r,".watcher.pid")}function H(r){let e=m(r);if(!fs.existsSync(e))return null;try{let t=fs.readFileSync(e,"utf-8").trim(),i=parseInt(t,10);return Number.isFinite(i)?i:null}catch{return null}}async function z(r,e){let t=m(r);await fs.promises.writeFile(t,String(e),"utf-8");}async function K(r){let e=m(r);try{await fs.promises.unlink(e);}catch{}}exports.a=v;exports.b=m;exports.c=H;exports.d=z;exports.e=K;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-47LKNS74.mjs';import {existsSync,readFileSync,promises}from'fs';import {isAbsolute,normalize,join}from'path';import {createRequire}from'module';import {Log,Ignore,errorMeta,NameErrors,PKG,Shell}from'@easbot/utils';var o=Log.create({service:"codebase.sync.file-watcher"});function A(){return process.env.EASBOT_CACHE_PATH||join(process.cwd(),".easbot",".cache")}var C=["node_modules/**",".git/**","dist/**","build/**","__pycache__/**","*.min.js","*.min.ts",".easbot/**",".codebase/**"],s=class s{constructor(){a(this,"wrapper",null);a(this,"error",null);}static get(){return s.instance||(s.instance=new s),s.instance}static clearCache(){s.instance&&(s.instance.wrapper=null,s.instance.error=null);}};a(s,"instance",null);var b=s;function R(){let r=process.platform==="linux"?`-${globalThis.EASBOT_LIBC||"glibc"}`:"";return `@parcel/watcher-${process.platform}-${process.arch}${r}`}async function T(){let r=b.get();if(r.wrapper)return r.wrapper;if(r.error)throw new NameErrors.OperationFailedError({message:r.error,operation:"parcel-watcher-binding-cache"});let e=R(),t=A(),i;try{await $(e,t)?i=join(t,"node_modules",e):(o.info("Parcel watcher binding not found, attempting to install",{binding:e,cachePath:t}),i=await q(e,t));}catch(u){let p=errorMeta(u).message,f=`binding "${e}" not found and auto-install failed. Run manually: pnpm install ${e}. Error: ${p}`;throw r.error=f,o.error("failed to install parcel watcher binding",{error:errorMeta(u),binding:e}),new NameErrors.OperationFailedError({message:f,operation:"parcel-watcher-binding-install"})}o.info("Loading Parcel watcher binding",{binding:e,modulePath:i});let{createWrapper:g}=await import('@parcel/watcher/wrapper.js'),l=createRequire(join(i,"package.json"))(e),c=g(l);return r.wrapper=c,c}async function $(r,e){try{return !!await PKG.resolve(r,void 0,{extraPaths:[e]})}catch{return false}}async function q(r,e){return o.info("Installing Parcel watcher binding",{binding:r,cachePath:e}),await Shell.install(r,"latest",e),join(e,"node_modules",r)}function P(){return process.platform==="darwin"?"fs-events":process.platform==="linux"?"inotify":process.platform==="win32"?"windows":"brute-force"}var v=class{constructor(e){a(this,"workspaceDir");a(this,"backendOpt");a(this,"ignorePatterns");a(this,"onLoadFailure");a(this,"ignoreInstance");a(this,"listeners",new Set);a(this,"unsubscribe",null);a(this,"disposed",false);a(this,"running",false);this.workspaceDir=isAbsolute(e.workspaceDir)?e.workspaceDir:normalize(e.workspaceDir),this.backendOpt=e.backend??"auto",this.ignorePatterns=e.ignorePatterns??[...C],this.onLoadFailure=e.onLoadFailure??"throw",this.ignoreInstance=Ignore.create().add(this.ignorePatterns);}getIgnoreInstance(){return this.ignoreInstance}getIgnorePatterns(){return this.ignorePatterns}getActiveBackend(){return this.backendOpt==="auto"?P():this.backendOpt}on(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async start(){if(this.running)return;this.running=true;let e=this.backendOpt==="auto"?P():this.backendOpt;o.info("FileWatcher start",{workspaceDir:this.workspaceDir,backend:e});let t;try{t=await T();}catch(i){if(this.running=false,this.onLoadFailure==="warn")return;throw i}await this.subscribeWithParcel(t,e);}async stop(){if(this.unsubscribe){try{await this.unsubscribe();}catch(e){o.warn("parcel unsubscribe error",{error:errorMeta(e)});}this.unsubscribe=null;}this.running=false;}async dispose(){await this.stop(),this.disposed=true,this.listeners.clear();}isRunning(){return this.running}isDisposed(){return this.disposed}static clearParcelWrapperCache(){b.clearCache();}async subscribeWithParcel(e,t){if(this.disposed)throw new NameErrors.OperationFailedError({message:"FileWatcher disposed before subscribe",operation:"file-watcher-disposed"});let i=(a,l)=>{if(this.disposed)return;let c=this.workspaceDir.replace(/\\/g,"/").replace(/\/$/,""),u=l.replace(/\\/g,"/"),p=l;if(u.startsWith(c+"/")&&(p=u.slice(c.length+1)),this.ignoreInstance.ignores(p,a==="create"&&p.endsWith("/")))return;let f=a==="create"?"add":a==="delete"?"unlink":"change";for(let k of this.listeners)try{k(f,p);}catch(W){o.warn("listener threw",{error:errorMeta(W)});}},g=await e.subscribe(this.workspaceDir,(a,l)=>{if(a){o.error("parcel subscribe callback error",{error:errorMeta(a)});return}for(let c of l)i(c.type,c.path);},{ignore:[...this.ignorePatterns],backend:t});if(this.disposed){await g.unsubscribe().catch(()=>{});return}this.unsubscribe=async()=>{await g.unsubscribe().catch(a=>{o.warn("parcel unsubscribe error",{error:errorMeta(a)});});};}};function m(r){return join(r,".watcher.pid")}function z(r){let e=m(r);if(!existsSync(e))return null;try{let t=readFileSync(e,"utf-8").trim(),i=parseInt(t,10);return Number.isFinite(i)?i:null}catch{return null}}async function K(r,e){let t=m(r);await promises.writeFile(t,String(e),"utf-8");}async function U(r){let e=m(r);try{await promises.unlink(e);}catch{}}export{v as a,m as b,z as c,K as d,U as e};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
'use strict';var chunkVZCOLSBF_cjs=require('./chunk-VZCOLSBF.cjs'),utils=require('@easbot/utils'),llm=require('@easbot/llm');exports.a=void 0;(C=>{let a=utils.Log.create({service:"codebase.llm"}),e=null,m=()=>{if(!e)throw new utils.NameErrors.OperationFailedError({message:"Llm is not initialized. Please call Llm.init() first.",operation:"llm-not-initialized"});return e};function T(t){if(c())return;let i=t;e={models:i.models,options:{evaluation:i.options?.evaluation},evaluationThreshold:d(i.evaluationThreshold)},llm.ModelManager.declare(e.models),a.info("Llm initialized",{evaluation:!!i.models.evaluation,embedding:!!i.models.embedding,evaluationThreshold:e.evaluationThreshold});}C.init=T;function E(){return e?.evaluationThreshold??chunkVZCOLSBF_cjs.f}C.getEvaluationThreshold=E;function c(){return e!==null}C.isInitialized=c;function L(){e=null;}C._resetForTest=L;function O(){return e?{evaluation:e.models.evaluation!==void 0,embedding:e.models.embedding!==void 0}:{evaluation:false,embedding:false}}C.capabilities=O;async function I(t){let i=m();if(i.models.embedding)return llm.probeEmbeddingDims(i.models.embedding,{timeoutMs:t?.timeoutMs??5e3})}C.probeEmbeddingDims=I;function M(){return e?.models.evaluation}C.getEvaluation=M;function R(){return e?.models.embedding}C.getEmbedding=R;async function N(t,i){if(!e?.models.evaluation)return a.debug("Llm.generateText: evaluation model not configured, return empty string"),"";try{return (await llm.LanguageProvider.generate({model:e.models.evaluation,user:{id:utils.Identifier.ascending("message"),sessionId:utils.Identifier.ascending("session"),model:{providerId:"",modelId:""}},sessionId:utils.Identifier.ascending("session"),agent:{name:"codebase-eval"},messages:[{role:"user",content:[{type:"text",text:t}]}],maxOutputTokens:i?.maxOutputTokens??e.options.evaluation?.maxOutputTokens,temperature:i?.temperature??e.options.evaluation?.temperature,activeTools:[]})).text}catch(n){return a.error("Llm.generateText failed",{error:utils.errorMeta(n)}),""}}C.generateText=N;let p=`The content under review is an automatic code knowledge graph extraction.
|
|
2
|
+
The reference extraction to compare against is provided as supporting material.
|
|
3
|
+
|
|
4
|
+
The extraction and the reference extraction use ONE of TWO JSON shapes \u2014 detect the shape from the JSON itself:
|
|
5
|
+
|
|
6
|
+
**Shape A \u2014 flat symbol list (common for search / recall evaluation):**
|
|
7
|
+
{ "expected": ["MemorySystem", "NoteKnowledge"], "query": "core classes" }
|
|
8
|
+
{ "actual": ["MemorySystem", "./parser"] }
|
|
9
|
+
|
|
10
|
+
**Shape B \u2014 structured extraction (full relation evaluation):**
|
|
11
|
+
{ "entities": [{ "name": "Foo", "type": "class" }], "relations": [{ "source": "Foo", "target": "Bar", "relation": "EXTENDS" }] }
|
|
12
|
+
{ "entities": [{ "name": "Foo", "type": "class" }], "relations": [] }
|
|
13
|
+
|
|
14
|
+
Grade the extraction against ALL of these criteria:
|
|
15
|
+
|
|
16
|
+
1. **Entity name match**: case-insensitive exact match is preferred; accept clear semantic synonyms (e.g. "UserService" \u2248 "UserSvc"); REJECT type-mismatched candidates (a file path is not a class name, and a class name is not a file path).
|
|
17
|
+
2. **Relation endpoints**: the source and target of a predicted relation must denote the same conceptual entities as in the reference.
|
|
18
|
+
3. **Relation type accuracy**: relation types are distinct \u2014 CALLS, REFERENCES and IMPORTS are not interchangeable.
|
|
19
|
+
4. **Type / category match**: a predicted entity must carry the same type as its reference counterpart.
|
|
20
|
+
|
|
21
|
+
Additional requirements:
|
|
22
|
+
5. The extraction MUST NOT contain entities absent from the reference (no hallucinated symbols).
|
|
23
|
+
6. The extraction MUST NOT contain factual errors about the codebase.
|
|
24
|
+
|
|
25
|
+
Scoring guidance:
|
|
26
|
+
- 1.0 \u2014 every entity and every relation matches the reference exactly
|
|
27
|
+
- 0.7-0.9 \u2014 most entities match, only minor relations are off
|
|
28
|
+
- 0.4-0.6 \u2014 about half match, significant misses
|
|
29
|
+
- 0.0-0.3 \u2014 little to no match (e.g. the extraction holds file paths while the reference holds class names)`,g=`How to read the inputs of this evaluation:
|
|
30
|
+
- CONTENT (the material under review) is the PREDICTED extraction \u2014 the actual output of the extractor.
|
|
31
|
+
- DOCUMENT (the supporting material) is the GOLD extraction \u2014 the ground truth it is measured against.
|
|
32
|
+
|
|
33
|
+
When the two JSON shapes above are present:
|
|
34
|
+
- Shape A: GOLD carries the "expected" array; PREDICTED carries the "actual" array.
|
|
35
|
+
- Shape B: both carry "entities" and "relations" arrays; compare them element-wise.
|
|
36
|
+
|
|
37
|
+
If the DOCUMENT section is absent, judge only against the criteria above.`;async function S(t){if(!e?.models.evaluation)return {score:-1,details:"evaluation model not configured",missingEntities:[],extraEntities:[],wrongRelations:[],missingRelations:[],passing:false};let i=d(t.threshold??e.evaluationThreshold);try{let n=await llm.EvaluationProvider.evaluate({type:"content-quality",query:p,response:t.predicted,document:t.gold,context:g,model:e.models.evaluation,maxOutputTokens:t.options?.maxOutputTokens??e.options.evaluation?.maxOutputTokens});if(n.type!=="content-quality")throw new utils.NameErrors.OperationFailedError({message:`Unexpected evaluation result type: ${n.type}`,operation:"codebase-evaluate-extraction"});let h=n.passing||n.score>=i;return {score:n.score,details:n.summary||n.feedback,missingEntities:n.violations,extraEntities:[],wrongRelations:[],missingRelations:[],passing:h}}catch(n){return a.error("Llm.evaluateExtraction failed",{error:utils.errorMeta(n)}),{score:-1,details:`evaluation failed: ${utils.errorMeta(n).message}`,missingEntities:[],extraEntities:[],wrongRelations:[],missingRelations:[],passing:false}}}C.evaluateExtraction=S;function d(t){return typeof t!="number"||!Number.isFinite(t)?chunkVZCOLSBF_cjs.f:t<=0||t>1?chunkVZCOLSBF_cjs.f:t}})(exports.a||(exports.a={}));var U=exports.a;exports.b=U;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import {f}from'./chunk-43WAI4Z7.mjs';import {Log,Identifier,errorMeta,NameErrors}from'@easbot/utils';import {ModelManager,probeEmbeddingDims,LanguageProvider,EvaluationProvider}from'@easbot/llm';var l;(C=>{let a=Log.create({service:"codebase.llm"}),e=null,m=()=>{if(!e)throw new NameErrors.OperationFailedError({message:"Llm is not initialized. Please call Llm.init() first.",operation:"llm-not-initialized"});return e};function T(t){if(c())return;let i=t;e={models:i.models,options:{evaluation:i.options?.evaluation},evaluationThreshold:d(i.evaluationThreshold)},ModelManager.declare(e.models),a.info("Llm initialized",{evaluation:!!i.models.evaluation,embedding:!!i.models.embedding,evaluationThreshold:e.evaluationThreshold});}C.init=T;function E(){return e?.evaluationThreshold??f}C.getEvaluationThreshold=E;function c(){return e!==null}C.isInitialized=c;function L(){e=null;}C._resetForTest=L;function O(){return e?{evaluation:e.models.evaluation!==void 0,embedding:e.models.embedding!==void 0}:{evaluation:false,embedding:false}}C.capabilities=O;async function I(t){let i=m();if(i.models.embedding)return probeEmbeddingDims(i.models.embedding,{timeoutMs:t?.timeoutMs??5e3})}C.probeEmbeddingDims=I;function M(){return e?.models.evaluation}C.getEvaluation=M;function R(){return e?.models.embedding}C.getEmbedding=R;async function N(t,i){if(!e?.models.evaluation)return a.debug("Llm.generateText: evaluation model not configured, return empty string"),"";try{return (await LanguageProvider.generate({model:e.models.evaluation,user:{id:Identifier.ascending("message"),sessionId:Identifier.ascending("session"),model:{providerId:"",modelId:""}},sessionId:Identifier.ascending("session"),agent:{name:"codebase-eval"},messages:[{role:"user",content:[{type:"text",text:t}]}],maxOutputTokens:i?.maxOutputTokens??e.options.evaluation?.maxOutputTokens,temperature:i?.temperature??e.options.evaluation?.temperature,activeTools:[]})).text}catch(n){return a.error("Llm.generateText failed",{error:errorMeta(n)}),""}}C.generateText=N;let p=`The content under review is an automatic code knowledge graph extraction.
|
|
2
|
+
The reference extraction to compare against is provided as supporting material.
|
|
3
|
+
|
|
4
|
+
The extraction and the reference extraction use ONE of TWO JSON shapes \u2014 detect the shape from the JSON itself:
|
|
5
|
+
|
|
6
|
+
**Shape A \u2014 flat symbol list (common for search / recall evaluation):**
|
|
7
|
+
{ "expected": ["MemorySystem", "NoteKnowledge"], "query": "core classes" }
|
|
8
|
+
{ "actual": ["MemorySystem", "./parser"] }
|
|
9
|
+
|
|
10
|
+
**Shape B \u2014 structured extraction (full relation evaluation):**
|
|
11
|
+
{ "entities": [{ "name": "Foo", "type": "class" }], "relations": [{ "source": "Foo", "target": "Bar", "relation": "EXTENDS" }] }
|
|
12
|
+
{ "entities": [{ "name": "Foo", "type": "class" }], "relations": [] }
|
|
13
|
+
|
|
14
|
+
Grade the extraction against ALL of these criteria:
|
|
15
|
+
|
|
16
|
+
1. **Entity name match**: case-insensitive exact match is preferred; accept clear semantic synonyms (e.g. "UserService" \u2248 "UserSvc"); REJECT type-mismatched candidates (a file path is not a class name, and a class name is not a file path).
|
|
17
|
+
2. **Relation endpoints**: the source and target of a predicted relation must denote the same conceptual entities as in the reference.
|
|
18
|
+
3. **Relation type accuracy**: relation types are distinct \u2014 CALLS, REFERENCES and IMPORTS are not interchangeable.
|
|
19
|
+
4. **Type / category match**: a predicted entity must carry the same type as its reference counterpart.
|
|
20
|
+
|
|
21
|
+
Additional requirements:
|
|
22
|
+
5. The extraction MUST NOT contain entities absent from the reference (no hallucinated symbols).
|
|
23
|
+
6. The extraction MUST NOT contain factual errors about the codebase.
|
|
24
|
+
|
|
25
|
+
Scoring guidance:
|
|
26
|
+
- 1.0 \u2014 every entity and every relation matches the reference exactly
|
|
27
|
+
- 0.7-0.9 \u2014 most entities match, only minor relations are off
|
|
28
|
+
- 0.4-0.6 \u2014 about half match, significant misses
|
|
29
|
+
- 0.0-0.3 \u2014 little to no match (e.g. the extraction holds file paths while the reference holds class names)`,g=`How to read the inputs of this evaluation:
|
|
30
|
+
- CONTENT (the material under review) is the PREDICTED extraction \u2014 the actual output of the extractor.
|
|
31
|
+
- DOCUMENT (the supporting material) is the GOLD extraction \u2014 the ground truth it is measured against.
|
|
32
|
+
|
|
33
|
+
When the two JSON shapes above are present:
|
|
34
|
+
- Shape A: GOLD carries the "expected" array; PREDICTED carries the "actual" array.
|
|
35
|
+
- Shape B: both carry "entities" and "relations" arrays; compare them element-wise.
|
|
36
|
+
|
|
37
|
+
If the DOCUMENT section is absent, judge only against the criteria above.`;async function S(t){if(!e?.models.evaluation)return {score:-1,details:"evaluation model not configured",missingEntities:[],extraEntities:[],wrongRelations:[],missingRelations:[],passing:false};let i=d(t.threshold??e.evaluationThreshold);try{let n=await EvaluationProvider.evaluate({type:"content-quality",query:p,response:t.predicted,document:t.gold,context:g,model:e.models.evaluation,maxOutputTokens:t.options?.maxOutputTokens??e.options.evaluation?.maxOutputTokens});if(n.type!=="content-quality")throw new NameErrors.OperationFailedError({message:`Unexpected evaluation result type: ${n.type}`,operation:"codebase-evaluate-extraction"});let h=n.passing||n.score>=i;return {score:n.score,details:n.summary||n.feedback,missingEntities:n.violations,extraEntities:[],wrongRelations:[],missingRelations:[],passing:h}}catch(n){return a.error("Llm.evaluateExtraction failed",{error:errorMeta(n)}),{score:-1,details:`evaluation failed: ${errorMeta(n).message}`,missingEntities:[],extraEntities:[],wrongRelations:[],missingRelations:[],passing:false}}}C.evaluateExtraction=S;function d(t){return typeof t!="number"||!Number.isFinite(t)?f:t<=0||t>1?f:t}})(l||(l={}));var k=l;export{l as a,k as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {f}from'./chunk-H4VZF3ZQ.mjs';import {b}from'./chunk-KTSR5VPT.mjs';import {e}from'./chunk-43WAI4Z7.mjs';import {existsSync,mkdirSync,writeFileSync}from'fs';import {Log,State,Filesystem,ConfigFileParse,errorMeta}from'@easbot/utils';var n=Log.create({service:"codebase.cache"}),R=[".easbot","codebase.json"],C=new Set;function P(){try{let e=f().directory;if(e&&e.length>0)return e}catch{}return process.cwd()}function c(s){return Filesystem.join(s,...R)}async function D(s){let e$1=c(s);if(C.add(Filesystem.normalize(e$1)),!existsSync(e$1))return {codebaseJson:{},exists:false,rootDir:s};try{return {codebaseJson:await ConfigFileParse.loadFile(e$1,{schema:e}),exists:!0,rootDir:s}}catch(i){return n.warn("codebase.json parse failed",{configPath:e$1,error:errorMeta(i)}),{codebaseJson:void 0,exists:true,rootDir:s}}}var h=State.holder(()=>{try{let e=f().directory;return e?Filesystem.normalize(e):"__codebase_cache_global__"}catch{return "__codebase_cache_global__"}},async()=>D(P())),_;(L=>{let s=false;async function e$1(){return h.get()}L.state=e$1;function u(t){h.clear(),s=false,ConfigFileParse.invalidate(t??c(P()),"codebase.resetState");}L.resetState=u;function i(){b$1||(b$1=ConfigFileParse.onChange(t=>{C.has(t)&&(n.info("codebase.json changed externally, reloading",{configPath:t}),ConfigFileParse.invalidateNormalized(t,"codebase.externalChange"),u(t));}));}let b$1;async function F(){s||(s=true,i(),n.info("CodebaseCache init"),await e$1());}L.init=F;async function z(){return (await e$1()).codebaseJson}L.getCodebaseJson=z;async function k(){return (await e$1()).exists}L.exists=k;async function N(){return (await e$1()).rootDir}L.getRootDir=N;async function O(t){let g=await e$1(),o=c(g.rootDir),J=ConfigFileParse.merge([g.codebaseJson??{},t]),r=e.safeParse(J);if(!r.success)throw n.error("codebase.json validation failed on write",{configPath:o,issues:r.error.issues}),new b.ConfigError({message:`codebase.json validation failed: ${r.error.message}`,field:o});let m=Filesystem.dirname(o);existsSync(m)||mkdirSync(m,{recursive:true});try{writeFileSync(o,JSON.stringify(r.data,null,2),"utf-8");}catch(x){throw n.error("codebase.json write failed",{configPath:o,error:errorMeta(x)}),x}return u(o),n.debug("codebase.json written",{configPath:o}),r.data}L.writeCodebaseJson=O;async function A(){let t=await e$1();return c(t.rootDir)}L.getConfigPath=A;})(_||(_={}));export{R as a,_ as b};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {b}from'./chunk-KTSR5VPT.mjs';import {a}from'./chunk-47LKNS74.mjs';import {Log,Filesystem,errorMeta,NameErrors}from'@easbot/utils';import {createSyncSqliteConnection}from'@easbot/database';var A=Log.create({service:"codebase.database.migrations"}),N=1,P=[{id:1,description:"v1 baseline: nodes / edges / file_hashes / nodes_fts / meta / embedding_cache / node_embeddings + unresolved_refs / name_segment_vocab / project_metadata / parse_errors + \u6027\u80FD index (nodes.file_path / edges.source/target)",up:[`CREATE TABLE IF NOT EXISTS nodes (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
name TEXT NOT NULL,
|
|
4
4
|
ast_type TEXT NOT NULL,
|
|
@@ -64,22 +64,22 @@ import {a}from'./chunk-2YMB6W5S.mjs';import i from'zod';import {NamedError,Log,F
|
|
|
64
64
|
message TEXT NOT NULL,
|
|
65
65
|
line INTEGER,
|
|
66
66
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
67
|
-
)`,"CREATE INDEX IF NOT EXISTS idx_parse_errors_file_path ON parse_errors(file_path)","CREATE INDEX IF NOT EXISTS idx_nodes_file_path ON nodes(file_path)","CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)"]}];function
|
|
67
|
+
)`,"CREATE INDEX IF NOT EXISTS idx_parse_errors_file_path ON parse_errors(file_path)","CREATE INDEX IF NOT EXISTS idx_nodes_file_path ON nodes(file_path)","CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)"]}];function v(E,e=N,t={}){E.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
68
68
|
id INTEGER PRIMARY KEY,
|
|
69
69
|
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
70
|
-
)`);let s=
|
|
70
|
+
)`);let s=E.prepare("SELECT id FROM schema_migrations").all(),n=new Set(s.map(a=>a.id)),r={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(a=>a.id)),targetVersion:e};for(let a of P){if(a.id>e)break;if(n.has(a.id)){r.pending.push(a.id);continue}if(t.dryRun){r.applied.push(a.id);continue}try{E.execBatch([...a.up]),E.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(a.id),n.add(a.id),r.applied.push(a.id),A.debug("migration applied",{id:a.id,description:a.description});}catch(i){let o=errorMeta(i).message,c=a.up[0]??"";r.errors.push({migrationId:a.id,sql:c,error:o}),A.warn("migration step failed (may be idempotent)",{id:a.id,error:errorMeta(i),sqlCount:a.up.length});}}return r}function w(E){try{let e=E.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(t=>t.id))}catch{return 0}}var l=Filesystem.toUnixPath,d=Log.create({service:"codebase.database"}),S=3,U=class{constructor(e){a(this,"db");a(this,"dbPath");a(this,"closed",false);a(this,"ftsAvailable",false);this.dbPath=e===":memory:"?e:Filesystem.normalize(e),this.db=createSyncSqliteConnection({path:this.dbPath,backend:"better-sqlite3",walMode:true,foreignKeys:true,busyTimeoutMs:3e4}),this.db.initialize();try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("foreign_keys = ON");}catch(t){d.warn("Failed to apply codebase PRAGMAs (synchronous / cache_size / foreign_keys)",{error:errorMeta(t)});}try{this.ensureSchema();let t=w(this.db);t>0&&this.setMeta("schema_version",String(t)),this.ftsAvailable=this.checkFtsAvailability(),this.detectAndMarkStaleOnInit();}catch(t){try{this.db.close();}catch{}throw this.closed=true,t}}ensureSchema(){try{v(this.db,N);let e=[["version","1.0.0"],["createdAt",new Date().toISOString()],["index_state","uninitialized"],["indexed_with_version","unknown"]],t=this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[s,n]of e)t.run(s,n);}catch(e){d.error("ensureSchema failed",{error:errorMeta(e)});let t=errorMeta(e).message,s=e instanceof Error?e.cause:void 0,n=s!==void 0?String(s):"",r=n&&n!==t?` (cause: ${n})`:"";throw new b.SchemaError({message:`Failed to create database schema: ${t}${r}`,missing:e instanceof Error?[t,n].filter(Boolean):[t]},{cause:e})}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:l(e.file_path)};this.db.prepare(`
|
|
71
71
|
INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
|
|
72
72
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
73
|
-
`).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(r=>({...r,file_path:
|
|
73
|
+
`).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(r=>({...r,file_path:l(r.file_path)})),s=this.db.prepare(`
|
|
74
74
|
INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
|
|
75
75
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
76
|
-
`);this.db.transaction(r=>{for(let a of r)s.run(a.id,a.name,a.ast_type,a.language,a.file_path,a.start_line,a.start_col,a.end_line,a.end_col,a.text,a.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(r);})(t);}updateFtsNodesInternal(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),n=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let r of e)try{let a=s.get(r.id);a&&t.run(a.rowid),n.run(r.id,r.name,r.ast_type,r.language,r.file_path,r.text);}catch(a){
|
|
76
|
+
`);this.db.transaction(r=>{for(let a of r)s.run(a.id,a.name,a.ast_type,a.language,a.file_path,a.start_line,a.start_col,a.end_line,a.end_col,a.text,a.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(r);})(t);}updateFtsNodesInternal(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),n=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let r of e)try{let a=s.get(r.id);a&&t.run(a.rowid),n.run(r.id,r.name,r.ast_type,r.language,r.file_path,r.text);}catch(a){d.warn("FTS update failed for node",{nodeId:r.id,error:errorMeta(a)});}}updateFtsNode(e){try{let t=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?").get(e.id);t&&this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(t.rowid),this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.ast_type,e.language,e.file_path,e.text);}catch(t){d.warn("FTS update failed for node",{nodeId:e.id,error:errorMeta(t)});}}updateFtsNodes(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),n=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(a=>{for(let i of a)try{let o=s.get(i.id);o&&t.run(o.rowid),n.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.text);}catch(o){d.warn("FTS update failed for node",{nodeId:i.id,error:errorMeta(o)});}})(e);}insertEdge(e){this.db.prepare(`
|
|
77
77
|
INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
|
|
78
78
|
VALUES (?, ?, ?, ?, ?)
|
|
79
79
|
`).run(e.id,e.source,e.target,e.relation,e.created_at);}insertEdges(e){if(e.length===0)return;let t=this.db.prepare(`
|
|
80
80
|
INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
|
|
81
81
|
VALUES (?, ?, ?, ?, ?)
|
|
82
|
-
`);this.db.transaction(n=>{for(let r of n)t.run(r.id,r.source,r.target,r.relation,r.created_at);})(e);}queryNodes(e){let t=[],s=[];e.filePath&&(t.push("file_path LIKE ?"),s.push(`%${
|
|
82
|
+
`);this.db.transaction(n=>{for(let r of n)t.run(r.id,r.source,r.target,r.relation,r.created_at);})(e);}queryNodes(e){let t=[],s=[];e.filePath&&(t.push("file_path LIKE ?"),s.push(`%${l(e.filePath)}%`)),e.astType&&(t.push("ast_type = ?"),s.push(e.astType)),e.name&&(t.push("name = ?"),s.push(e.name)),e.language&&(t.push("language = ?"),s.push(e.language));let n="SELECT * FROM nodes";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY file_path, start_line",e.limit&&(n+=" LIMIT ?",s.push(e.limit)),e.offset&&(n+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(n).all(...s)}catch(r){throw new b.DatabaseError({message:"Failed to query nodes",operation:"queryNodes"},{cause:r})}}findNodesByName(e){if(!e.name)return [];let t=e.limit??50,s=e.kind?`%${e.kind.toLowerCase()}%`:null,n=new Set,r=[],a=(o,c)=>{n.has(o.id)||(n.add(o.id),r.push({node:o,matchKind:c}));},i=(o,c)=>{e.file&&(e.file.includes("/")?(o.push("file_path = ?"),c.push(e.file)):(o.push("file_path LIKE '%/' || ?"),c.push(e.file))),s&&(o.push("LOWER(ast_type) LIKE ?"),c.push(s));};try{let o=["name = ?"],c=[e.name];i(o,c),c.push(t);let p=this.db.prepare(`SELECT * FROM nodes WHERE ${o.join(" AND ")} LIMIT ?`).all(...c);for(let u of p)a(u,"exact");if(p.length>0&&e.file)return r.slice(0,t);if(r.length<t){let u=this.db.prepare("SELECT * FROM nodes WHERE name LIKE ? LIMIT ?").all(`%${e.name}%`,t);for(let g of u)a(g,"qualified");}if(r.length>0&&e.file)return r.slice(0,t);if(r.length===0&&e.name){let u=["name LIKE ?"],g=[`%${e.name}%`];e.file&&(e.file.includes("/")?(u.push("file_path = ?"),g.push(e.file)):(u.push("file_path LIKE '%/' || ?"),g.push(e.file))),s&&(u.push("LOWER(ast_type) LIKE ?"),g.push(s)),u.push("?"),g.push(t);let f=this.db.prepare(`SELECT * FROM nodes WHERE ${u.join(" AND ")}`).all(...g);for(let _ of f)a(_,"substring");}return r.slice(0,t)}catch(o){throw new b.DatabaseError({message:"Failed to find nodes by name",operation:"findNodesByName"},{cause:o})}}queryEdges(e){let t=[],s=[];if(e.sourceOrTarget&&e.sourceOrTarget.length>0){let r=e.sourceOrTarget.map(()=>"?").join(",");t.push(`(source IN (${r}) OR target IN (${r}))`),s.push(...e.sourceOrTarget,...e.sourceOrTarget);}else e.source&&(t.push("source = ?"),s.push(e.source)),e.target&&(t.push("target = ?"),s.push(e.target));e.relation&&(t.push("relation = ?"),s.push(e.relation));let n="SELECT * FROM edges";t.length>0&&(n+=` WHERE ${t.join(" AND ")}`),n+=" ORDER BY created_at DESC",e.limit&&(n+=" LIMIT ?",s.push(e.limit)),e.offset&&(n+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(n).all(...s)}catch(r){throw new b.DatabaseError({message:"Failed to query edges",operation:"queryEdges"},{cause:r})}}queryAll(e,t){try{let s=this.db.prepare(e);return t?s.all(...t):s.all()}catch(s){throw new b.DatabaseError({message:"Failed to execute query",operation:"queryAll"},{cause:s})}}searchNodesFts(e,t=20){if(d.debug("searchNodesFts start",{query:e,limit:t,ftsAvailable:this.ftsAvailable}),!this.ftsAvailable)return d.debug("searchNodesFts skip - FTS not available"),[];try{let s=e.split(/\s+/).map(i=>`${i}*`).join(" ");d.debug("searchNodesFts query",{ftsQuery:s});let a=this.db.prepare(`
|
|
83
83
|
SELECT
|
|
84
84
|
nodes_fts.id,
|
|
85
85
|
nodes_fts.name,
|
|
@@ -97,62 +97,62 @@ import {a}from'./chunk-2YMB6W5S.mjs';import i from'zod';import {NamedError,Log,F
|
|
|
97
97
|
WHERE nodes_fts.text MATCH ?
|
|
98
98
|
ORDER BY score DESC
|
|
99
99
|
LIMIT ?
|
|
100
|
-
`).all(s,t);return
|
|
100
|
+
`).all(s,t);return d.debug("searchNodesFts done",{resultCount:a.length}),a}catch(s){return d.warn("searchNodesFts failed",{error:errorMeta(s)}),[]}}deleteNodesByFile(e){let t=l(e);if(this.ftsAvailable)try{let n=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let r of n)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(r.rowid);}catch(n){d.warn("FTS delete failed for file",{filePath:t,error:errorMeta(n)});}return this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t).changes}deleteEdgesByFile(e){let t=l(e);return this.db.prepare(`
|
|
101
101
|
DELETE FROM edges
|
|
102
102
|
WHERE source IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
103
103
|
OR target IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
104
|
-
`).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(
|
|
104
|
+
`).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(l(e))?.content_hash??null}setFileHash(e,t){this.db.prepare(`
|
|
105
105
|
INSERT OR REPLACE INTO file_hashes (file_path, content_hash, last_modified)
|
|
106
106
|
VALUES (?, ?, ?)
|
|
107
|
-
`).run(
|
|
107
|
+
`).run(l(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(l(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}checkIntegrity(){let e=b=>this.db.prepare(b).get().c,t=b=>e(b),s={nodes:t("SELECT COUNT(*) as c FROM nodes"),edges:t("SELECT COUNT(*) as c FROM edges"),file_hashes:t("SELECT COUNT(*) as c FROM file_hashes"),fts:t("SELECT COUNT(*) as c FROM nodes_fts"),node_embeddings:t("SELECT COUNT(*) as c FROM node_embeddings"),embedding_cache:t("SELECT COUNT(*) as c FROM embedding_cache"),parse_errors:t("SELECT COUNT(*) as c FROM parse_errors"),unresolved_refs:t("SELECT COUNT(*) as c FROM unresolved_refs"),name_segment_vocab:t("SELECT COUNT(*) as c FROM name_segment_vocab"),project_metadata:t("SELECT COUNT(*) as c FROM project_metadata"),schema_migrations:t("SELECT COUNT(*) as c FROM schema_migrations"),meta:t("SELECT COUNT(*) as c FROM meta")},n=[],r=t(`
|
|
108
108
|
SELECT COUNT(*) as c FROM node_embeddings e
|
|
109
109
|
LEFT JOIN nodes n ON n.id = e.node_id WHERE n.id IS NULL
|
|
110
110
|
`);r>0&&n.push({severity:"error",message:`orphan node_embeddings: ${r}`});let a=t(`
|
|
111
111
|
SELECT COUNT(*) as c FROM edges e
|
|
112
112
|
WHERE e.relation != 'IMPORTS'
|
|
113
113
|
AND NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.source)
|
|
114
|
-
`);a>0&&n.push({severity:"error",message:`orphan edges (source): ${a}`});let
|
|
114
|
+
`);a>0&&n.push({severity:"error",message:`orphan edges (source): ${a}`});let i=t(`
|
|
115
115
|
SELECT COUNT(*) as c FROM edges e
|
|
116
116
|
WHERE e.relation NOT IN ('CALLS', 'IMPORTS')
|
|
117
117
|
AND NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.target)
|
|
118
|
-
`);
|
|
118
|
+
`);i>0&&n.push({severity:"error",message:`orphan edges (target): ${i}`});let o=t("SELECT COUNT(*) as c FROM edges WHERE source = target");o>0&&n.push({severity:"error",message:`self-loop edges: ${o} \u2014 re-run \`easbot codebase sync\` to filter (fixed in Wave 4 R3-2)`});t("SELECT COUNT(DISTINCT file_path) as c FROM nodes");let p=t(`
|
|
119
119
|
SELECT COUNT(*) as c FROM file_hashes fh
|
|
120
120
|
WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.file_path = fh.file_path)
|
|
121
|
-
`);
|
|
121
|
+
`);p>0&&n.push({severity:"warn",message:`orphan file_hashes (no nodes): ${p} \u2014 run \`easbot codebase sync\` to cleanup`});let u=t(`
|
|
122
122
|
SELECT COUNT(DISTINCT n.file_path) as c FROM nodes n
|
|
123
123
|
WHERE NOT EXISTS (SELECT 1 FROM file_hashes fh WHERE fh.file_path = n.file_path)
|
|
124
|
-
`);
|
|
124
|
+
`);u>0&&n.push({severity:"warn",message:`node files without hash: ${u}`});let g=t("SELECT COUNT(*) as c FROM nodes WHERE name IS NULL OR name = ''");g>0&&n.push({severity:"error",message:`nodes with null/empty name: ${g}`});let f=t("SELECT COUNT(*) as c FROM nodes WHERE ast_type IS NULL OR ast_type = ''");f>0&&n.push({severity:"error",message:`nodes with null/empty ast_type: ${f}`});let _=t("SELECT COUNT(*) as c FROM nodes WHERE language IS NULL OR language = ''");_>0&&n.push({severity:"error",message:`nodes with null/empty language: ${_}`});let O=t("SELECT COUNT(*) as c FROM nodes WHERE file_path IS NULL OR file_path = ''");O>0&&n.push({severity:"error",message:`nodes with null/empty file_path: ${O}`});let I=this.db.prepare("SELECT id, COUNT(*) as c FROM nodes GROUP BY id HAVING c > 1").all().length;I>0&&n.push({severity:"error",message:`duplicate node ids: ${I}`});let L=t("SELECT COUNT(*) as c FROM nodes WHERE file_path LIKE '%\\\\%'");L>0&&n.push({severity:"warn",message:`nodes with backslash in file_path: ${L}`});let C=t(`
|
|
125
125
|
SELECT COUNT(*) as c FROM nodes
|
|
126
126
|
WHERE start_line IS NOT NULL AND end_line IS NOT NULL AND start_line > end_line
|
|
127
|
-
`);
|
|
127
|
+
`);C>0&&n.push({severity:"error",message:`invalid line ranges: ${C}`});let F=this.db.prepare("SELECT id, COUNT(*) as c FROM edges GROUP BY id HAVING c > 1").all().length;F>0&&n.push({severity:"error",message:`duplicate edge ids: ${F}`});let M=t("SELECT COUNT(*) as c FROM nodes_fts_content");return M!==s.nodes&&n.push({severity:"error",message:`FTS content desync: ${M} vs ${s.nodes} (run \`easbot codebase recreate\` to rebuild)`}),s.parse_errors>100&&n.push({severity:"warn",message:`parse_errors > 100 (${s.parse_errors}) \u2014\u2014 many files failed to parse`}),{issues:n,stats:s}}getStatus(){let e=this.db.prepare("SELECT COUNT(*) as c FROM nodes").get(),t=this.db.prepare("SELECT COUNT(*) as c FROM edges").get(),s=this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get(),n=this.db.prepare("SELECT key, value FROM meta").all(),r={};for(let a of n)r[a.key]=a.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:s?.c??0,dbPath:this.dbPath,meta:r,indexState:this.getIndexState(),extractionVersion:parseInt(this.getMeta("indexed_with_extraction_version")??"0",10),isStale:this.isIndexStale()}}setLastSync(){this.db.prepare(`
|
|
128
128
|
INSERT OR REPLACE INTO meta (key, value)
|
|
129
129
|
VALUES ('lastSync', ?)
|
|
130
|
-
`).run(new Date().toISOString());}getIndexState(){return this.getMeta("index_state")??"uninitialized"}setIndexState(e){this.setMeta("index_state",e),this.setMeta("last_index_state_change",new Date().toISOString());}markIndexed(e){this.setMeta("indexed_with_version",e),this.setMeta("indexed_with_extraction_version",String(
|
|
130
|
+
`).run(new Date().toISOString());}getIndexState(){return this.getMeta("index_state")??"uninitialized"}setIndexState(e){this.setMeta("index_state",e),this.setMeta("last_index_state_change",new Date().toISOString());}markIndexed(e){this.setMeta("indexed_with_version",e),this.setMeta("indexed_with_extraction_version",String(S)),this.setMeta("index_state","complete"),this.setMeta("last_index_state_change",new Date().toISOString());}isIndexStale(){let e=this.getMeta("indexed_with_extraction_version");if(!e)return false;let t=parseInt(e,10);return Number.isNaN(t)||t<S}detectAndMarkStaleOnInit(){if(this.isIndexStale()){let e=this.getMeta("indexed_with_extraction_version");d.warn("codebase db is stale",{recorded:e??"(none)",current:String(S),hint:"run `easbot codebase recreate` or `easbot codebase index --force` to rebuild"});let t=this.getIndexState();(t==="complete"||t==="partial")&&this.setIndexState("stale");}}getNodeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM nodes").get()?.c??0}getEdgeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM edges").get()?.c??0}getFileCount(){return this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get()?.c??0}getNodeById(e){return this.db.prepare("SELECT * FROM nodes WHERE id = ?").get(e)??null}getEdgeById(e){return this.db.prepare("SELECT * FROM edges WHERE id = ?").get(e)??null}clearAll(e={}){this.db.exec("DELETE FROM nodes"),this.db.exec("DELETE FROM edges"),this.db.exec("DELETE FROM file_hashes"),this.db.exec("DELETE FROM meta"),e.keepEmbeddings||(this.db.exec("DELETE FROM node_embeddings"),this.db.exec("DELETE FROM embedding_cache")),this.ftsAvailable&&this.db.exec("DELETE FROM nodes_fts");try{this.db.exec("DELETE FROM sqlite_sequence WHERE name IN ('nodes', 'edges', 'file_hashes', 'meta')");}catch{}}getCachedEmbedding(e){let s=this.db.prepare(`
|
|
131
131
|
SELECT embedding FROM embedding_cache WHERE content_hash = ?
|
|
132
132
|
`).get(e);return s?new Float32Array(s.embedding.buffer,s.embedding.byteOffset,s.embedding.length/4):null}getVectorDims(){let e=this.db.prepare("SELECT value FROM meta WHERE key = ?").get("vectorDims");return e?parseInt(e.value,10):void 0}ensureVectorDims(e){this.db.prepare("SELECT value FROM meta WHERE key = ?").get("vectorDims")||this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)").run("vectorDims",String(e));}cacheEmbedding(e,t){if(this.db.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(e))return;this.ensureVectorDims(t.length),this.db.prepare(`
|
|
133
133
|
INSERT OR REPLACE INTO embedding_cache (content_hash, embedding)
|
|
134
134
|
VALUES (?, ?)
|
|
135
|
-
`).run(e,t);}deleteEmbeddingsByFile(e){let t=
|
|
135
|
+
`).run(e,t);}deleteEmbeddingsByFile(e){let t=l(e);return this.db.prepare(`
|
|
136
136
|
DELETE FROM node_embeddings WHERE node_id IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
137
137
|
`).run(t).changes}getAllNodeEmbeddings(){return this.db.prepare("SELECT node_id, embedding FROM node_embeddings").all()}storeNodeEmbeddings(e){if(e.length===0)return;this.ensureVectorDims(e[0].embedding.length);let t=this.db.prepare(`
|
|
138
138
|
INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
|
|
139
139
|
VALUES (?, ?, ?)
|
|
140
|
-
`);this.db.transaction(n=>{for(let r of n)try{t.run(r.nodeId,r.embeddingText,r.embedding);}catch(a){
|
|
140
|
+
`);this.db.transaction(n=>{for(let r of n)try{t.run(r.nodeId,r.embeddingText,r.embedding);}catch(a){d.warn("Failed to store embedding for node",{nodeId:r.nodeId,error:errorMeta(a)});}})(e);}insertParseError(e){return this.db.prepare(`
|
|
141
141
|
INSERT INTO parse_errors (file_path, language, stage, message, line)
|
|
142
142
|
VALUES (?, ?, ?, ?, ?)
|
|
143
|
-
`).run(
|
|
143
|
+
`).run(l(e.filePath),e.language,e.stage,e.message,e.line??null).changes}insertUnresolvedRef(e){return this.db.prepare(`
|
|
144
144
|
INSERT INTO unresolved_refs
|
|
145
145
|
(from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
|
|
146
146
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
147
|
-
`).run(e.fromNodeId??null,e.referenceName,e.referenceKind,e.line??null,e.col??null,
|
|
147
|
+
`).run(e.fromNodeId??null,e.referenceName,e.referenceKind,e.line??null,e.col??null,l(e.filePath),e.language,e.candidates?JSON.stringify(e.candidates):null).changes}insertUnresolvedRefsBatch(e){if(e.length===0)return 0;let s=`
|
|
148
148
|
INSERT INTO unresolved_refs
|
|
149
149
|
(from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
|
|
150
150
|
VALUES ${e.map(()=>"(?, ?, ?, ?, ?, ?, ?, ?)").join(", ")}
|
|
151
|
-
`,n=[];for(let
|
|
151
|
+
`,n=[];for(let i of e)n.push(i.fromNodeId??null,i.referenceName,i.referenceKind,i.line??null,i.col??null,l(i.filePath),i.language,i.candidates?JSON.stringify(i.candidates):null);return this.db.prepare(s).run(...n).changes}insertNameSegment(e,t){return this.db.prepare(`
|
|
152
152
|
INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES (?, ?)
|
|
153
153
|
`).run(e,t).changes}insertNameSegmentsBatch(e){if(e.length===0)return 0;let s=`
|
|
154
154
|
INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES ${e.map(()=>"(?, ?)").join(", ")}
|
|
155
|
-
`,n=[];for(let
|
|
155
|
+
`,n=[];for(let i of e)n.push(i.segment,i.name);return this.db.prepare(s).run(...n).changes}setProjectMetadata(e,t){let s=e==="worktree"||e==="project"?l(t):t;return this.db.prepare(`
|
|
156
156
|
INSERT OR REPLACE INTO project_metadata (key, value, updated_at)
|
|
157
157
|
VALUES (?, ?, CURRENT_TIMESTAMP)
|
|
158
|
-
`).run(e,s).changes}getNodeIdsByFile(e){let t=e.replace(/\\/g,"/");return this.db.prepare("SELECT id FROM nodes WHERE file_path = ?").all(t).map(n=>n.id)}deleteFtsByFile(e){let t=e.replace(/\\/g,"/"),s=this.getNodeIdsByFile(t);if(s.length===0)return 0;let n=this.db.prepare("DELETE FROM nodes_fts WHERE id = ?");return this.db.transaction(a=>{for(let
|
|
158
|
+
`).run(e,s).changes}getNodeIdsByFile(e){let t=e.replace(/\\/g,"/");return this.db.prepare("SELECT id FROM nodes WHERE file_path = ?").all(t).map(n=>n.id)}deleteFtsByFile(e){let t=e.replace(/\\/g,"/"),s=this.getNodeIdsByFile(t);if(s.length===0)return 0;let n=this.db.prepare("DELETE FROM nodes_fts WHERE id = ?");return this.db.transaction(a=>{for(let i of a)n.run(i);})(s),s.length}initialize(){if(this.closed)throw new b.DatabaseError({message:"Cannot initialize closed database",operation:"initialize"})}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){d.warn("Database close error",{error:errorMeta(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}countSqliteObjects(){if(!this.db)throw new NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});return this.db.prepare("SELECT COUNT(*) as n FROM sqlite_master WHERE type IN ('table', 'index', 'trigger', 'view')").get()?.n??0}deleteMeta(e){if(!this.db)throw new NameErrors.OperationFailedError({message:"Database not initialized",operation:"db-not-initialized"});this.db.prepare("DELETE FROM meta WHERE key = ?").run(e);}};function G(E){return E.isClosed()}function j(E){return E.getDbPath()}function Q(E,e){return E.transaction(e)}export{N as a,P as b,v as c,w as d,S as e,U as f,G as g,j as h,Q as i};
|