@easbot/codebase 0.3.23 → 0.3.25
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/dist/chunks/{chunk-UAWXUGY5.cjs → chunk-3IB5XZ2D.cjs} +22 -22
- package/dist/chunks/chunk-4HJ7RFP7.cjs +1 -0
- package/dist/chunks/{chunk-GWR5LCUV.mjs → chunk-7CL37IYG.mjs} +28 -24
- package/dist/chunks/chunk-ICEJ23S3.mjs +203 -0
- package/dist/chunks/chunk-JCJFUUU2.cjs +203 -0
- package/dist/chunks/chunk-QMTGRU63.mjs +47 -0
- package/dist/chunks/chunk-TGCR6O3S.cjs +62 -0
- package/dist/chunks/{chunk-3NTIN3AN.cjs → chunk-UHNJOT5S.cjs} +28 -24
- package/dist/chunks/chunk-WRM2FP4O.mjs +62 -0
- package/dist/chunks/chunk-ZPEE2LSX.mjs +1 -0
- package/dist/chunks/cli-handler-FQ7LQDAN.cjs +1 -0
- package/dist/chunks/cli-handler-Z6VGOAMV.mjs +1 -0
- package/dist/chunks/code-base-BFLIOZXA.cjs +1 -0
- package/dist/chunks/{code-base-HAX5SGRL.mjs → code-base-DMVLROV6.mjs} +1 -1
- package/dist/chunks/database-manager-GT3LOQUV.cjs +1 -0
- package/dist/chunks/database-manager-N5WLNG3F.mjs +1 -0
- package/dist/chunks/file-watcher-QS442D52.cjs +1 -0
- package/dist/chunks/file-watcher-X56TEWNY.mjs +1 -0
- package/dist/chunks/stdio-server-4X7YFQA2.mjs +30 -0
- package/dist/chunks/stdio-server-5UQVBBZP.cjs +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 +39 -4
- package/dist/index.d.ts +39 -4
- package/dist/index.mjs +1 -1
- package/package.json +8 -8
- package/dist/chunks/chunk-A4EAKE3M.mjs +0 -49
- package/dist/chunks/chunk-DHH2XXGJ.mjs +0 -203
- package/dist/chunks/chunk-HRFLFP6O.cjs +0 -1
- package/dist/chunks/chunk-KU6UZET2.cjs +0 -49
- package/dist/chunks/chunk-QQXDOGRV.mjs +0 -1
- package/dist/chunks/chunk-XXH7ZLAJ.mjs +0 -47
- package/dist/chunks/chunk-YY3Z7NGV.cjs +0 -203
- package/dist/chunks/cli-handler-7XFZK7GK.cjs +0 -1
- package/dist/chunks/cli-handler-H6VHMEHB.mjs +0 -1
- package/dist/chunks/code-base-E5TX7O7M.cjs +0 -1
- package/dist/chunks/database-manager-WTV3TBJS.cjs +0 -1
- package/dist/chunks/database-manager-YGQQHLYR.mjs +0 -1
- package/dist/chunks/file-watcher-HVST5PAC.cjs +0 -1
- package/dist/chunks/file-watcher-LCQ55MPE.mjs +0 -1
- package/dist/chunks/stdio-server-2QHQ7ESX.cjs +0 -47
- package/dist/chunks/stdio-server-5YSJE5E5.mjs +0 -47
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var chunkM2YU5LAI_cjs=require('./chunk-M2YU5LAI.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database');var F=class o extends Error{constructor(t,s,r){super(t);chunkM2YU5LAI_cjs.a(this,"name","ParserError");chunkM2YU5LAI_cjs.a(this,"filePath");chunkM2YU5LAI_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}}},p=class o extends Error{constructor(t,s,r){super(t);chunkM2YU5LAI_cjs.a(this,"name","DatabaseError");chunkM2YU5LAI_cjs.a(this,"operation");chunkM2YU5LAI_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);chunkM2YU5LAI_cjs.a(this,"name","FileSystemError");chunkM2YU5LAI_cjs.a(this,"filePath");chunkM2YU5LAI_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}}},
|
|
1
|
+
'use strict';var chunkM2YU5LAI_cjs=require('./chunk-M2YU5LAI.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database');var F=class o extends Error{constructor(t,s,r){super(t);chunkM2YU5LAI_cjs.a(this,"name","ParserError");chunkM2YU5LAI_cjs.a(this,"filePath");chunkM2YU5LAI_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}}},p=class o extends Error{constructor(t,s,r){super(t);chunkM2YU5LAI_cjs.a(this,"name","DatabaseError");chunkM2YU5LAI_cjs.a(this,"operation");chunkM2YU5LAI_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);chunkM2YU5LAI_cjs.a(this,"name","FileSystemError");chunkM2YU5LAI_cjs.a(this,"filePath");chunkM2YU5LAI_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}}},_=class o extends Error{constructor(t,s){super(t);chunkM2YU5LAI_cjs.a(this,"name","SchemaError");chunkM2YU5LAI_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);chunkM2YU5LAI_cjs.a(this,"name","ConfigError");chunkM2YU5LAI_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);chunkM2YU5LAI_cjs.a(this,"name","IndexError");chunkM2YU5LAI_cjs.a(this,"filePath");chunkM2YU5LAI_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);chunkM2YU5LAI_cjs.a(this,"name","QueryError");chunkM2YU5LAI_cjs.a(this,"params");chunkM2YU5LAI_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}`);chunkM2YU5LAI_cjs.a(this,"name","UnsupportedLanguageError");chunkM2YU5LAI_cjs.a(this,"extension");chunkM2YU5LAI_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"}),S=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
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
name TEXT NOT NULL,
|
|
4
4
|
ast_type TEXT NOT NULL,
|
|
@@ -67,19 +67,19 @@
|
|
|
67
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=S,t={}){o.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=o.prepare("SELECT id FROM schema_migrations").all(),r=new Set(s.map(
|
|
70
|
+
)`);let s=o.prepare("SELECT id FROM schema_migrations").all(),r=new Set(s.map(i=>i.id)),n={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(i=>i.id)),targetVersion:e};for(let i of W){if(i.id>e)break;if(r.has(i.id)){n.pending.push(i.id);continue}if(t.dryRun){n.applied.push(i.id);continue}try{o.execBatch([...i.up]),o.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(i.id),r.add(i.id),n.applied.push(i.id),P.info("migration applied",{id:i.id,description:i.description});}catch(a){let c=a instanceof Error?a.message:String(a),u=i.up[0]??"";n.errors.push({migrationId:i.id,sql:u,error:c}),P.warn("migration step failed (may be idempotent)",{id:i.id,error:c,sqlCount:i.up.length});}}return n}function H(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"}),b=3,X=class{constructor(e){chunkM2YU5LAI_cjs.a(this,"db");chunkM2YU5LAI_cjs.a(this,"dbPath");chunkM2YU5LAI_cjs.a(this,"closed",false);chunkM2YU5LAI_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){E.warn("Failed to apply codebase PRAGMAs (synchronous / cache_size / foreign_keys)",{error:String(t)});}try{this.ensureSchema();let t=H(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,S);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){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});let t=e instanceof Error?e.message:String(e),s=e instanceof Error?e.cause:void 0,r=s!==void 0?String(s):"",n=r&&r!==t?` (cause: ${r})`:"";throw new _(`Failed to create database schema: ${t}${n}`,e instanceof Error?[t,r].filter(Boolean):[t])}}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(
|
|
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
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(
|
|
76
|
+
`);this.db.transaction(n=>{for(let i of n)s.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.start_line,i.start_col,i.end_line,i.end_col,i.text,i.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 i=s.get(n.id);i&&t.run(i.rowid),r.run(n.id,n.name,n.ast_type,n.language,n.file_path,n.text);}catch(i){E.warn("FTS update failed for node",{nodeId:n.id,error:String(i)});}}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(i=>{for(let a of i)try{let c=s.get(a.id);c&&t.run(c.rowid),r.run(a.id,a.name,a.ast_type,a.language,a.file_path,a.text);}catch(c){E.warn("FTS update failed for node",{nodeId:a.id,error:String(c)});}})(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(r=>{for(let
|
|
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 p("Failed to query nodes","queryNodes",n instanceof Error?n:new Error(String(n)))}}findNodesByName(e){if(!e.name)return [];let t=e.limit??50,s=e.kind?`%${e.kind.toLowerCase()}%`:null,r=new Set,n=[],i=(c,u)=>{r.has(c.id)||(r.add(c.id),n.push({node:c,matchKind:u}));},a=(c,u)=>{e.file&&(e.file.includes("/")?(c.push("file_path = ?"),u.push(e.file)):(c.push("file_path LIKE '%/' || ?"),u.push(e.file))),s&&(c.push("LOWER(ast_type) LIKE ?"),u.push(s));};try{let c=["name = ?"],u=[e.name];a(c,u),u.push(t);let m=this.db.prepare(`SELECT * FROM nodes WHERE ${c.join(" AND ")} LIMIT ?`).all(...u);for(let g of m)i(g,"exact");if(m.length>0&&e.file)return n.slice(0,t);if(n.length<t){let g=this.db.prepare("SELECT * FROM nodes WHERE name LIKE ? LIMIT ?").all(`%${e.name}%`,t);for(let h of g)i(h,"qualified");}if(n.length>0&&e.file)return n.slice(0,t);if(n.length===0&&e.name){let g=["name LIKE ?"],h=[`%${e.name}%`];e.file&&(e.file.includes("/")?(g.push("file_path = ?"),h.push(e.file)):(g.push("file_path LIKE '%/' || ?"),h.push(e.file))),s&&(g.push("LOWER(ast_type) LIKE ?"),h.push(s)),g.push("?"),h.push(t);let T=this.db.prepare(`SELECT * FROM nodes WHERE ${g.join(" AND ")}`).all(...h);for(let f of T)i(f,"substring");}return n.slice(0,t)}catch(c){throw new p("Failed to find nodes by name","findNodesByName",c instanceof Error?c:new Error(String(c)))}}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 p("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 p("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(a=>`${a}*`).join(" ");E.debug("searchNodesFts query",{ftsQuery:s});let i=this.db.prepare(`
|
|
83
83
|
SELECT
|
|
84
84
|
nodes_fts.id,
|
|
85
85
|
nodes_fts.name,
|
|
@@ -97,58 +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 E.debug("searchNodesFts done",{resultCount:i.length}),i}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
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=R=>this.db.prepare(R).get().c,t=R=>e(R),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")},r=[],n=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
|
-
`);
|
|
111
|
-
SELECT COUNT(*) as c FROM edges e
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
`);
|
|
110
|
+
`);n>0&&r.push({severity:"error",message:`orphan node_embeddings: ${n}`});let i=t(`
|
|
111
|
+
SELECT COUNT(*) as c FROM edges e
|
|
112
|
+
WHERE e.relation != 'IMPORTS'
|
|
113
|
+
AND NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.source)
|
|
114
|
+
`);i>0&&r.push({severity:"error",message:`orphan edges (source): ${i}`});let a=t(`
|
|
115
|
+
SELECT COUNT(*) as c FROM edges e
|
|
116
|
+
WHERE e.relation NOT IN ('CALLS', 'IMPORTS')
|
|
117
|
+
AND NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.target)
|
|
118
|
+
`);a>0&&r.push({severity:"error",message:`orphan edges (target): ${a}`});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 m=t(`
|
|
115
119
|
SELECT COUNT(*) as c FROM file_hashes fh
|
|
116
120
|
WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.file_path = fh.file_path)
|
|
117
|
-
`);
|
|
121
|
+
`);m>0&&r.push({severity:"warn",message:`orphan file_hashes (no nodes): ${m} \u2014 run \`easbot codebase sync\` to cleanup`});let g=t(`
|
|
118
122
|
SELECT COUNT(DISTINCT n.file_path) as c FROM nodes n
|
|
119
123
|
WHERE NOT EXISTS (SELECT 1 FROM file_hashes fh WHERE fh.file_path = n.file_path)
|
|
120
|
-
`);
|
|
124
|
+
`);g>0&&r.push({severity:"warn",message:`node files without hash: ${g}`});let h=t("SELECT COUNT(*) as c FROM nodes WHERE name IS NULL OR name = ''");h>0&&r.push({severity:"error",message:`nodes with null/empty name: ${h}`});let T=t("SELECT COUNT(*) as c FROM nodes WHERE ast_type IS NULL OR ast_type = ''");T>0&&r.push({severity:"error",message:`nodes with null/empty ast_type: ${T}`});let f=t("SELECT COUNT(*) as c FROM nodes WHERE language IS NULL OR language = ''");f>0&&r.push({severity:"error",message:`nodes with null/empty language: ${f}`});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
125
|
SELECT COUNT(*) as c FROM nodes
|
|
122
126
|
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(),
|
|
127
|
+
`);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 i of r)n[i.key]=i.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
128
|
INSERT OR REPLACE INTO meta (key, value)
|
|
125
129
|
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(
|
|
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(b)),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<b}detectAndMarkStaleOnInit(){if(this.isIndexStale()){let e=this.getMeta("indexed_with_extraction_version");E.warn("codebase db is stale",{recorded:e??"(none)",current:String(b),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
131
|
SELECT embedding FROM embedding_cache WHERE content_hash = ?
|
|
128
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(`
|
|
129
133
|
INSERT OR REPLACE INTO embedding_cache (content_hash, embedding)
|
|
130
134
|
VALUES (?, ?)
|
|
131
|
-
`).run(e,t);}deleteEmbeddingsByFile(e){let t=
|
|
135
|
+
`).run(e,t);}deleteEmbeddingsByFile(e){let t=l(e);return this.db.prepare(`
|
|
132
136
|
DELETE FROM node_embeddings WHERE node_id IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
133
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(`
|
|
134
138
|
INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
|
|
135
139
|
VALUES (?, ?, ?)
|
|
136
|
-
`);this.db.transaction(r=>{for(let
|
|
140
|
+
`);this.db.transaction(r=>{for(let n of r)try{t.run(n.nodeId,n.embeddingText,n.embedding);}catch(i){E.warn("Failed to store embedding for node",{nodeId:n.nodeId,error:String(i)});}})(e);}insertParseError(e){return this.db.prepare(`
|
|
137
141
|
INSERT INTO parse_errors (file_path, language, stage, message, line)
|
|
138
142
|
VALUES (?, ?, ?, ?, ?)
|
|
139
|
-
`).run(
|
|
143
|
+
`).run(l(e.filePath),e.language,e.stage,e.message,e.line??null).changes}insertUnresolvedRef(e){return this.db.prepare(`
|
|
140
144
|
INSERT INTO unresolved_refs
|
|
141
145
|
(from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
|
|
142
146
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
143
|
-
`).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=`
|
|
144
148
|
INSERT INTO unresolved_refs
|
|
145
149
|
(from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
|
|
146
150
|
VALUES ${e.map(()=>"(?, ?, ?, ?, ?, ?, ?, ?)").join(", ")}
|
|
147
|
-
`,r=[];for(let a of e)r.push(a.fromNodeId??null,a.referenceName,a.referenceKind,a.line??null,a.col??null,
|
|
151
|
+
`,r=[];for(let a of e)r.push(a.fromNodeId??null,a.referenceName,a.referenceKind,a.line??null,a.col??null,l(a.filePath),a.language,a.candidates?JSON.stringify(a.candidates):null);return this.db.prepare(s).run(...r).changes}insertNameSegment(e,t){return this.db.prepare(`
|
|
148
152
|
INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES (?, ?)
|
|
149
153
|
`).run(e,t).changes}insertNameSegmentsBatch(e){if(e.length===0)return 0;let s=`
|
|
150
154
|
INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES ${e.map(()=>"(?, ?)").join(", ")}
|
|
151
|
-
`,r=[];for(let a of e)r.push(a.segment,a.name);return this.db.prepare(s).run(...r).changes}setProjectMetadata(e,t){let s=e==="worktree"||e==="project"?
|
|
155
|
+
`,r=[];for(let a of e)r.push(a.segment,a.name);return this.db.prepare(s).run(...r).changes}setProjectMetadata(e,t){let s=e==="worktree"||e==="project"?l(t):t;return this.db.prepare(`
|
|
152
156
|
INSERT OR REPLACE INTO project_metadata (key, value, updated_at)
|
|
153
157
|
VALUES (?, ?, CURRENT_TIMESTAMP)
|
|
154
|
-
`).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(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(
|
|
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(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(i=>{for(let a of i)r.run(a);})(s),s.length}initialize(){if(this.closed)throw new p("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);}countSqliteObjects(){if(!this.db)throw new Error("Database 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 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=p;exports.c=M;exports.d=_;exports.e=A;exports.f=v;exports.g=x;exports.h=w;exports.i=S;exports.j=W;exports.k=D;exports.l=H;exports.m=b;exports.n=X;exports.o=te;exports.p=se;exports.q=re;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import {b,c,s}from'./chunk-ICEJ23S3.mjs';import {a}from'./chunk-2YMB6W5S.mjs';import {Log,Filesystem,TruncateContent}from'@easbot/utils';import {DEFAULT_SEARCH_CONFIG,DEFAULT_PARSER_CONFIG,DEFAULT_INDEXER_CONFIG,DEFAULT_EMBEDDING_CONFIG}from'@easbot/types';import {existsSync,statSync}from'fs';var S=class extends Error{constructor(n,o,l){super(n);a(this,"code",o);a(this,"details",l);this.name="ServiceError";}},$=class extends S{constructor(t,n=[]){super(`Node not found: ${t}`,"NOT_FOUND",{name:t,candidates:n});}},O=class extends S{constructor(t,n){super(`Ambiguous name "${t}" \u2014 ${n.length} candidates`,"AMBIGUOUS",{name:t,candidates:n});}};var te=Log.create({service:"codebase-service"}),N=Filesystem.toUnixPath;function Ne(e,t){let n={exact:1,qualified:.85,substring:.5}[e];return t?Math.min(1,n+.2):n}function Re(e,t){if(!t)return false;if(e===t)return true;let n=e.split(/[/\\]/).pop()??"",o=t.split(/[/\\]/).pop()??"";return !!(n&&o&&n===o||t.includes("/")&&e.endsWith("/"+t))}async function _(e,t,n){if(n.nodeId){let s=e.getNode(n.nodeId);if(!s)throw new $(`nodeId=${n.nodeId}`);return {node:s,candidates:[]}}if(!n.name)throw new S("Either name or nodeId is required","NOT_FOUND",n);let l=e.getDatabase().findNodesByName({name:n.name,file:n.file,kind:n.kind,limit:50});if(l.length===0)throw new $(n.name);let a=!!n.file,d=n.file?N(n.file):null,i=l.map(s=>{let g=d?Re(N(s.node.file_path),d):false;return {node:s.node,score:Ne(s.matchKind,g),matchKind:s.matchKind,inFile:g}});if(i.sort((s,g)=>g.score-s.score),i.length===1)return {node:i[0].node,candidates:i.map(s=>({node:s.node,score:s.score}))};let c=i[0].score,r=i.filter(s=>s.score===c);if(r.length===1)return {node:r[0].node,candidates:i.slice(0,10).map(s=>({node:s.node,score:s.score}))};if(a&&r.length>1){let s=r.filter(g=>g.inFile);if(s.length===1)return {node:s[0].node,candidates:i.slice(0,10).map(g=>({node:g.node,score:g.score}))}}throw new O(n.name,i.slice(0,10).map(s=>({node:s.node,score:s.score})))}async function R(e){let t=c(e.rootDir),n=new s({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 z(e,t,n,o){let l=n.map(()=>"?").join(","),a=t.name.split("@")[0]??t.name,d=a.includes(".")?a.split(".").pop()??a:a,i=new Set([`${t.language}:*:*:${a}`]);d!==a&&i.add(`${t.language}:*:*:${d}`);let c=[];d!==a&&c.push(`${t.language}:*:*:%${d}`);let r=Array.from(i),s=r.map(()=>"?").join(","),u=c.length>0?"OR LOWER(target) LIKE LOWER(?)":"";r.length>1&&te.warn("queryIncomingEdgesWithWildcard: multi-variant wildcards (bare+namespaced)",{rootName:t.name,wildcards:r,hint:"\u540C\u540D\u540C namespace \u4E0D\u540C file \u7684\u65B9\u6CD5\u53EF\u80FD\u90FD\u88AB\u547D\u4E2D\uFF0CLLM \u63A8\u7406\u8BF7\u7528 file \u8FC7\u6EE4\u8F85\u4F50"});let m=`
|
|
2
|
+
SELECT id, source, target, relation, created_at FROM edges
|
|
3
|
+
WHERE relation IN (${l})
|
|
4
|
+
AND source != target
|
|
5
|
+
AND (
|
|
6
|
+
target = ?
|
|
7
|
+
OR target IN (${s})
|
|
8
|
+
${u}
|
|
9
|
+
)
|
|
10
|
+
GROUP BY id
|
|
11
|
+
LIMIT ?
|
|
12
|
+
`;return e.queryAll(m,[...n,t.id,...r,...c,o])}function Pe(e){return e==="class_declaration"||e==="class_definition"||e==="interface_declaration"||e==="struct_declaration"||e==="struct_specifier"||e==="record_declaration"}function Se(e,t,n,o,l){let d=e.queryAll("SELECT id FROM nodes WHERE file_path = ? AND start_line >= ? AND end_line <= ? AND ast_type IN ('method_definition', 'method_declaration') LIMIT 1000",[t.file_path,t.start_line,t.end_line]).map(r=>r.id),i=new Set,c=[];for(let r of n)r.id&&!i.has(r.id)&&(i.add(r.id),c.push(r));if(d.length>0){let r=o.map(()=>"?").join(","),s=d.map(()=>"?").join(","),g=`
|
|
13
|
+
SELECT id, source, target, relation, created_at FROM edges
|
|
14
|
+
WHERE relation IN (${r})
|
|
15
|
+
AND source != target
|
|
16
|
+
AND source IN (${s})
|
|
17
|
+
GROUP BY id
|
|
18
|
+
LIMIT ?
|
|
19
|
+
`,u=e.queryAll(g,[...o,...d,l]);for(let m of u)m.id&&!i.has(m.id)&&(i.add(m.id),c.push(m));}return c.slice(0,l)}function ne(e,t,n,o){let a=`
|
|
20
|
+
SELECT id, source, target, relation, created_at FROM edges
|
|
21
|
+
WHERE relation IN (${n.map(()=>"?").join(",")})
|
|
22
|
+
AND source != target
|
|
23
|
+
AND source = ?
|
|
24
|
+
LIMIT ?
|
|
25
|
+
`;return e.queryAll(a,[...n,t.id,o])}function re(e,t,n,o){let l=o==="in"?e.source:e.target;t.id;let d=n.getNodeById(l);if(!d&&l.includes(":*:")){let i=l.split(":").pop()??l,c=i.split("@")[0]??i;if(c&&c!==l){let r=n.findNodesByName({name:c}),s=t.file_path??"",g=s.split(/[/\\]/).pop()??"",u=s.split(/[/\\]/).filter(Boolean),m=r.find(p=>p.node.file_path?p.node.file_path===s:false)??r.find(p=>!p.node.file_path||!g?false:p.node.file_path.split(/[/\\]/).pop()===g)??r.find(p=>{if(!p.node.file_path)return false;let f=p.node.file_path.split(/[/\\]/).filter(Boolean);return u.length<2||f.length<2?false:u[0]===f[0]&&u[1]===f[1]})??null;m&&(d=m.node);}}if(!d){let i=l.split(":").pop()??l;return {id:l,name:i,astType:"unresolved",filePath:"(unresolved)",startLine:0,relation:e.relation}}return {id:d.id,name:d.name,astType:d.ast_type,filePath:N(d.file_path),startLine:d.start_line??0,relation:e.relation}}async function oe(e,t){let n=Date.now(),d=await(await R(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 r=t.kind.toLowerCase();d=d.filter(s=>s.ast_type.includes(r)||s.name.toLowerCase().includes(r));}if(t.file){let r=N(t.file);d=d.filter(s=>N(s.file_path).endsWith(r)||N(s.file_path).includes(r));}let i=t.maxEdgesPerNode??10,c=d.map(r=>({nodeId:r.id,name:r.name,kind:r.ast_type??"unknown",filePath:N(r.file_path),startLine:r.start_line,endLine:r.end_line,edges:(r.edges??[]).slice(0,i),source:"basic",score:0,snippet:(r.text??"").slice(0,200).replace(/\s+/g," ").trim()}));return {total:c.length,hits:c,durationMs:Date.now()-n,truncated:false}}async function Ce(e,t){let n=await R(e),o=n.getQuery(),l=n.getDatabase(),{node:a}=await _(o,e,t),d=[];if(t.includeEdges){let i=t.maxEdgesPerNode??10,c=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"],r=z(l,a,c,i+1),s=ne(l,a,c,i+1),g=new Set,u=[];for(let m of [...r,...s])m.id&&!g.has(m.id)&&(g.add(m.id),u.push(m));d=u.slice(0,i);}return {node:a,edges:d}}var Ie=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"];async function Le(e,t){let n=await R(e),o=n.getQuery(),l=n.getDatabase(),{node:a}=await _(o,e,t);if(!a)return {root:null,nodes:[],edges:[],truncated:false,totalNodes:0,totalEdges:0};let d=t.depth??2,i=t.maxNodes??100,c=t.direction??"both";t.maxEdgesPerNode??10;let s=new Map,g=[{nodeId:a.id,depth:0}];s.set(a.id,0);let u=[],m=false;for(;g.length>0;){let h=g.shift();if(h.depth>=d)continue;if(s.size>=i){m=true;break}let D=o.queryNeighbors(h.nodeId,{direction:c,relationTypes:t.relationTypes??Ie,limit:i-s.size+1});for(let y of D.edges){u.push(y);let I=y.source===h.nodeId?y.target:y.source;if(!s.has(I)&&(s.set(I,h.depth+1),g.push({nodeId:I,depth:h.depth+1}),s.size>=i)){m=true;break}}if(m)break}let p=new Set,f=[];for(let h of u)!h.id||p.has(h.id)||(p.add(h.id),f.push(h));let b=Array.from(s.keys()),E=b.length>0?l.queryNodes({ids:b}):[],C=new Map(E.map(h=>[h.id,h])),x=[];for(let[h,D]of s.entries()){let y=C.get(h);y&&x.push({node:y,depth:D});}return {root:a,nodes:x,edges:f,truncated:m,totalNodes:x.length,totalEdges:u.length}}var Te=["CALLS","IMPORTS","TYPE_REFERENCES"];async function $e(e,t){let n=await R(e),o=n.getQuery(),l=n.getDatabase(),{node:a}=await _(o,e,t);if(!a)return {root:null,totalImpacted:0,buckets:[]};let d=t.depth??2,i=t.maxResults??10,c=t.relationTypes??Te,r=t.maxEdgesPerNode??10,s=new Set([a.id]),g=[],u=[a.id];for(let m=1;m<=d&&!(u.length===0||s.size-1>=i);m++){let p=z(l,a,c,r+1),f=[],b=new Set;for(let E of p)if(!s.has(E.source)&&!b.has(E.source)&&(b.add(E.source),s.add(E.source),f.push(E.source),s.size-1>=i))break;if(f.length>0){let E=f.slice(0,10),C=l.queryNodes({ids:E}),x=new Map(C.map(y=>[y.id,y])),h=new Map;for(let y of p)h.has(y.source)||h.set(y.source,y.relation);let D=E.map(y=>{let I=x.get(y);return {id:y,name:I?.name??"(unknown)",filePath:I?N(I.file_path):"(unknown)",relation:h.get(y)??"CALLS"}});g.push({depth:m,count:f.length,sample:D});}u=f;}return g.length===0&&te.warn("impact: no incoming edges found",{root:a.name,depth:d,relationTypes:c}),{root:a,totalImpacted:s.size-1,buckets:g}}var se=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","METHOD_OVERRIDES"];async function _e(e,t){return ie(e,t)}async function we(e,t){return ae(e,t)}async function ie(e,t){let n=await R(e),o=n.getQuery(),l=n.getDatabase(),{node:a}=await _(o,e,t);if(!a)return {root:null,callers:[],truncated:false};let d=t.maxResults??10,i=t.maxEdgesPerNode??d,c=t.relationTypes??se,r=z(l,a,c,i+1),s=[];for(let u of r){let m=re(u,a,l,"in");m&&s.push(m);}let g=s.length>d;return {root:a,callers:g?s.slice(0,d):s,truncated:g}}async function ae(e,t){let n=await R(e),o=n.getQuery(),l=n.getDatabase(),{node:a}=await _(o,e,t);if(!a)return {root:null,callees:[],truncated:false};let d=t.maxResults??10,i=t.maxEdgesPerNode??d,c=t.relationTypes??se,r=ne(l,a,c,i+1),s=Pe(a.ast_type)?Se(l,a,r,c,i+1):r,g=[];for(let m of s){let p=re(m,a,l,"out");p&&g.push(p);}let u=g.length>d;return {root:a,callees:u?g.slice(0,d):g,truncated:u}}async function Fe(e,t){if(!t.query)throw new S("explore requires a non-empty query","NOT_FOUND",{query:t.query});let o=await R(e),l=o.getQuery(),a=o.getDatabase(),i=(await oe(e,{query:t.query,file:t.file,kind:t.kind,intent:t.intent,maxResults:t.maxFiles??5,enableFts:true,enableEmbedding:true})).hits;if(t.file||t.kind)try{let u=await _(l,e,{name:t.query,file:t.file,kind:t.kind});if(u?.node){let m={nodeId:u.node.id,name:u.node.name,kind:u.node.ast_type,filePath:N(u.node.file_path),startLine:u.node.start_line,endLine:u.node.end_line,edges:[],source:"basic",score:0,snippet:(u.node.text??"").slice(0,200).replace(/\s+/g," ").trim()},p=i.filter(f=>f.nodeId!==m.nodeId);i=[m,...p];}}catch{}let c=new Map;for(let u of i){let m=N(u.filePath),p=c.get(m);p?p.push(u):c.set(m,[u]);}let r=t.maxSymbols??3,s=t.maxEdgesPerNode??10,g=[];for(let[u,m]of c){let p=m.slice(0,r),f=[];for(let b of p){let E=await ie(e,{name:b.name,file:u,kind:t.kind,maxResults:s,maxEdgesPerNode:s}),C=await ae(e,{name:b.name,file:u,kind:t.kind,maxResults:s,maxEdgesPerNode:s});f.push({node:(()=>{let x={id:b.nodeId,name:b.name,ast_type:b.kind,language:"ts",file_path:b.filePath,start_line:b.startLine??0,end_line:b.endLine??0};try{let h=a.getNodeById(b.nodeId);return {...x,text:h?.text??""}}catch{return {...x,text:""}}})(),callers:E.callers,callees:C.callees});}g.push({file:u,symbols:f});}return {query:t.query,entryPoints:g,totalHits:i.length}}async function Ae(e,t){let o=await(await R(e)).getStatus();o.package="codebase",o.workspaceDir=e.workspaceDir;let l=b(e.workspaceDir),a=existsSync(l),d=existsSync(o.dbPath),i;if(d)try{i=statSync(o.dbPath).size;}catch{}o.configPath=l,o.configExists=a,o.dbExists=d,o.dbSize=i,o.vectorEnabled=o.meta?.vector_enabled==="true"||o.meta?.vector_enabled==="1";let c=o.meta?.embeddingDims;c&&Number.isFinite(Number.parseInt(c,10))&&(o.embeddingDims=Number.parseInt(c,10));let r={initialized:false,capabilities:{embedding:false,graphLlm:false}};try{let{Llm:s}=await import('./llm-ADBGTSCV.mjs');if(s.isInitialized()){r.initialized=!0;let g=s.capabilities();r.capabilities={embedding:g.embedding===!0,graphLlm:g.graphLlm===!0},r.embeddingModel=r.capabilities.embedding?"configured":void 0,r.graphModel=r.capabilities.graphLlm?"configured":void 0;}}catch{}o.llm=r;try{let{DatabaseManager:s}=await import('./database-manager-N5WLNG3F.mjs'),g=new s(o.dbPath);try{let{stats:u}=g.checkIntegrity();o.dbStats=u,o.ftsAvailable=g.isFtsAvailable();}finally{g.close();}}catch{}return o}async function De(e,t){return await(await R(e)).healthCheck()}var le=Filesystem.toUnixPath;function ke(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 ve(e){let t=e.text??"";if(!t)return [];let n=t.slice(0,80),o=[];return /\basync\s/.test(n)&&o.push("async"),/\bstatic\s/.test(n)&&o.push("static"),/\babstract\s/.test(n)&&o.push("abstract"),/\breadonly\s/.test(n)&&o.push("readonly"),/\bconst\s/.test(n)&&o.push("const"),/\blet\s/.test(n)&&o.push("let"),o}function P(e){return {id:e.id,name:e.name,astType:e.ast_type,language:e.language,filePath:le(e.file_path),startLine:e.start_line??0,endLine:e.end_line??0,isExported:ke(e),modifiers:ve(e)}}function w(e,t){return {id:e.id,source:e.source,target:e.target,relation:e.relation,direction:t}}function G(e){return e.map(t=>({node:{id:t.nodeId,name:t.name,astType:t.kind,language:"typescript",filePath:le(t.filePath),startLine:t.startLine??0,endLine:t.endLine??0,isExported:false,modifiers:[]},source:t.source,score:t.score,snippet:(t.snippet??"").slice(0,200),edges:(t.edges??[]).slice(0,10).map(n=>w({...n}))}))}function W(){return {id:"",name:"",astType:"",language:"",filePath:"",startLine:0,endLine:0,isExported:false,modifiers:[]}}var He=Log.create({service:"codebase-format-truncate"}),Q="**`",qe="**",de=24e3,ue=25e3;async function v(e,t={}){let n=t.softLimit??de,o=t.hardCeiling??ue,l=t.toolName??"codebase",a=t.writeToDisk!==false;if(e.length<=n)return {content:e,truncated:false};let d=e.slice(0,o),i=d.lastIndexOf(`
|
|
26
|
+
${Q}`),c=d.lastIndexOf(`
|
|
27
|
+
`),r;i>o*.5?r=i:c>0?r=c:r=-1;let s=r>0?d.slice(0,r):d,u=s+"\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(!a)return {content:u,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-s.length}/${e.length} characters truncated ...`};try{let m=await TruncateContent.truncate(e,{maxChars:s.length,direction:"head",label:`${l}-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-s.length}/${e.length} characters truncated ...`}}catch(m){return He.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-s.length}/${e.length} characters truncated ...`}}}function M(e,t={}){let n=t.softLimit??de,o=t.hardCeiling??ue;if(e.length<=n)return {content:e,truncated:false};let l=e.slice(0,o),a=l.lastIndexOf(`
|
|
28
|
+
${Q}`),d=l.lastIndexOf(`
|
|
29
|
+
`),i;a>o*.5?i=a:d>0?i=d:i=-1;let c=i>0?l.slice(0,i):l;return {content:c+`
|
|
30
|
+
|
|
31
|
+
... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${e.length-c.length}/${e.length} characters truncated ...`}}function Be(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(l=>t.has(l.path));return n.length===0?null:`\u26A0\uFE0F Index may be stale for: ${n.map(l=>`${l.path} (edited ${Be(l.lastEventAt)})`).join(", ")}
|
|
32
|
+
|
|
33
|
+
`}function k(e,t,n={}){return (ge[e]??ge.default).replace(/<(\w+)>/g,(l,a)=>a==="tool"?t:n[a]??`<${a}>`)}var ge={search:`---
|
|
34
|
+
|
|
35
|
+
> **Complete source for N files is included above \u2014 do NOT re-read them.**
|
|
36
|
+
> 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:`---
|
|
37
|
+
|
|
38
|
+
> **Output truncated to budget; the content above is the source of truth.**
|
|
39
|
+
> For more detail, call \`<tool>\` with refined parameters.`};async function q(e,t){let{pendingFiles:n,toolName:o,sync:l=false}=t;if(e.length===0)return F(o,"No matches found.","Try broader search terms, or use `explore` to read source.");let a=Ke(e),d=new Set(a.keys()),i=[];i.push(H(n,d)??"");let c="[[codebase-search-summary]]";i.push(c+`
|
|
40
|
+
`);let r=e.length;i.push(`**Files with matches:** ${a.size}
|
|
41
|
+
`);for(let[m,p]of a){let f=p.map(x=>x.node.name),b=f.slice(0,5).join(", "),E=f.length>5?`, +${f.length-5} more`:"";i.push(`**\`${m}\`** \u2014 ${b}${E}
|
|
42
|
+
`);let C=p[0]?.node.language??"";i.push("```"+C);for(let x of p)i.push(`L${x.node.startLine} ${x.snippet}`);i.push("```\n");}i.push(k("search",o,{}));let s=i.join(`
|
|
43
|
+
`),g=`Found ${r} symbol${r===1?"":"s"} across ${a.size} file${a.size===1?"":"s"}.`,u=s.replace(c,g);return A(u,t,l)}async function B(e,t,n){let{pendingFiles:o,toolName:l,sync:a=false}=n;if(t.length===0||t.every(r=>r.count===0))return F(l,`No incoming edges for \`${e.name}\`.`,"This symbol has no callers \u2014 safe to refactor.");let d=t.reduce((r,s)=>r+s.count,0),i=Ue(d),c=[];c.push(H(o,new Set([e.filePath]))??""),c.push(`**Impact for \`${e.name}\`** (root: ${e.filePath}:${e.startLine}, total impacted: ${d})
|
|
44
|
+
`);for(let r of t){c.push(`- **d=${r.depth}** (${r.count} nodes) \u2014 ${r.riskLabel}`);for(let s of r.samples.slice(0,5))c.push(` - \`${s.name}\` ${s.file}:${s.line} [${s.relation}]`);r.samples.length>5&&c.push(` - ... and ${r.samples.length-5} more`);}return c.push(k("impact",l,{root:e.name,riskLevel:i})),A(c.join(`
|
|
45
|
+
`),n,a)}function Ue(e){return e>=100?"CRITICAL":e>=50?"HIGH":e>=10?"MEDIUM":"LOW"}function Y(e){return e===1?"WILL BREAK (direct callers)":e===2?"LIKELY AFFECTED (indirect)":"MAY NEED TESTING (transitive)"}async function V(e,t){let{root:n,incoming:o,outgoing:l,neighbors:a}=e,{pendingFiles:d,toolName:i,sync:c=false}=t;if(o.length===0&&l.length===0&&a.length===0)return F(i,`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})
|
|
46
|
+
`),r.push(`**Incoming** (${o.length}):`);for(let s of o.slice(0,10))r.push(`- ${s.source} \u2192 [${s.relation}] \u2192 \`${n.name}\``);o.length>10&&r.push(`- ... and ${o.length-10} more`),r.push(""),r.push(`**Outgoing** (${l.length}):`);for(let s of l.slice(0,10))r.push(`- \`${n.name}\` \u2192 [${s.relation}] \u2192 ${s.target}`);if(l.length>10&&r.push(`- ... and ${l.length-10} more`),r.push(""),a.length>0){r.push(`**Neighbors** (${a.length}):`);for(let s of a.slice(0,20))r.push(`- [d=${s.depth}] \`${s.node.name}\` (${s.node.astType}) ${s.node.filePath}:${s.node.startLine}`);a.length>20&&r.push(`- ... and ${a.length-20} more`),r.push("");}return r.push(k("context",i,{})),A(r.join(`
|
|
47
|
+
`),t,c)}async function U(e,t,n){let{pendingFiles:o,toolName:l,sync:a=false}=n;if(!e.id)return F(l,"Node not found.","Check the node ID or use `search` to find it.");let d=t.filter(r=>r.direction==="in"),i=t.filter(r=>r.direction==="out"),c=[];c.push(H(o,new Set([e.filePath]))??""),c.push(`**Node: \`${e.name}\`**
|
|
48
|
+
`),c.push(`- ID: \`${e.id}\``),c.push(`- Kind: ${e.astType}`),c.push(`- Language: ${e.language}`),c.push(`- Location: ${e.filePath}:${e.startLine}-${e.endLine}`),c.push(`- Exported: ${e.isExported}`),e.modifiers.length>0&&c.push(`- Modifiers: ${e.modifiers.join(", ")}`),c.push(""),c.push(`**Edges** (incoming: ${d.length} / outgoing: ${i.length}):`);for(let r of d.slice(0,5))c.push(`- \u2190 [${r.relation}] ${r.source}`);for(let r of i.slice(0,5))c.push(`- \u2192 [${r.relation}] ${r.target}`);return t.length>10&&c.push(`- ... and ${t.length-10} more`),c.push(k("default",l,{})),A(c.join(`
|
|
49
|
+
`),n,a)}async function K(e,t,n,o,l){let{toolName:a,sync:d=false}=l,i=n==="callers"?"Callers":"Callees",c="of",r=n==="callers"?"Use `node <name>` to read full source of any caller.":"Use `node <name>` to read full source of any callee.",s=t?.name??"?";if(e.length===0)return F(a,`**${i} ${c} \`${s}\`** (0)`,n==="callers"?"This symbol has no callers \u2014 safe to refactor.":"This symbol has no outgoing calls \u2014 leaf node.");let g=[];g.push(`**${i} ${c} \`${s}\`** (${e.length}${o?"+":""})
|
|
50
|
+
`);for(let u of e.slice(0,10)){let m=u.filePath==="(unresolved)",p=m?u.filePath:`${u.filePath}:${u.startLine}`,f=m?" _(wildcard)_":"";g.push(`- [${u.relation}] \`${u.name}\` ${p}${f}`);}return e.length>10&&g.push(`- ... and ${e.length-10} more`),g.push(`
|
|
51
|
+
---
|
|
52
|
+
> ${r}`),A(g.join(`
|
|
53
|
+
`),l,d)}async function me(e,t){let{entryPoints:n,totalHits:o,query:l}=e,{toolName:a,sync:d=false}=t;if(n.length===0)return F(a,`No matches for \`${l}\`.`,"Try broader search terms, or use `callers` / `callees` to traverse from a known symbol.");let i=[];i.push(`## Code Context
|
|
54
|
+
`),i.push(`**Query:** ${l} `),i.push(`**Total hits:** ${o} `),i.push(`**Entry points:** ${n.length}
|
|
55
|
+
`);for(let c of n){i.push(`**\`${c.file}\`** \u2014 ${c.symbols.length} symbol${c.symbols.length===1?"":"s"}
|
|
56
|
+
`);for(let r of c.symbols){let s=(r.source??"").trim()||"(source not included)",g=r.node.language;if(i.push("```"+g),i.push(`L${r.node.startLine}-L${r.node.endLine} ${r.node.name} (${r.node.astType}${r.node.modifiers.length>0?`, ${r.node.modifiers.join(" ")}`:""})`),i.push(""),i.push(s),i.push("```\n"),r.callers.length>0){i.push(`**Callers of \`${r.node.name}\` (${r.callers.length}):**`);for(let u of r.callers.slice(0,5))i.push(`- [${u.relation}] \`${u.name}\` ${u.filePath}:${u.startLine}`);r.callers.length>5&&i.push(`- ... and ${r.callers.length-5} more`),i.push("");}if(r.callees.length>0){i.push(`**Callees of \`${r.node.name}\` (${r.callees.length}):**`);for(let u of r.callees.slice(0,5))i.push(`- [${u.relation}] \`${u.name}\` ${u.filePath}:${u.startLine}`);r.callees.length>5&&i.push(`- ... and ${r.callees.length-5} more`),i.push("");}}}return i.push(`---
|
|
57
|
+
`),i.push(k("context",a,{})),A(i.join(`
|
|
58
|
+
`),t,d)}function Ke(e){let t=new Map;for(let n of e){let o=n.node.filePath,l=t.get(o);l?l.push(n):t.set(o,[n]);}return t}function F(e,t,n){return `**${e}**
|
|
59
|
+
|
|
60
|
+
${t}
|
|
61
|
+
|
|
62
|
+
> **Tip:** ${n}`}async function A(e,t,n){let o={softLimit:t.softLimit,hardCeiling:t.hardCeiling,toolName:t.toolName,writeToDisk:n?false:t.writeToDisk};return (n?M(e,o):await v(e,o)).content}var ze=Log.create({service:"codebase-format-render"});async function Ge(e,t){if(e.length===0)return q([],t);let n=G(e);return q(n,t)}async function We(e,t,n){if(t.length===0)return B(P(e),[],n);let o=[{depth:1,count:t.length,riskLabel:Y(1),samples:t.slice(0,10).map(l=>({name:l.source.name,file:P(l.source).filePath,line:l.source.start_line??0,relation:l.relation}))}];return B(P(e),o,n)}async function Qe(e,t,n,o,l){let a=P(e),d=t.map(r=>w(r,"in")),i=n.map(r=>w(r,"out")),c=o.map(r=>({node:P(r),depth:1}));return V({root:a,incoming:d,outgoing:i,neighbors:c},l)}async function Ye(e,t){return K(e.callers,e.root,"callers",e.truncated,t)}async function Ve(e,t){return K(e.callees,e.root,"callees",e.truncated,t)}async function Xe(e,t){let{renderKnowledgeStatus:n}=await import('@easbot/terminal');return n({packageName:"codebase",rootDir:e.workspaceDir,configPath:e.configPath??"",configExists:typeof e.configExists=="boolean"?e.configExists:false,dbPath:e.dbPath,dbExists:typeof e.dbExists=="boolean"?e.dbExists:true,dbSize:e.dbSize,indexState:e.indexState,schemaVersion:(()=>{let o=e.meta?.schema_version;return o&&Number.isFinite(Number.parseInt(o,10))?Number.parseInt(o,10):void 0})(),extractionVersion:e.extractionVersion,lastSyncAt:e.lastSync,vectorEnabled:typeof e.vectorEnabled=="boolean"?e.vectorEnabled:false,embeddingDims:typeof e.embeddingDims=="number"?e.embeddingDims:void 0,llm:e.llm??{initialized:false,capabilities:{}},healthy:e.healthy,dbStats:e.dbStats,extras:(()=>{let o={};if(e.isStale===true&&(o.stale="yes \u2014 reindex recommended"),typeof e.ftsAvailable=="boolean"&&(o.fts_available=e.ftsAvailable?"yes":"no"),e.meta&&typeof e.meta=="object")for(let[l,a]of Object.entries(e.meta))a!=null&&(o[`meta/${l}`]=String(a));return Object.keys(o).length>0?o:void 0})()})}async function Je(e,t,n){if(!e)return U(W(),[],n);let o=P(e),l=t.map(a=>{let d=a.target===e.id?"in":"out";return w(a,d)});return U(o,l,n)}async function Ze(e,t){let n={query:e.query,totalHits:e.totalHits,entryPoints:e.entryPoints.map(o=>({file:o.file,symbols:o.symbols.map(l=>({node:P(l.node),source:l.node.text??"",callers:l.callers.map(a=>({name:a.name,filePath:a.filePath,startLine:a.startLine,relation:a.relation})),callees:l.callees.map(a=>({name:a.name,filePath:a.filePath,startLine:a.startLine,relation:a.relation}))}))}))};return me(n,t)}ze.debug("format/render.ts loaded");export{Ge as A,We as B,Qe as C,Ye as D,Ve as E,Xe as F,Je as G,Ze as H,S as a,$ as b,O as c,oe as d,Ce as e,Le as f,$e as g,_e as h,we as i,Fe as j,Ae as k,De as l,P as m,w as n,G as o,W as p,Q as q,qe as r,v as s,M as t,q as u,B as v,Y as w,V as x,U as y,K as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-2YMB6W5S.mjs';import {existsSync,readFileSync,promises}from'fs';import {isAbsolute,normalize,join}from'path';import {createRequire}from'module';import {Log,Ignore,PKG,Shell}from'@easbot/utils';var o=Log.create({service:"codebase-file-watcher"});function O(){return process.env.EASBOT_CACHE_PATH||join(process.cwd(),".easbot","cache")}var S=["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 f=s;function A(){let r=process.platform==="linux"?`-${globalThis.EASBOT_LIBC||"glibc"}`:"";return `@parcel/watcher-${process.platform}-${process.arch}${r}`}async function C(){let r=f.get();if(r.wrapper)return r.wrapper;if(r.error)throw new Error(r.error);let e=A(),t=O(),i;try{await R(e,t)?i=join(t,"node_modules",e):(o.info("Parcel watcher binding not found, attempting to install",{binding:e,cachePath:t}),i=await T(e,t));}catch(l){let p=l instanceof Error?l.message:String(l),g=`binding "${e}" not found and auto-install failed. Run manually: pnpm install ${e}. Error: ${p}`;throw r.error=g,o.error("failed to install parcel watcher binding",{error:l,binding:e}),new Error(g)}o.info("Loading Parcel watcher binding",{binding:e,modulePath:i});let{createWrapper:h}=await import('@parcel/watcher/wrapper.js'),u=createRequire(join(i,"package.json"))(e),c=h(u);return r.wrapper=c,c}async function R(r,e){try{return !!await PKG.resolve(r,void 0,{extraPaths:[e]})}catch{return false}}async function T(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 w(){return process.platform==="darwin"?"fs-events":process.platform==="linux"?"inotify":process.platform==="win32"?"windows":"brute-force"}var m=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??[...S],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"?w():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"?w():this.backendOpt;o.info("FileWatcher start",{workspaceDir:this.workspaceDir,backend:e});let t;try{t=await C();}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: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(){f.clearCache();}async subscribeWithParcel(e,t){if(this.disposed)throw new Error("FileWatcher disposed before subscribe");let i=(a,u)=>{if(this.disposed)return;let c=this.workspaceDir.replace(/\\/g,"/").replace(/\/$/,""),l=u.replace(/\\/g,"/"),p=u;if(l.startsWith(c+"/")&&(p=l.slice(c.length+1)),this.ignoreInstance.ignores(p,a==="create"&&p.endsWith("/")))return;let g=a==="create"?"add":a==="delete"?"unlink":"change";for(let v of this.listeners)try{v(g,p);}catch(k){o.warn("listener threw",{error:k});}},h=await e.subscribe(this.workspaceDir,(a,u)=>{if(a){o.error("parcel subscribe callback error",{error:a});return}for(let c of u)i(c.type,c.path);},{ignore:[...this.ignorePatterns],backend:t});if(this.disposed){await h.unsubscribe().catch(()=>{});return}this.unsubscribe=async()=>{await h.unsubscribe().catch(a=>{o.warn("parcel unsubscribe error",{error:a});});};}};function b(r){return join(r,".watcher.pid")}function M(r){let e=b(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 N(r,e){let t=b(r);await promises.writeFile(t,String(e),"utf-8");}async function z(r){let e=b(r);try{await promises.unlink(e);}catch{}}export{m as a,b,M as c,N as d,z as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunk3IB5XZ2D_cjs=require('./chunk-3IB5XZ2D.cjs');require('./chunk-4HJ7RFP7.cjs'),require('./chunk-TGCR6O3S.cjs'),require('./chunk-JCJFUUU2.cjs'),require('./chunk-JVX6PHPN.cjs'),require('./chunk-UHNJOT5S.cjs'),require('./chunk-VPWALTY7.cjs'),require('./chunk-M2YU5LAI.cjs');Object.defineProperty(exports,"COMMANDS_HELP",{enumerable:true,get:function(){return chunk3IB5XZ2D_cjs.c}});Object.defineProperty(exports,"handleCodebaseCli",{enumerable:true,get:function(){return chunk3IB5XZ2D_cjs.d}});Object.defineProperty(exports,"mapCodebaseDoctor",{enumerable:true,get:function(){return chunk3IB5XZ2D_cjs.e}});Object.defineProperty(exports,"renderBanner",{enumerable:true,get:function(){return chunk3IB5XZ2D_cjs.a}});Object.defineProperty(exports,"renderHelp",{enumerable:true,get:function(){return chunk3IB5XZ2D_cjs.b}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{c as COMMANDS_HELP,d as handleCodebaseCli,e as mapCodebaseDoctor,a as renderBanner,b as renderHelp}from'./chunk-QMTGRU63.mjs';import'./chunk-ZPEE2LSX.mjs';import'./chunk-WRM2FP4O.mjs';import'./chunk-ICEJ23S3.mjs';import'./chunk-34CU2EU4.mjs';import'./chunk-7CL37IYG.mjs';import'./chunk-GWCRGM4D.mjs';import'./chunk-2YMB6W5S.mjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkJCJFUUU2_cjs=require('./chunk-JCJFUUU2.cjs');require('./chunk-JVX6PHPN.cjs');var chunkUHNJOT5S_cjs=require('./chunk-UHNJOT5S.cjs');require('./chunk-VPWALTY7.cjs'),require('./chunk-M2YU5LAI.cjs');Object.defineProperty(exports,"CodeBase",{enumerable:true,get:function(){return chunkJCJFUUU2_cjs.s}});Object.defineProperty(exports,"EdgeExtractor",{enumerable:true,get:function(){return chunkJCJFUUU2_cjs.m}});Object.defineProperty(exports,"FILE_EXTENSION_MAP",{enumerable:true,get:function(){return chunkJCJFUUU2_cjs.g}});Object.defineProperty(exports,"Indexer",{enumerable:true,get:function(){return chunkJCJFUUU2_cjs.o}});Object.defineProperty(exports,"NodeExtractor",{enumerable:true,get:function(){return chunkJCJFUUU2_cjs.k}});Object.defineProperty(exports,"ParserManager",{enumerable:true,get:function(){return chunkJCJFUUU2_cjs.h}});Object.defineProperty(exports,"QueryInterface",{enumerable:true,get:function(){return chunkJCJFUUU2_cjs.q}});Object.defineProperty(exports,"createCodebase",{enumerable:true,get:function(){return chunkJCJFUUU2_cjs.t}});Object.defineProperty(exports,"createEdgeExtractor",{enumerable:true,get:function(){return chunkJCJFUUU2_cjs.n}});Object.defineProperty(exports,"createIndexer",{enumerable:true,get:function(){return chunkJCJFUUU2_cjs.p}});Object.defineProperty(exports,"createNodeExtractor",{enumerable:true,get:function(){return chunkJCJFUUU2_cjs.l}});Object.defineProperty(exports,"createQueryInterface",{enumerable:true,get:function(){return chunkJCJFUUU2_cjs.r}});Object.defineProperty(exports,"getParserManager",{enumerable:true,get:function(){return chunkJCJFUUU2_cjs.i}});Object.defineProperty(exports,"resetParserManager",{enumerable:true,get:function(){return chunkJCJFUUU2_cjs.j}});Object.defineProperty(exports,"ConfigError",{enumerable:true,get:function(){return chunkUHNJOT5S_cjs.e}});Object.defineProperty(exports,"DatabaseError",{enumerable:true,get:function(){return chunkUHNJOT5S_cjs.b}});Object.defineProperty(exports,"DatabaseManager",{enumerable:true,get:function(){return chunkUHNJOT5S_cjs.n}});Object.defineProperty(exports,"FileSystemError",{enumerable:true,get:function(){return chunkUHNJOT5S_cjs.c}});Object.defineProperty(exports,"IndexError",{enumerable:true,get:function(){return chunkUHNJOT5S_cjs.f}});Object.defineProperty(exports,"ParserError",{enumerable:true,get:function(){return chunkUHNJOT5S_cjs.a}});Object.defineProperty(exports,"QueryError",{enumerable:true,get:function(){return chunkUHNJOT5S_cjs.g}});Object.defineProperty(exports,"SchemaError",{enumerable:true,get:function(){return chunkUHNJOT5S_cjs.d}});Object.defineProperty(exports,"UnsupportedLanguageError",{enumerable:true,get:function(){return chunkUHNJOT5S_cjs.h}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{s as CodeBase,m as EdgeExtractor,g as FILE_EXTENSION_MAP,o as Indexer,k as NodeExtractor,h as ParserManager,q as QueryInterface,t as createCodebase,n as createEdgeExtractor,p as createIndexer,l as createNodeExtractor,r as createQueryInterface,i as getParserManager,j as resetParserManager}from'./chunk-
|
|
1
|
+
export{s as CodeBase,m as EdgeExtractor,g as FILE_EXTENSION_MAP,o as Indexer,k as NodeExtractor,h as ParserManager,q as QueryInterface,t as createCodebase,n as createEdgeExtractor,p as createIndexer,l as createNodeExtractor,r as createQueryInterface,i as getParserManager,j as resetParserManager}from'./chunk-ICEJ23S3.mjs';import'./chunk-34CU2EU4.mjs';export{e as ConfigError,b as DatabaseError,n as DatabaseManager,c as FileSystemError,f as IndexError,a as ParserError,g as QueryError,d as SchemaError,h as UnsupportedLanguageError}from'./chunk-7CL37IYG.mjs';import'./chunk-GWCRGM4D.mjs';import'./chunk-2YMB6W5S.mjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkUHNJOT5S_cjs=require('./chunk-UHNJOT5S.cjs');require('./chunk-M2YU5LAI.cjs');Object.defineProperty(exports,"DatabaseManager",{enumerable:true,get:function(){return chunkUHNJOT5S_cjs.n}});Object.defineProperty(exports,"EXTRACTION_VERSION",{enumerable:true,get:function(){return chunkUHNJOT5S_cjs.m}});Object.defineProperty(exports,"getDbPath",{enumerable:true,get:function(){return chunkUHNJOT5S_cjs.p}});Object.defineProperty(exports,"isClosed",{enumerable:true,get:function(){return chunkUHNJOT5S_cjs.o}});Object.defineProperty(exports,"transaction",{enumerable:true,get:function(){return chunkUHNJOT5S_cjs.q}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{n as DatabaseManager,m as EXTRACTION_VERSION,p as getDbPath,o as isClosed,q as transaction}from'./chunk-7CL37IYG.mjs';import'./chunk-2YMB6W5S.mjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunk4HJ7RFP7_cjs=require('./chunk-4HJ7RFP7.cjs');require('./chunk-M2YU5LAI.cjs');Object.defineProperty(exports,"FileWatcher",{enumerable:true,get:function(){return chunk4HJ7RFP7_cjs.a}});Object.defineProperty(exports,"clearWatcherPid",{enumerable:true,get:function(){return chunk4HJ7RFP7_cjs.e}});Object.defineProperty(exports,"getWatcherPidPath",{enumerable:true,get:function(){return chunk4HJ7RFP7_cjs.b}});Object.defineProperty(exports,"readWatcherPid",{enumerable:true,get:function(){return chunk4HJ7RFP7_cjs.c}});Object.defineProperty(exports,"writeWatcherPid",{enumerable:true,get:function(){return chunk4HJ7RFP7_cjs.d}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{a as FileWatcher,e as clearWatcherPid,b as getWatcherPidPath,c as readWatcherPid,d as writeWatcherPid}from'./chunk-ZPEE2LSX.mjs';import'./chunk-2YMB6W5S.mjs';
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import {d,A,e,G,f as f$1,C,g,B as B$1,h,D,i as i$1,E,j,H,k,F,l,b,c}from'./chunk-WRM2FP4O.mjs';import'./chunk-ICEJ23S3.mjs';import'./chunk-34CU2EU4.mjs';import'./chunk-7CL37IYG.mjs';import'./chunk-GWCRGM4D.mjs';import'./chunk-2YMB6W5S.mjs';import {ToolRegistry,createAndStartStdioServer,formatFailClosed}from'@easbot/mcp';import {Log}from'@easbot/utils';var f=Log.create({service:"codebase-mcp-stdio"}),X=["query","node","context","impact","callers","callees","explore","status","doctor"],B;(t=>{let n;function s(){return n||(f.debug("initializing CodebaseStdioServer state factory (lazy)"),n=()=>({toolNames:[...X],cachedConfigId:"",cachedConfigName:"",cachedConfigVersion:""})),n}async function a(o,r){let p=s()(),g=(process.env.EASBOT_MCP_TRUSTED_LOCAL??"true").toLowerCase()!=="false",c=new ToolRegistry;pe(c,o,g);let y=p.toolNames;f.info("starting codebase MCP stdio server",{id:r.id,name:r.name,toolCount:y.length});let b=await createAndStartStdioServer(r,c),x=null,W=new Promise(d=>{x=d;}),E=d=>{f.info("received signal, stopping MCP server",{signal:d}),x?.();},S=()=>E("SIGINT"),T=()=>E("SIGTERM");process.on("SIGINT",S),process.on("SIGTERM",T);try{await W;}finally{try{process.off("SIGINT",S),process.off("SIGTERM",T);}catch(d){f.warn("failed to remove signal handlers",{error:d instanceof Error?d.message:String(d)});}try{await b.stop();}catch(d){f.warn("server.stop failed during cleanup",{error:d instanceof Error?d.message:String(d)});}try{await o.close();}catch(d){f.warn("codebase.close failed during cleanup",{error:d instanceof Error?d.message:String(d)});}}return {id:r.id,name:r.name,version:r.version,tools:y}}t.start=a;function l(){return s()().toolNames}t.getToolNames=l;function e(){n=void 0;}t.__resetForTests=e;})(B||(B={}));var z={readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false},K={type:"object",additionalProperties:false,properties:{query:{type:"string",description:'Symbol name or partial name (e.g., "auth", "UserService"). Empty string returns recent nodes.'},kind:{type:"string",description:"Filter by node kind. One of: class, function, method, interface, type, variable, route, component, const.",enum:["class","function","method","interface","type","variable","route","component","const"]},file:{type:"string",description:'Filter by file path (substring match, e.g., "src/auth").'},intent:{type:"string",description:'LLM context for ranking (e.g., "adding OAuth support").'},includeContent:{type:"boolean",description:"Include source code snippets (default false; use `explore` for full code).",default:false},maxResults:{type:"number",description:"Maximum results",default:10,minimum:1,maximum:100},language:{type:"string",description:"Filter by programming language",enum:["ts","tsx","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"]},astType:{type:"string",description:"Filter by AST node type (more specific than kind)."}},required:[]},V={type:"object",additionalProperties:false,properties:{name:{type:"string",description:'Symbol name (e.g., "AuthService"). Recommended \u2014 LLM workflow: query \u2192 use returned name.'},nodeId:{type:"string",description:"Node ID (direct lookup, zero ambiguity)."},file:{type:"string",description:"File path or basename to disambiguate when multiple same-named symbols exist."},kind:{type:"string",description:"Filter by node kind (class, function, method, interface, type, variable, route, component, const)."},includeContent:{type:"boolean",description:"Include source code body (default true).",default:true},includeEdges:{type:"boolean",description:"Include edge listing (incoming + outgoing).",default:true},maxEdgesPerNode:{type:"number",description:"Max edges to return (default 10; range [1, 100]).",default:10,minimum:1,maximum:100}},required:[]},J={type:"object",additionalProperties:false,properties:{name:{type:"string",description:"Symbol name \u2014 LLM workflow friendly."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind in BFS result."},depth:{type:"number",description:"BFS depth (1 = direct only, 2 = default, 3 = max).",default:2,minimum:1,maximum:3},maxNodes:{type:"number",description:"Max nodes in result.",default:100,minimum:1,maximum:500},direction:{type:"string",description:"Edge direction filter",enum:["incoming","outgoing","both"],default:"both"},maxEdgesPerNode:{type:"number",description:"Max edges per direction per BFS level (default 10; range [1, 100]).",default:10,minimum:1,maximum:100}},required:[]},Z={type:"object",additionalProperties:false,properties:{name:{type:"string",description:"Symbol name \u2014 LLM workflow friendly."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind in BFS result."},depth:{type:"number",description:"Max BFS depth (1-3).",default:2,minimum:1,maximum:3},maxResults:{type:"number",description:"Max affected symbols (default 10; range [1, 200]).",default:10,minimum:1,maximum:200},maxEdgesPerNode:{type:"number",description:"Max incoming edges per BFS level (default 10; range [1, 100]).",default:10,minimum:1,maximum:100}},required:[]},ee={type:"object",additionalProperties:false,properties:{name:{type:"string",description:"Symbol name to find callers for."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind."},maxResults:{type:"number",description:"Max callers to return (default 10; range [1, 200]).",default:10,minimum:1,maximum:200},maxEdgesPerNode:{type:"number",description:"Max incoming edges (default 10; range [1, 100]).",default:10,minimum:1,maximum:100}},required:[]},te={type:"object",additionalProperties:false,properties:{name:{type:"string",description:"Symbol name to find callees for."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind."},maxResults:{type:"number",description:"Max callees to return (default 10; range [1, 200]).",default:10,minimum:1,maximum:200},maxEdgesPerNode:{type:"number",description:"Max outgoing edges (default 10; range [1, 100]).",default:10,minimum:1,maximum:100}},required:[]},ne={type:"object",additionalProperties:false,properties:{query:{type:"string",description:'Symbol name or natural language query (e.g., "auth flow", "MemorySystem").'},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind."},maxFiles:{type:"number",description:"Max entry-point files.",default:5,minimum:1,maximum:20},maxSymbols:{type:"number",description:"Max symbols per file.",default:3,minimum:1,maximum:10},maxEdgesPerNode:{type:"number",description:"Max caller/callee edges per symbol (default 10; range [1, 100]).",default:10,minimum:1,maximum:100},depth:{type:"number",description:"Neighbor depth for callers/callees (default 1).",default:1,minimum:1,maximum:2},includeContent:{type:"boolean",description:"Include source code body (default true).",default:true},intent:{type:"string",description:"LLM context for ranking."}},required:["query"]},$={type:"object",additionalProperties:false,properties:{}},oe={query:'Hybrid search over indexed code nodes (FTS + vector + basic + name-segment). Returns symbol locations grouped by file with line-numbered snippets.\n\nWHEN TO USE: Quick lookup of "where is X defined?" \u2014 get symbol locations and snippets in one call. Use `context` to understand a symbol\'s surroundings; use `impact` to see blast radius; use `explore` to get the actual source.\n\nAFTER THIS: Use `node <name>` to fetch full details of one match; use `context` to walk neighbors; use `explore` to get source code.\n\nNOTES: Default FTS-only (fast). Pass `includeContent: true` to include code snippets in results. Use `kind` for friendlier semantic filter (class/function/method/...) instead of `astType`.',node:"Show details for a single symbol: kind, language, location, modifiers, source code, edges.\n\nWHEN TO USE: After `query` / `context` returns a list \u2014 fetch one match's full metadata and edge summary. Pass `name` (preferred) or `nodeId`.\n\nAFTER THIS: Use `context` to walk neighbors; use `impact` for blast radius; use `explore` to get source code + caller/callee trail.\n\nNOTES: `name` is the LLM-friendly input. `file` / `kind` disambiguate when multiple same-named symbols exist. Source code is included by default (set `includeContent: false` for metadata only).",context:"Build a sub-graph around a symbol (BFS to N-level neighbors). Returns incoming/outgoing edges and neighbor nodes grouped by depth.\n\nWHEN TO USE: Understand a symbol's surroundings \u2014 who calls it, what it calls, who extends it. Use after `query` / `node` to get the symbol.\n\nAFTER THIS: Use `impact` for blast-radius (callers only, deeper depth). Use `callers` / `callees` for a flat list. Use `query` to find related symbols.\n\nNOTES: `name` is the LLM-friendly input. Does NOT include source code (use `explore` for code). Set `direction` to narrow to incoming/outgoing only.",impact:"Blast radius of changing a symbol: BFS incoming edges (CALLS / IMPORTS / TYPE_REFERENCES), bucketed by depth. d=1 (WILL BREAK) / d=2 (LIKELY AFFECTED) / d=3 (MAY NEED TESTING).\n\nWHEN TO USE: Before refactoring a symbol \u2014 see what depends on it. Use after `query` to get the symbol.\n\nAFTER THIS: Review d=1 first (those WILL BREAK). Use `node <name>` on high-risk nodes to read their source.\n\nNOTES: `name` is the LLM-friendly input. Returns counts per depth bucket, not full lists. For flat caller list, use `callers`.",callers:'Flat list of who calls <symbol> (incoming CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS / METHOD_OVERRIDES).\n\nWHEN TO USE: Quick "who depends on this?" lookup. Use `impact` for bucketed risk analysis; use `context` for both directions.\n\nAFTER THIS: Use `node <name>` on a high-traffic caller to read its source.\n\nNOTES: `name` is the LLM-friendly input. Returns up to `maxResults` callers (default 10). Use `file` / `kind` to disambiguate.',callees:'Flat list of what <symbol> calls (outgoing CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS).\n\nWHEN TO USE: Quick "what does this function do?" lookup. Use `context` for both directions.\n\nAFTER THIS: Use `node <name>` on a key callee to read its source.\n\nNOTES: `name` is the LLM-friendly input. Returns up to `maxResults` callees (default 10). Use `file` / `kind` to disambiguate.',explore:"**PRIMARY TOOL \u2014 call FIRST** for almost any question OR before an edit: how does X work, architecture, a bug, where/what is X, surveying an area, or symbols you are about to change.\n\nReturns verbatim source of relevant symbols grouped by file in ONE capped call (Read-equivalent \u2014 treat shown source as already Read; do NOT re-open those files), plus caller/callee trail.\n\nWHEN TO USE: Whenever you need to understand an area of the codebase or before refactoring. Query can be a symbol name or natural language.\n\nAFTER THIS: Use `node <name>` for metadata only; use `impact` for blast-radius; use `callers` / `callees` for flat lists.\n\nNOTES: Usually the ONLY call you need \u2014 more accurate context, in far fewer tokens and round-trips than search/Read/Grep loop. The single most cost-effective tool.",status:`Show index state, db path, node/edge counts, indexed files, meta config.
|
|
2
|
+
|
|
3
|
+
WHEN TO USE: Diagnostic only \u2014 check whether the index is up-to-date or stale. Skip unless debugging.
|
|
4
|
+
|
|
5
|
+
AFTER THIS: If index is stale, run \`easbot codebase sync\` from CLI; \`doctor\` for deeper health check.
|
|
6
|
+
|
|
7
|
+
NOTES: Read-only. Output is a structured markdown summary.`,doctor:`Run health checks: db connection, FTS availability, parser status, node/edge counts.
|
|
8
|
+
|
|
9
|
+
WHEN TO USE: Diagnostic only \u2014 check why queries return empty or fail. Skip unless debugging.
|
|
10
|
+
|
|
11
|
+
AFTER THIS: If unhealthy, fix the reported issue (usually run \`easbot codebase index\` from CLI).
|
|
12
|
+
|
|
13
|
+
NOTES: Read-only. Returns healthy/unhealthy + a list of issues.`};function i(n,s=false){return {content:[{type:"text",text:n}],...s&&{isError:true}}}function u(n){return {workspaceDir:n.getWorkspaceDir?.()??process.cwd(),rootDir:n.getWorkspaceDir?.()??process.cwd()}}function m(n,s,a){if(n instanceof b)return `**${s}** \u2014 node not found. Try \`query\` first to discover the symbol.`;if(n instanceof c){let l=n.details?.candidates??[],e=l.slice(0,5).map(t=>`- \`${t.node.name}\` in \`${t.node.file_path}\``).join(`
|
|
14
|
+
`);return `**${s}** \u2014 ambiguous name. Specify \`file\` to disambiguate:
|
|
15
|
+
|
|
16
|
+
${e}
|
|
17
|
+
|
|
18
|
+
... and ${l.length-5} more candidates.`}return formatFailClosed(n,a)}function se(n,s){return async(a,l)=>{let e=a;try{let t=u(n),o=await d(t,{query:e.query,kind:e.kind,file:e.file,intent:e.intent,includeContent:e.includeContent??!1,maxResults:e.maxResults??10,language:e.language,astType:e.astType,maxEdgesPerNode:e.maxEdgesPerNode??10}),r=await A(o.hits,{pendingFiles:[],toolName:"query",writeToDisk:!1});return i(r)}catch(t){return i(m(t,"query",s),true)}}}function re(n,s){return async(a,l)=>{let e$1=a;try{let t=u(n),o=await e(t,{name:e$1.name,nodeId:e$1.nodeId,file:e$1.file,kind:e$1.kind,includeEdges:e$1.includeEdges??!0,includeContent:e$1.includeContent??!0,maxEdgesPerNode:e$1.maxEdgesPerNode??10}),r=await G(o.node,o.edges,{pendingFiles:[],toolName:"node",writeToDisk:!1});return i(r)}catch(t){return i(m(t,"node",s),true)}}}function ae(n,s){return async(a,l)=>{let e=a;try{let t=u(n),o=await f$1(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,depth:e.depth??2,maxNodes:e.maxNodes??100,direction:e.direction??"both",maxEdgesPerNode:e.maxEdgesPerNode??10});if(!o.root)return i("**context** \u2014 node not found.");let r=[],p=[];for(let c of o.edges)c.target===o.root.id?r.push(c):p.push(c);let g=await C(o.root,r,p,o.nodes.map(c=>c.node),{pendingFiles:[],toolName:"context",writeToDisk:!1});return i(g)}catch(t){return i(m(t,"context",s),true)}}}function ie(n,s){return async(a,l)=>{let e=a;try{let t=u(n),o=await g(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,depth:e.depth??2,maxResults:e.maxResults??10,maxEdgesPerNode:e.maxEdgesPerNode??10});if(!o.root)return i("**impact** \u2014 node not found.");let r=[],p=n.getDatabase();for(let c of o.buckets)for(let y of c.sample){let b=p.getNodeById(y.id);b&&r.push({source:b,relation:y.relation});}let g$1=await B$1(o.root,r,{pendingFiles:[],toolName:"impact",writeToDisk:!1});return i(g$1)}catch(t){return i(m(t,"impact",s),true)}}}function de(n,s){return async(a,l)=>{let e=a;try{let t=u(n),o=await h(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,maxResults:e.maxResults??10,maxEdgesPerNode:e.maxEdgesPerNode??10}),r=await D(o,{toolName:"codebase_callers"});return i(r)}catch(t){return i(m(t,"callers",s),true)}}}function le(n,s){return async(a,l)=>{let e=a;try{let t=u(n),o=await i$1(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,maxResults:e.maxResults??10,maxEdgesPerNode:e.maxEdgesPerNode??10}),r=await E(o,{toolName:"codebase_callees"});return i(r)}catch(t){return i(m(t,"callees",s),true)}}}function ce(n,s){return async(a,l)=>{let e=a;try{let t=u(n),o=await j(t,{query:e.query,file:e.file,kind:e.kind,maxFiles:e.maxFiles??5,maxSymbols:e.maxSymbols??3,maxEdgesPerNode:e.maxEdgesPerNode??10,depth:e.depth??1,includeContent:e.includeContent??!0,intent:e.intent}),r=await H(o,{pendingFiles:[],toolName:"explore",writeToDisk:!1});return i(r)}catch(t){return i(m(t,"explore",s),true)}}}function ue(n,s){return async(a,l)=>{try{let e=u(n),t=await k(e,{}),o=await F(t,{toolName:"codebase_status"});return i(o)}catch(e){return i(m(e,"status",s),true)}}}function me(n,s){return async(a,l$1)=>{try{let e=u(n),t=await l(e,{}),o=await k(e,{}),r=`**Codebase Health Check**
|
|
19
|
+
|
|
20
|
+
- Healthy: ${t.healthy?"\u2713 yes":"\u2717 no"}
|
|
21
|
+
- Nodes: ${o.nodeCount}
|
|
22
|
+
- Edges: ${o.edgeCount}
|
|
23
|
+
- Indexed files: ${o.indexedFiles}
|
|
24
|
+
- DB path: \`${o.dbPath}\`
|
|
25
|
+
- FTS available: ${t.ftsAvailable}
|
|
26
|
+
|
|
27
|
+
${t.issues.length>0?`**Issues:**
|
|
28
|
+
${t.issues.map(p=>`- ${p}`).join(`
|
|
29
|
+
`)}
|
|
30
|
+
`:""}> ${t.healthy?"Index is healthy. Use `query` to search.":"Index has issues. Check status details above."}`;return i(r)}catch(e){return i(m(e,"doctor",s),true)}}}function pe(n,s,a){let l=[{name:"query",schema:K,factory:se},{name:"node",schema:V,factory:re},{name:"context",schema:J,factory:ae},{name:"impact",schema:Z,factory:ie},{name:"callers",schema:ee,factory:de},{name:"callees",schema:te,factory:le},{name:"explore",schema:ne,factory:ce},{name:"status",schema:$,factory:ue},{name:"doctor",schema:$,factory:me}];for(let e of l)n.register({name:e.name,description:oe[e.name]??"",inputSchema:e.schema,annotations:z,handler:e.factory(s,a)});}export{B as CodebaseStdioServer};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
'use strict';var chunkTGCR6O3S_cjs=require('./chunk-TGCR6O3S.cjs');require('./chunk-JCJFUUU2.cjs'),require('./chunk-JVX6PHPN.cjs'),require('./chunk-UHNJOT5S.cjs'),require('./chunk-VPWALTY7.cjs'),require('./chunk-M2YU5LAI.cjs');var mcp=require('@easbot/mcp'),utils=require('@easbot/utils');var f=utils.Log.create({service:"codebase-mcp-stdio"}),X=["query","node","context","impact","callers","callees","explore","status","doctor"];exports.CodebaseStdioServer=void 0;(t=>{let n;function s(){return n||(f.debug("initializing CodebaseStdioServer state factory (lazy)"),n=()=>({toolNames:[...X],cachedConfigId:"",cachedConfigName:"",cachedConfigVersion:""})),n}async function a(o,r){let p=s()(),g=(process.env.EASBOT_MCP_TRUSTED_LOCAL??"true").toLowerCase()!=="false",c=new mcp.ToolRegistry;pe(c,o,g);let y=p.toolNames;f.info("starting codebase MCP stdio server",{id:r.id,name:r.name,toolCount:y.length});let b=await mcp.createAndStartStdioServer(r,c),x=null,W=new Promise(d=>{x=d;}),E=d=>{f.info("received signal, stopping MCP server",{signal:d}),x?.();},S=()=>E("SIGINT"),T=()=>E("SIGTERM");process.on("SIGINT",S),process.on("SIGTERM",T);try{await W;}finally{try{process.off("SIGINT",S),process.off("SIGTERM",T);}catch(d){f.warn("failed to remove signal handlers",{error:d instanceof Error?d.message:String(d)});}try{await b.stop();}catch(d){f.warn("server.stop failed during cleanup",{error:d instanceof Error?d.message:String(d)});}try{await o.close();}catch(d){f.warn("codebase.close failed during cleanup",{error:d instanceof Error?d.message:String(d)});}}return {id:r.id,name:r.name,version:r.version,tools:y}}t.start=a;function l(){return s()().toolNames}t.getToolNames=l;function e(){n=void 0;}t.__resetForTests=e;})(exports.CodebaseStdioServer||(exports.CodebaseStdioServer={}));var z={readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false},K={type:"object",additionalProperties:false,properties:{query:{type:"string",description:'Symbol name or partial name (e.g., "auth", "UserService"). Empty string returns recent nodes.'},kind:{type:"string",description:"Filter by node kind. One of: class, function, method, interface, type, variable, route, component, const.",enum:["class","function","method","interface","type","variable","route","component","const"]},file:{type:"string",description:'Filter by file path (substring match, e.g., "src/auth").'},intent:{type:"string",description:'LLM context for ranking (e.g., "adding OAuth support").'},includeContent:{type:"boolean",description:"Include source code snippets (default false; use `explore` for full code).",default:false},maxResults:{type:"number",description:"Maximum results",default:10,minimum:1,maximum:100},language:{type:"string",description:"Filter by programming language",enum:["ts","tsx","js","py","rs","go","c","cpp","csharp","java","scala","ruby","php","zig"]},astType:{type:"string",description:"Filter by AST node type (more specific than kind)."}},required:[]},V={type:"object",additionalProperties:false,properties:{name:{type:"string",description:'Symbol name (e.g., "AuthService"). Recommended \u2014 LLM workflow: query \u2192 use returned name.'},nodeId:{type:"string",description:"Node ID (direct lookup, zero ambiguity)."},file:{type:"string",description:"File path or basename to disambiguate when multiple same-named symbols exist."},kind:{type:"string",description:"Filter by node kind (class, function, method, interface, type, variable, route, component, const)."},includeContent:{type:"boolean",description:"Include source code body (default true).",default:true},includeEdges:{type:"boolean",description:"Include edge listing (incoming + outgoing).",default:true},maxEdgesPerNode:{type:"number",description:"Max edges to return (default 10; range [1, 100]).",default:10,minimum:1,maximum:100}},required:[]},J={type:"object",additionalProperties:false,properties:{name:{type:"string",description:"Symbol name \u2014 LLM workflow friendly."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind in BFS result."},depth:{type:"number",description:"BFS depth (1 = direct only, 2 = default, 3 = max).",default:2,minimum:1,maximum:3},maxNodes:{type:"number",description:"Max nodes in result.",default:100,minimum:1,maximum:500},direction:{type:"string",description:"Edge direction filter",enum:["incoming","outgoing","both"],default:"both"},maxEdgesPerNode:{type:"number",description:"Max edges per direction per BFS level (default 10; range [1, 100]).",default:10,minimum:1,maximum:100}},required:[]},Z={type:"object",additionalProperties:false,properties:{name:{type:"string",description:"Symbol name \u2014 LLM workflow friendly."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind in BFS result."},depth:{type:"number",description:"Max BFS depth (1-3).",default:2,minimum:1,maximum:3},maxResults:{type:"number",description:"Max affected symbols (default 10; range [1, 200]).",default:10,minimum:1,maximum:200},maxEdgesPerNode:{type:"number",description:"Max incoming edges per BFS level (default 10; range [1, 100]).",default:10,minimum:1,maximum:100}},required:[]},ee={type:"object",additionalProperties:false,properties:{name:{type:"string",description:"Symbol name to find callers for."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind."},maxResults:{type:"number",description:"Max callers to return (default 10; range [1, 200]).",default:10,minimum:1,maximum:200},maxEdgesPerNode:{type:"number",description:"Max incoming edges (default 10; range [1, 100]).",default:10,minimum:1,maximum:100}},required:[]},te={type:"object",additionalProperties:false,properties:{name:{type:"string",description:"Symbol name to find callees for."},nodeId:{type:"string",description:"Node ID (direct lookup)."},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind."},maxResults:{type:"number",description:"Max callees to return (default 10; range [1, 200]).",default:10,minimum:1,maximum:200},maxEdgesPerNode:{type:"number",description:"Max outgoing edges (default 10; range [1, 100]).",default:10,minimum:1,maximum:100}},required:[]},ne={type:"object",additionalProperties:false,properties:{query:{type:"string",description:'Symbol name or natural language query (e.g., "auth flow", "MemorySystem").'},file:{type:"string",description:"File path or basename to disambiguate."},kind:{type:"string",description:"Filter by node kind."},maxFiles:{type:"number",description:"Max entry-point files.",default:5,minimum:1,maximum:20},maxSymbols:{type:"number",description:"Max symbols per file.",default:3,minimum:1,maximum:10},maxEdgesPerNode:{type:"number",description:"Max caller/callee edges per symbol (default 10; range [1, 100]).",default:10,minimum:1,maximum:100},depth:{type:"number",description:"Neighbor depth for callers/callees (default 1).",default:1,minimum:1,maximum:2},includeContent:{type:"boolean",description:"Include source code body (default true).",default:true},intent:{type:"string",description:"LLM context for ranking."}},required:["query"]},$={type:"object",additionalProperties:false,properties:{}},oe={query:'Hybrid search over indexed code nodes (FTS + vector + basic + name-segment). Returns symbol locations grouped by file with line-numbered snippets.\n\nWHEN TO USE: Quick lookup of "where is X defined?" \u2014 get symbol locations and snippets in one call. Use `context` to understand a symbol\'s surroundings; use `impact` to see blast radius; use `explore` to get the actual source.\n\nAFTER THIS: Use `node <name>` to fetch full details of one match; use `context` to walk neighbors; use `explore` to get source code.\n\nNOTES: Default FTS-only (fast). Pass `includeContent: true` to include code snippets in results. Use `kind` for friendlier semantic filter (class/function/method/...) instead of `astType`.',node:"Show details for a single symbol: kind, language, location, modifiers, source code, edges.\n\nWHEN TO USE: After `query` / `context` returns a list \u2014 fetch one match's full metadata and edge summary. Pass `name` (preferred) or `nodeId`.\n\nAFTER THIS: Use `context` to walk neighbors; use `impact` for blast radius; use `explore` to get source code + caller/callee trail.\n\nNOTES: `name` is the LLM-friendly input. `file` / `kind` disambiguate when multiple same-named symbols exist. Source code is included by default (set `includeContent: false` for metadata only).",context:"Build a sub-graph around a symbol (BFS to N-level neighbors). Returns incoming/outgoing edges and neighbor nodes grouped by depth.\n\nWHEN TO USE: Understand a symbol's surroundings \u2014 who calls it, what it calls, who extends it. Use after `query` / `node` to get the symbol.\n\nAFTER THIS: Use `impact` for blast-radius (callers only, deeper depth). Use `callers` / `callees` for a flat list. Use `query` to find related symbols.\n\nNOTES: `name` is the LLM-friendly input. Does NOT include source code (use `explore` for code). Set `direction` to narrow to incoming/outgoing only.",impact:"Blast radius of changing a symbol: BFS incoming edges (CALLS / IMPORTS / TYPE_REFERENCES), bucketed by depth. d=1 (WILL BREAK) / d=2 (LIKELY AFFECTED) / d=3 (MAY NEED TESTING).\n\nWHEN TO USE: Before refactoring a symbol \u2014 see what depends on it. Use after `query` to get the symbol.\n\nAFTER THIS: Review d=1 first (those WILL BREAK). Use `node <name>` on high-risk nodes to read their source.\n\nNOTES: `name` is the LLM-friendly input. Returns counts per depth bucket, not full lists. For flat caller list, use `callers`.",callers:'Flat list of who calls <symbol> (incoming CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS / METHOD_OVERRIDES).\n\nWHEN TO USE: Quick "who depends on this?" lookup. Use `impact` for bucketed risk analysis; use `context` for both directions.\n\nAFTER THIS: Use `node <name>` on a high-traffic caller to read its source.\n\nNOTES: `name` is the LLM-friendly input. Returns up to `maxResults` callers (default 10). Use `file` / `kind` to disambiguate.',callees:'Flat list of what <symbol> calls (outgoing CALLS / IMPORTS / TYPE_REFERENCES / EXTENDS / IMPLEMENTS).\n\nWHEN TO USE: Quick "what does this function do?" lookup. Use `context` for both directions.\n\nAFTER THIS: Use `node <name>` on a key callee to read its source.\n\nNOTES: `name` is the LLM-friendly input. Returns up to `maxResults` callees (default 10). Use `file` / `kind` to disambiguate.',explore:"**PRIMARY TOOL \u2014 call FIRST** for almost any question OR before an edit: how does X work, architecture, a bug, where/what is X, surveying an area, or symbols you are about to change.\n\nReturns verbatim source of relevant symbols grouped by file in ONE capped call (Read-equivalent \u2014 treat shown source as already Read; do NOT re-open those files), plus caller/callee trail.\n\nWHEN TO USE: Whenever you need to understand an area of the codebase or before refactoring. Query can be a symbol name or natural language.\n\nAFTER THIS: Use `node <name>` for metadata only; use `impact` for blast-radius; use `callers` / `callees` for flat lists.\n\nNOTES: Usually the ONLY call you need \u2014 more accurate context, in far fewer tokens and round-trips than search/Read/Grep loop. The single most cost-effective tool.",status:`Show index state, db path, node/edge counts, indexed files, meta config.
|
|
2
|
+
|
|
3
|
+
WHEN TO USE: Diagnostic only \u2014 check whether the index is up-to-date or stale. Skip unless debugging.
|
|
4
|
+
|
|
5
|
+
AFTER THIS: If index is stale, run \`easbot codebase sync\` from CLI; \`doctor\` for deeper health check.
|
|
6
|
+
|
|
7
|
+
NOTES: Read-only. Output is a structured markdown summary.`,doctor:`Run health checks: db connection, FTS availability, parser status, node/edge counts.
|
|
8
|
+
|
|
9
|
+
WHEN TO USE: Diagnostic only \u2014 check why queries return empty or fail. Skip unless debugging.
|
|
10
|
+
|
|
11
|
+
AFTER THIS: If unhealthy, fix the reported issue (usually run \`easbot codebase index\` from CLI).
|
|
12
|
+
|
|
13
|
+
NOTES: Read-only. Returns healthy/unhealthy + a list of issues.`};function i(n,s=false){return {content:[{type:"text",text:n}],...s&&{isError:true}}}function u(n){return {workspaceDir:n.getWorkspaceDir?.()??process.cwd(),rootDir:n.getWorkspaceDir?.()??process.cwd()}}function m(n,s,a){if(n instanceof chunkTGCR6O3S_cjs.b)return `**${s}** \u2014 node not found. Try \`query\` first to discover the symbol.`;if(n instanceof chunkTGCR6O3S_cjs.c){let l=n.details?.candidates??[],e=l.slice(0,5).map(t=>`- \`${t.node.name}\` in \`${t.node.file_path}\``).join(`
|
|
14
|
+
`);return `**${s}** \u2014 ambiguous name. Specify \`file\` to disambiguate:
|
|
15
|
+
|
|
16
|
+
${e}
|
|
17
|
+
|
|
18
|
+
... and ${l.length-5} more candidates.`}return mcp.formatFailClosed(n,a)}function se(n,s){return async(a,l)=>{let e=a;try{let t=u(n),o=await chunkTGCR6O3S_cjs.d(t,{query:e.query,kind:e.kind,file:e.file,intent:e.intent,includeContent:e.includeContent??!1,maxResults:e.maxResults??10,language:e.language,astType:e.astType,maxEdgesPerNode:e.maxEdgesPerNode??10}),r=await chunkTGCR6O3S_cjs.A(o.hits,{pendingFiles:[],toolName:"query",writeToDisk:!1});return i(r)}catch(t){return i(m(t,"query",s),true)}}}function re(n,s){return async(a,l)=>{let e=a;try{let t=u(n),o=await chunkTGCR6O3S_cjs.e(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,includeEdges:e.includeEdges??!0,includeContent:e.includeContent??!0,maxEdgesPerNode:e.maxEdgesPerNode??10}),r=await chunkTGCR6O3S_cjs.G(o.node,o.edges,{pendingFiles:[],toolName:"node",writeToDisk:!1});return i(r)}catch(t){return i(m(t,"node",s),true)}}}function ae(n,s){return async(a,l)=>{let e=a;try{let t=u(n),o=await chunkTGCR6O3S_cjs.f(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,depth:e.depth??2,maxNodes:e.maxNodes??100,direction:e.direction??"both",maxEdgesPerNode:e.maxEdgesPerNode??10});if(!o.root)return i("**context** \u2014 node not found.");let r=[],p=[];for(let c of o.edges)c.target===o.root.id?r.push(c):p.push(c);let g=await chunkTGCR6O3S_cjs.C(o.root,r,p,o.nodes.map(c=>c.node),{pendingFiles:[],toolName:"context",writeToDisk:!1});return i(g)}catch(t){return i(m(t,"context",s),true)}}}function ie(n,s){return async(a,l)=>{let e=a;try{let t=u(n),o=await chunkTGCR6O3S_cjs.g(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,depth:e.depth??2,maxResults:e.maxResults??10,maxEdgesPerNode:e.maxEdgesPerNode??10});if(!o.root)return i("**impact** \u2014 node not found.");let r=[],p=n.getDatabase();for(let c of o.buckets)for(let y of c.sample){let b=p.getNodeById(y.id);b&&r.push({source:b,relation:y.relation});}let g=await chunkTGCR6O3S_cjs.B(o.root,r,{pendingFiles:[],toolName:"impact",writeToDisk:!1});return i(g)}catch(t){return i(m(t,"impact",s),true)}}}function de(n,s){return async(a,l)=>{let e=a;try{let t=u(n),o=await chunkTGCR6O3S_cjs.h(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,maxResults:e.maxResults??10,maxEdgesPerNode:e.maxEdgesPerNode??10}),r=await chunkTGCR6O3S_cjs.D(o,{toolName:"codebase_callers"});return i(r)}catch(t){return i(m(t,"callers",s),true)}}}function le(n,s){return async(a,l)=>{let e=a;try{let t=u(n),o=await chunkTGCR6O3S_cjs.i(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,maxResults:e.maxResults??10,maxEdgesPerNode:e.maxEdgesPerNode??10}),r=await chunkTGCR6O3S_cjs.E(o,{toolName:"codebase_callees"});return i(r)}catch(t){return i(m(t,"callees",s),true)}}}function ce(n,s){return async(a,l)=>{let e=a;try{let t=u(n),o=await chunkTGCR6O3S_cjs.j(t,{query:e.query,file:e.file,kind:e.kind,maxFiles:e.maxFiles??5,maxSymbols:e.maxSymbols??3,maxEdgesPerNode:e.maxEdgesPerNode??10,depth:e.depth??1,includeContent:e.includeContent??!0,intent:e.intent}),r=await chunkTGCR6O3S_cjs.H(o,{pendingFiles:[],toolName:"explore",writeToDisk:!1});return i(r)}catch(t){return i(m(t,"explore",s),true)}}}function ue(n,s){return async(a,l)=>{try{let e=u(n),t=await chunkTGCR6O3S_cjs.k(e,{}),o=await chunkTGCR6O3S_cjs.F(t,{toolName:"codebase_status"});return i(o)}catch(e){return i(m(e,"status",s),true)}}}function me(n,s){return async(a,l)=>{try{let e=u(n),t=await chunkTGCR6O3S_cjs.l(e,{}),o=await chunkTGCR6O3S_cjs.k(e,{}),r=`**Codebase Health Check**
|
|
19
|
+
|
|
20
|
+
- Healthy: ${t.healthy?"\u2713 yes":"\u2717 no"}
|
|
21
|
+
- Nodes: ${o.nodeCount}
|
|
22
|
+
- Edges: ${o.edgeCount}
|
|
23
|
+
- Indexed files: ${o.indexedFiles}
|
|
24
|
+
- DB path: \`${o.dbPath}\`
|
|
25
|
+
- FTS available: ${t.ftsAvailable}
|
|
26
|
+
|
|
27
|
+
${t.issues.length>0?`**Issues:**
|
|
28
|
+
${t.issues.map(p=>`- ${p}`).join(`
|
|
29
|
+
`)}
|
|
30
|
+
`:""}> ${t.healthy?"Index is healthy. Use `query` to search.":"Index has issues. Check status details above."}`;return i(r)}catch(e){return i(m(e,"doctor",s),true)}}}function pe(n,s,a){let l=[{name:"query",schema:K,factory:se},{name:"node",schema:V,factory:re},{name:"context",schema:J,factory:ae},{name:"impact",schema:Z,factory:ie},{name:"callers",schema:ee,factory:de},{name:"callees",schema:te,factory:le},{name:"explore",schema:ne,factory:ce},{name:"status",schema:$,factory:ue},{name:"doctor",schema:$,factory:me}];for(let e of l)n.register({name:e.name,description:oe[e.name]??"",inputSchema:e.schema,annotations:z,handler:e.factory(s,a)});}
|
package/dist/cli.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';var chunkM2YU5LAI_cjs=require('./chunks/chunk-M2YU5LAI.cjs'),fs=require('fs'),path=require('path'),url=require('url');var G=path.dirname(url.fileURLToPath(chunkM2YU5LAI_cjs.b));function y(){try{let e=path.join(G,"..","package.json");return JSON.parse(fs.readFileSync(e,"utf-8")).version??"0.0.0"}catch{return "0.0.0"}}var d=new Set(["DEBUG","INFO","WARN","ERROR"]);function E(e){let n={logLevel:"INFO",printLogs:false,debug:false};for(let s=0;s<e.length;s++){let t=e[s];if(t)if(t==="--cwd"&&s+1<e.length){let o=e[s+1];o&&!o.startsWith("-")&&(n.cwd=o,s++);}else if(t.startsWith("--cwd="))n.cwd=t.slice(6);else if(t==="--config"&&s+1<e.length){let o=e[s+1];o&&!o.startsWith("-")&&(n.configPath=o,s++);}else if(t.startsWith("--config="))n.configPath=t.slice(9);else if(t==="--log-level"&&s+1<e.length){let o=e[s+1];if(o&&!o.startsWith("-")){let a=o.toUpperCase();d.has(a)&&(n.logLevel=a,s++);}}else if(t.startsWith("--log-level=")){let o=t.slice(12).toUpperCase();d.has(o)&&(n.logLevel=o);}else t==="--print-logs"?n.printLogs=true:t==="--debug"&&(n.debug=true);}return n}async function A(){let e=process.argv.slice(2),n=y(),{loadEnv:s}=await import('@easbot/utils');s(),process.env.EASBOT_LANG||(process.env.EASBOT_LANG="en-US");let t=E(e),{Log:o}=await import('@easbot/utils'),{getXdgData:a}=await import('./chunks/interfaces-YX56SVRQ.cjs'),h=path.join(a(),"log");if(await o.init({logDir:h,print:t.printLogs,dev:t.debug||false,level:t.logLevel}),e.length===0){let{renderBanner:l}=await import('./chunks/cli-handler-
|
|
2
|
+
'use strict';var chunkM2YU5LAI_cjs=require('./chunks/chunk-M2YU5LAI.cjs'),fs=require('fs'),path=require('path'),url=require('url');var G=path.dirname(url.fileURLToPath(chunkM2YU5LAI_cjs.b));function y(){try{let e=path.join(G,"..","package.json");return JSON.parse(fs.readFileSync(e,"utf-8")).version??"0.0.0"}catch{return "0.0.0"}}var d=new Set(["DEBUG","INFO","WARN","ERROR"]);function E(e){let n={logLevel:"INFO",printLogs:false,debug:false};for(let s=0;s<e.length;s++){let t=e[s];if(t)if(t==="--cwd"&&s+1<e.length){let o=e[s+1];o&&!o.startsWith("-")&&(n.cwd=o,s++);}else if(t.startsWith("--cwd="))n.cwd=t.slice(6);else if(t==="--config"&&s+1<e.length){let o=e[s+1];o&&!o.startsWith("-")&&(n.configPath=o,s++);}else if(t.startsWith("--config="))n.configPath=t.slice(9);else if(t==="--log-level"&&s+1<e.length){let o=e[s+1];if(o&&!o.startsWith("-")){let a=o.toUpperCase();d.has(a)&&(n.logLevel=a,s++);}}else if(t.startsWith("--log-level=")){let o=t.slice(12).toUpperCase();d.has(o)&&(n.logLevel=o);}else t==="--print-logs"?n.printLogs=true:t==="--debug"&&(n.debug=true);}return n}async function A(){let e=process.argv.slice(2),n=y(),{loadEnv:s}=await import('@easbot/utils');s(),process.env.EASBOT_LANG||(process.env.EASBOT_LANG="en-US");let t=E(e),{Log:o}=await import('@easbot/utils'),{getXdgData:a}=await import('./chunks/interfaces-YX56SVRQ.cjs'),h=path.join(a(),"log");if(await o.init({logDir:h,print:t.printLogs,dev:t.debug||false,level:t.logLevel}),e.length===0){let{renderBanner:l}=await import('./chunks/cli-handler-FQ7LQDAN.cjs');l();return}if(e[0]==="--help"||e[0]==="-h"){let{renderHelp:l}=await import('./chunks/cli-handler-FQ7LQDAN.cjs');l();return}if(e[0]==="--version"||e[0]==="-v"){console.log(n);return}let r=t.cwd??process.cwd(),{handleCodebaseCli:m}=await import('./chunks/cli-handler-FQ7LQDAN.cjs'),{setInstanceAdapter:w}=await import('./chunks/interfaces-YX56SVRQ.cjs');w({directory:r,worktree:r});let{Llm:b}=await import('./chunks/llm-BDMNIGOH.cjs'),{bootstrapLlm:u,setAdapterRegistry:L}=await import('@easbot/llm'),{getGlobal:i,getInstance:c}=await import('./chunks/interfaces-YX56SVRQ.cjs');L({config:void 0,instance:{getDirectory:()=>c().directory,getWorktree:()=>c().worktree},global:{home:i().Path.home,data:i().Path.data,cache:i().Path.cache,config:i().Path.config,state:i().Path.state,log:i().Path.log,bin:i().Path.bin},installation:{getVersion:()=>n,getChannel:()=>"local",getUserAgent:()=>`easbot-codebase/${n}`}}),await u({target:b,cwd:r,subConfigPath:".easbot/codebase.json",embedding:true});let g=await m(e,{version:n,cwd:r});g.code!==0&&(process.exitCode=g.code);}A().catch(e=>{console.error(e),process.exitCode=1;}).finally(async()=>{try{let{Log:e}=await import('@easbot/utils');await e.close();}catch{}process.exit(process.exitCode??0);});
|
package/dist/cli.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import'./chunks/chunk-2YMB6W5S.mjs';import {readFileSync}from'fs';import {dirname,join}from'path';import {fileURLToPath}from'url';var P=dirname(fileURLToPath(import.meta.url));function G(){try{let e=join(P,"..","package.json");return JSON.parse(readFileSync(e,"utf-8")).version??"0.0.0"}catch{return "0.0.0"}}var p=new Set(["DEBUG","INFO","WARN","ERROR"]);function y(e){let n={logLevel:"INFO",printLogs:false,debug:false};for(let s=0;s<e.length;s++){let t=e[s];if(t)if(t==="--cwd"&&s+1<e.length){let o=e[s+1];o&&!o.startsWith("-")&&(n.cwd=o,s++);}else if(t.startsWith("--cwd="))n.cwd=t.slice(6);else if(t==="--config"&&s+1<e.length){let o=e[s+1];o&&!o.startsWith("-")&&(n.configPath=o,s++);}else if(t.startsWith("--config="))n.configPath=t.slice(9);else if(t==="--log-level"&&s+1<e.length){let o=e[s+1];if(o&&!o.startsWith("-")){let a=o.toUpperCase();p.has(a)&&(n.logLevel=a,s++);}}else if(t.startsWith("--log-level=")){let o=t.slice(12).toUpperCase();p.has(o)&&(n.logLevel=o);}else t==="--print-logs"?n.printLogs=true:t==="--debug"&&(n.debug=true);}return n}async function E(){let e=process.argv.slice(2),n=G(),{loadEnv:s}=await import('@easbot/utils');s(),process.env.EASBOT_LANG||(process.env.EASBOT_LANG="en-US");let t=y(e),{Log:o}=await import('@easbot/utils'),{getXdgData:a}=await import('./chunks/interfaces-DPFLQBQ6.mjs'),f=join(a(),"log");if(await o.init({logDir:f,print:t.printLogs,dev:t.debug||false,level:t.logLevel}),e.length===0){let{renderBanner:l}=await import('./chunks/cli-handler-
|
|
2
|
+
import'./chunks/chunk-2YMB6W5S.mjs';import {readFileSync}from'fs';import {dirname,join}from'path';import {fileURLToPath}from'url';var P=dirname(fileURLToPath(import.meta.url));function G(){try{let e=join(P,"..","package.json");return JSON.parse(readFileSync(e,"utf-8")).version??"0.0.0"}catch{return "0.0.0"}}var p=new Set(["DEBUG","INFO","WARN","ERROR"]);function y(e){let n={logLevel:"INFO",printLogs:false,debug:false};for(let s=0;s<e.length;s++){let t=e[s];if(t)if(t==="--cwd"&&s+1<e.length){let o=e[s+1];o&&!o.startsWith("-")&&(n.cwd=o,s++);}else if(t.startsWith("--cwd="))n.cwd=t.slice(6);else if(t==="--config"&&s+1<e.length){let o=e[s+1];o&&!o.startsWith("-")&&(n.configPath=o,s++);}else if(t.startsWith("--config="))n.configPath=t.slice(9);else if(t==="--log-level"&&s+1<e.length){let o=e[s+1];if(o&&!o.startsWith("-")){let a=o.toUpperCase();p.has(a)&&(n.logLevel=a,s++);}}else if(t.startsWith("--log-level=")){let o=t.slice(12).toUpperCase();p.has(o)&&(n.logLevel=o);}else t==="--print-logs"?n.printLogs=true:t==="--debug"&&(n.debug=true);}return n}async function E(){let e=process.argv.slice(2),n=G(),{loadEnv:s}=await import('@easbot/utils');s(),process.env.EASBOT_LANG||(process.env.EASBOT_LANG="en-US");let t=y(e),{Log:o}=await import('@easbot/utils'),{getXdgData:a}=await import('./chunks/interfaces-DPFLQBQ6.mjs'),f=join(a(),"log");if(await o.init({logDir:f,print:t.printLogs,dev:t.debug||false,level:t.logLevel}),e.length===0){let{renderBanner:l}=await import('./chunks/cli-handler-Z6VGOAMV.mjs');l();return}if(e[0]==="--help"||e[0]==="-h"){let{renderHelp:l}=await import('./chunks/cli-handler-Z6VGOAMV.mjs');l();return}if(e[0]==="--version"||e[0]==="-v"){console.log(n);return}let r=t.cwd??process.cwd(),{handleCodebaseCli:h}=await import('./chunks/cli-handler-Z6VGOAMV.mjs'),{setInstanceAdapter:m}=await import('./chunks/interfaces-DPFLQBQ6.mjs');m({directory:r,worktree:r});let{Llm:w}=await import('./chunks/llm-ADBGTSCV.mjs'),{bootstrapLlm:b,setAdapterRegistry:u}=await import('@easbot/llm'),{getGlobal:i,getInstance:c}=await import('./chunks/interfaces-DPFLQBQ6.mjs');u({config:void 0,instance:{getDirectory:()=>c().directory,getWorktree:()=>c().worktree},global:{home:i().Path.home,data:i().Path.data,cache:i().Path.cache,config:i().Path.config,state:i().Path.state,log:i().Path.log,bin:i().Path.bin},installation:{getVersion:()=>n,getChannel:()=>"local",getUserAgent:()=>`easbot-codebase/${n}`}}),await b({target:w,cwd:r,subConfigPath:".easbot/codebase.json",embedding:true});let g=await h(e,{version:n,cwd:r});g.code!==0&&(process.exitCode=g.code);}E().catch(e=>{console.error(e),process.exitCode=1;}).finally(async()=>{try{let{Log:e}=await import('@easbot/utils');await e.close();}catch{}process.exit(process.exitCode??0);});
|