@easbot/codebase 0.3.21 → 0.3.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.en.md +46 -0
  2. package/README.md +46 -0
  3. package/dist/chunks/{chunk-JWTI3BWI.cjs → chunk-3NTIN3AN.cjs} +19 -19
  4. package/dist/chunks/chunk-A4EAKE3M.mjs +49 -0
  5. package/dist/chunks/chunk-DHH2XXGJ.mjs +203 -0
  6. package/dist/chunks/{chunk-22PKTMO5.mjs → chunk-GWR5LCUV.mjs} +19 -19
  7. package/dist/chunks/{chunk-BEQN3CKO.cjs → chunk-HRFLFP6O.cjs} +1 -1
  8. package/dist/chunks/chunk-KU6UZET2.cjs +49 -0
  9. package/dist/chunks/{chunk-WXWENWCY.mjs → chunk-QQXDOGRV.mjs} +1 -1
  10. package/dist/chunks/chunk-UAWXUGY5.cjs +47 -0
  11. package/dist/chunks/chunk-XXH7ZLAJ.mjs +47 -0
  12. package/dist/chunks/chunk-YY3Z7NGV.cjs +203 -0
  13. package/dist/chunks/cli-handler-7XFZK7GK.cjs +1 -0
  14. package/dist/chunks/cli-handler-H6VHMEHB.mjs +1 -0
  15. package/dist/chunks/code-base-E5TX7O7M.cjs +1 -0
  16. package/dist/chunks/code-base-HAX5SGRL.mjs +1 -0
  17. package/dist/chunks/database-manager-WTV3TBJS.cjs +1 -0
  18. package/dist/chunks/database-manager-YGQQHLYR.mjs +1 -0
  19. package/dist/chunks/file-watcher-HVST5PAC.cjs +1 -0
  20. package/dist/chunks/file-watcher-LCQ55MPE.mjs +1 -0
  21. package/dist/chunks/{interfaces-5HZADUYB.mjs → interfaces-DPFLQBQ6.mjs} +1 -1
  22. package/dist/chunks/{interfaces-ORRCH4XV.cjs → interfaces-YX56SVRQ.cjs} +1 -1
  23. package/dist/chunks/{llm-MPD7FHPM.mjs → llm-ADBGTSCV.mjs} +1 -1
  24. package/dist/chunks/{llm-JQV6XWGD.cjs → llm-BDMNIGOH.cjs} +1 -1
  25. package/dist/chunks/stdio-server-2QHQ7ESX.cjs +47 -0
  26. package/dist/chunks/stdio-server-5YSJE5E5.mjs +47 -0
  27. package/dist/cli.cjs +1 -1
  28. package/dist/cli.mjs +1 -1
  29. package/dist/index.cjs +1 -1
  30. package/dist/index.d.cts +35 -3
  31. package/dist/index.d.ts +35 -3
  32. package/dist/index.mjs +1 -1
  33. package/package.json +12 -12
  34. package/dist/chunks/chunk-AGZFRKQ4.mjs +0 -188
  35. package/dist/chunks/chunk-CSMSBVAG.mjs +0 -34
  36. package/dist/chunks/chunk-R74KIJM2.cjs +0 -34
  37. package/dist/chunks/chunk-TR3DFBJH.mjs +0 -47
  38. package/dist/chunks/chunk-VFTVDTEY.cjs +0 -188
  39. package/dist/chunks/chunk-YYF5OQDS.cjs +0 -47
  40. package/dist/chunks/cli-handler-3I5JC3HY.cjs +0 -1
  41. package/dist/chunks/cli-handler-IJ2PNNTK.mjs +0 -1
  42. package/dist/chunks/code-base-6TM7JDJ6.cjs +0 -1
  43. package/dist/chunks/code-base-BSRUQYXN.mjs +0 -1
  44. package/dist/chunks/database-manager-26PY6VTD.mjs +0 -1
  45. package/dist/chunks/database-manager-U7D7QIHC.cjs +0 -1
  46. package/dist/chunks/file-watcher-GHRFHOQF.cjs +0 -1
  47. package/dist/chunks/file-watcher-OORREWFV.mjs +0 -1
  48. package/dist/chunks/stdio-server-2GBPZY6J.cjs +0 -47
  49. package/dist/chunks/stdio-server-BZYPM34X.mjs +0 -47
  50. /package/dist/chunks/{chunk-TMICZT3L.mjs → chunk-2YMB6W5S.mjs} +0 -0
  51. /package/dist/chunks/{chunk-NVGACA7W.cjs → chunk-M2YU5LAI.cjs} +0 -0
package/README.en.md CHANGED
@@ -249,6 +249,52 @@ interface SearchOptions {
249
249
  }
250
250
  ```
251
251
 
252
+ ## Name Lookup Behavior (Decision 0087)
253
+
254
+ The 5 graph operations (`node` / `callers` / `callees` / `impact` / `context`) share a `resolveName()` function to locate nodes. This section explains its matching semantics and the recommended LLM workflow.
255
+
256
+ ### 3-tier SQL fallback (priority order)
257
+
258
+ | Tier | Match Mode | SQL Condition | Use Case |
259
+ |------|-----------|---------------|----------|
260
+ | 1. **exact** | `name` field equality | `WHERE name = ?` | Short class names / namespaces / fully qualified names (with `@<line>`) |
261
+ | 2. **qualified** | `name` contains target string (fallback) | `WHERE name LIKE %?%` | Short method names / class name prefix mismatch |
262
+ | 3. **substring** | When tier 1-2 return 0 + `file`/`kind` filter | `WHERE name LIKE %?% AND file_path/kind` | Extreme edge cases (e.g., typo in class name) |
263
+
264
+ ### Recommended LLM Workflow
265
+
266
+ ```
267
+ search → (pick name + file) → callers | callees | impact | context | node
268
+ ↑ ↓
269
+ └─────────────── explore (PRIMARY, source code + 1-level) ←──────┘
270
+ ```
271
+
272
+ **Step 1**: First call `search(query="AuthService")` to obtain `name + file_path`.
273
+
274
+ **Step 2**: Use the `name + file` returned by `search` as input to subsequent operations:
275
+
276
+ ```typescript
277
+ // ✅ Recommended: short class name + file filter (strongest disambiguation signal)
278
+ await service.callers(ctx, { name: 'AuthService', file: 'auth-service.ts' });
279
+
280
+ // ✅ Recommended: fully qualified name (with namespace + @<line>)
281
+ await service.callers(ctx, { name: 'AuthService.login@20' });
282
+
283
+ // ✅ Recommended: nodeId direct lookup (zero ambiguity)
284
+ await service.callers(ctx, { nodeId: 'ts:src/auth-service.ts:method_definition:AuthService.login@20' });
285
+
286
+ // ❌ Anti-pattern: short class name without file
287
+ await service.callers(ctx, { name: 'AuthService' });
288
+ // → AmbiguousError: 3 candidates (AuthService class + AuthService.login@20 + AuthService.validate@30)
289
+ ```
290
+
291
+ ### Error Handling
292
+
293
+ | Error | Trigger | Fix |
294
+ |-------|---------|-----|
295
+ | `NotFoundError` | 0 candidates | Check `name` spelling / typo / non-existent symbol |
296
+ | `AmbiguousError` | ≥2 candidates and no `file` disambiguation | Pick one `name + file` from the returned `candidates[]` list and retry |
297
+
252
298
  ## Data Model
253
299
 
254
300
  ### Node
package/README.md CHANGED
@@ -283,6 +283,52 @@ interface SearchOptions {
283
283
  }
284
284
  ```
285
285
 
286
+ ## Name Lookup 行为(决策 0087)
287
+
288
+ 5 个图操作(`node` / `callers` / `callees` / `impact` / `context`)通过共享 `resolveName()` 函数定位节点。本节说明其匹配语义与 LLM 推荐用法。
289
+
290
+ ### 3 层 SQL fallback(按优先级)
291
+
292
+ | 层级 | 匹配模式 | SQL 条件 | 适用场景 |
293
+ |------|---------|---------|---------|
294
+ | 1. **exact** | `name` 字段全等 | `WHERE name = ?` | 短类名 / namespace / 完全限定名(含 `@<line>`) |
295
+ | 2. **qualified** | `name` 含目标字符串(兜底) | `WHERE name LIKE %?%` | 短方法名 / 类名前缀不匹配 |
296
+ | 3. **substring** | 前两层全空 + `file`/`kind` 过滤 | `WHERE name LIKE %?% AND file_path/kind` | 极端罕见场景(如类名拼写模糊) |
297
+
298
+ ### LLM 推荐用法(workflow)
299
+
300
+ ```
301
+ search → (pick name + file) → callers | callees | impact | context | node
302
+ ↑ ↓
303
+ └─────────────── explore (PRIMARY, source code + 1-level) ←──────┘
304
+ ```
305
+
306
+ **Step 1**:先用 `search(query="AuthService")` 拿到 `name + file_path`。
307
+
308
+ **Step 2**:以 `search` 返回的 `name + file` 作为后续操作的输入:
309
+
310
+ ```typescript
311
+ // ✅ 推荐:短类名 + file 过滤(最强消歧信号)
312
+ await service.callers(ctx, { name: 'AuthService', file: 'auth-service.ts' });
313
+
314
+ // ✅ 推荐:完全限定名(name 含 namespace + @<line>)
315
+ await service.callers(ctx, { name: 'AuthService.login@20' });
316
+
317
+ // ✅ 推荐:nodeId 直接定位(零歧义)
318
+ await service.callers(ctx, { nodeId: 'ts:src/auth-service.ts:method_definition:AuthService.login@20' });
319
+
320
+ // ❌ 反模式:短类名 + 无 file
321
+ await service.callers(ctx, { name: 'AuthService' });
322
+ // → AmbiguousError: 3 candidates (AuthService 类 + AuthService.login@20 + AuthService.validate@30)
323
+ ```
324
+
325
+ ### 错误处理
326
+
327
+ | 错误 | 触发条件 | 修复 |
328
+ |------|---------|------|
329
+ | `NotFoundError` | 0 候选 | 检查 `name` 拼写 / 拼写错误 / 不存在的符号 |
330
+ | `AmbiguousError` | ≥2 候选且无 `file` 消歧 | 从错误返回的 `candidates[]` 列表中选一个 `name + file` 重试 |
331
+
286
332
  ## 数据模型
287
333
 
288
334
  ### 节点 (Node)
@@ -1,4 +1,4 @@
1
- 'use strict';var chunkNVGACA7W_cjs=require('./chunk-NVGACA7W.cjs'),utils=require('@easbot/utils'),database=require('@easbot/database');var F=class o extends Error{constructor(t,s,r){super(t);chunkNVGACA7W_cjs.a(this,"name","ParserError");chunkNVGACA7W_cjs.a(this,"filePath");chunkNVGACA7W_cjs.a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `ParserError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},g=class o extends Error{constructor(t,s,r){super(t);chunkNVGACA7W_cjs.a(this,"name","DatabaseError");chunkNVGACA7W_cjs.a(this,"operation");chunkNVGACA7W_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);chunkNVGACA7W_cjs.a(this,"name","FileSystemError");chunkNVGACA7W_cjs.a(this,"filePath");chunkNVGACA7W_cjs.a(this,"cause");this.filePath=s,this.cause=r,Object.setPrototypeOf(this,o.prototype);}toString(){let t=this.cause?` (caused by: ${this.cause.message})`:"";return `FileSystemError: ${this.message} at ${this.filePath}${t}`}toJSON(){return {name:this.name,message:this.message,filePath:this.filePath,cause:this.cause?.message}}},u=class o extends Error{constructor(t,s){super(t);chunkNVGACA7W_cjs.a(this,"name","SchemaError");chunkNVGACA7W_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);chunkNVGACA7W_cjs.a(this,"name","ConfigError");chunkNVGACA7W_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);chunkNVGACA7W_cjs.a(this,"name","IndexError");chunkNVGACA7W_cjs.a(this,"filePath");chunkNVGACA7W_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);chunkNVGACA7W_cjs.a(this,"name","QueryError");chunkNVGACA7W_cjs.a(this,"params");chunkNVGACA7W_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}`);chunkNVGACA7W_cjs.a(this,"name","UnsupportedLanguageError");chunkNVGACA7W_cjs.a(this,"extension");chunkNVGACA7W_cjs.a(this,"filePath");this.extension=t,this.filePath=s,Object.setPrototypeOf(this,o.prototype);}toString(){return `UnsupportedLanguageError: ${this.extension} at ${this.filePath}`}toJSON(){return {name:this.name,message:this.message,extension:this.extension,filePath:this.filePath}}};var P=utils.Log.create({service:"codebase-schema-migrations"}),p=1,W=[{id:1,description:"v1 baseline: nodes / edges / file_hashes / nodes_fts / meta / embedding_cache / node_embeddings + unresolved_refs / name_segment_vocab / project_metadata / parse_errors + \u6027\u80FD index (nodes.file_path / edges.source/target)",up:[`CREATE TABLE IF NOT EXISTS nodes (
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}}},R=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,
@@ -64,22 +64,22 @@
64
64
  message TEXT NOT NULL,
65
65
  line INTEGER,
66
66
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
67
- )`,"CREATE INDEX IF NOT EXISTS idx_parse_errors_file_path ON parse_errors(file_path)","CREATE INDEX IF NOT EXISTS idx_nodes_file_path ON nodes(file_path)","CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)"]}];function D(o,e=p,t={}){o.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
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(a=>a.id)),n={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(a=>a.id)),targetVersion:e};for(let a of W){if(a.id>e)break;if(r.has(a.id)){n.pending.push(a.id);continue}if(t.dryRun){n.applied.push(a.id);continue}try{o.execBatch([...a.up]),o.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(a.id),r.add(a.id),n.applied.push(a.id),P.info("migration applied",{id:a.id,description:a.description});}catch(i){let l=i instanceof Error?i.message:String(i),T=a.up[0]??"";n.errors.push({migrationId:a.id,sql:T,error:l}),P.warn("migration step failed (may be idempotent)",{id:a.id,error:l,sqlCount:a.up.length});}}return n}function X(o){try{let e=o.prepare("SELECT id FROM schema_migrations").all();return e.length===0?0:Math.max(...e.map(t=>t.id))}catch{return 0}}var c=utils.Filesystem.toUnixPath,E=utils.Log.create({service:"codebase-database"}),m=2,H=class{constructor(e){chunkNVGACA7W_cjs.a(this,"db");chunkNVGACA7W_cjs.a(this,"dbPath");chunkNVGACA7W_cjs.a(this,"closed",false);chunkNVGACA7W_cjs.a(this,"ftsAvailable",false);this.dbPath=e===":memory:"?e:utils.Filesystem.normalize(e),this.db=database.createSyncSqliteConnection({path:this.dbPath,backend:"better-sqlite3",walMode:true,foreignKeys:true,busyTimeoutMs:5e3}),this.db.initialize();try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("foreign_keys = ON");}catch(t){E.warn("Failed to apply codebase PRAGMAs (synchronous / cache_size / foreign_keys)",{error:String(t)});}try{this.ensureSchema();let t=X(this.db);t>0&&this.setMeta("schema_version",String(t)),this.ftsAvailable=this.checkFtsAvailability(),this.detectAndMarkStaleOnInit();}catch(t){try{this.db.close();}catch{}throw this.closed=true,t}}ensureSchema(){try{D(this.db,p);let e=[["version","1.0.0"],["createdAt",new Date().toISOString()],["index_state","uninitialized"],["indexed_with_version","unknown"]],t=this.db.prepare("INSERT OR IGNORE INTO meta (key, value) VALUES (?, ?)");for(let[s,r]of e)t.run(s,r);}catch(e){throw E.error("ensureSchema failed",{message:e instanceof Error?e.message:String(e),cause:e instanceof Error?e.cause:void 0,stack:e instanceof Error?e.stack:void 0}),new u("Failed to create database schema",e instanceof Error?[e.message]:[String(e)])}}checkFtsAvailability(){try{return this.db.exec("SELECT * FROM nodes_fts WHERE nodes_fts MATCH 'test' LIMIT 1"),!0}catch{return false}}isFtsAvailable(){return this.ftsAvailable}insertNode(e){let t={...e,file_path:c(e.file_path)};this.db.prepare(`
70
+ )`);let s=o.prepare("SELECT id FROM schema_migrations").all(),r=new Set(s.map(n=>n.id)),i={applied:[],pending:[],errors:[],currentVersion:Math.max(0,...s.map(n=>n.id)),targetVersion:e};for(let n of W){if(n.id>e)break;if(r.has(n.id)){i.pending.push(n.id);continue}if(t.dryRun){i.applied.push(n.id);continue}try{o.execBatch([...n.up]),o.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(n.id),r.add(n.id),i.applied.push(n.id),P.info("migration applied",{id:n.id,description:n.description});}catch(a){let u=a instanceof Error?a.message:String(a),E=n.up[0]??"";i.errors.push({migrationId:n.id,sql:E,error:u}),P.warn("migration step failed (may be idempotent)",{id:n.id,error:u,sqlCount:n.up.length});}}return i}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 c=utils.Filesystem.toUnixPath,l=utils.Log.create({service:"codebase-database"}),N=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:5e3}),this.db.initialize();try{this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("foreign_keys = ON");}catch(t){l.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){throw l.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 R("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:c(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(n=>({...n,file_path:c(n.file_path)})),s=this.db.prepare(`
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(i=>({...i,file_path:c(i.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(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 l=s.get(i.id);l&&t.run(l.rowid),r.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.text);}catch(l){E.warn("FTS update failed for node",{nodeId:i.id,error:String(l)});}})(e);}insertEdge(e){this.db.prepare(`
76
+ `);this.db.transaction(i=>{for(let n of i)s.run(n.id,n.name,n.ast_type,n.language,n.file_path,n.start_line,n.start_col,n.end_line,n.end_col,n.text,n.created_at);this.ftsAvailable&&this.updateFtsNodesInternal(i);})(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 i of e)try{let n=s.get(i.id);n&&t.run(n.rowid),r.run(i.id,i.name,i.ast_type,i.language,i.file_path,i.text);}catch(n){l.warn("FTS update failed for node",{nodeId:i.id,error:String(n)});}}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){l.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(n=>{for(let a of n)try{let u=s.get(a.id);u&&t.run(u.rowid),r.run(a.id,a.name,a.ast_type,a.language,a.file_path,a.text);}catch(u){l.warn("FTS update failed for node",{nodeId:a.id,error:String(u)});}})(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 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(`%${c(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(`
82
+ `);this.db.transaction(r=>{for(let i of r)t.run(i.id,i.source,i.target,i.relation,i.created_at);})(e);}queryNodes(e){let t=[],s=[];e.filePath&&(t.push("file_path LIKE ?"),s.push(`%${c(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(i){throw new p("Failed to query nodes","queryNodes",i instanceof Error?i:new Error(String(i)))}}findNodesByName(e){if(!e.name)return [];let t=e.limit??50,s=e.file?`%${c(e.file)}%`:null,r=e.kind?`%${e.kind.toLowerCase()}%`:null,i=new Set,n=[],a=(E,g)=>{i.has(E.id)||(i.add(E.id),n.push({node:E,matchKind:g}));},u=(E,g)=>{s&&(E.push("file_path LIKE ?"),g.push(s)),r&&(E.push("LOWER(ast_type) LIKE ?"),g.push(r));};try{let E=["name = ?"],g=[e.name];u(E,g),g.push(t);let T=this.db.prepare(`SELECT * FROM nodes WHERE ${E.join(" AND ")} LIMIT ?`).all(...g);for(let h of T)a(h,"exact");if(T.length>0&&e.file)return n.slice(0,t);if(n.length<t){let h=this.db.prepare("SELECT * FROM nodes WHERE name LIKE ? LIMIT ?").all(`%${e.name}%`,t);for(let m of h)a(m,"qualified");}if(n.length>0&&e.file)return n.slice(0,t);if(n.length===0&&e.name){let h=["name LIKE ?"],m=[`%${e.name}%`];s&&(h.push("file_path LIKE ?"),m.push(s)),r&&(h.push("LOWER(ast_type) LIKE ?"),m.push(r)),h.push("?"),m.push(t);let f=this.db.prepare(`SELECT * FROM nodes WHERE ${h.join(" AND ")}`).all(...m);for(let _ of f)a(_,"substring");}return n.slice(0,t)}catch(E){throw new p("Failed to find nodes by name","findNodesByName",E instanceof Error?E:new Error(String(E)))}}queryEdges(e){let t=[],s=[];if(e.sourceOrTarget&&e.sourceOrTarget.length>0){let i=e.sourceOrTarget.map(()=>"?").join(",");t.push(`(source IN (${i}) OR target IN (${i}))`),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(i){throw new p("Failed to query edges","queryEdges",i instanceof Error?i:new Error(String(i)))}}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(l.debug("searchNodesFts start",{query:e,limit:t,ftsAvailable:this.ftsAvailable}),!this.ftsAvailable)return l.debug("searchNodesFts skip - FTS not available"),[];try{let s=e.split(/\s+/).map(a=>`${a}*`).join(" ");l.debug("searchNodesFts query",{ftsQuery:s});let n=this.db.prepare(`
83
83
  SELECT
84
84
  nodes_fts.id,
85
85
  nodes_fts.name,
@@ -97,33 +97,33 @@
97
97
  WHERE nodes_fts.text MATCH ?
98
98
  ORDER BY score DESC
99
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=c(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=c(e);return this.db.prepare(`
100
+ `).all(s,t);return l.debug("searchNodesFts done",{resultCount:n.length}),n}catch(s){return l.warn("searchNodesFts failed",{error:String(s)}),[]}}deleteNodesByFile(e){let t=c(e);if(this.ftsAvailable)try{let r=this.db.prepare("SELECT rowid FROM nodes_fts WHERE file_path = ?").all(t);for(let i of r)this.db.prepare("DELETE FROM nodes_fts WHERE rowid = ?").run(i.rowid);}catch(r){l.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=c(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
104
  `).run(t,t).changes}getFileHash(e){return this.db.prepare("SELECT content_hash FROM file_hashes WHERE file_path = ?").get(c(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(c(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(c(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(`
107
+ `).run(c(e),t,new Date().toISOString());}deleteFileHash(e){this.db.prepare("DELETE FROM file_hashes WHERE file_path = ?").run(c(e));}getAllFileHashes(){return this.db.prepare("SELECT * FROM file_hashes").all()}checkIntegrity(){let e=b=>this.db.prepare(b).get().c,t=b=>e(b),s={nodes:t("SELECT COUNT(*) as c FROM nodes"),edges:t("SELECT COUNT(*) as c FROM edges"),file_hashes:t("SELECT COUNT(*) as c FROM file_hashes"),fts:t("SELECT COUNT(*) as c FROM nodes_fts"),node_embeddings:t("SELECT COUNT(*) as c FROM node_embeddings"),embedding_cache:t("SELECT COUNT(*) as c FROM embedding_cache"),parse_errors:t("SELECT COUNT(*) as c FROM parse_errors"),unresolved_refs:t("SELECT COUNT(*) as c FROM unresolved_refs"),name_segment_vocab:t("SELECT COUNT(*) as c FROM name_segment_vocab"),project_metadata:t("SELECT COUNT(*) as c FROM project_metadata"),schema_migrations:t("SELECT COUNT(*) as c FROM schema_migrations"),meta:t("SELECT COUNT(*) as c FROM meta")},r=[],i=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
- `);n>0&&r.push({severity:"error",message:`orphan node_embeddings: ${n}`});let a=t(`
110
+ `);i>0&&r.push({severity:"error",message:`orphan node_embeddings: ${i}`});let n=t(`
111
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(`
112
+ `);n>0&&r.push({severity:"error",message:`orphan edges (source): ${n}`});let a=t(`
113
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 l=t("SELECT COUNT(*) as c FROM edges WHERE source = target");l>0&&r.push({severity:"error",message:`self-loop edges: ${l} \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(`
114
+ `);a>0&&r.push({severity:"error",message:`orphan edges (target): ${a}`});let u=t("SELECT COUNT(*) as c FROM edges WHERE source = target");u>0&&r.push({severity:"error",message:`self-loop edges: ${u} \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 g=t(`
115
115
  SELECT COUNT(*) as c FROM file_hashes fh
116
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(`
117
+ `);g>0&&r.push({severity:"warn",message:`orphan file_hashes (no nodes): ${g} \u2014 run \`easbot codebase sync\` to cleanup`});let T=t(`
118
118
  SELECT COUNT(DISTINCT n.file_path) as c FROM nodes n
119
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(`
120
+ `);T>0&&r.push({severity:"warn",message:`node files without hash: ${T}`});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 m=t("SELECT COUNT(*) as c FROM nodes WHERE ast_type IS NULL OR ast_type = ''");m>0&&r.push({severity:"error",message:`nodes with null/empty ast_type: ${m}`});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 _=t("SELECT COUNT(*) as c FROM nodes WHERE file_path IS NULL OR file_path = ''");_>0&&r.push({severity:"error",message:`nodes with null/empty file_path: ${_}`});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
121
  SELECT COUNT(*) as c FROM nodes
122
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(`
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(),i={};for(let n of r)i[n.key]=n.value;return {nodeCount:e?.c??0,edgeCount:t?.c??0,indexedFiles:s?.c??0,dbPath:this.dbPath,meta:i,indexState:this.getIndexState(),extractionVersion:parseInt(this.getMeta("indexed_with_extraction_version")??"0",10),isStale:this.isIndexStale()}}setLastSync(){this.db.prepare(`
124
124
  INSERT OR REPLACE INTO meta (key, value)
125
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(`
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(N)),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<N}detectAndMarkStaleOnInit(){if(this.isIndexStale()){let e=this.getMeta("indexed_with_extraction_version");l.warn("codebase db is stale",{recorded:e??"(none)",current:String(N),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
127
  SELECT embedding FROM embedding_cache WHERE content_hash = ?
128
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
129
  INSERT OR REPLACE INTO embedding_cache (content_hash, embedding)
@@ -133,7 +133,7 @@
133
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
134
  INSERT OR REPLACE INTO node_embeddings (node_id, embedding_text, embedding)
135
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(`
136
+ `);this.db.transaction(r=>{for(let i of r)try{t.run(i.nodeId,i.embeddingText,i.embedding);}catch(n){l.warn("Failed to store embedding for node",{nodeId:i.nodeId,error:String(n)});}})(e);}insertParseError(e){return this.db.prepare(`
137
137
  INSERT INTO parse_errors (file_path, language, stage, message, line)
138
138
  VALUES (?, ?, ?, ?, ?)
139
139
  `).run(c(e.filePath),e.language,e.stage,e.message,e.line??null).changes}insertUnresolvedRef(e){return this.db.prepare(`
@@ -144,11 +144,11 @@
144
144
  INSERT INTO unresolved_refs
145
145
  (from_node_id, reference_name, reference_kind, line, col, file_path, language, candidates)
146
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,c(i.filePath),i.language,i.candidates?JSON.stringify(i.candidates):null);return this.db.prepare(s).run(...r).changes}insertNameSegment(e,t){return this.db.prepare(`
147
+ `,r=[];for(let a of e)r.push(a.fromNodeId??null,a.referenceName,a.referenceKind,a.line??null,a.col??null,c(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
148
  INSERT OR IGNORE INTO name_segment_vocab (segment, name) VALUES (?, ?)
149
149
  `).run(e,t).changes}insertNameSegmentsBatch(e){if(e.length===0)return 0;let s=`
150
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){let s=e==="worktree"||e==="project"?c(t):t;return this.db.prepare(`
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"?c(t):t;return this.db.prepare(`
152
152
  INSERT OR REPLACE INTO project_metadata (key, value, updated_at)
153
153
  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(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);}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=g;exports.c=M;exports.d=u;exports.e=A;exports.f=v;exports.g=x;exports.h=w;exports.i=p;exports.j=W;exports.k=D;exports.l=X;exports.m=m;exports.n=H;exports.o=te;exports.p=se;exports.q=re;
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(n=>{for(let a of n)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){l.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=R;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=N;exports.n=X;exports.o=te;exports.p=se;exports.q=re;
@@ -0,0 +1,49 @@
1
+ import {c,s}from'./chunk-DHH2XXGJ.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';var T=class extends Error{constructor(n,c,a$1){super(n);a(this,"code",c);a(this,"details",a$1);this.name="ServiceError";}},L=class extends T{constructor(t,n=[]){super(`Node not found: ${t}`,"NOT_FOUND",{name:t,candidates:n});}},_=class extends T{constructor(t,n){super(`Ambiguous name "${t}" \u2014 ${n.length} candidates`,"AMBIGUOUS",{name:t,candidates:n});}};var xe=Log.create({service:"codebase-service"}),x=Filesystem.toUnixPath;function Ne(e,t){let n={exact:1,qualified:.85,substring:.5}[e];return t?Math.min(1,n+.2):n}async function k(e,t,n){if(n.nodeId){let l=e.getNode(n.nodeId);if(!l)throw new L(`nodeId=${n.nodeId}`);return {node:l,candidates:[]}}if(!n.name)throw new T("Either name or nodeId is required","NOT_FOUND",n);let a=e.getDatabase().findNodesByName({name:n.name,file:n.file,kind:n.kind,limit:50});if(a.length===0)throw new L(n.name);let s=!!n.file,d=n.file?x(n.file):null,o=a.map(l=>{let u=d?x(l.node.file_path).endsWith(d)||x(l.node.file_path).includes(d):false;return {node:l.node,score:Ne(l.matchKind,u),matchKind:l.matchKind,inFile:u}});if(o.sort((l,u)=>u.score-l.score),o.length===1)return {node:o[0].node,candidates:o.map(l=>({node:l.node,score:l.score}))};let i=o[0].score,r=o.filter(l=>l.score===i);if(r.length===1)return {node:r[0].node,candidates:o.slice(0,10).map(l=>({node:l.node,score:l.score}))};if(s&&r.length>1){let l=r.filter(u=>u.inFile);if(l.length===1)return {node:l[0].node,candidates:o.slice(0,10).map(u=>({node:u.node,score:u.score}))}}throw new _(n.name,o.slice(0,10).map(l=>({node:l.node,score:l.score})))}async function P(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 Re(e,t,n,c){let s=`
2
+ SELECT id, source, target, relation, created_at FROM edges
3
+ WHERE relation IN (${n.map(()=>"?").join(",")})
4
+ AND source != target
5
+ AND (
6
+ target = ?
7
+ OR target = ?
8
+ )
9
+ LIMIT ?
10
+ `,d=t.name.split("@")[0]??t.name,o=`${t.language}:*:*:${d}`;return e.queryAll(s,[...n,t.id,o,c])}function Pe(e,t,n,c){let s=`
11
+ SELECT id, source, target, relation, created_at FROM edges
12
+ WHERE relation IN (${n.map(()=>"?").join(",")})
13
+ AND source != target
14
+ AND source = ?
15
+ LIMIT ?
16
+ `;return e.queryAll(s,[...n,t.id,c])}function ne(e,t,n,c){let a=c==="in"?e.source:e.target;t.id;let d=n.getNodeById(a);if(!d&&a.includes(":*:")){let o=a.split(":").pop()??a,i=o.split("@")[0]??o;if(i&&i!==a){let r=n.findNodesByName({name:i}),l=t.file_path??"",u=l.split(/[/\\]/).pop()??"",p=r.find(g=>!g.node.file_path||!l?false:g.node.file_path===l||u&&g.node.file_path.split(/[/\\]/).pop()===u)??r[0];p&&(d=p.node);}}if(!d){let o=a.split(":").pop()??a;return {id:a,name:o,astType:"unresolved",filePath:"(unresolved)",startLine:0,relation:e.relation}}return {id:d.id,name:d.name,astType:d.ast_type,filePath:x(d.file_path),startLine:d.start_line??0,relation:e.relation}}async function re(e,t){let n=Date.now(),d=await(await P(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 i=t.kind.toLowerCase();d=d.filter(r=>r.ast_type.includes(i)||r.name.toLowerCase().includes(i));}if(t.file){let i=x(t.file);d=d.filter(r=>x(r.file_path).endsWith(i)||x(r.file_path).includes(i));}let o=d.map(i=>({nodeId:i.id,name:i.name,kind:i.ast_type??"unknown",filePath:x(i.file_path),startLine:i.start_line,endLine:i.end_line,edges:i.edges??[],source:"basic",score:0,snippet:(i.text??"").slice(0,200).replace(/\s+/g," ").trim()}));return {total:o.length,hits:o,durationMs:Date.now()-n,truncated:false}}async function Ce(e,t){let n=await P(e),c=n.getQuery(),a=n.getDatabase(),{node:s}=await k(c,e,t),d=[];if(t.includeEdges){let o=t.edgesLimit??50;d=a.queryEdges({sourceOrTarget:[s.id],limit:o});}return {node:s,edges:d}}var Te=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","HAS_METHOD","HAS_PROPERTY","METHOD_OVERRIDES"];async function Se(e,t){let n=await P(e),c=n.getQuery(),a=n.getDatabase(),{node:s}=await k(c,e,t);if(!s)return {root:null,nodes:[],edges:[],truncated:false,totalNodes:0,totalEdges:0};let d=t.depth??2,o=t.maxNodes??100,i=t.direction??"both",r=new Map,l=[{nodeId:s.id,depth:0}];r.set(s.id,0);let u=[],p=false;for(;l.length>0;){let f=l.shift();if(f.depth>=d)continue;if(r.size>=o){p=true;break}let b=c.queryNeighbors(f.nodeId,{direction:i,relationTypes:t.relationTypes??Te,limit:o-r.size+1});for(let h of b.edges){u.push(h);let $=h.source===f.nodeId?h.target:h.source;if(!r.has($)&&(r.set($,f.depth+1),l.push({nodeId:$,depth:f.depth+1}),r.size>=o)){p=true;break}}if(p)break}let g=Array.from(r.keys()),N=g.length>0?a.queryNodes({ids:g}):[],m=new Map(N.map(f=>[f.id,f])),R=[];for(let[f,b]of r.entries()){let h=m.get(f);h&&R.push({node:h,depth:b});}return {root:s,nodes:R,edges:u,truncated:p,totalNodes:R.length,totalEdges:u.length}}var Ie=["CALLS","IMPORTS","TYPE_REFERENCES"];async function $e(e,t){let n=await P(e),c=n.getQuery(),a=n.getDatabase(),{node:s}=await k(c,e,t);if(!s)return {root:null,totalImpacted:0,buckets:[]};let d=t.depth??2,o=t.maxResults??50,i=t.relationTypes??Ie,r=new Set([s.id]),l=[],u=[s.id],p=new Map([[s.id,s.name]]);for(let g=1;g<=d&&!(u.length===0||r.size-1>=o);g++){u.map(()=>"?").join(",");let m=i.map(()=>"?").join(","),R=s,f=u.map(E=>{let A=p.get(E)??"",K=A.split("@")[0]??A;return `${R.language}:*:*:${K}`}),b=[...u,...f],h=b.map(()=>"?").join(","),$=a.queryAll(`SELECT source, target, relation FROM edges WHERE target IN (${h}) AND relation IN (${m})`,[...b,...i]),w=[],Z=new Set;for(let E of $)if(!r.has(E.source)&&!Z.has(E.source)&&(Z.add(E.source),r.add(E.source),w.push(E.source),r.size-1>=o))break;if(w.length>0){let E=w.slice(0,10),A=a.queryNodes({ids:E}),K=new Map(A.map(y=>[y.id,y]));for(let y of A)y?.name&&!p.has(y.id)&&p.set(y.id,y.name);let j=new Map;for(let y of $)j.has(y.source)||j.set(y.source,y.relation);let ge=E.map(y=>{let W=K.get(y);return {id:y,name:W?.name??"(unknown)",filePath:W?x(W.file_path):"(unknown)",relation:j.get(y)??"CALLS"}});l.push({depth:g,count:w.length,sample:ge});}u=w;}return l.length===0&&xe.warn("impact: no incoming edges found",{root:s.name,depth:d,relationTypes:i}),{root:s,totalImpacted:r.size-1,buckets:l}}var oe=["CALLS","IMPORTS","TYPE_REFERENCES","EXTENDS","IMPLEMENTS","METHOD_OVERRIDES"];async function Le(e,t){return se(e,t)}async function Fe(e,t){return ae(e,t)}async function se(e,t){let n=await P(e),c=n.getQuery(),a=n.getDatabase(),{node:s}=await k(c,e,t);if(!s)return {root:null,callers:[],truncated:false};let d=t.maxResults??20,o=t.relationTypes??oe,i=Re(a,s,o,d+1),r=[];for(let u of i){let p=ne(u,s,a,"in");p&&r.push(p);}let l=r.length>d;return {root:s,callers:l?r.slice(0,d):r,truncated:l}}async function ae(e,t){let n=await P(e),c=n.getQuery(),a=n.getDatabase(),{node:s}=await k(c,e,t);if(!s)return {root:null,callees:[],truncated:false};let d=t.maxResults??20,o=t.relationTypes??oe,i=Pe(a,s,o,d+1),r=[];for(let u of i){let p=ne(u,s,a,"out");p&&r.push(p);}let l=r.length>d;return {root:s,callees:l?r.slice(0,d):r,truncated:l}}async function we(e,t){if(!t.query)throw new T("explore requires a non-empty query","NOT_FOUND",{query:t.query});let c=await P(e);c.getQuery();let s=c.getDatabase(),o=(await re(e,{query:t.query,file:t.file,kind:t.kind,intent:t.intent,maxResults:t.maxFiles??5,enableFts:true,enableEmbedding:true})).hits,i=new Map;for(let u of o){let p=x(u.filePath),g=i.get(p);g?g.push(u):i.set(p,[u]);}let r=t.maxSymbols??3,l=[];for(let[u,p]of i){let g=p.slice(0,r),N=[];for(let m of g){let R=await se(e,{name:m.name,file:u,kind:t.kind,maxResults:5}),f=await ae(e,{name:m.name,file:u,kind:t.kind,maxResults:5});N.push({node:(()=>{let b={id:m.nodeId,name:m.name,ast_type:m.kind,language:"ts",file_path:m.filePath,start_line:m.startLine??0,end_line:m.endLine??0};try{let h=s.getNodeById(m.nodeId);return {...b,text:h?.text??""}}catch{return {...b,text:""}}})(),callers:R.callers,callees:f.callees});}l.push({file:u,symbols:N});}return {query:t.query,entryPoints:l,totalHits:o.length}}async function Ae(e,t){return await(await P(e)).getStatus()}async function _e(e,t){return await(await P(e)).healthCheck()}var ie=Filesystem.toUnixPath;function Oe(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 De(e){let t=e.text??"";if(!t)return [];let n=t.slice(0,80),c=[];return /\basync\s/.test(n)&&c.push("async"),/\bstatic\s/.test(n)&&c.push("static"),/\babstract\s/.test(n)&&c.push("abstract"),/\breadonly\s/.test(n)&&c.push("readonly"),/\bconst\s/.test(n)&&c.push("const"),/\blet\s/.test(n)&&c.push("let"),c}function C(e){return {id:e.id,name:e.name,astType:e.ast_type,language:e.language,filePath:ie(e.file_path),startLine:e.start_line??0,endLine:e.end_line??0,isExported:Oe(e),modifiers:De(e)}}function F(e,t){return {id:e.id,source:e.source,target:e.target,relation:e.relation,direction:t}}function z(e){return e.map(t=>({node:{id:t.nodeId,name:t.name,astType:t.kind,language:"typescript",filePath:ie(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=>F({...n}))}))}function Y(){return {id:"",name:"",astType:"",language:"",filePath:"",startLine:0,endLine:0,isExported:false,modifiers:[]}}var qe=Log.create({service:"codebase-format-truncate"}),X="**`",Me="**",ce=24e3,de=25e3;async function q(e,t={}){let n=t.softLimit??ce,c=t.hardCeiling??de,a=t.toolName??"codebase",s=t.writeToDisk!==false;if(e.length<=n)return {content:e,truncated:false};let d=e.slice(0,c),o=d.lastIndexOf(`
17
+ ${X}`),i=d.lastIndexOf(`
18
+ `),r;o>c*.5?r=o:i>0?r=i:r=-1;let l=r>0?d.slice(0,r):d,p=l+"\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(!s)return {content:p,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-l.length}/${e.length} characters truncated ...`};try{let g=await TruncateContent.truncate(e,{maxChars:l.length,direction:"head",label:`${a}-output`});return g.truncated?{content:p,truncated:!0,outputPath:g.outputPath,hint:TruncateContent.formatHint(g),info:`... ${g.removedLength}/${g.originalLength} characters truncated ...`}:{content:p,truncated:!0,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-l.length}/${e.length} characters truncated ...`}}catch(g){return qe.warn("TruncateContent.truncate failed, returning without disk hint",{error:g instanceof Error?g.message:String(g)}),{content:p,truncated:true,outputPath:"",hint:"Use Grep/Read to inspect the truncated sections.",info:`... ${e.length-l.length}/${e.length} characters truncated ...`}}}function M(e,t={}){let n=t.softLimit??ce,c=t.hardCeiling??de;if(e.length<=n)return {content:e,truncated:false};let a=e.slice(0,c),s=a.lastIndexOf(`
19
+ ${X}`),d=a.lastIndexOf(`
20
+ `),o;s>c*.5?o=s:d>0?o=d:o=-1;let i=o>0?a.slice(0,o):a;return {content:i+`
21
+
22
+ ... (output truncated; tail dropped at section boundary)`,truncated:true,outputPath:"",hint:"",info:`... ${e.length-i.length}/${e.length} characters truncated ...`}}function He(e,t=Date.now()){let n=Math.max(0,Math.floor((t-e)/1e3));return n>60?">60s ago":`${n}s ago`}function H(e,t){if(!e||e.length===0)return null;let n=e.filter(a=>t.has(a.path));return n.length===0?null:`\u26A0\uFE0F Index may be stale for: ${n.map(a=>`${a.path} (edited ${He(a.lastEventAt)})`).join(", ")}
23
+
24
+ `}function O(e,t,n={}){return (ue[e]??ue.default).replace(/<(\w+)>/g,(a,s)=>s==="tool"?t:n[s]??`<${s}>`)}var ue={search:`---
25
+
26
+ > **Complete source for N files is included above \u2014 do NOT re-read them.**
27
+ > 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:`---
28
+
29
+ > **Output truncated to budget; the content above is the source of truth.**
30
+ > For more detail, call \`<tool>\` with refined parameters.`};async function B(e,t){let{pendingFiles:n,toolName:c,sync:a=false}=t;if(e.length===0)return D(c,"No matches found.","Try broader search terms, or use `explore` to read source.");let s=Ue(e),d=new Set(s.keys()),o=[];o.push(H(n,d)??"");let i="[[codebase-search-summary]]";o.push(i+`
31
+ `);let r=e.length;o.push(`**Files with matches:** ${s.size}
32
+ `);for(let[g,N]of s){let m=N.map(h=>h.node.name),R=m.slice(0,5).join(", "),f=m.length>5?`, +${m.length-5} more`:"";o.push(`**\`${g}\`** \u2014 ${R}${f}
33
+ `);let b=N[0]?.node.language??"";o.push("```"+b);for(let h of N)o.push(`L${h.node.startLine} ${h.snippet}`);o.push("```\n");}o.push(O("search",c,{}));let l=o.join(`
34
+ `),u=`Found ${r} symbol${r===1?"":"s"} across ${s.size} file${s.size===1?"":"s"}.`,p=l.replace(i,u);return v(p,t,a)}async function U(e,t,n){let{pendingFiles:c,toolName:a,sync:s=false}=n;if(t.length===0||t.every(r=>r.count===0))return D(a,`No incoming edges for \`${e.name}\`.`,"This symbol has no callers \u2014 safe to refactor.");let d=t.reduce((r,l)=>r+l.count,0),o=Be(d),i=[];i.push(H(c,new Set([e.filePath]))??""),i.push(`**Impact for \`${e.name}\`** (root: ${e.filePath}:${e.startLine}, total impacted: ${d})
35
+ `);for(let r of t){i.push(`- **d=${r.depth}** (${r.count} nodes) \u2014 ${r.riskLabel}`);for(let l of r.samples.slice(0,5))i.push(` - \`${l.name}\` ${l.file}:${l.line} [${l.relation}]`);r.samples.length>5&&i.push(` - ... and ${r.samples.length-5} more`);}return i.push(O("impact",a,{root:e.name,riskLevel:o})),v(i.join(`
36
+ `),n,s)}function Be(e){return e>=100?"CRITICAL":e>=50?"HIGH":e>=10?"MEDIUM":"LOW"}function V(e){return e===1?"WILL BREAK (direct callers)":e===2?"LIKELY AFFECTED (indirect)":"MAY NEED TESTING (transitive)"}async function J(e,t){let{root:n,incoming:c,outgoing:a,neighbors:s}=e,{pendingFiles:d,toolName:o,sync:i=false}=t;if(c.length===0&&a.length===0&&s.length===0)return D(o,`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})
37
+ `),r.push(`**Incoming** (${c.length}):`);for(let l of c.slice(0,10))r.push(`- ${l.source} \u2192 [${l.relation}] \u2192 \`${n.name}\``);c.length>10&&r.push(`- ... and ${c.length-10} more`),r.push(""),r.push(`**Outgoing** (${a.length}):`);for(let l of a.slice(0,10))r.push(`- \`${n.name}\` \u2192 [${l.relation}] \u2192 ${l.target}`);if(a.length>10&&r.push(`- ... and ${a.length-10} more`),r.push(""),s.length>0){r.push(`**Neighbors** (${s.length}):`);for(let l of s.slice(0,20))r.push(`- [d=${l.depth}] \`${l.node.name}\` (${l.node.astType}) ${l.node.filePath}:${l.node.startLine}`);s.length>20&&r.push(`- ... and ${s.length-20} more`),r.push("");}return r.push(O("context",o,{})),v(r.join(`
38
+ `),t,i)}async function G(e,t,n){let{pendingFiles:c,toolName:a,sync:s=false}=n;if(!e.id)return D(a,"Node not found.","Check the node ID or use `search` to find it.");let d=t.filter(r=>r.direction==="in"),o=t.filter(r=>r.direction==="out"),i=[];i.push(H(c,new Set([e.filePath]))??""),i.push(`**Node: \`${e.name}\`**
39
+ `),i.push(`- ID: \`${e.id}\``),i.push(`- Kind: ${e.astType}`),i.push(`- Language: ${e.language}`),i.push(`- Location: ${e.filePath}:${e.startLine}-${e.endLine}`),i.push(`- Exported: ${e.isExported}`),e.modifiers.length>0&&i.push(`- Modifiers: ${e.modifiers.join(", ")}`),i.push(""),i.push(`**Edges** (incoming: ${d.length} / outgoing: ${o.length}):`);for(let r of d.slice(0,5))i.push(`- \u2190 [${r.relation}] ${r.source}`);for(let r of o.slice(0,5))i.push(`- \u2192 [${r.relation}] ${r.target}`);return t.length>10&&i.push(`- ... and ${t.length-10} more`),i.push(O("default",a,{})),v(i.join(`
40
+ `),n,s)}async function pe(e,t){let{entryPoints:n,totalHits:c,query:a}=e,{toolName:s,sync:d=false}=t;if(n.length===0)return D(s,`No matches for \`${a}\`.`,"Try broader search terms, or use `callers` / `callees` to traverse from a known symbol.");let o=[];o.push(`## Code Context
41
+ `),o.push(`**Query:** ${a} `),o.push(`**Total hits:** ${c} `),o.push(`**Entry points:** ${n.length}
42
+ `);for(let i of n){o.push(`**\`${i.file}\`** \u2014 ${i.symbols.length} symbol${i.symbols.length===1?"":"s"}
43
+ `);for(let r of i.symbols){let l=(r.source??"").trim()||"(source not included)",u=r.node.language;if(o.push("```"+u),o.push(`L${r.node.startLine}-L${r.node.endLine} ${r.node.name} (${r.node.astType}${r.node.modifiers.length>0?`, ${r.node.modifiers.join(" ")}`:""})`),o.push(""),o.push(l),o.push("```\n"),r.callers.length>0){o.push(`**Callers of \`${r.node.name}\` (${r.callers.length}):**`);for(let p of r.callers.slice(0,5))o.push(`- [${p.relation}] \`${p.name}\` ${p.filePath}:${p.startLine}`);r.callers.length>5&&o.push(`- ... and ${r.callers.length-5} more`),o.push("");}if(r.callees.length>0){o.push(`**Callees of \`${r.node.name}\` (${r.callees.length}):**`);for(let p of r.callees.slice(0,5))o.push(`- [${p.relation}] \`${p.name}\` ${p.filePath}:${p.startLine}`);r.callees.length>5&&o.push(`- ... and ${r.callees.length-5} more`),o.push("");}}}return o.push(`---
44
+ `),o.push(O("context",s,{})),v(o.join(`
45
+ `),t,d)}function Ue(e){let t=new Map;for(let n of e){let c=n.node.filePath,a=t.get(c);a?a.push(n):t.set(c,[n]);}return t}function D(e,t,n){return `**${e}**
46
+
47
+ ${t}
48
+
49
+ > **Tip:** ${n}`}async function v(e,t,n){let c={softLimit:t.softLimit,hardCeiling:t.hardCeiling,toolName:t.toolName,writeToDisk:n?false:t.writeToDisk};return (n?M(e,c):await q(e,c)).content}var Ke=Log.create({service:"codebase-format-render"});async function je(e,t){if(e.length===0)return B([],t);let n=z(e);return B(n,t)}async function We(e,t,n){if(t.length===0)return U(C(e),[],n);let c=[{depth:1,count:t.length,riskLabel:V(1),samples:t.slice(0,10).map(a=>({name:a.source.name,file:C(a.source).filePath,line:a.source.start_line??0,relation:a.relation}))}];return U(C(e),c,n)}async function Qe(e,t,n,c,a){let s=C(e),d=t.map(r=>F(r,"in")),o=n.map(r=>F(r,"out")),i=c.map(r=>({node:C(r),depth:1}));return J({root:s,incoming:d,outgoing:o,neighbors:i},a)}async function ze(e,t,n){if(!e)return G(Y(),[],n);let c=C(e),a=t.map(s=>{let d=s.target===e.id?"in":"out";return F(s,d)});return G(c,a,n)}async function Ye(e,t){let n={query:e.query,totalHits:e.totalHits,entryPoints:e.entryPoints.map(c=>({file:c.file,symbols:c.symbols.map(a=>({node:C(a.node),source:a.node.text??"",callers:a.callers.map(s=>({name:s.name,filePath:s.filePath,startLine:s.startLine,relation:s.relation})),callees:a.callees.map(s=>({name:s.name,filePath:s.filePath,startLine:s.startLine,relation:s.relation}))}))}))};return pe(n,t)}Ke.debug("format/render.ts loaded");export{We as A,Qe as B,ze as C,Ye as D,T as a,L as b,_ as c,re as d,Ce as e,Se as f,$e as g,Le as h,Fe as i,we as j,Ae as k,_e as l,C as m,F as n,z as o,Y as p,X as q,Me as r,q as s,M as t,B as u,U as v,V as w,J as x,G as y,je as z};