@easbot/codebase 0.3.2 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -0
- package/dist/chunks/chunk-3ZA3AOKC.mjs +58 -0
- package/dist/chunks/chunk-7XCIIOM6.cjs +1 -0
- package/dist/chunks/chunk-AUNBGHMC.cjs +58 -0
- package/dist/chunks/chunk-CJSKATXN.mjs +2 -0
- package/dist/chunks/chunk-EVDJNYI2.cjs +1 -0
- package/dist/chunks/chunk-G3IYU6TZ.mjs +1 -0
- package/dist/chunks/chunk-IXERCMYQ.cjs +2 -0
- package/dist/chunks/chunk-JDULI4R5.cjs +234 -0
- package/dist/chunks/chunk-RLZHDTHY.cjs +154 -0
- package/dist/chunks/chunk-TGMIUXU3.mjs +34 -0
- package/dist/chunks/chunk-TS4OAYIJ.cjs +1 -0
- package/dist/chunks/chunk-UEILXBZB.mjs +1 -0
- package/dist/chunks/chunk-UTKA3WG3.mjs +1 -0
- package/dist/chunks/chunk-VBIXWHTD.mjs +234 -0
- package/dist/chunks/chunk-XAODNPHT.cjs +34 -0
- package/dist/chunks/chunk-Z4Y3VCYS.mjs +154 -0
- package/dist/chunks/code-base-HCFLEKJN.cjs +1 -0
- package/dist/chunks/code-base-N3PTDWLC.mjs +1 -0
- package/dist/chunks/database-manager-DRLNOQ6C.cjs +1 -0
- package/dist/chunks/database-manager-WOYUSWKD.mjs +1 -0
- package/dist/chunks/file-watcher-5WEDJY6M.mjs +1 -0
- package/dist/chunks/file-watcher-LZZUEGMY.cjs +1 -0
- package/dist/chunks/stdio-server-DIGUR2PS.mjs +47 -0
- package/dist/chunks/stdio-server-LJGVWMB7.cjs +47 -0
- package/dist/chunks/sync-52O2GQKE.cjs +1 -0
- package/dist/chunks/sync-JNCNYSWI.mjs +1 -0
- package/dist/cli.cjs +2 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.mjs +2 -0
- package/dist/index.cjs +1 -108
- package/dist/index.d.cts +497 -21
- package/dist/index.d.ts +497 -21
- package/dist/index.mjs +1 -108
- package/package.json +13 -6
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import {a}from'./chunk-G3IYU6TZ.mjs';import {Log,Filesystem}from'@easbot/utils';import {createSyncSqliteConnection}from'@easbot/database';var F=class o extends Error{constructor(t,s,r){super(t);a(this,"name","ParserError");a(this,"filePath");a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},g=class o extends Error{constructor(t,s,r){super(t);a(this,"name","DatabaseError");a(this,"operation");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);a(this,"name","FileSystemError");a(this,"filePath");a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},u=class o extends Error{constructor(t,s){super(t);a(this,"name","SchemaError");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);a(this,"name","ConfigError");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);a(this,"name","IndexError");a(this,"filePath");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);a(this,"name","QueryError");a(this,"params");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}`);a(this,"name","UnsupportedLanguageError");a(this,"extension");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 D=Log.create({service:"codebase-schema-migrations"}),p=1,V=[{id:1,description:"v1 baseline: nodes / edges / file_hashes / nodes_fts / meta / embedding_cache / node_embeddings + unresolved_refs / name_segment_vocab / project_metadata / parse_errors + \u6027\u80FD index (nodes.file_path / edges.source/target)",up:[`CREATE TABLE IF NOT EXISTS nodes (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
name TEXT NOT NULL,
|
|
4
|
+
ast_type TEXT NOT NULL,
|
|
5
|
+
language TEXT NOT NULL,
|
|
6
|
+
file_path TEXT NOT NULL,
|
|
7
|
+
start_line INTEGER,
|
|
8
|
+
start_col INTEGER,
|
|
9
|
+
end_line INTEGER,
|
|
10
|
+
end_col INTEGER,
|
|
11
|
+
text TEXT,
|
|
12
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
13
|
+
)`,`CREATE TABLE IF NOT EXISTS edges (
|
|
14
|
+
id TEXT PRIMARY KEY,
|
|
15
|
+
source TEXT NOT NULL,
|
|
16
|
+
target TEXT NOT NULL,
|
|
17
|
+
relation TEXT NOT NULL,
|
|
18
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
19
|
+
FOREIGN KEY (source) REFERENCES nodes(id) ON DELETE CASCADE,
|
|
20
|
+
FOREIGN KEY (target) REFERENCES nodes(id) ON DELETE CASCADE
|
|
21
|
+
)`,`CREATE TABLE IF NOT EXISTS file_hashes (
|
|
22
|
+
file_path TEXT PRIMARY KEY,
|
|
23
|
+
content_hash TEXT NOT NULL,
|
|
24
|
+
last_modified DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
25
|
+
)`,`CREATE VIRTUAL TABLE IF NOT EXISTS nodes_fts USING fts5(
|
|
26
|
+
id, name, ast_type, language, file_path, text,
|
|
27
|
+
tokenize='unicode61'
|
|
28
|
+
)`,`CREATE TABLE IF NOT EXISTS meta (
|
|
29
|
+
key TEXT PRIMARY KEY,
|
|
30
|
+
value TEXT
|
|
31
|
+
)`,`CREATE TABLE IF NOT EXISTS embedding_cache (
|
|
32
|
+
content_hash TEXT PRIMARY KEY,
|
|
33
|
+
embedding BLOB NOT NULL
|
|
34
|
+
)`,`CREATE TABLE IF NOT EXISTS node_embeddings (
|
|
35
|
+
node_id TEXT PRIMARY KEY,
|
|
36
|
+
embedding_text TEXT NOT NULL,
|
|
37
|
+
embedding BLOB NOT NULL,
|
|
38
|
+
FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
|
|
39
|
+
)`,`CREATE TABLE IF NOT EXISTS unresolved_refs (
|
|
40
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
41
|
+
from_node_id TEXT,
|
|
42
|
+
reference_name TEXT NOT NULL,
|
|
43
|
+
reference_kind TEXT NOT NULL,
|
|
44
|
+
line INTEGER,
|
|
45
|
+
col INTEGER,
|
|
46
|
+
file_path TEXT NOT NULL,
|
|
47
|
+
language TEXT NOT NULL,
|
|
48
|
+
candidates TEXT,
|
|
49
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
50
|
+
FOREIGN KEY (from_node_id) REFERENCES nodes(id) ON DELETE SET NULL
|
|
51
|
+
)`,"CREATE INDEX IF NOT EXISTS idx_unresolved_refs_file_path ON unresolved_refs(file_path)","CREATE INDEX IF NOT EXISTS idx_unresolved_refs_kind ON unresolved_refs(reference_kind)",`CREATE TABLE IF NOT EXISTS name_segment_vocab (
|
|
52
|
+
segment TEXT NOT NULL,
|
|
53
|
+
name TEXT NOT NULL,
|
|
54
|
+
PRIMARY KEY (segment, name)
|
|
55
|
+
) WITHOUT ROWID`,"CREATE INDEX IF NOT EXISTS idx_name_segment ON name_segment_vocab(segment)",`CREATE TABLE IF NOT EXISTS project_metadata (
|
|
56
|
+
key TEXT PRIMARY KEY,
|
|
57
|
+
value TEXT,
|
|
58
|
+
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
59
|
+
)`,`CREATE TABLE IF NOT EXISTS parse_errors (
|
|
60
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
61
|
+
file_path TEXT NOT NULL,
|
|
62
|
+
language TEXT NOT NULL,
|
|
63
|
+
stage TEXT NOT NULL,
|
|
64
|
+
message TEXT NOT NULL,
|
|
65
|
+
line INTEGER,
|
|
66
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
67
|
+
)`,"CREATE INDEX IF NOT EXISTS idx_parse_errors_file_path ON parse_errors(file_path)","CREATE INDEX IF NOT EXISTS idx_nodes_file_path ON nodes(file_path)","CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)"]}];function X(o,e=p,t={}){o.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
68
|
+
id INTEGER PRIMARY KEY,
|
|
69
|
+
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
70
|
+
)`);let s=o.prepare("SELECT id FROM schema_migrations").all(),r=new Set(s.map(a=>a.id)),n={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(a=>a.id)),targetVersion:e};for(let a of V){if(a.id>e)break;if(r.has(a.id)){n.pending.push(a.id);continue}if(t.dryRun){n.applied.push(a.id);continue}try{o.execBatch([...a.up]),o.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(a.id),r.add(a.id),n.applied.push(a.id),D.info("migration applied",{id:a.id,description:a.description});}catch(i){let c=i instanceof Error?i.message:String(i),T=a.up[0]??"";n.errors.push({migrationId:a.id,sql:T,error:c}),D.warn("migration step failed (may be idempotent)",{id:a.id,error:c,sqlCount:a.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=Filesystem.toUnixPath,E=Log.create({service:"codebase-database"}),m=2,$=class{constructor(e){a(this,"db");a(this,"dbPath");a(this,"closed",false);a(this,"ftsAvailable",false);this.dbPath=e===":memory:"?e:Filesystem.normalize(e),this.db=createSyncSqliteConnection({path:this.dbPath,backend:"better-sqlite3",walMode:true,foreignKeys:true,busyTimeoutMs:5e3}),this.db.initialize();try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("foreign_keys = ON");}catch(t){E.warn("Failed to apply codebase PRAGMAs (synchronous / cache_size / foreign_keys)",{error:String(t)});}try{this.ensureSchema();let t=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{X(this.db,p);let e=[["version","1.0.0"],["createdAt",new Date().toISOString()],["index_state","uninitialized"],["indexed_with_version","unknown"]],t=this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[s,r]of e)t.run(s,r);}catch(e){throw E.error("ensureSchema failed",{message:e instanceof Error?e.message:String(e),cause:e instanceof Error?e.cause:void 0,stack:e instanceof Error?e.stack:void 0}),new u("Failed to create database schema",e instanceof Error?[e.message]:[String(e)])}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:l(e.file_path)};this.db.prepare(`
|
|
71
|
+
INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
|
|
72
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
73
|
+
`).run(t.id,t.name,t.ast_type,t.language,t.file_path,t.start_line,t.start_col,t.end_line,t.end_col,t.text,t.created_at),this.ftsAvailable&&this.updateFtsNode(t);}insertNodes(e){if(e.length===0)return;let t=e.map(n=>({...n,file_path:l(n.file_path)})),s=this.db.prepare(`
|
|
74
|
+
INSERT OR REPLACE INTO nodes (id, name, ast_type, language, file_path, start_line, start_col, end_line, end_col, text, created_at)
|
|
75
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
76
|
+
`);this.db.transaction(n=>{for(let a of n)s.run(a.id,a.name,a.ast_type,a.language,a.file_path,a.start_line,a.start_col,a.end_line,a.end_col,a.text,a.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(n);})(t);}updateFtsNodesInternal(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),r=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");for(let n of e)try{let a=s.get(n.id);a&&t.run(a.rowid),r.run(n.id,n.name,n.ast_type,n.language,n.file_path,n.text);}catch(a){E.warn("FTS update failed for node",{nodeId:n.id,error:String(a)});}}updateFtsNode(e){try{let t=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?").get(e.id);t&&this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(t.rowid),this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.ast_type,e.language,e.file_path,e.text);}catch(t){E.warn("FTS update failed for node",{nodeId:e.id,error:String(t)});}}updateFtsNodes(e){let t=this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?"),s=this.db.prepare("SELECT rowid FROM nodes_fts WHERE id = ?"),r=this.db.prepare("INSERT INTO nodes_fts(id, name, ast_type, language, file_path, text) VALUES (?, ?, ?, ?, ?, ?)");this.db.transaction(a=>{for(let i of a)try{let c=s.get(i.id);c&&t.run(c.rowid),r.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.text);}catch(c){E.warn("FTS update failed for node",{nodeId:i.id,error:String(c)});}})(e);}insertEdge(e){this.db.prepare(`
|
|
77
|
+
INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
|
|
78
|
+
VALUES (?, ?, ?, ?, ?)
|
|
79
|
+
`).run(e.id,e.source,e.target,e.relation,e.created_at);}insertEdges(e){if(e.length===0)return;let t=this.db.prepare(`
|
|
80
|
+
INSERT OR REPLACE INTO edges (id, source, target, relation, created_at)
|
|
81
|
+
VALUES (?, ?, ?, ?, ?)
|
|
82
|
+
`);this.db.transaction(r=>{for(let n of r)t.run(n.id,n.source,n.target,n.relation,n.created_at);})(e);}queryNodes(e){let t=[],s=[];e.filePath&&(t.push("file_path LIKE ?"),s.push(`%${l(e.filePath)}%`)),e.astType&&(t.push("ast_type = ?"),s.push(e.astType)),e.name&&(t.push("name = ?"),s.push(e.name)),e.language&&(t.push("language = ?"),s.push(e.language));let r="SELECT * FROM nodes";t.length>0&&(r+=` WHERE ${t.join(" AND ")}`),r+=" ORDER BY file_path, start_line",e.limit&&(r+=" LIMIT ?",s.push(e.limit)),e.offset&&(r+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(r).all(...s)}catch(n){throw new g("Failed to query nodes","queryNodes",n instanceof Error?n:new Error(String(n)))}}queryEdges(e){let t=[],s=[];if(e.sourceOrTarget&&e.sourceOrTarget.length>0){let n=e.sourceOrTarget.map(()=>"?").join(",");t.push(`(source IN (${n}) OR target IN (${n}))`),s.push(...e.sourceOrTarget,...e.sourceOrTarget);}else e.source&&(t.push("source = ?"),s.push(e.source)),e.target&&(t.push("target = ?"),s.push(e.target));e.relation&&(t.push("relation = ?"),s.push(e.relation));let r="SELECT * FROM edges";t.length>0&&(r+=` WHERE ${t.join(" AND ")}`),r+=" ORDER BY created_at DESC",e.limit&&(r+=" LIMIT ?",s.push(e.limit)),e.offset&&(r+=" OFFSET ?",s.push(e.offset));try{return this.db.prepare(r).all(...s)}catch(n){throw new g("Failed to query edges","queryEdges",n instanceof Error?n:new Error(String(n)))}}queryAll(e,t){try{let s=this.db.prepare(e);return t?s.all(...t):s.all()}catch(s){throw new g("Failed to execute query","queryAll",s instanceof Error?s:new Error(String(s)))}}searchNodesFts(e,t=20){if(E.debug("searchNodesFts start",{query:e,limit:t,ftsAvailable:this.ftsAvailable}),!this.ftsAvailable)return E.debug("searchNodesFts skip - FTS not available"),[];try{let s=e.split(/\s+/).map(i=>`${i}*`).join(" ");E.debug("searchNodesFts query",{ftsQuery:s});let a=this.db.prepare(`
|
|
83
|
+
SELECT
|
|
84
|
+
nodes_fts.id,
|
|
85
|
+
nodes_fts.name,
|
|
86
|
+
nodes_fts.ast_type,
|
|
87
|
+
nodes_fts.language,
|
|
88
|
+
nodes_fts.file_path,
|
|
89
|
+
nodes_fts.text,
|
|
90
|
+
nodes.start_line,
|
|
91
|
+
nodes.start_col,
|
|
92
|
+
nodes.end_line,
|
|
93
|
+
nodes.end_col,
|
|
94
|
+
bm25(nodes_fts) as score
|
|
95
|
+
FROM nodes_fts
|
|
96
|
+
JOIN nodes ON nodes.id = nodes_fts.id
|
|
97
|
+
WHERE nodes_fts.text MATCH ?
|
|
98
|
+
ORDER BY score DESC
|
|
99
|
+
LIMIT ?
|
|
100
|
+
`).all(s,t);return E.debug("searchNodesFts done",{resultCount:a.length}),a}catch(s){return E.warn("searchNodesFts failed",{error:String(s)}),[]}}deleteNodesByFile(e){let t=l(e);if(this.ftsAvailable)try{let r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let n of r)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(n.rowid);}catch(r){E.warn("FTS delete failed for file",{filePath:t,error:String(r)});}return this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(t).changes}deleteEdgesByFile(e){let t=l(e);return this.db.prepare(`
|
|
101
|
+
DELETE FROM edges
|
|
102
|
+
WHERE source IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
103
|
+
OR target IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
104
|
+
`).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(l(e))?.content_hash??null}setFileHash(e,t){this.db.prepare(`
|
|
105
|
+
INSERT OR REPLACE INTO file_hashes (file_path, content_hash, last_modified)
|
|
106
|
+
VALUES (?, ?, ?)
|
|
107
|
+
`).run(l(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(l(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}checkIntegrity(){let e=h=>this.db.prepare(h).get().c,t=h=>e(h),s={nodes:t("SELECT COUNT(*) as c FROM nodes"),edges:t("SELECT COUNT(*) as c FROM edges"),file_hashes:t("SELECT COUNT(*) as c FROM file_hashes"),fts:t("SELECT COUNT(*) as c FROM nodes_fts"),node_embeddings:t("SELECT COUNT(*) as c FROM node_embeddings"),embedding_cache:t("SELECT COUNT(*) as c FROM embedding_cache"),parse_errors:t("SELECT COUNT(*) as c FROM parse_errors"),unresolved_refs:t("SELECT COUNT(*) as c FROM unresolved_refs"),name_segment_vocab:t("SELECT COUNT(*) as c FROM name_segment_vocab"),project_metadata:t("SELECT COUNT(*) as c FROM project_metadata"),meta:t("SELECT COUNT(*) as c FROM meta")},r=[],n=t(`
|
|
108
|
+
SELECT COUNT(*) as c FROM node_embeddings e
|
|
109
|
+
LEFT JOIN nodes n ON n.id = e.node_id WHERE n.id IS NULL
|
|
110
|
+
`);n>0&&r.push({severity:"error",message:`orphan node_embeddings: ${n}`});let a=t(`
|
|
111
|
+
SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.source)
|
|
112
|
+
`);a>0&&r.push({severity:"error",message:`orphan edges (source): ${a}`});let i=t(`
|
|
113
|
+
SELECT COUNT(*) as c FROM edges e WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.id = e.target)
|
|
114
|
+
`);i>0&&r.push({severity:"error",message:`orphan edges (target): ${i}`});let c=t("SELECT COUNT(*) as c FROM edges WHERE source = target");c>0&&r.push({severity:"error",message:`self-loop edges: ${c} \u2014 re-run \`easbot codebase sync\` to filter (fixed in Wave 4 R3-2)`});t("SELECT COUNT(DISTINCT file_path) as c FROM nodes");let f=t(`
|
|
115
|
+
SELECT COUNT(*) as c FROM file_hashes fh
|
|
116
|
+
WHERE NOT EXISTS (SELECT 1 FROM nodes n WHERE n.file_path = fh.file_path)
|
|
117
|
+
`);f>0&&r.push({severity:"warn",message:`orphan file_hashes (no nodes): ${f} \u2014 run \`easbot codebase sync\` to cleanup`});let _=t(`
|
|
118
|
+
SELECT COUNT(DISTINCT n.file_path) as c FROM nodes n
|
|
119
|
+
WHERE NOT EXISTS (SELECT 1 FROM file_hashes fh WHERE fh.file_path = n.file_path)
|
|
120
|
+
`);_>0&&r.push({severity:"warn",message:`node files without hash: ${_}`});let R=t("SELECT COUNT(*) as c FROM nodes WHERE name IS NULL OR name = ''");R>0&&r.push({severity:"error",message:`nodes with null/empty name: ${R}`});let S=t("SELECT COUNT(*) as c FROM nodes WHERE ast_type IS NULL OR ast_type = ''");S>0&&r.push({severity:"error",message:`nodes with null/empty ast_type: ${S}`});let b=t("SELECT COUNT(*) as c FROM nodes WHERE language IS NULL OR language = ''");b>0&&r.push({severity:"error",message:`nodes with null/empty language: ${b}`});let N=t("SELECT COUNT(*) as c FROM nodes WHERE file_path IS NULL OR file_path = ''");N>0&&r.push({severity:"error",message:`nodes with null/empty file_path: ${N}`});let O=this.db.prepare("SELECT id, COUNT(*) as c FROM nodes GROUP BY id HAVING c > 1").all().length;O>0&&r.push({severity:"error",message:`duplicate node ids: ${O}`});let I=t("SELECT COUNT(*) as c FROM nodes WHERE file_path LIKE '%\\\\%'");I>0&&r.push({severity:"warn",message:`nodes with backslash in file_path: ${I}`});let L=t(`
|
|
121
|
+
SELECT COUNT(*) as c FROM nodes
|
|
122
|
+
WHERE start_line IS NOT NULL AND end_line IS NOT NULL AND start_line > end_line
|
|
123
|
+
`);L>0&&r.push({severity:"error",message:`invalid line ranges: ${L}`});let y=this.db.prepare("SELECT id, COUNT(*) as c FROM edges GROUP BY id HAVING c > 1").all().length;y>0&&r.push({severity:"error",message:`duplicate edge ids: ${y}`});let C=t("SELECT COUNT(*) as c FROM nodes_fts_content");return C!==s.nodes&&r.push({severity:"error",message:`FTS content desync: ${C} vs ${s.nodes} (run \`easbot codebase recreate\` to rebuild)`}),s.parse_errors>100&&r.push({severity:"warn",message:`parse_errors > 100 (${s.parse_errors}) \u2014\u2014 many files failed to parse`}),{issues:r,stats:s}}getStatus(){let e=this.db.prepare("SELECT COUNT(*) as c FROM nodes").get(),t=this.db.prepare("SELECT COUNT(*) as c FROM edges").get(),s=this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get(),r=this.db.prepare("SELECT key, value FROM meta").all(),n={};for(let a of r)n[a.key]=a.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:s?.c??0,dbPath:this.dbPath,meta:n,indexState:this.getIndexState(),extractionVersion:parseInt(this.getMeta("indexed_with_extraction_version")??"0",10),isStale:this.isIndexStale()}}setLastSync(){this.db.prepare(`
|
|
124
|
+
INSERT OR REPLACE INTO meta (key, value)
|
|
125
|
+
VALUES ('lastSync', ?)
|
|
126
|
+
`).run(new Date().toISOString());}getIndexState(){return this.getMeta("index_state")??"uninitialized"}setIndexState(e){this.setMeta("index_state",e),this.setMeta("last_index_state_change",new Date().toISOString());}markIndexed(e){this.setMeta("indexed_with_version",e),this.setMeta("indexed_with_extraction_version",String(m)),this.setMeta("index_state","complete"),this.setMeta("last_index_state_change",new Date().toISOString());}isIndexStale(){let e=this.getMeta("indexed_with_extraction_version");if(!e)return false;let t=parseInt(e,10);return Number.isNaN(t)||t<m}detectAndMarkStaleOnInit(){if(this.isIndexStale()){let e=this.getMeta("indexed_with_extraction_version");E.warn("codebase db is stale",{recorded:e??"(none)",current:String(m),hint:"run `easbot codebase recreate` or `easbot codebase index --force` to rebuild"});let t=this.getIndexState();(t==="complete"||t==="partial")&&this.setIndexState("stale");}}getNodeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM nodes").get()?.c??0}getEdgeCount(){return this.db.prepare("SELECT COUNT(*) as c FROM edges").get()?.c??0}getFileCount(){return this.db.prepare("SELECT COUNT(*) as c FROM file_hashes").get()?.c??0}getNodeById(e){return this.db.prepare("SELECT * FROM nodes WHERE id = ?").get(e)??null}getEdgeById(e){return this.db.prepare("SELECT * FROM edges WHERE id = ?").get(e)??null}clearAll(e={}){this.db.exec("DELETE FROM nodes"),this.db.exec("DELETE FROM edges"),this.db.exec("DELETE FROM file_hashes"),this.db.exec("DELETE FROM meta"),e.keepEmbeddings||(this.db.exec("DELETE FROM node_embeddings"),this.db.exec("DELETE FROM embedding_cache")),this.ftsAvailable&&this.db.exec("DELETE FROM nodes_fts");try{this.db.exec("DELETE FROM sqlite_sequence WHERE name IN ('nodes', 'edges', 'file_hashes', 'meta')");}catch{}}getCachedEmbedding(e){let s=this.db.prepare(`
|
|
127
|
+
SELECT embedding FROM embedding_cache WHERE content_hash = ?
|
|
128
|
+
`).get(e);return s?new Float32Array(s.embedding.buffer,s.embedding.byteOffset,s.embedding.length/4):null}getVectorDims(){let e=this.db.prepare("SELECT value FROM meta WHERE key = ?").get("vectorDims");return e?parseInt(e.value,10):void 0}ensureVectorDims(e){this.db.prepare("SELECT value FROM meta WHERE key = ?").get("vectorDims")||this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)").run("vectorDims",String(e));}cacheEmbedding(e,t){if(this.db.prepare("SELECT embedding FROM embedding_cache WHERE content_hash = ?").get(e))return;this.ensureVectorDims(t.length),this.db.prepare(`
|
|
129
|
+
INSERT OR REPLACE INTO embedding_cache (content_hash, embedding)
|
|
130
|
+
VALUES (?, ?)
|
|
131
|
+
`).run(e,t);}deleteEmbeddingsByFile(e){let t=l(e);return this.db.prepare(`
|
|
132
|
+
DELETE FROM node_embeddings WHERE node_id IN (SELECT id FROM nodes WHERE file_path = ?)
|
|
133
|
+
`).run(t).changes}getAllNodeEmbeddings(){return this.db.prepare("SELECT node_id, embedding FROM node_embeddings").all()}storeNodeEmbeddings(e){if(e.length===0)return;this.ensureVectorDims(e[0].embedding.length);let t=this.db.prepare(`
|
|
134
|
+
INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
|
|
135
|
+
VALUES (?, ?, ?)
|
|
136
|
+
`);this.db.transaction(r=>{for(let n of r)try{t.run(n.nodeId,n.embeddingText,n.embedding);}catch(a){E.warn("Failed to store embedding for node",{nodeId:n.nodeId,error:String(a)});}})(e);}insertParseError(e){return this.db.prepare(`
|
|
137
|
+
INSERT INTO parse_errors (file_path, language, stage, message, line)
|
|
138
|
+
VALUES (?, ?, ?, ?, ?)
|
|
139
|
+
`).run(e.filePath.replace(/\\/g,"/"),e.language,e.stage,e.message,e.line??null).changes}insertUnresolvedRef(e){return this.db.prepare(`
|
|
140
|
+
INSERT INTO unresolved_refs
|
|
141
|
+
(from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
|
|
142
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
143
|
+
`).run(e.fromNodeId??null,e.referenceName,e.referenceKind,e.line??null,e.col??null,e.filePath.replace(/\\/g,"/"),e.language,e.candidates?JSON.stringify(e.candidates):null).changes}insertUnresolvedRefsBatch(e){if(e.length===0)return 0;let s=`
|
|
144
|
+
INSERT INTO unresolved_refs
|
|
145
|
+
(from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
|
|
146
|
+
VALUES ${e.map(()=>"(?, ?, ?, ?, ?, ?, ?, ?)").join(", ")}
|
|
147
|
+
`,r=[];for(let i of e)r.push(i.fromNodeId??null,i.referenceName,i.referenceKind,i.line??null,i.col??null,i.filePath.replace(/\\/g,"/"),i.language,i.candidates?JSON.stringify(i.candidates):null);return this.db.prepare(s).run(...r).changes}insertNameSegment(e,t){return this.db.prepare(`
|
|
148
|
+
INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES (?, ?)
|
|
149
|
+
`).run(e,t).changes}insertNameSegmentsBatch(e){if(e.length===0)return 0;let s=`
|
|
150
|
+
INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES ${e.map(()=>"(?, ?)").join(", ")}
|
|
151
|
+
`,r=[];for(let i of e)r.push(i.segment,i.name);return this.db.prepare(s).run(...r).changes}setProjectMetadata(e,t){return this.db.prepare(`
|
|
152
|
+
INSERT OR REPLACE INTO project_metadata (key, value, updated_at)
|
|
153
|
+
VALUES (?, ?, CURRENT_TIMESTAMP)
|
|
154
|
+
`).run(e,t).changes}getNodeIdsByFile(e){let t=e.replace(/\\/g,"/");return this.db.prepare("SELECT id FROM nodes WHERE file_path = ?").all(t).map(r=>r.id)}deleteFtsByFile(e){let t=e.replace(/\\/g,"/"),s=this.getNodeIdsByFile(t);if(s.length===0)return 0;let r=this.db.prepare("DELETE FROM nodes_fts WHERE id = ?");return this.db.transaction(a=>{for(let i of a)r.run(i);})(s),s.length}initialize(){if(this.closed)throw new g("Cannot initialize closed database","initialize")}close(){if(!this.closed){this.closed=true;try{this.db.close();}catch(e){E.warn("Database close error",{error:String(e)});}}}isClosed(){return this.closed}getDbPath(){return this.dbPath}transaction(e){return this.db.transaction(e)()}getMeta(e){if(!this.db)throw new Error("Database not initialized");return this.db.prepare("SELECT value FROM meta WHERE key = ?").get(e)?.value??null}setMeta(e,t){if(!this.db)throw new Error("Database not initialized");this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run(e,t);}deleteMeta(e){if(!this.db)throw new Error("Database not initialized");this.db.prepare("DELETE FROM meta WHERE key = ?").run(e);}};function se(o){return o.isClosed()}function re(o){return o.getDbPath()}function ne(o,e){return o.transaction(e)}export{F as a,g as b,M as c,u as d,A as e,v as f,x as g,w as h,p as i,V as j,X as k,H as l,m,$ as n,se as o,re as p,ne as q};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkJDULI4R5_cjs=require('./chunk-JDULI4R5.cjs'),chunkRLZHDTHY_cjs=require('./chunk-RLZHDTHY.cjs');require('./chunk-7XCIIOM6.cjs'),require('./chunk-TS4OAYIJ.cjs');Object.defineProperty(exports,"CodeBase",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.o}});Object.defineProperty(exports,"EdgeExtractor",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.h}});Object.defineProperty(exports,"FILE_EXTENSION_MAP",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.b}});Object.defineProperty(exports,"Indexer",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.j}});Object.defineProperty(exports,"NodeExtractor",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.f}});Object.defineProperty(exports,"ParserManager",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.c}});Object.defineProperty(exports,"QueryInterface",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.m}});Object.defineProperty(exports,"createCodebase",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.p}});Object.defineProperty(exports,"createEdgeExtractor",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.i}});Object.defineProperty(exports,"createIndexer",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.k}});Object.defineProperty(exports,"createNodeExtractor",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.g}});Object.defineProperty(exports,"createQueryInterface",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.n}});Object.defineProperty(exports,"getParserManager",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.d}});Object.defineProperty(exports,"resetParserManager",{enumerable:true,get:function(){return chunkJDULI4R5_cjs.e}});Object.defineProperty(exports,"ConfigError",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.e}});Object.defineProperty(exports,"DatabaseError",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.b}});Object.defineProperty(exports,"DatabaseManager",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.n}});Object.defineProperty(exports,"FileSystemError",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.c}});Object.defineProperty(exports,"IndexError",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.f}});Object.defineProperty(exports,"ParserError",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.a}});Object.defineProperty(exports,"QueryError",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.g}});Object.defineProperty(exports,"SchemaError",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.d}});Object.defineProperty(exports,"UnsupportedLanguageError",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.h}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{o as CodeBase,h as EdgeExtractor,b as FILE_EXTENSION_MAP,j as Indexer,f as NodeExtractor,c as ParserManager,m as QueryInterface,p as createCodebase,i as createEdgeExtractor,k as createIndexer,g as createNodeExtractor,n as createQueryInterface,d as getParserManager,e as resetParserManager}from'./chunk-VBIXWHTD.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-Z4Y3VCYS.mjs';import'./chunk-UTKA3WG3.mjs';import'./chunk-G3IYU6TZ.mjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkRLZHDTHY_cjs=require('./chunk-RLZHDTHY.cjs');require('./chunk-TS4OAYIJ.cjs');Object.defineProperty(exports,"DatabaseManager",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.n}});Object.defineProperty(exports,"EXTRACTION_VERSION",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.m}});Object.defineProperty(exports,"getDbPath",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.p}});Object.defineProperty(exports,"isClosed",{enumerable:true,get:function(){return chunkRLZHDTHY_cjs.o}});Object.defineProperty(exports,"transaction",{enumerable:true,get:function(){return chunkRLZHDTHY_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-Z4Y3VCYS.mjs';import'./chunk-G3IYU6TZ.mjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{a as FileWatcher,e as clearWatcherPid,b as getWatcherPidPath,c as readWatcherPid,d as writeWatcherPid}from'./chunk-UEILXBZB.mjs';import'./chunk-G3IYU6TZ.mjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkEVDJNYI2_cjs=require('./chunk-EVDJNYI2.cjs');require('./chunk-TS4OAYIJ.cjs');Object.defineProperty(exports,"FileWatcher",{enumerable:true,get:function(){return chunkEVDJNYI2_cjs.a}});Object.defineProperty(exports,"clearWatcherPid",{enumerable:true,get:function(){return chunkEVDJNYI2_cjs.e}});Object.defineProperty(exports,"getWatcherPidPath",{enumerable:true,get:function(){return chunkEVDJNYI2_cjs.b}});Object.defineProperty(exports,"readWatcherPid",{enumerable:true,get:function(){return chunkEVDJNYI2_cjs.c}});Object.defineProperty(exports,"writeWatcherPid",{enumerable:true,get:function(){return chunkEVDJNYI2_cjs.d}});
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import {d,z as z$1,e,C,f as f$1,B,g,A,h,i,j,D as D$1,k,l,b,c,a as a$1}from'./chunk-TGMIUXU3.mjs';import'./chunk-VBIXWHTD.mjs';import'./chunk-Z4Y3VCYS.mjs';import'./chunk-UTKA3WG3.mjs';import'./chunk-G3IYU6TZ.mjs';import {ToolRegistry,createAndStartStdioServer}from'@easbot/mcp';import {Log}from'@easbot/utils';var f=Log.create({service:"codebase-mcp-stdio"}),Y=["query","node","context","impact","callers","callees","explore","status","doctor"],U;(o=>{let n;function r(){return n||(f.debug("initializing CodebaseStdioServer state factory (lazy)"),n=()=>({toolNames:[...Y],cachedConfigId:"",cachedConfigName:"",cachedConfigVersion:""})),n}async function c(s,i){let u=r()(),l=new ToolRegistry;ce(l,s);let g=u.toolNames;f.info("starting codebase MCP stdio server",{id:i.id,name:i.name,toolCount:g.length});let y=await createAndStartStdioServer(i,l),b=null,q=new Promise(d=>{b=d;}),S=d=>{f.info("received signal, stopping MCP server",{signal:d}),b?.();},x=()=>S("SIGINT"),T=()=>S("SIGTERM");process.on("SIGINT",x),process.on("SIGTERM",T);try{await q;}finally{try{process.off("SIGINT",x),process.off("SIGTERM",T);}catch(d){f.warn("failed to remove signal handlers",{error:d instanceof Error?d.message:String(d)});}try{await y.stop();}catch(d){f.warn("server.stop failed during cleanup",{error:d instanceof Error?d.message:String(d)});}try{await s.close();}catch(d){f.warn("codebase.close failed during cleanup",{error:d instanceof Error?d.message:String(d)});}}return {id:i.id,name:i.name,version:i.version,tools:g}}o.start=c;function e(){return r()().toolNames}o.getToolNames=e;function t(){n=void 0;}o.__resetForTests=t;})(U||(U={}));var G={readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false},Q={type:"object",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:[]},X={type:"object",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},edgesLimit:{type:"number",description:"Max edges to return (default 50).",default:50}},required:[]},V={type:"object",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"}},required:[]},z={type:"object",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:50,minimum:1,maximum:200}},required:[]},P={type:"object",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:20,minimum:1,maximum:200}},required:[]},K=P,J={type:"object",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},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"]},D={type:"object",properties:{}},Z={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 20). 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 20). 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 a(n,r=false){return {content:[{type:"text",text:n}],...r&&{isError:true}}}function m(n){return {workspaceDir:n.getWorkspaceDir?.()??process.cwd(),rootDir:n.getWorkspaceDir?.()??process.cwd()}}function p(n,r){if(n instanceof b)return `**${r}** \u2014 node not found. Try \`query\` first to discover the symbol.`;if(n instanceof c){let c=n.details?.candidates??[],e=c.slice(0,5).map(t=>`- \`${t.node.name}\` in \`${t.node.file_path}\``).join(`
|
|
14
|
+
`);return `**${r}** \u2014 ambiguous name. Specify \`file\` to disambiguate:
|
|
15
|
+
|
|
16
|
+
${e}
|
|
17
|
+
|
|
18
|
+
... and ${c.length-5} more candidates.`}return n instanceof a$1?`**${r}** \u2014 ${n.message}`:n instanceof Error?`**${r}** \u2014 internal error: ${n.message}`:`**${r}** \u2014 internal error: ${String(n)}`}function ee(n){return async(r,c)=>{let e=r;try{let t=m(n),s=(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})).hits.map(u=>u.node),i=await z$1(s,{pendingFiles:[],toolName:"query",writeToDisk:!1});return a(i)}catch(t){return a(p(t,"query"),true)}}}function te(n){return async(r,c)=>{let e$1=r;try{let t=m(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,edgesLimit:e$1.edgesLimit??50}),s=await C(o.node,o.edges,{pendingFiles:[],toolName:"node",writeToDisk:!1});return a(s)}catch(t){return a(p(t,"node"),true)}}}function ne(n){return async(r,c)=>{let e=r;try{let t=m(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"});if(!o.root)return a("**context** \u2014 node not found.");let s=[],i=[];for(let l of o.edges)l.target===o.root.id?s.push(l):i.push(l);let u=await B(o.root,s,i,o.nodes.map(l=>l.node),{pendingFiles:[],toolName:"context",writeToDisk:!1});return a(u)}catch(t){return a(p(t,"context"),true)}}}function oe(n){return async(r,c)=>{let e=r;try{let t=m(n),o=await g(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,depth:e.depth??2,maxResults:e.maxResults??50});if(!o.root)return a("**impact** \u2014 node not found.");let s=[],i=n.getDatabase();for(let l of o.buckets)for(let g of l.sample){let y=i.getNodeById(g.id);y&&s.push({source:y,relation:g.relation});}let u=await A(o.root,s,{pendingFiles:[],toolName:"impact",writeToDisk:!1});return a(u)}catch(t){return a(p(t,"impact"),true)}}}function se(n){return async(r,c)=>{let e=r;try{let t=m(n),o=await h(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,maxResults:e.maxResults??20}),s=[];s.push(`**Callers of \`${o.root?.name??"?"}\`** (${o.callers.length}${o.truncated?"+":""})
|
|
19
|
+
`);for(let i of o.callers)s.push(`- [${i.relation}] \`${i.name}\` ${i.filePath}:${i.startLine}`);return o.callers.length===0&&s.push("(no incoming edges)"),s.push("\n---\n> Use `node <name>` to read full source of any caller."),a(s.join(`
|
|
20
|
+
`))}catch(t){return a(p(t,"callers"),true)}}}function re(n){return async(r,c)=>{let e=r;try{let t=m(n),o=await i(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,maxResults:e.maxResults??20}),s=[];s.push(`**Callees of \`${o.root?.name??"?"}\`** (${o.callers.length}${o.truncated?"+":""})
|
|
21
|
+
`);for(let i of o.callers)s.push(`- [${i.relation}] \`${i.name}\` ${i.filePath}:${i.startLine}`);return o.callers.length===0&&s.push("(no outgoing edges)"),s.push("\n---\n> Use `node <name>` to read full source of any callee."),a(s.join(`
|
|
22
|
+
`))}catch(t){return a(p(t,"callees"),true)}}}function ie(n){return async(r,c)=>{let e=r;try{let t=m(n),o=await j(t,{query:e.query,file:e.file,kind:e.kind,maxFiles:e.maxFiles??5,maxSymbols:e.maxSymbols??3,depth:e.depth??1,includeContent:e.includeContent??!0,intent:e.intent}),s=await D$1(o,{pendingFiles:[],toolName:"explore",writeToDisk:!1});return a(s)}catch(t){return a(p(t,"explore"),true)}}}function ae(n){return async(r,c)=>{try{let e=m(n),t=await k(e,{}),o=t.workspaceDir,s=t.meta.indexed_with_version??"unknown",i=t.meta.lastSync??"never",u=`**Codebase Status**
|
|
23
|
+
|
|
24
|
+
- DB path: \`${t.dbPath}\`
|
|
25
|
+
- Workspace: \`${o}\`
|
|
26
|
+
- Nodes: ${t.nodeCount}
|
|
27
|
+
- Edges: ${t.edgeCount}
|
|
28
|
+
- Indexed files: ${t.indexedFiles}
|
|
29
|
+
- Index state: \`${t.indexState??"unknown"}\`
|
|
30
|
+
- Extraction version: ${t.extractionVersion??"unknown"}
|
|
31
|
+
- Indexed with version: ${s}
|
|
32
|
+
- Last sync: ${i}
|
|
33
|
+
- Stale: ${t.isStale?"\u26A0\uFE0F yes (extraction_version mismatch)":"no"}
|
|
34
|
+
|
|
35
|
+
> Use \`doctor\` for deeper health check.`;return a(u)}catch(e){return a(p(e,"status"),true)}}}function de(n){return async(r,c)=>{try{let e=m(n),t=await l(e,{}),o=await k(e,{}),s=`**Codebase Health Check**
|
|
36
|
+
|
|
37
|
+
- Healthy: ${t.healthy?"\u2713 yes":"\u2717 no"}
|
|
38
|
+
- Nodes: ${o.nodeCount}
|
|
39
|
+
- Edges: ${o.edgeCount}
|
|
40
|
+
- Indexed files: ${o.indexedFiles}
|
|
41
|
+
- DB path: \`${o.dbPath}\`
|
|
42
|
+
- FTS available: ${t.ftsAvailable}
|
|
43
|
+
|
|
44
|
+
${t.issues.length>0?`**Issues:**
|
|
45
|
+
${t.issues.map(i=>`- ${i}`).join(`
|
|
46
|
+
`)}
|
|
47
|
+
`:""}> ${t.healthy?"Index is healthy. Use `query` to search.":"Index has issues. Check status details above."}`;return a(s)}catch(e){return a(p(e,"doctor"),true)}}}function ce(n,r){let c=[{name:"query",schema:Q,factory:ee},{name:"node",schema:X,factory:te},{name:"context",schema:V,factory:ne},{name:"impact",schema:z,factory:oe},{name:"callers",schema:P,factory:se},{name:"callees",schema:K,factory:re},{name:"explore",schema:J,factory:ie},{name:"status",schema:D,factory:ae},{name:"doctor",schema:D,factory:de}];for(let e of c)n.register({name:e.name,description:Z[e.name]??"",inputSchema:e.schema,annotations:G,handler:e.factory(r)});}async function ye(n){throw new Error("startMcpStdioServer \u5DF2\u5E9F\u5F03\uFF0C\u8BF7\u6539\u7528 CodebaseStdioServer.start(codebase, config)\u3002")}function he(n){throw new Error("buildCodebaseMcpTools \u5DF2\u5E9F\u5F03\uFF0C\u8BF7\u6539\u7528 CodebaseStdioServer.start(codebase, config)\u3002")}export{U as CodebaseStdioServer,he as buildCodebaseMcpTools,ye as startMcpStdioServer};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
'use strict';var chunkXAODNPHT_cjs=require('./chunk-XAODNPHT.cjs');require('./chunk-JDULI4R5.cjs'),require('./chunk-RLZHDTHY.cjs'),require('./chunk-7XCIIOM6.cjs'),require('./chunk-TS4OAYIJ.cjs');var mcp=require('@easbot/mcp'),utils=require('@easbot/utils');var f=utils.Log.create({service:"codebase-mcp-stdio"}),Y=["query","node","context","impact","callers","callees","explore","status","doctor"];exports.CodebaseStdioServer=void 0;(o=>{let n;function r(){return n||(f.debug("initializing CodebaseStdioServer state factory (lazy)"),n=()=>({toolNames:[...Y],cachedConfigId:"",cachedConfigName:"",cachedConfigVersion:""})),n}async function c(s,i){let u=r()(),l=new mcp.ToolRegistry;ce(l,s);let g=u.toolNames;f.info("starting codebase MCP stdio server",{id:i.id,name:i.name,toolCount:g.length});let y=await mcp.createAndStartStdioServer(i,l),b=null,q=new Promise(d=>{b=d;}),S=d=>{f.info("received signal, stopping MCP server",{signal:d}),b?.();},x=()=>S("SIGINT"),T=()=>S("SIGTERM");process.on("SIGINT",x),process.on("SIGTERM",T);try{await q;}finally{try{process.off("SIGINT",x),process.off("SIGTERM",T);}catch(d){f.warn("failed to remove signal handlers",{error:d instanceof Error?d.message:String(d)});}try{await y.stop();}catch(d){f.warn("server.stop failed during cleanup",{error:d instanceof Error?d.message:String(d)});}try{await s.close();}catch(d){f.warn("codebase.close failed during cleanup",{error:d instanceof Error?d.message:String(d)});}}return {id:i.id,name:i.name,version:i.version,tools:g}}o.start=c;function e(){return r()().toolNames}o.getToolNames=e;function t(){n=void 0;}o.__resetForTests=t;})(exports.CodebaseStdioServer||(exports.CodebaseStdioServer={}));var G={readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false},Q={type:"object",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:[]},X={type:"object",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},edgesLimit:{type:"number",description:"Max edges to return (default 50).",default:50}},required:[]},V={type:"object",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"}},required:[]},z={type:"object",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:50,minimum:1,maximum:200}},required:[]},P={type:"object",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:20,minimum:1,maximum:200}},required:[]},K=P,J={type:"object",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},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"]},D={type:"object",properties:{}},Z={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 20). 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 20). 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 a(n,r=false){return {content:[{type:"text",text:n}],...r&&{isError:true}}}function m(n){return {workspaceDir:n.getWorkspaceDir?.()??process.cwd(),rootDir:n.getWorkspaceDir?.()??process.cwd()}}function p(n,r){if(n instanceof chunkXAODNPHT_cjs.b)return `**${r}** \u2014 node not found. Try \`query\` first to discover the symbol.`;if(n instanceof chunkXAODNPHT_cjs.c){let c=n.details?.candidates??[],e=c.slice(0,5).map(t=>`- \`${t.node.name}\` in \`${t.node.file_path}\``).join(`
|
|
14
|
+
`);return `**${r}** \u2014 ambiguous name. Specify \`file\` to disambiguate:
|
|
15
|
+
|
|
16
|
+
${e}
|
|
17
|
+
|
|
18
|
+
... and ${c.length-5} more candidates.`}return n instanceof chunkXAODNPHT_cjs.a?`**${r}** \u2014 ${n.message}`:n instanceof Error?`**${r}** \u2014 internal error: ${n.message}`:`**${r}** \u2014 internal error: ${String(n)}`}function ee(n){return async(r,c)=>{let e=r;try{let t=m(n),s=(await chunkXAODNPHT_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})).hits.map(u=>u.node),i=await chunkXAODNPHT_cjs.z(s,{pendingFiles:[],toolName:"query",writeToDisk:!1});return a(i)}catch(t){return a(p(t,"query"),true)}}}function te(n){return async(r,c)=>{let e=r;try{let t=m(n),o=await chunkXAODNPHT_cjs.e(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,includeEdges:e.includeEdges??!0,includeContent:e.includeContent??!0,edgesLimit:e.edgesLimit??50}),s=await chunkXAODNPHT_cjs.C(o.node,o.edges,{pendingFiles:[],toolName:"node",writeToDisk:!1});return a(s)}catch(t){return a(p(t,"node"),true)}}}function ne(n){return async(r,c)=>{let e=r;try{let t=m(n),o=await chunkXAODNPHT_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"});if(!o.root)return a("**context** \u2014 node not found.");let s=[],i=[];for(let l of o.edges)l.target===o.root.id?s.push(l):i.push(l);let u=await chunkXAODNPHT_cjs.B(o.root,s,i,o.nodes.map(l=>l.node),{pendingFiles:[],toolName:"context",writeToDisk:!1});return a(u)}catch(t){return a(p(t,"context"),true)}}}function oe(n){return async(r,c)=>{let e=r;try{let t=m(n),o=await chunkXAODNPHT_cjs.g(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,depth:e.depth??2,maxResults:e.maxResults??50});if(!o.root)return a("**impact** \u2014 node not found.");let s=[],i=n.getDatabase();for(let l of o.buckets)for(let g of l.sample){let y=i.getNodeById(g.id);y&&s.push({source:y,relation:g.relation});}let u=await chunkXAODNPHT_cjs.A(o.root,s,{pendingFiles:[],toolName:"impact",writeToDisk:!1});return a(u)}catch(t){return a(p(t,"impact"),true)}}}function se(n){return async(r,c)=>{let e=r;try{let t=m(n),o=await chunkXAODNPHT_cjs.h(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,maxResults:e.maxResults??20}),s=[];s.push(`**Callers of \`${o.root?.name??"?"}\`** (${o.callers.length}${o.truncated?"+":""})
|
|
19
|
+
`);for(let i of o.callers)s.push(`- [${i.relation}] \`${i.name}\` ${i.filePath}:${i.startLine}`);return o.callers.length===0&&s.push("(no incoming edges)"),s.push("\n---\n> Use `node <name>` to read full source of any caller."),a(s.join(`
|
|
20
|
+
`))}catch(t){return a(p(t,"callers"),true)}}}function re(n){return async(r,c)=>{let e=r;try{let t=m(n),o=await chunkXAODNPHT_cjs.i(t,{name:e.name,nodeId:e.nodeId,file:e.file,kind:e.kind,maxResults:e.maxResults??20}),s=[];s.push(`**Callees of \`${o.root?.name??"?"}\`** (${o.callers.length}${o.truncated?"+":""})
|
|
21
|
+
`);for(let i of o.callers)s.push(`- [${i.relation}] \`${i.name}\` ${i.filePath}:${i.startLine}`);return o.callers.length===0&&s.push("(no outgoing edges)"),s.push("\n---\n> Use `node <name>` to read full source of any callee."),a(s.join(`
|
|
22
|
+
`))}catch(t){return a(p(t,"callees"),true)}}}function ie(n){return async(r,c)=>{let e=r;try{let t=m(n),o=await chunkXAODNPHT_cjs.j(t,{query:e.query,file:e.file,kind:e.kind,maxFiles:e.maxFiles??5,maxSymbols:e.maxSymbols??3,depth:e.depth??1,includeContent:e.includeContent??!0,intent:e.intent}),s=await chunkXAODNPHT_cjs.D(o,{pendingFiles:[],toolName:"explore",writeToDisk:!1});return a(s)}catch(t){return a(p(t,"explore"),true)}}}function ae(n){return async(r,c)=>{try{let e=m(n),t=await chunkXAODNPHT_cjs.k(e,{}),o=t.workspaceDir,s=t.meta.indexed_with_version??"unknown",i=t.meta.lastSync??"never",u=`**Codebase Status**
|
|
23
|
+
|
|
24
|
+
- DB path: \`${t.dbPath}\`
|
|
25
|
+
- Workspace: \`${o}\`
|
|
26
|
+
- Nodes: ${t.nodeCount}
|
|
27
|
+
- Edges: ${t.edgeCount}
|
|
28
|
+
- Indexed files: ${t.indexedFiles}
|
|
29
|
+
- Index state: \`${t.indexState??"unknown"}\`
|
|
30
|
+
- Extraction version: ${t.extractionVersion??"unknown"}
|
|
31
|
+
- Indexed with version: ${s}
|
|
32
|
+
- Last sync: ${i}
|
|
33
|
+
- Stale: ${t.isStale?"\u26A0\uFE0F yes (extraction_version mismatch)":"no"}
|
|
34
|
+
|
|
35
|
+
> Use \`doctor\` for deeper health check.`;return a(u)}catch(e){return a(p(e,"status"),true)}}}function de(n){return async(r,c)=>{try{let e=m(n),t=await chunkXAODNPHT_cjs.l(e,{}),o=await chunkXAODNPHT_cjs.k(e,{}),s=`**Codebase Health Check**
|
|
36
|
+
|
|
37
|
+
- Healthy: ${t.healthy?"\u2713 yes":"\u2717 no"}
|
|
38
|
+
- Nodes: ${o.nodeCount}
|
|
39
|
+
- Edges: ${o.edgeCount}
|
|
40
|
+
- Indexed files: ${o.indexedFiles}
|
|
41
|
+
- DB path: \`${o.dbPath}\`
|
|
42
|
+
- FTS available: ${t.ftsAvailable}
|
|
43
|
+
|
|
44
|
+
${t.issues.length>0?`**Issues:**
|
|
45
|
+
${t.issues.map(i=>`- ${i}`).join(`
|
|
46
|
+
`)}
|
|
47
|
+
`:""}> ${t.healthy?"Index is healthy. Use `query` to search.":"Index has issues. Check status details above."}`;return a(s)}catch(e){return a(p(e,"doctor"),true)}}}function ce(n,r){let c=[{name:"query",schema:Q,factory:ee},{name:"node",schema:X,factory:te},{name:"context",schema:V,factory:ne},{name:"impact",schema:z,factory:oe},{name:"callers",schema:P,factory:se},{name:"callees",schema:K,factory:re},{name:"explore",schema:J,factory:ie},{name:"status",schema:D,factory:ae},{name:"doctor",schema:D,factory:de}];for(let e of c)n.register({name:e.name,description:Z[e.name]??"",inputSchema:e.schema,annotations:G,handler:e.factory(r)});}async function ge(n){throw new Error("startMcpStdioServer \u5DF2\u5E9F\u5F03\uFF0C\u8BF7\u6539\u7528 CodebaseStdioServer.start(codebase, config)\u3002")}function ye(n){throw new Error("buildCodebaseMcpTools \u5DF2\u5E9F\u5F03\uFF0C\u8BF7\u6539\u7528 CodebaseStdioServer.start(codebase, config)\u3002")}exports.buildCodebaseMcpTools=ye;exports.startMcpStdioServer=ge;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkIXERCMYQ_cjs=require('./chunk-IXERCMYQ.cjs');require('./chunk-7XCIIOM6.cjs'),require('./chunk-TS4OAYIJ.cjs');Object.defineProperty(exports,"formatSyncText",{enumerable:true,get:function(){return chunkIXERCMYQ_cjs.o}});Object.defineProperty(exports,"parseSyncOptions",{enumerable:true,get:function(){return chunkIXERCMYQ_cjs.m}});Object.defineProperty(exports,"runSync",{enumerable:true,get:function(){return chunkIXERCMYQ_cjs.n}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{o as formatSyncText,m as parseSyncOptions,n as runSync}from'./chunk-CJSKATXN.mjs';import'./chunk-UTKA3WG3.mjs';import'./chunk-G3IYU6TZ.mjs';
|
package/dist/cli.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';var chunkAUNBGHMC_cjs=require('./chunks/chunk-AUNBGHMC.cjs');require('./chunks/chunk-EVDJNYI2.cjs');var chunkIXERCMYQ_cjs=require('./chunks/chunk-IXERCMYQ.cjs');require('./chunks/chunk-XAODNPHT.cjs'),require('./chunks/chunk-JDULI4R5.cjs'),require('./chunks/chunk-RLZHDTHY.cjs'),require('./chunks/chunk-7XCIIOM6.cjs');var chunkTS4OAYIJ_cjs=require('./chunks/chunk-TS4OAYIJ.cjs'),fs=require('fs'),path=require('path'),url=require('url');var l=path.dirname(url.fileURLToPath(chunkTS4OAYIJ_cjs.b));function u(){try{let e=path.join(l,"..","package.json");return JSON.parse(fs.readFileSync(e,"utf-8")).version??"0.0.0"}catch{return "0.0.0"}}async function g(){let e=process.argv.slice(2),r=u(),o=process.cwd();if(chunkIXERCMYQ_cjs.d({directory:o,worktree:o}),!process.env.EASBOT_LANG&&!process.env.LANG&&(process.env.EASBOT_LANG="en-US"),e.length===0){chunkAUNBGHMC_cjs.a();return}if(e[0]==="--help"||e[0]==="-h"){chunkAUNBGHMC_cjs.b();return}if(e[0]==="--version"||e[0]==="-v"){console.log(r);return}let n=await chunkAUNBGHMC_cjs.c(e,{version:r,cwd:o});n.code!==0&&(process.exitCode=n.code);}g().catch(e=>{console.error(e),process.exitCode=1;});
|
package/dist/cli.d.cts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {a,b,c}from'./chunks/chunk-3ZA3AOKC.mjs';import'./chunks/chunk-UEILXBZB.mjs';import {d}from'./chunks/chunk-CJSKATXN.mjs';import'./chunks/chunk-TGMIUXU3.mjs';import'./chunks/chunk-VBIXWHTD.mjs';import'./chunks/chunk-Z4Y3VCYS.mjs';import'./chunks/chunk-UTKA3WG3.mjs';import'./chunks/chunk-G3IYU6TZ.mjs';import {readFileSync}from'fs';import {dirname,join}from'path';import {fileURLToPath}from'url';var f=dirname(fileURLToPath(import.meta.url));function l(){try{let e=join(f,"..","package.json");return JSON.parse(readFileSync(e,"utf-8")).version??"0.0.0"}catch{return "0.0.0"}}async function u(){let e=process.argv.slice(2),r=l(),o=process.cwd();if(d({directory:o,worktree:o}),!process.env.EASBOT_LANG&&!process.env.LANG&&(process.env.EASBOT_LANG="en-US"),e.length===0){a();return}if(e[0]==="--help"||e[0]==="-h"){b();return}if(e[0]==="--version"||e[0]==="-v"){console.log(r);return}let n=await c(e,{version:r,cwd:o});n.code!==0&&(process.exitCode=n.code);}u().catch(e=>{console.error(e),process.exitCode=1;});
|