@easbot/codebase 0.3.2 → 0.3.4
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.md +30 -0
- package/dist/chunks/chunk-3ZA3AOKC.mjs +58 -0
- package/dist/chunks/chunk-7XCIIOM6.cjs +1 -0
- package/dist/chunks/chunk-AUNBGHMC.cjs +58 -0
- package/dist/chunks/chunk-CJSKATXN.mjs +2 -0
- package/dist/chunks/chunk-EVDJNYI2.cjs +1 -0
- package/dist/chunks/chunk-G3IYU6TZ.mjs +1 -0
- package/dist/chunks/chunk-IXERCMYQ.cjs +2 -0
- package/dist/chunks/chunk-JDULI4R5.cjs +234 -0
- package/dist/chunks/chunk-RLZHDTHY.cjs +154 -0
- package/dist/chunks/chunk-TGMIUXU3.mjs +34 -0
- package/dist/chunks/chunk-TS4OAYIJ.cjs +1 -0
- package/dist/chunks/chunk-UEILXBZB.mjs +1 -0
- package/dist/chunks/chunk-UTKA3WG3.mjs +1 -0
- package/dist/chunks/chunk-VBIXWHTD.mjs +234 -0
- package/dist/chunks/chunk-XAODNPHT.cjs +34 -0
- package/dist/chunks/chunk-Z4Y3VCYS.mjs +154 -0
- package/dist/chunks/code-base-HCFLEKJN.cjs +1 -0
- package/dist/chunks/code-base-N3PTDWLC.mjs +1 -0
- package/dist/chunks/database-manager-DRLNOQ6C.cjs +1 -0
- package/dist/chunks/database-manager-WOYUSWKD.mjs +1 -0
- package/dist/chunks/file-watcher-5WEDJY6M.mjs +1 -0
- package/dist/chunks/file-watcher-LZZUEGMY.cjs +1 -0
- package/dist/chunks/stdio-server-DIGUR2PS.mjs +47 -0
- package/dist/chunks/stdio-server-LJGVWMB7.cjs +47 -0
- package/dist/chunks/sync-52O2GQKE.cjs +1 -0
- package/dist/chunks/sync-JNCNYSWI.mjs +1 -0
- package/dist/cli.cjs +2 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.mjs +2 -0
- package/dist/index.cjs +1 -108
- package/dist/index.d.cts +497 -21
- package/dist/index.d.ts +497 -21
- package/dist/index.mjs +1 -108
- package/package.json +13 -6
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
'use strict';var chunkTS4OAYIJ_cjs=require('./chunk-TS4OAYIJ.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database');var F=class o extends Error{constructor(t,s,r){super(t);chunkTS4OAYIJ_cjs.a(this,"name","ParserError");chunkTS4OAYIJ_cjs.a(this,"filePath");chunkTS4OAYIJ_cjs.a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},g=class o extends Error{constructor(t,s,r){super(t);chunkTS4OAYIJ_cjs.a(this,"name","DatabaseError");chunkTS4OAYIJ_cjs.a(this,"operation");chunkTS4OAYIJ_cjs.a(this,"cause");this.operation=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `DatabaseError: ${this.message} during ${this.operation}${t}`}toJSON(){return {name:this.name,message:this.message,operation:this.operation,cause:this.cause?.message}}},M=class o extends Error{constructor(t,s,r){super(t);chunkTS4OAYIJ_cjs.a(this,"name","FileSystemError");chunkTS4OAYIJ_cjs.a(this,"filePath");chunkTS4OAYIJ_cjs.a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},u=class o extends Error{constructor(t,s){super(t);chunkTS4OAYIJ_cjs.a(this,"name","SchemaError");chunkTS4OAYIJ_cjs.a(this,"missing");this.missing=s,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.missing?` (missing: ${this.missing.join(", ")})`:"";return `SchemaError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,missing:this.missing}}},A=class o extends Error{constructor(t,s){super(t);chunkTS4OAYIJ_cjs.a(this,"name","ConfigError");chunkTS4OAYIJ_cjs.a(this,"field");this.field=s,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.field?` (field: ${this.field})`:"";return `ConfigError: ${this.message}${t}`}toJSON(){return {name:this.name,message:this.message,field:this.field}}},v=class o extends Error{constructor(t,s,r){super(t);chunkTS4OAYIJ_cjs.a(this,"name","IndexError");chunkTS4OAYIJ_cjs.a(this,"filePath");chunkTS4OAYIJ_cjs.a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=[this.message];return this.filePath&&t.push(`at ${this.filePath}`),this.cause&&t.push(`(caused by: ${this.cause.message})`),`IndexError: ${t.join(" ")}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},x=class o extends Error{constructor(t,s,r){super(t);chunkTS4OAYIJ_cjs.a(this,"name","QueryError");chunkTS4OAYIJ_cjs.a(this,"params");chunkTS4OAYIJ_cjs.a(this,"cause");this.params=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.params?` (params: ${JSON.stringify(this.params)})`:"",s=this.cause?` (caused by: ${this.cause.message})`:"";return `QueryError: ${this.message}${t}${s}`}toJSON(){return {name:this.name,message:this.message,params:this.params,cause:this.cause?.message}}},w=class o extends Error{constructor(t,s){super(`Unsupported language: ${t}`);chunkTS4OAYIJ_cjs.a(this,"name","UnsupportedLanguageError");chunkTS4OAYIJ_cjs.a(this,"extension");chunkTS4OAYIJ_cjs.a(this,"filePath");this.extension=t,this.filePath=s,Object.setPrototypeOf(this,o.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var P=utils.Log.create({service:"codebase-schema-migrations"}),p=1,W=[{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
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
name TEXT NOT NULL,
|
|
4
|
+
ast_type TEXT NOT NULL,
|
|
5
|
+
language TEXT NOT NULL,
|
|
6
|
+
file_path TEXT NOT NULL,
|
|
7
|
+
start_line INTEGER,
|
|
8
|
+
start_col INTEGER,
|
|
9
|
+
end_line INTEGER,
|
|
10
|
+
end_col INTEGER,
|
|
11
|
+
text TEXT,
|
|
12
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
13
|
+
)`,`CREATE TABLE IF NOT EXISTS edges (
|
|
14
|
+
id TEXT PRIMARY KEY,
|
|
15
|
+
source TEXT NOT NULL,
|
|
16
|
+
target TEXT NOT NULL,
|
|
17
|
+
relation TEXT NOT NULL,
|
|
18
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
19
|
+
FOREIGN KEY (source) REFERENCES nodes(id) ON DELETE CASCADE,
|
|
20
|
+
FOREIGN KEY (target) REFERENCES nodes(id) ON DELETE CASCADE
|
|
21
|
+
)`,`CREATE TABLE IF NOT EXISTS file_hashes (
|
|
22
|
+
file_path TEXT PRIMARY KEY,
|
|
23
|
+
content_hash TEXT NOT NULL,
|
|
24
|
+
last_modified DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
25
|
+
)`,`CREATE VIRTUAL TABLE IF NOT EXISTS nodes_fts USING fts5(
|
|
26
|
+
id, name, ast_type, language, file_path, text,
|
|
27
|
+
tokenize='unicode61'
|
|
28
|
+
)`,`CREATE TABLE IF NOT EXISTS meta (
|
|
29
|
+
key TEXT PRIMARY KEY,
|
|
30
|
+
value TEXT
|
|
31
|
+
)`,`CREATE TABLE IF NOT EXISTS embedding_cache (
|
|
32
|
+
content_hash TEXT PRIMARY KEY,
|
|
33
|
+
embedding BLOB NOT NULL
|
|
34
|
+
)`,`CREATE TABLE IF NOT EXISTS node_embeddings (
|
|
35
|
+
node_id TEXT PRIMARY KEY,
|
|
36
|
+
embedding_text TEXT NOT NULL,
|
|
37
|
+
embedding BLOB NOT NULL,
|
|
38
|
+
FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
|
|
39
|
+
)`,`CREATE TABLE IF NOT EXISTS unresolved_refs (
|
|
40
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
41
|
+
from_node_id TEXT,
|
|
42
|
+
reference_name TEXT NOT NULL,
|
|
43
|
+
reference_kind TEXT NOT NULL,
|
|
44
|
+
line INTEGER,
|
|
45
|
+
col INTEGER,
|
|
46
|
+
file_path TEXT NOT NULL,
|
|
47
|
+
language TEXT NOT NULL,
|
|
48
|
+
candidates TEXT,
|
|
49
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
50
|
+
FOREIGN KEY (from_node_id) REFERENCES nodes(id) ON DELETE SET NULL
|
|
51
|
+
)`,"CREATE INDEX IF NOT EXISTS idx_unresolved_refs_file_path ON unresolved_refs(file_path)","CREATE INDEX IF NOT EXISTS idx_unresolved_refs_kind ON unresolved_refs(reference_kind)",`CREATE TABLE IF NOT EXISTS name_segment_vocab (
|
|
52
|
+
segment TEXT NOT NULL,
|
|
53
|
+
name TEXT NOT NULL,
|
|
54
|
+
PRIMARY KEY (segment, name)
|
|
55
|
+
) WITHOUT ROWID`,"CREATE INDEX IF NOT EXISTS idx_name_segment ON name_segment_vocab(segment)",`CREATE TABLE IF NOT EXISTS project_metadata (
|
|
56
|
+
key TEXT PRIMARY KEY,
|
|
57
|
+
value TEXT,
|
|
58
|
+
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
59
|
+
)`,`CREATE TABLE IF NOT EXISTS parse_errors (
|
|
60
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
61
|
+
file_path TEXT NOT NULL,
|
|
62
|
+
language TEXT NOT NULL,
|
|
63
|
+
stage TEXT NOT NULL,
|
|
64
|
+
message TEXT NOT NULL,
|
|
65
|
+
line INTEGER,
|
|
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 D(o,e=p,t={}){o.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
68
|
+
id INTEGER PRIMARY KEY,
|
|
69
|
+
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
70
|
+
)`);let s=o.prepare("SELECT id FROM schema_migrations").all(),r=new Set(s.map(a=>a.id)),n={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(a=>a.id)),targetVersion:e};for(let a of W){if(a.id>e)break;if(r.has(a.id)){n.pending.push(a.id);continue}if(t.dryRun){n.applied.push(a.id);continue}try{o.execBatch([...a.up]),o.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(a.id),r.add(a.id),n.applied.push(a.id),P.info("migration applied",{id:a.id,description:a.description});}catch(i){let c=i instanceof Error?i.message:String(i),T=a.up[0]??"";n.errors.push({migrationId:a.id,sql:T,error:c}),P.warn("migration step failed (may be idempotent)",{id:a.id,error:c,sqlCount:a.up.length});}}return n}function X(o){try{let e=o.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,E=utils.Log.create({service:"codebase-database"}),m=2,H=class{constructor(e){chunkTS4OAYIJ_cjs.a(this,"db");chunkTS4OAYIJ_cjs.a(this,"dbPath");chunkTS4OAYIJ_cjs.a(this,"closed",false);chunkTS4OAYIJ_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:5e3}),this.db.initialize();try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("foreign_keys = ON");}catch(t){E.warn("Failed to apply codebase PRAGMAs (synchronous / cache_size / foreign_keys)",{error:String(t)});}try{this.ensureSchema();let t=X(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{D(this.db,p);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,r]of e)t.run(s,r);}catch(e){throw E.error("ensureSchema failed",{message:e instanceof Error?e.message:String(e),cause:e instanceof Error?e.cause:void 0,stack:e instanceof Error?e.stack:void 0}),new u("Failed to create database schema",e instanceof Error?[e.message]:[String(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
|
+
INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
|
|
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(n=>({...n,file_path:l(n.file_path)})),s=this.db.prepare(`
|
|
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
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
76
|
+
`);this.db.transaction(n=>{for(let a of n)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(n);})(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 = ?"),r=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let n of e)try{let a=s.get(n.id);a&&t.run(a.rowid),r.run(n.id,n.name,n.ast_type,n.language,n.file_path,n.text);}catch(a){E.warn("FTS update failed for node",{nodeId:n.id,error:String(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){E.warn("FTS update failed for node",{nodeId:e.id,error:String(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 = ?"),r=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 c=s.get(i.id);c&&t.run(c.rowid),r.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.text);}catch(c){E.warn("FTS update failed for node",{nodeId:i.id,error:String(c)});}})(e);}insertEdge(e){this.db.prepare(`
|
|
77
|
+
INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
|
|
78
|
+
VALUES (?, ?, ?, ?, ?)
|
|
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
|
+
INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
|
|
81
|
+
VALUES (?, ?, ?, ?, ?)
|
|
82
|
+
`);this.db.transaction(r=>{for(let n of r)t.run(n.id,n.source,n.target,n.relation,n.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 r="SELECT * FROM nodes";t.length>0&&(r+=` WHERE ${t.join(" AND ")}`),r+=" ORDER BY file_path, start_line",e.limit&&(r+=" LIMIT ?",s.push(e.limit)),e.offset&&(r+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(r).all(...s)}catch(n){throw new g("Failed to query nodes","queryNodes",n instanceof Error?n:new Error(String(n)))}}queryEdges(e){let t=[],s=[];if(e.sourceOrTarget&&e.sourceOrTarget.length>0){let n=e.sourceOrTarget.map(()=>"?").join(",");t.push(`(source IN (${n}) OR target IN (${n}))`),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 r="SELECT * FROM edges";t.length>0&&(r+=` WHERE ${t.join(" AND ")}`),r+=" ORDER BY created_at DESC",e.limit&&(r+=" LIMIT ?",s.push(e.limit)),e.offset&&(r+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(r).all(...s)}catch(n){throw new g("Failed to query edges","queryEdges",n instanceof Error?n:new Error(String(n)))}}queryAll(e,t){try{let s=this.db.prepare(e);return t?s.all(...t):s.all()}catch(s){throw new g("Failed to execute query","queryAll",s instanceof Error?s:new Error(String(s)))}}searchNodesFts(e,t=20){if(E.debug("searchNodesFts start",{query:e,limit:t,ftsAvailable:this.ftsAvailable}),!this.ftsAvailable)return E.debug("searchNodesFts skip - FTS not available"),[];try{let s=e.split(/\s+/).map(i=>`${i}*`).join(" ");E.debug("searchNodesFts query",{ftsQuery:s});let a=this.db.prepare(`
|
|
83
|
+
SELECT
|
|
84
|
+
nodes_fts.id,
|
|
85
|
+
nodes_fts.name,
|
|
86
|
+
nodes_fts.ast_type,
|
|
87
|
+
nodes_fts.language,
|
|
88
|
+
nodes_fts.file_path,
|
|
89
|
+
nodes_fts.text,
|
|
90
|
+
nodes.start_line,
|
|
91
|
+
nodes.start_col,
|
|
92
|
+
nodes.end_line,
|
|
93
|
+
nodes.end_col,
|
|
94
|
+
bm25(nodes_fts) as score
|
|
95
|
+
FROM nodes_fts
|
|
96
|
+
JOIN nodes ON nodes.id = nodes_fts.id
|
|
97
|
+
WHERE nodes_fts.text MATCH ?
|
|
98
|
+
ORDER BY score DESC
|
|
99
|
+
LIMIT ?
|
|
100
|
+
`).all(s,t);return E.debug("searchNodesFts done",{resultCount:a.length}),a}catch(s){return E.warn("searchNodesFts failed",{error:String(s)}),[]}}deleteNodesByFile(e){let t=l(e);if(this.ftsAvailable)try{let r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let n of r)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(n.rowid);}catch(r){E.warn("FTS delete failed for file",{filePath:t,error:String(r)});}return this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t).changes}deleteEdgesByFile(e){let t=l(e);return this.db.prepare(`
|
|
101
|
+
DELETE FROM edges
|
|
102
|
+
WHERE source IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
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(l(e))?.content_hash??null}setFileHash(e,t){this.db.prepare(`
|
|
105
|
+
INSERT OR REPLACE INTO file_hashes (file_path, content_hash, last_modified)
|
|
106
|
+
VALUES (?, ?, ?)
|
|
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=h=>this.db.prepare(h).get().c,t=h=>e(h),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"),meta:t("SELECT COUNT(*) as c FROM meta")},r=[],n=t(`
|
|
108
|
+
SELECT COUNT(*) as c FROM node_embeddings e
|
|
109
|
+
LEFT JOIN nodes n ON n.id = e.node_id WHERE n.id IS NULL
|
|
110
|
+
`);n>0&&r.push({severity:"error",message:`orphan node_embeddings: ${n}`});let a=t(`
|
|
111
|
+
SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.source)
|
|
112
|
+
`);a>0&&r.push({severity:"error",message:`orphan edges (source): ${a}`});let i=t(`
|
|
113
|
+
SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.target)
|
|
114
|
+
`);i>0&&r.push({severity:"error",message:`orphan edges (target): ${i}`});let c=t("SELECT COUNT(*) as c FROM edges WHERE source = target");c>0&&r.push({severity:"error",message:`self-loop edges: ${c} \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 f=t(`
|
|
115
|
+
SELECT COUNT(*) as c FROM file_hashes fh
|
|
116
|
+
WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.file_path = fh.file_path)
|
|
117
|
+
`);f>0&&r.push({severity:"warn",message:`orphan file_hashes (no nodes): ${f} \u2014 run \`easbot codebase sync\` to cleanup`});let _=t(`
|
|
118
|
+
SELECT COUNT(DISTINCT n.file_path) as c FROM nodes n
|
|
119
|
+
WHERE NOT EXISTS (SELECT 1 FROM file_hashes fh WHERE fh.file_path = n.file_path)
|
|
120
|
+
`);_>0&&r.push({severity:"warn",message:`node files without hash: ${_}`});let R=t("SELECT COUNT(*) as c FROM nodes WHERE name IS NULL OR name = ''");R>0&&r.push({severity:"error",message:`nodes with null/empty name: ${R}`});let S=t("SELECT COUNT(*) as c FROM nodes WHERE ast_type IS NULL OR ast_type = ''");S>0&&r.push({severity:"error",message:`nodes with null/empty ast_type: ${S}`});let b=t("SELECT COUNT(*) as c FROM nodes WHERE language IS NULL OR language = ''");b>0&&r.push({severity:"error",message:`nodes with null/empty language: ${b}`});let N=t("SELECT COUNT(*) as c FROM nodes WHERE file_path IS NULL OR file_path = ''");N>0&&r.push({severity:"error",message:`nodes with null/empty file_path: ${N}`});let O=this.db.prepare("SELECT id, COUNT(*) as c FROM nodes GROUP BY id HAVING c > 1").all().length;O>0&&r.push({severity:"error",message:`duplicate node ids: ${O}`});let I=t("SELECT COUNT(*) as c FROM nodes WHERE file_path LIKE '%\\\\%'");I>0&&r.push({severity:"warn",message:`nodes with backslash in file_path: ${I}`});let L=t(`
|
|
121
|
+
SELECT COUNT(*) as c FROM nodes
|
|
122
|
+
WHERE start_line IS NOT NULL AND end_line IS NOT NULL AND start_line > end_line
|
|
123
|
+
`);L>0&&r.push({severity:"error",message:`invalid line ranges: ${L}`});let y=this.db.prepare("SELECT id, COUNT(*) as c FROM edges GROUP BY id HAVING c > 1").all().length;y>0&&r.push({severity:"error",message:`duplicate edge ids: ${y}`});let C=t("SELECT COUNT(*) as c FROM nodes_fts_content");return C!==s.nodes&&r.push({severity:"error",message:`FTS content desync: ${C} vs ${s.nodes} (run \`easbot codebase recreate\` to rebuild)`}),s.parse_errors>100&&r.push({severity:"warn",message:`parse_errors > 100 (${s.parse_errors}) \u2014\u2014 many files failed to parse`}),{issues:r,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(),r=this.db.prepare("SELECT key, value FROM meta").all(),n={};for(let a of r)n[a.key]=a.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:s?.c??0,dbPath:this.dbPath,meta:n,indexState:this.getIndexState(),extractionVersion:parseInt(this.getMeta("indexed_with_extraction_version")??"0",10),isStale:this.isIndexStale()}}setLastSync(){this.db.prepare(`
|
|
124
|
+
INSERT OR REPLACE INTO meta (key, value)
|
|
125
|
+
VALUES ('lastSync', ?)
|
|
126
|
+
`).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(m)),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<m}detectAndMarkStaleOnInit(){if(this.isIndexStale()){let e=this.getMeta("indexed_with_extraction_version");E.warn("codebase db is stale",{recorded:e??"(none)",current:String(m),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(`
|
|
127
|
+
SELECT embedding FROM embedding_cache WHERE content_hash = ?
|
|
128
|
+
`).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(`
|
|
129
|
+
INSERT OR REPLACE INTO embedding_cache (content_hash, embedding)
|
|
130
|
+
VALUES (?, ?)
|
|
131
|
+
`).run(e,t);}deleteEmbeddingsByFile(e){let t=l(e);return this.db.prepare(`
|
|
132
|
+
DELETE FROM node_embeddings WHERE node_id IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
133
|
+
`).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(`
|
|
134
|
+
INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
|
|
135
|
+
VALUES (?, ?, ?)
|
|
136
|
+
`);this.db.transaction(r=>{for(let n of r)try{t.run(n.nodeId,n.embeddingText,n.embedding);}catch(a){E.warn("Failed to store embedding for node",{nodeId:n.nodeId,error:String(a)});}})(e);}insertParseError(e){return this.db.prepare(`
|
|
137
|
+
INSERT INTO parse_errors (file_path, language, stage, message, line)
|
|
138
|
+
VALUES (?, ?, ?, ?, ?)
|
|
139
|
+
`).run(e.filePath.replace(/\\/g,"/"),e.language,e.stage,e.message,e.line??null).changes}insertUnresolvedRef(e){return this.db.prepare(`
|
|
140
|
+
INSERT INTO unresolved_refs
|
|
141
|
+
(from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
|
|
142
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
143
|
+
`).run(e.fromNodeId??null,e.referenceName,e.referenceKind,e.line??null,e.col??null,e.filePath.replace(/\\/g,"/"),e.language,e.candidates?JSON.stringify(e.candidates):null).changes}insertUnresolvedRefsBatch(e){if(e.length===0)return 0;let s=`
|
|
144
|
+
INSERT INTO unresolved_refs
|
|
145
|
+
(from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
|
|
146
|
+
VALUES ${e.map(()=>"(?, ?, ?, ?, ?, ?, ?, ?)").join(", ")}
|
|
147
|
+
`,r=[];for(let i of e)r.push(i.fromNodeId??null,i.referenceName,i.referenceKind,i.line??null,i.col??null,i.filePath.replace(/\\/g,"/"),i.language,i.candidates?JSON.stringify(i.candidates):null);return this.db.prepare(s).run(...r).changes}insertNameSegment(e,t){return this.db.prepare(`
|
|
148
|
+
INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES (?, ?)
|
|
149
|
+
`).run(e,t).changes}insertNameSegmentsBatch(e){if(e.length===0)return 0;let s=`
|
|
150
|
+
INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES ${e.map(()=>"(?, ?)").join(", ")}
|
|
151
|
+
`,r=[];for(let i of e)r.push(i.segment,i.name);return this.db.prepare(s).run(...r).changes}setProjectMetadata(e,t){return this.db.prepare(`
|
|
152
|
+
INSERT OR REPLACE INTO project_metadata (key, value, updated_at)
|
|
153
|
+
VALUES (?, ?, CURRENT_TIMESTAMP)
|
|
154
|
+
`).run(e,t).changes}getNodeIdsByFile(e){let t=e.replace(/\\/g,"/");return this.db.prepare("SELECT id FROM nodes WHERE file_path = ?").all(t).map(r=>r.id)}deleteFtsByFile(e){let t=e.replace(/\\/g,"/"),s=this.getNodeIdsByFile(t);if(s.length===0)return 0;let r=this.db.prepare("DELETE FROM nodes_fts WHERE id = ?");return this.db.transaction(a=>{for(let i of a)r.run(i);})(s),s.length}initialize(){if(this.closed)throw new g("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){E.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}deleteMeta(e){if(!this.db)throw new Error("Database not initialized");this.db.prepare("DELETE FROM meta WHERE key = ?").run(e);}};function te(o){return o.isClosed()}function se(o){return o.getDbPath()}function re(o,e){return o.transaction(e)}exports.a=F;exports.b=g;exports.c=M;exports.d=u;exports.e=A;exports.f=v;exports.g=x;exports.h=w;exports.i=p;exports.j=W;exports.k=D;exports.l=X;exports.m=m;exports.n=H;exports.o=te;exports.p=se;exports.q=re;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import {o,l}from'./chunk-VBIXWHTD.mjs';import {c}from'./chunk-UTKA3WG3.mjs';import {a}from'./chunk-G3IYU6TZ.mjs';import {Log,Filesystem,TruncateContent}from'@easbot/utils';import {DEFAULT_SEARCH_CONFIG,DEFAULT_PARSER_CONFIG,DEFAULT_INDEXER_CONFIG,DEFAULT_EMBEDDING_CONFIG}from'@easbot/types';var R=class extends Error{constructor(n,l,a$1){super(n);a(this,"code",l);a(this,"details",a$1);this.name="ServiceError";}},P=class extends R{constructor(t,n=[]){super(`Node not found: ${t}`,"NOT_FOUND",{name:t,candidates:n});}},F=class extends R{constructor(t,n){super(`Ambiguous name "${t}" \u2014 ${n.length} candidates`,"AMBIGUOUS",{name:t,candidates:n});}};Log.create({service:"codebase-service"});var N=Filesystem.toUnixPath;async function D(e,t,n){if(n.nodeId){let o=e.getNode(n.nodeId);if(!o)throw new P(`nodeId=${n.nodeId}`);return {node:o,candidates:[]}}if(!n.name)throw new R("Either name or nodeId is required","NOT_FOUND",n);let a=e.queryNodes({limit:5e3});if(n.file){let o=N(n.file),r=a.filter(c=>N(c.file_path).endsWith(o)||N(c.file_path).includes(o));r.length>0&&(a=r);}if(n.kind){let o=n.kind.toLowerCase(),r=a.filter(c=>c.ast_type.includes(o)||c.name.toLowerCase().includes(o));r.length>0&&(a=r);}let i=a.find(o=>o.name===n.name||o.id.split(":").pop()===n.name);if(i)return {node:i,candidates:[]};let d=l(n.name,a,{limit:10,minScore:.5});if(d.length===0)throw new P(n.name);if(d.length===1){let o=e.getNode(d[0].nodeId);if(!o)throw new P(n.name);return {node:o,candidates:d.map(r=>({node:o,score:r.score}))}}let s=[];for(let o of d){let r=e.getNode(o.nodeId);r&&s.push({node:r,score:o.score});}throw s.length===0?new P(n.name):new F(n.name,s)}async function C(e){let t=c(e.rootDir),n=new o({workspaceDir:e.workspaceDir,database:{path:t,walMode:true},embedding:DEFAULT_EMBEDDING_CONFIG,indexer:DEFAULT_INDEXER_CONFIG,parser:DEFAULT_PARSER_CONFIG,search:DEFAULT_SEARCH_CONFIG,sync:{onBoot:false,onSearch:false,onSessionStart:false,intervalMs:0}});return await n.initialize(),n}function ue(e,t,n,l){let a=l==="in"?e.source:e.target,i=n.getNodeById(a);return i?{id:i.id,name:i.name,astType:i.ast_type,filePath:N(i.file_path),startLine:i.start_line??0,relation:e.relation}:null}async function J(e,t){let n=Date.now(),d=await(await C(e)).getQuery().search(t.query??"",{maxResults:t.maxResults??10,language:t.language,filePath:t.file,astType:t.astType,includeEdges:true,enableFts:t.enableFts!==false,enableEmbedding:t.enableEmbedding!==false});if(t.kind){let o=t.kind.toLowerCase();d=d.filter(r=>r.ast_type.includes(o)||r.name.toLowerCase().includes(o));}if(t.file){let o=N(t.file);d=d.filter(r=>N(r.file_path).endsWith(o)||N(r.file_path).includes(o));}let s=d.map(o=>({node:o,edges:o.edges??[],source:"basic",score:0,snippet:(o.text??"").slice(0,200).replace(/\s+/g," ").trim()}));return {total:s.length,hits:s,durationMs:Date.now()-n,truncated:false}}async function pe(e,t){let n=await C(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await D(l,e,t),d=[];if(t.includeEdges){let s=t.edgesLimit??50;d=a.queryEdges({sourceOrTarget:[i.id],limit:s});}return {node:i,edges:d}}var me=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"];async function ge(e,t){let n=await C(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await D(l,e,t);if(!i)return {root:null,nodes:[],edges:[],truncated:false,totalNodes:0,totalEdges:0};let d=t.depth??2,s=t.maxNodes??100,o=t.direction??"both",r=new Map,c=[{nodeId:i.id,depth:0}];r.set(i.id,0);let p=[],u=false;for(;c.length>0;){let g=c.shift();if(g.depth>=d)continue;if(r.size>=s){u=true;break}let f=l.queryNeighbors(g.nodeId,{direction:o,relationTypes:t.relationTypes??me,limit:s-r.size+1});for(let h of f.edges){p.push(h);let I=h.source===g.nodeId?h.target:h.source;if(!r.has(I)&&(r.set(I,g.depth+1),c.push({nodeId:I,depth:g.depth+1}),r.size>=s)){u=true;break}}if(u)break}let m=Array.from(r.keys()),y=m.length>0?a.queryNodes({ids:m}):[],E=new Map(y.map(g=>[g.id,g])),b=[];for(let[g,f]of r.entries()){let h=E.get(g);h&&b.push({node:h,depth:f});}return {root:i,nodes:b,edges:p,truncated:u,totalNodes:b.length,totalEdges:p.length}}var fe=["CALLS","IMPORTS","TYPE_REFERENCES"];async function he(e,t){let n=await C(e),l=n.getQuery(),a=n.getDatabase(),{node:i}=await D(l,e,t);if(!i)return {root:null,totalImpacted:0,buckets:[]};let d=t.depth??2,s=t.maxResults??50,o=t.relationTypes??fe,r=new Set([i.id]),c=[],p=[i.id];for(let u=1;u<=d&&!(p.length===0||r.size-1>=s);u++){let m=p.map(()=>"?").join(","),y=o.map(()=>"?").join(","),E=a.queryAll(`SELECT source, target, relation FROM edges WHERE target IN (${m}) AND relation IN (${y})`,[...p,...o]),b=[],g=new Set;for(let f of E)if(!r.has(f.source)&&!g.has(f.source)&&(g.add(f.source),r.add(f.source),b.push(f.source),r.size-1>=s))break;if(b.length>0){let f=b.slice(0,10),h=a.queryNodes({ids:f}),I=new Map(h.map(L=>[L.id,L])),oe=f.map(L=>{let U=I.get(L);return {id:L,name:U?.name??"(unknown)",filePath:U?N(U.file_path):"(unknown)",relation:"CALLS"}});c.push({depth:u,count:b.length,sample:oe});}p=b;}return {root:i,totalImpacted:r.size-1,buckets:c}}var ye=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","METHOD_OVERRIDES"];async function be(e,t){return k(e,t,"incoming")}async function Ee(e,t){return k(e,t,"outgoing")}async function k(e,t,n,l){let a=await C(e),i=a.getQuery(),d=a.getDatabase(),{node:s}=await D(i,e,t);if(!s)return {root:null,callers:[],truncated:false};let o=t.maxResults??20,r=t.relationTypes??ye,c=i.queryNeighbors(s.id,{direction:n,relationTypes:r,limit:o+1}),p=[];for(let m of c.edges){let y=ue(m,s.id,d,n==="incoming"?"in":"out");y&&p.push(y);}let u=p.length>o;return {root:s,callers:u?p.slice(0,o):p,truncated:u}}async function xe(e,t){if(!t.query)throw new R("explore requires a non-empty query","NOT_FOUND",{query:t.query});let l=await C(e);l.getQuery();l.getDatabase();let s=(await J(e,{query:t.query,file:t.file,kind:t.kind,intent:t.intent,maxResults:t.maxFiles??5,enableFts:true,enableEmbedding:true})).hits,o=new Map;for(let p of s){let u=N(p.node.file_path),m=o.get(u);m?m.push(p):o.set(u,[p]);}let r=t.maxSymbols??3,c=[];for(let[p,u]of o){let m=u.slice(0,r),y=[];for(let E of m){let b=await k(e,{name:E.node.name,file:p,kind:t.kind,maxResults:5},"incoming"),g=await k(e,{name:E.node.name,file:p,kind:t.kind,maxResults:5},"outgoing");y.push({node:E.node,callers:b.callers,callees:g.callers});}c.push({file:p,symbols:y});}return {query:t.query,entryPoints:c,totalHits:s.length}}async function Ne(e,t){return await(await C(e)).getStatus()}async function Re(e,t){return await(await C(e)).healthCheck()}var Ce=Filesystem.toUnixPath;function Se(e){let t=e.text??"";if(!t)return false;let n=t.slice(0,80);return /\bexport\s/.test(n)||/\bpublic\s/.test(n)?true:(false)}function Te(e){let t=e.text??"";if(!t)return [];let n=t.slice(0,80),l=[];return /\basync\s/.test(n)&&l.push("async"),/\bstatic\s/.test(n)&&l.push("static"),/\babstract\s/.test(n)&&l.push("abstract"),/\breadonly\s/.test(n)&&l.push("readonly"),/\bconst\s/.test(n)&&l.push("const"),/\blet\s/.test(n)&&l.push("let"),l}function x(e){return {id:e.id,name:e.name,astType:e.ast_type,language:e.language,filePath:Ce(e.file_path),startLine:e.start_line??0,endLine:e.end_line??0,isExported:Se(e),modifiers:Te(e)}}function $(e,t){return {id:e.id,source:e.source,target:e.target,relation:e.relation,direction:t}}function j(e,t,n){return e.map((l,a)=>({node:x(l),source:t[a]??"basic",score:n[a]??0,snippet:(l.text??"").slice(0,200).replace(/\s+/g," ").trim(),edges:(l.edges??[]).slice(0,10).map(i=>$(i))}))}function Q(){return {id:"",name:"",astType:"",language:"",filePath:"",startLine:0,endLine:0,isExported:false,modifiers:[]}}var Ie=Log.create({service:"codebase-format-truncate"}),z="**`",Le="**",ee=24e3,te=25e3;async function _(e,t={}){let n=t.softLimit??ee,l=t.hardCeiling??te,a=t.toolName??"codebase",i=t.writeToDisk!==false;if(e.length<=n)return {content:e,truncated:false};let d=e.slice(0,l),s=d.lastIndexOf(`
|
|
2
|
+
${z}`),o=d.lastIndexOf(`
|
|
3
|
+
`),r;s>l*.5?r=s:o>0?r=o:r=-1;let c=r>0?d.slice(0,r):d,u=c+"\n\n... (output truncated to budget; the source above is complete and verbatim \u2014 treat it as already Read. For any area not covered, make ANOTHER `<tool>` targeting those names \u2014 do NOT Read these files.)";if(!i)return {content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-c.length}/${e.length} characters truncated ...`};try{let m=await TruncateContent.truncate(e,{maxChars:c.length,direction:"head",label:`${a}-output`});return m.truncated?{content:u,truncated:!0,outputPath:m.outputPath,hint:TruncateContent.formatHint(m),info:`... ${m.removedLength}/${m.originalLength} characters truncated ...`}:{content:u,truncated:!0,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-c.length}/${e.length} characters truncated ...`}}catch(m){return Ie.warn("TruncateContent.truncate failed, returning without disk hint",{error:m instanceof Error?m.message:String(m)}),{content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-c.length}/${e.length} characters truncated ...`}}}function v(e,t={}){let n=t.softLimit??ee,l=t.hardCeiling??te;if(e.length<=n)return {content:e,truncated:false};let a=e.slice(0,l),i=a.lastIndexOf(`
|
|
4
|
+
${z}`),d=a.lastIndexOf(`
|
|
5
|
+
`),s;i>l*.5?s=i:d>0?s=d:s=-1;let o=s>0?a.slice(0,s):a;return {content:o+`
|
|
6
|
+
|
|
7
|
+
... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${e.length-o.length}/${e.length} characters truncated ...`}}function Fe(e,t=Date.now()){let n=Math.max(0,Math.floor((t-e)/1e3));return n>60?">60s ago":`${n}s ago`}function H(e,t){if(!e||e.length===0)return null;let n=e.filter(a=>t.has(a.path));return n.length===0?null:`\u26A0\uFE0F Index may be stale for: ${n.map(a=>`${a.path} (edited ${Fe(a.lastEventAt)})`).join(", ")}
|
|
8
|
+
|
|
9
|
+
`}function w(e,t,n={}){return (ne[e]??ne.default).replace(/<(\w+)>/g,(a,i)=>i==="tool"?t:n[i]??`<${i}>`)}var ne={search:`---
|
|
10
|
+
|
|
11
|
+
> **Complete source for N files is included above \u2014 do NOT re-read them.**
|
|
12
|
+
> If your question also needs files/symbols listed under "Not shown above" (or any area this call didn't cover), make ANOTHER \`<tool>\` targeting those names \u2014 it returns the same source with line numbers and is cheaper and more complete than reading.`,impact:"---\n\n> **Risk: <riskLevel>**. Before editing `<root>`, review d=1 first \u2014 those WILL BREAK.\n> Use `<tool>` to read full source of any direct caller.",context:"---\n\n> **Use `impact` for blast-radius analysis. Use `explore` to read source.**",default:`---
|
|
13
|
+
|
|
14
|
+
> **Output truncated to budget; the content above is the source of truth.**
|
|
15
|
+
> For more detail, call \`<tool>\` with refined parameters.`};async function M(e,t){let{pendingFiles:n,toolName:l,sync:a=false}=t;if(e.length===0)return O(l,"No matches found.","Try broader search terms, or use `explore` to read source.");let i=Oe(e),d=new Set(i.keys()),s=[];s.push(H(n,d)??"");let o="[[codebase-search-summary]]";s.push(o+`
|
|
16
|
+
`);let r=e.length;s.push(`**Files with matches:** ${i.size}
|
|
17
|
+
`);for(let[m,y]of i){let E=y.map(h=>h.node.name),b=E.slice(0,5).join(", "),g=E.length>5?`, +${E.length-5} more`:"";s.push(`**\`${m}\`** \u2014 ${b}${g}
|
|
18
|
+
`);let f=y[0]?.node.language??"";s.push("```"+f);for(let h of y)s.push(`L${h.node.startLine} ${h.snippet}`);s.push("```\n");}s.push(w("search",l,{}));let c=s.join(`
|
|
19
|
+
`),p=`Found ${r} symbol${r===1?"":"s"} across ${i.size} file${i.size===1?"":"s"}.`,u=c.replace(o,p);return A(u,t,a)}async function q(e,t,n){let{pendingFiles:l,toolName:a,sync:i=false}=n;if(t.length===0||t.every(r=>r.count===0))return O(a,`No incoming edges for \`${e.name}\`.`,"This symbol has no callers \u2014 safe to refactor.");let d=t.reduce((r,c)=>r+c.count,0),s=we(d),o=[];o.push(H(l,new Set([e.filePath]))??""),o.push(`**Impact for \`${e.name}\`** (root: ${e.filePath}:${e.startLine}, total impacted: ${d})
|
|
20
|
+
`);for(let r of t){o.push(`- **d=${r.depth}** (${r.count} nodes) \u2014 ${r.riskLabel}`);for(let c of r.samples.slice(0,5))o.push(` - \`${c.name}\` ${c.file}:${c.line} [${c.relation}]`);r.samples.length>5&&o.push(` - ... and ${r.samples.length-5} more`);}return o.push(w("impact",a,{root:e.name,riskLevel:s})),A(o.join(`
|
|
21
|
+
`),n,i)}function we(e){return e>=100?"CRITICAL":e>=50?"HIGH":e>=10?"MEDIUM":"LOW"}function K(e){return e===1?"WILL BREAK (direct callers)":e===2?"LIKELY AFFECTED (indirect)":"MAY NEED TESTING (transitive)"}async function W(e,t){let{root:n,incoming:l,outgoing:a,neighbors:i}=e,{pendingFiles:d,toolName:s,sync:o=false}=t;if(l.length===0&&a.length===0&&i.length===0)return O(s,`No relations found for \`${n.name}\`.`,"This is a leaf node.");let r=[];r.push(H(d,new Set([n.filePath]))??""),r.push(`**Context for \`${n.name}\`** (${n.astType}, ${n.language}, ${n.filePath}:${n.startLine})
|
|
22
|
+
`),r.push(`**Incoming** (${l.length}):`);for(let c of l.slice(0,10))r.push(`- ${c.source} \u2192 [${c.relation}] \u2192 \`${n.name}\``);l.length>10&&r.push(`- ... and ${l.length-10} more`),r.push(""),r.push(`**Outgoing** (${a.length}):`);for(let c of a.slice(0,10))r.push(`- \`${n.name}\` \u2192 [${c.relation}] \u2192 ${c.target}`);if(a.length>10&&r.push(`- ... and ${a.length-10} more`),r.push(""),i.length>0){r.push(`**Neighbors** (${i.length}):`);for(let c of i.slice(0,20))r.push(`- [d=${c.depth}] \`${c.node.name}\` (${c.node.astType}) ${c.node.filePath}:${c.node.startLine}`);i.length>20&&r.push(`- ... and ${i.length-20} more`),r.push("");}return r.push(w("context",s,{})),A(r.join(`
|
|
23
|
+
`),t,o)}async function B(e,t,n){let{pendingFiles:l,toolName:a,sync:i=false}=n;if(!e.id)return O(a,"Node not found.","Check the node ID or use `search` to find it.");let d=t.filter(r=>r.direction==="in"),s=t.filter(r=>r.direction==="out"),o=[];o.push(H(l,new Set([e.filePath]))??""),o.push(`**Node: \`${e.name}\`**
|
|
24
|
+
`),o.push(`- ID: \`${e.id}\``),o.push(`- Kind: ${e.astType}`),o.push(`- Language: ${e.language}`),o.push(`- Location: ${e.filePath}:${e.startLine}-${e.endLine}`),o.push(`- Exported: ${e.isExported}`),e.modifiers.length>0&&o.push(`- Modifiers: ${e.modifiers.join(", ")}`),o.push(""),o.push(`**Edges** (incoming: ${d.length} / outgoing: ${s.length}):`);for(let r of d.slice(0,5))o.push(`- \u2190 [${r.relation}] ${r.source}`);for(let r of s.slice(0,5))o.push(`- \u2192 [${r.relation}] ${r.target}`);return t.length>10&&o.push(`- ... and ${t.length-10} more`),o.push(w("default",a,{})),A(o.join(`
|
|
25
|
+
`),n,i)}async function re(e,t){let{entryPoints:n,totalHits:l,query:a}=e,{toolName:i,sync:d=false}=t;if(n.length===0)return O(i,`No matches for \`${a}\`.`,"Try broader search terms, or use `callers` / `callees` to traverse from a known symbol.");let s=[];s.push(`## Code Context
|
|
26
|
+
`),s.push(`**Query:** ${a} `),s.push(`**Total hits:** ${l} `),s.push(`**Entry points:** ${n.length}
|
|
27
|
+
`);for(let o of n){s.push(`**\`${o.file}\`** \u2014 ${o.symbols.length} symbol${o.symbols.length===1?"":"s"}
|
|
28
|
+
`);for(let r of o.symbols){let c=(r.source??"").trim()||"(source not included)",p=r.node.language;if(s.push("```"+p),s.push(`L${r.node.startLine}-L${r.node.endLine} ${r.node.name} (${r.node.astType}${r.node.modifiers.length>0?`, ${r.node.modifiers.join(" ")}`:""})`),s.push(""),s.push(c),s.push("```\n"),r.callers.length>0){s.push(`**Callers of \`${r.node.name}\` (${r.callers.length}):**`);for(let u of r.callers.slice(0,5))s.push(`- [${u.relation}] \`${u.name}\` ${u.filePath}:${u.startLine}`);r.callers.length>5&&s.push(`- ... and ${r.callers.length-5} more`),s.push("");}if(r.callees.length>0){s.push(`**Callees of \`${r.node.name}\` (${r.callees.length}):**`);for(let u of r.callees.slice(0,5))s.push(`- [${u.relation}] \`${u.name}\` ${u.filePath}:${u.startLine}`);r.callees.length>5&&s.push(`- ... and ${r.callees.length-5} more`),s.push("");}}}return s.push(`---
|
|
29
|
+
`),s.push(w("context",i,{})),A(s.join(`
|
|
30
|
+
`),t,d)}function Oe(e){let t=new Map;for(let n of e){let l=n.node.filePath,a=t.get(l);a?a.push(n):t.set(l,[n]);}return t}function O(e,t,n){return `**${e}**
|
|
31
|
+
|
|
32
|
+
${t}
|
|
33
|
+
|
|
34
|
+
> **Tip:** ${n}`}async function A(e,t,n){let l={softLimit:t.softLimit,hardCeiling:t.hardCeiling,toolName:t.toolName,writeToDisk:n?false:t.writeToDisk};return (n?v(e,l):await _(e,l)).content}var ke=Log.create({service:"codebase-format-render"});async function De(e,t){if(e.length===0)return M([],t);let n=j(e,e.map(()=>"basic"),e.map(()=>0));return M(n,t)}async function _e(e,t,n){if(t.length===0)return q(x(e),[],n);let l=[{depth:1,count:t.length,riskLabel:K(1),samples:t.slice(0,10).map(a=>({name:a.source.name,file:x(a.source).filePath,line:a.source.start_line??0,relation:a.relation}))}];return q(x(e),l,n)}async function ve(e,t,n,l,a){let i=x(e),d=t.map(r=>$(r,"in")),s=n.map(r=>$(r,"out")),o=l.map(r=>({node:x(r),depth:1}));return W({root:i,incoming:d,outgoing:s,neighbors:o},a)}async function He(e,t,n){if(!e)return B(Q(),[],n);let l=x(e),a=t.map(i=>{let d=i.target===e.id?"in":"out";return $(i,d)});return B(l,a,n)}async function Me(e,t){let n={query:e.query,totalHits:e.totalHits,entryPoints:e.entryPoints.map(l=>({file:l.file,symbols:l.symbols.map(a=>({node:x(a.node),source:a.node.text??"",callers:a.callers.map(i=>({name:i.name,filePath:i.filePath,startLine:i.startLine,relation:i.relation})),callees:a.callees.map(i=>({name:i.name,filePath:i.filePath,startLine:i.startLine,relation:i.relation}))}))}))};return re(n,t)}ke.debug("format/render.ts loaded");export{_e as A,ve as B,He as C,Me as D,R as a,P as b,F as c,J as d,pe as e,ge as f,he as g,be as h,Ee as i,xe as j,Ne as k,Re as l,x as m,$ as n,j as o,Q as p,z as q,Le as r,_ as s,v as t,M as u,q as v,K as w,W as x,B as y,De as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var n=Object.defineProperty;var c=(t,e,r)=>e in t?n(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r;var m=(t,e,r)=>c(t,typeof e!="symbol"?e+"":e,r);var o=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,u=o();exports.a=m;exports.b=u;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-G3IYU6TZ.mjs';import {existsSync,readFileSync,promises}from'fs';import {isAbsolute,normalize,join,dirname}from'path';import {createRequire}from'module';import {fileURLToPath}from'url';import {Log,Ignore}from'@easbot/utils';var s=Log.create({service:"codebase-file-watcher"}),O=["node_modules/**",".git/**","dist/**","build/**","__pycache__/**","*.min.js","*.min.ts",".easbot/**",".codebase/**"],d=null,l=null;function S(){let n=process.platform==="linux"?`-${globalThis.EASBOT_LIBC||"glibc"}`:"";return `@parcel/watcher-${process.platform}-${process.arch}${n}`}async function $(n){if(d)return d;if(l){let e=new Error(l);throw n==="warn"&&s.warn("@parcel/watcher previously failed",{error:l}),e}let r=dirname(fileURLToPath(import.meta.url)),t=S();try{let c=(await import('@parcel/watcher/wrapper.js')).createWrapper;if(typeof c!="function")throw new Error("@parcel/watcher/wrapper.js: createWrapper not exported");let p=createRequire(r+"/")(t),o=c(p);return d=o,s.info("@parcel/watcher loaded",{binding:t,backend:"available"}),o}catch(e){let c=e instanceof Error?e.message:String(e),i=`binding "${t}" not found or failed to load. Run: pnpm install ${t}`;throw l=`${c}. ${i}`,s.error("failed to load @parcel/watcher",{error:e,binding:t}),n==="warn"&&s.warn("continuing without watcher (warn mode)"),e instanceof Error?new Error(l):new Error(l)}}function w(){return process.platform==="darwin"?"fs-events":process.platform==="linux"?"inotify":process.platform==="win32"?"windows":"brute-force"}var g=class{constructor(r){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(r.workspaceDir)?r.workspaceDir:normalize(r.workspaceDir),this.backendOpt=r.backend??"auto",this.ignorePatterns=r.ignorePatterns??[...O],this.onLoadFailure=r.onLoadFailure??"throw",this.ignoreInstance=Ignore.create().add(this.ignorePatterns);}getIgnoreInstance(){return this.ignoreInstance}getIgnorePatterns(){return this.ignorePatterns}getActiveBackend(){return this.backendOpt==="auto"?w():this.backendOpt}on(r){return this.listeners.add(r),()=>this.listeners.delete(r)}async start(){if(this.running)return;this.running=true;let r=this.backendOpt==="auto"?w():this.backendOpt;s.info("FileWatcher start",{workspaceDir:this.workspaceDir,backend:r});let t;try{t=await $(this.onLoadFailure);}catch(e){if(this.running=false,this.onLoadFailure==="warn")return;throw e}await this.subscribeWithParcel(t,r);}async stop(){if(this.unsubscribe){try{await this.unsubscribe();}catch(r){s.warn("parcel unsubscribe error",{error:r});}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}async subscribeWithParcel(r,t){if(this.disposed)throw new Error("FileWatcher disposed before subscribe");let e=(i,p)=>{if(this.disposed)return;let o=this.workspaceDir.replace(/\\/g,"/").replace(/\/$/,""),f=p.replace(/\\/g,"/"),u=p;if(f.startsWith(o+"/")&&(u=f.slice(o.length+1)),this.ignoreInstance.ignores(u,i==="create"&&u.endsWith("/")))return;let m=i==="create"?"add":i==="delete"?"unlink":"change";for(let P of this.listeners)try{P(m,u);}catch(v){s.warn("listener threw",{error:v});}},c=await r.subscribe(this.workspaceDir,(i,p)=>{if(i){s.error("parcel subscribe callback error",{error:i});return}for(let o of p)e(o.type,o.path);},{ignore:[...this.ignorePatterns],backend:t});if(this.disposed){await c.unsubscribe().catch(()=>{});return}this.unsubscribe=async()=>{await c.unsubscribe().catch(i=>{s.warn("parcel unsubscribe error",{error:i});});};}};function h(n){return join(n,".watcher.pid")}function C(n){let r=h(n);if(!existsSync(r))return null;try{let t=readFileSync(r,"utf-8").trim(),e=parseInt(t,10);return Number.isFinite(e)?e:null}catch{return null}}async function U(n,r){let t=h(n);await promises.writeFile(t,String(r),"utf-8");}async function z(n){let r=h(n);try{await promises.unlink(r);}catch{}}export{g as a,h as b,C as c,U as d,z as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {join}from'path';import {existsSync,mkdirSync}from'fs';function t(r){return join(r,".easbot")}function d(r){return join(t(r),"codebase.json")}function b(r){return join(t(r),"db","codebase.db")}function f(r){existsSync(r)||mkdirSync(r,{recursive:true});}export{t as a,d as b,b as c,f as d};
|