Skip to content

Latest commit

 

History

History
201 lines (154 loc) · 9.37 KB

File metadata and controls

201 lines (154 loc) · 9.37 KB
source docs/API.md
source_version 0.7.0
translation_version 0.7.0
last_synced 2026-07-16
status complete

EngramGraph API

语言: English · 繁體中文 · 简体中文

engramgraph 的 library 参考。以下全部都从包根目录导出:

import { /* ... */ } from "engramgraph";

包以 ESM 为主并附 CJS build;类型已内置。运行环境:Node ≥ 22。

graph-db — Kuzu 抽象

class GraphConnection

  • static open(dbPath: string): GraphConnection — 在 dbPath 打开(或创建)Kuzu 数据库。
  • query(cypher: string, params?: Record<string, KuzuValue>): Promise<GraphRow[]>
  • close(): Promise<void> — 销毁注意事项见 CONTRIBUTING.md; 建议使用长生命周期连接。

initSchema(conn): Promise<void>

幂等创建 6 个节点表 + 8 个关系表。另外导出:NODE_TABLE_DDLREL_TABLE_DDLNODE_TABLESREL_TABLES

clearGraph(conn): Promise<void>

清空所有数据但保留表(对每个节点表 DETACH DELETE),让重新索引可清掉已不存在的节点 (MERGE writer 从不删除)。

resolveDbPath(loc?) / openGraph(loc?)

解析图谱 DB 路径 / 打开它(建目录 + schema)。loc 为字符串路径或 GraphLocationOptions = { dbPath?, graph?, isolation?, cwd? }。优先级: dbPath > env ENGRAM_DB > graph 名 → .engram/<name>.db > isolation: "git-branch"(按当前分支)> 默认 .engram/graph.dbIsolationMode = "single" | "git-branch"

writeFragment(conn, fragment: GraphFragment): Promise<void>

持久化一个与供应商无关的 { nodes, edges } 片段。

Schema(DDL)

NODE Function(id, name, file, start_line, confidence, provider)   PK id
NODE Class(id, name, file, provider)                              PK id
NODE Module(id, path)                                             PK id
NODE Spec(id, title, status, confidence, origin)                  PK id
NODE Decision(id, title, date, confidence, origin)                PK id
NODE Doc(id, title, status, confidence, origin)                   PK id

REL CALLS(Function → Function, call_count, confidence, provider)
REL IMPORTS(Module → Module)
REL DEFINES(Module → Function)
REL IMPLEMENTS(Module → Spec)
REL IMPACTS(Decision → Spec)
REL SUPERSEDES(Decision → Decision)
REL RELATES(Spec → Spec)
REL REFERENCES(Doc → Doc)

类型:GraphRowGraphNodeGraphEdgeGraphFragmentNodeLabelRelLabel,以及各节点 FunctionNode / ClassNode / ModuleNode / SpecNode / DecisionNode / DocNode

code-graph — 源代码 → 图谱

tree-sitter 将 .ts / .tsx / .js 解析为 Function / Class / Module 节点并解析 CALLS 边。函数 id 为作用域限定且在重新索引时稳定—— file#outer.helperfile#Class.method

  • extractCodeGraph(source: string, opts: ExtractOptions): Extraction — 将单文件 解析为片段(不写入 DB)。ExtractOptions = { filePath, language? }
  • extractProject(files: ProjectFile[]): ProjectExtraction — 解析整个 repo,跨文件解析 CALLS。
  • indexFile(conn, source, opts: ExtractOptions): Promise<IndexResult> — 提取 + 写入单文件。IndexResult = { module, functions, classes, calls }
  • indexProject(conn, files: ProjectFile[]): Promise<ProjectIndexResult> — 索引整个 repo(跨文件 CALLS)。ProjectIndexResult = { files, functions, classes, calls, ambiguous, unresolved }(ambiguous = 被调用名称匹配到 > 1 个函数; unresolved = 匹配不到——两者都跳过)。

ProjectFile = { path, source, language? };省略 language 时由路径扩展名推断。

查询

  • callers(conn, name: string, depth = 1): Promise<CallNode[]> — 可传递调用 name 的函数(depth 夹到 1..10)。
  • callees(conn, name: string, depth = 1): Promise<CallNode[]>name 可传递调用的函数。
  • callChain(conn, symbol: string, direction: CallDirection = "both", depth = 1): Promise<CallChainResult>

CallNode = { id, name, file }CallDirection = "callers" | "callees" | "both"CallChainResult = { symbol, direction, depth, callers, callees }

knowledge-graph — spec/decision markdown → 图谱

一个 参考 知识 adapter:spec 文档 → Spec、decision / ADR 文档 → Decision、 关系 front-matter + [[ref]] 链接 → IMPACTS / SUPERSEDES

  • indexKnowledgeDocs(conn, docs: KnowledgeDoc[]): Promise<KnowledgeIndexResult>KnowledgeDoc = { content, fallbackId? };结果计数 { specs, decisions, impacts, supersedes }
  • parseKnowledgeDoc(doc): ParsedKnowledgeDoc | null — 解析单一文档(不写入); 若无法解析出 id(来自 front-matter idfallbackId 或正文)则返回 null
  • classifyRef(id): ClassifiedRef — 将 id 分类为 SpecDecision
  • impactAnalysis(conn, nodeId: string, maxHops = 3): Promise<ImpactAnalysisResult> — 某 spec 影响链中的决策;maxHops(SUPERSEDES 深度)夹到 1..10ImpactAnalysisResult = { nodeId, decisions: ImpactNode[] }ImpactNode = { id, title, via: "direct" | "supersedes" }
  • XspecDecKnowledgeSource — 参考 KnowledgeSource 实例。

Front-matter schema

知识导入会读取开头的 --- YAML 式 front-matter 块:

字段 含义
id 节点 id(否则用 fallbackId,再否则从正文推断)
title 节点标题
status 节点状态(默认 unknown
relatedimpactsimpacted_bysupersedesimplements 关系字段 → IMPACTS / SUPERSEDES

正文中的行内 [[ref]] 链接也会被提取为引用。

sage — 自演化置信度

置信度落在 [MIN_CONFIDENCE, MAX_CONFIDENCE] = [0.1, 1.0]。一个信号以 weight × STEPSTEP = 0.25)移动之,并做夹值。

  • applyFeedback(conn, event: FeedbackEvent, label: ConfidenceLabel = "Function"): Promise<ConfidenceUpdate | null> — 应用一个事件;节点不存在则返回 nullConfidenceUpdate = { nodeId, label, before, after }
  • feedbackForEventType(type: IngestEventType): { signal, weight } — 对应 test_fail → 负向/1.0、test_pass → 正向/0.4、human_fix → 正向/0.6、 status_change → 中性/0。
  • ingestFeedback(...)runEvolution(...) — 批量反馈 / 演化循环。
  • topByConfidence(conn, label: ConfidenceLabel, limit = 10): Promise<RankedNode[]> — 置信度最高者优先(limit 夹到 1..1000)。RankedNode = { id, confidence }
  • rankedImpact(conn, nodeId, maxHops?) — 按置信度排名的影响决策。

ConfidenceLabel = "Function" | "Spec" | "Decision" | "Doc"FeedbackEvent = { nodeId, signal: "positive"|"negative"|"neutral", weight, source? }。 另导出常量 STEPMIN_CONFIDENCEMAX_CONFIDENCE

adapters — 可插拔接口 + 默认

  • 知识来源KnowledgeSource;默认 MarkdownKnowledgeSource (通用 front-matter markdown → Doc 节点)。辅助函数 parseFrontMatterextractRefs;类型 MarkdownDoc
  • 隔离模型IsolationModel.dbPath(ctx?: IsolationContext): stringSingleRepoIsolation(默认,单一 graph.db)| OrgProjectIsolationorg-{orgId}/project-{projectId}/graph.db)| GitBranchIsolation( 每分支 <git-common-dir>/engram/<branch>.db,附 fallback 模型)。
  • 信号来源SignalSource → FeedbackEvent[]GitHistorySignalSourceTestExitCodeSignalSource。类型 FeedbackEventFeedbackSignal

api — REST(Hono)

  • createServer(options?: { connection?: GraphConnection }): Hono — 始终挂载 GET /health。提供 connection 时,挂载图谱路由:/graph/impact-analysis/graph/ingest/graph/call-chain

mcp — Model Context Protocol

  • createMcpServer(conn: GraphConnection): McpServer — 注册 8 个工具 (index_codeindex_docscall_chainimpact_analysisingest_feedbackimplementersimplemented_specsrelated)。 见 MCP.md

embedded — 同进程客户端

class EmbeddedClient {
  constructor(isolation?: IsolationModel, ctx?: IsolationContext);
  init(): Promise<void>;                 // 打开 DB + 确保 schema(幂等)
  query(cypher, params?): Promise<GraphRow[]>;
  // 高级 facade——与 REST/MCP 相同的操作,免持有原始 GraphConnection:
  indexCode(files: ProjectFile[]): Promise<ProjectIndexResult>;
  indexDocs(docs: KnowledgeDoc[]): Promise<KnowledgeIndexResult>;
  callChain(symbol, direction?, depth?): Promise<CallChainResult>;
  callers(name, depth?): Promise<CallNode[]>;
  callees(name, depth?): Promise<CallNode[]>;
  impactAnalysis(nodeId, maxHops?): Promise<ImpactAnalysisResult>;
  ingestFeedback(nodeId, type, nodeLabel?, weight?): Promise<ConfidenceUpdate | null>;
  topByConfidence(label, limit?): Promise<RankedNode[]>;
  close(): Promise<void>;                // 仅 shutdown 用(销毁注意事项)
}

默认 SingleRepoIsolation。零 HTTP 开销——直接包住 GraphConnection 供同进程使用者使用。 除原始 query 外,高级 facade 暴露与 REST/MCP 相同的操作,因此嵌入式宿主应用无需持有 原始 GraphConnection。连接为长生命周期——init() 幂等;close() 仅供 shutdown。