/** * graph-memory * * By: adoresever * Email: Wywelljob@gmail.com */ /** * graph-memory 类型定义 * * 节点:TASK / SKILL / EVENT * 边:EDGE_TYPES 单一事实源(7 类,见「边」小节) */ // ─── 节点 ───────────────────────────────────────────────────── export type NodeType = "TASK" | "SKILL" | "EVENT"; export type NodeStatus = "active" | "deprecated"; export type TurnOutcome = "completed" | "partial" | "failed" | "informational" | "unknown"; export interface NodeTemporal { /** Time stated by the evidence, preserved as written instead of guessed. */ eventTime?: string; /** When the fact or decision starts to apply, if the dialogue says so. */ validFrom?: string; /** When it stops applying, if known. */ validUntil?: string; state?: "current" | "historical" | "uncertain" | "superseded"; } export interface GmNode { id: string; type: NodeType; name: string; description: string; content: string; temporal: NodeTemporal; status: NodeStatus; validatedCount: number; sourceSessions: string[]; communityId: string | null; pagerank: number; createdAt: number; updatedAt: number; } /** * Compact episodic index for one completed question/final-answer pair. * The exact source messages remain in gm_messages; this record is the first * retrieval surface and never replaces its evidence. */ export interface GmTurnMemory { id: string; sessionId: string; summary: string; outcome: TurnOutcome; sources: Array<{ messageId: string; turnIndex: number }>; createdAt: number; updatedAt: number; } /** * A lightweight subject-predicate-object index into one turn memory. * It is navigation metadata only; the turn summary and exact source Q/A are * the evidence returned to the model after retrieval. */ export interface GmNavigationTriple { id: string; memoryId: string; sessionId: string; subjectId: string; subject: string; predicate: string; objectId: string; object: string; subjectCommunityId: string | null; objectCommunityId: string | null; createdAt: number; } // ─── 边 ─────────────────────────────────────────────────────── /** * 边类型单一事实源(运行时常量,PR #69 移植)。 * 新增/移除边类型时只改这里:EdgeType 类型、DB CHECK 清单(db.ts 派生)、 * 校验白名单一律跟随,勿在别处内联成员清单。 */ export const EDGE_TYPES = [ "RELATES", "SUPERSEDES", "USED_SKILL", "SOLVED_BY", "REQUIRES", "PATCHES", "CONFLICTS_WITH", ] as const; export type EdgeType = (typeof EDGE_TYPES)[number]; /** RELATES / SUPERSEDES 为通用关系,不约束端点节点类型。 */ const ANY_NODE_ENDPOINTS: readonly NodeType[] = ["TASK", "SKILL", "EVENT"]; /** * 边端点方向规则表(结构照搬 PR #69 EDGE_DIRECTION_RULES), * 供 gm_link 等维护工具做方向校验(违反给警告不阻断)。 * - RELATES:对称双向 —— 任意端点类型、方向不设限 * (m13 语义:通用导航关系,谓词存于 instruction,不绑定业务领域); * - SUPERSEDES:有向 —— from=被取代者、to=取代者,端点类型不限; * - 其余 5 类照搬 PR 规则:TASK→SKILL / EVENT|SKILL→SKILL / SKILL→SKILL。 * Record 在编译期强制规则表覆盖全部成员(exhaustiveness 钉子)。 */ export const EDGE_DIRECTION_RULES: Record = { RELATES: { from: ANY_NODE_ENDPOINTS, to: ANY_NODE_ENDPOINTS }, SUPERSEDES: { from: ANY_NODE_ENDPOINTS, to: ANY_NODE_ENDPOINTS }, USED_SKILL: { from: ["TASK"], to: ["SKILL"] }, SOLVED_BY: { from: ["EVENT", "SKILL"], to: ["SKILL"] }, REQUIRES: { from: ["SKILL"], to: ["SKILL"] }, PATCHES: { from: ["SKILL"], to: ["SKILL"] }, CONFLICTS_WITH: { from: ["SKILL"], to: ["SKILL"] }, }; export interface GmEdge { id: string; fromId: string; toId: string; type: EdgeType; instruction: string; condition?: string; sessionId: string; createdAt: number; } // ─── 提取结果 ───────────────────────────────────────────────── export interface ExtractionResult { turn: { /** One self-contained sentence describing the request and observed result. */ summary: string; /** Outcome reported by the completed dialogue; not external verification. */ outcome: TurnOutcome; }; /** Simple navigation derived from turn.summary; never a second fact body. */ triples: Array<{ subject: string; predicate: string; object: string; }>; } // ─── 召回结果 ───────────────────────────────────────────────── export interface RecallResult { nodes: GmNode[]; edges: GmEdge[]; /** Query-matched episodic summaries, ordered by retrieval relevance. */ turnMemories: GmTurnMemory[]; /** Navigation triples attached to the matched turn memories. */ triples: GmNavigationTriple[]; } // ─── Embedding 配置 ────────────────────────────────────────── export interface EmbeddingConfig { apiKey?: string; /** Runtime-only credential resolver. Host adapters use this to avoid putting secrets in config. */ apiKeyResolver?: () => Promise; baseURL?: string; /** Alias used by OpenClaw and several OpenAI-compatible providers. */ baseUrl?: string; model?: string; dimensions?: number; /** * Per-request timeout baseline (ms) for production embed calls * (single = baseline; batch = max(baseline, 2s×texts.length)). * Unset falls back to the engine default (10000). */ requestTimeoutMs?: number; } // ─── 插件配置 ───────────────────────────────────────────────── /** * 遗忘曲线(decay)维护链的宿主覆盖段(PR #69 cfg.decay 配置面的本地裁剪)。 * 只暴露维护链实际消费的四个策略字段;评分公式内部参数(半衰期/权重/阈值等) * 保持 src/graph/decay.ts 的 DEFAULT_DECAY_CONFIG 常量,不进宿主配置面。 * 所有字段可选:未提供 = 逐字段回退默认(enabled 默认 true)。 */ export interface DecayOverrideConfig { /** 遗忘曲线总开关:false 时评分写回与自动弃用跳过(purge 仍独立执行,见 purgeAfterDays)。 */ enabled?: boolean; /** 阶段一开关:静默 peripheral 低分节点是否自动弃用(断联,可复活)。 */ autoDeprecate?: boolean; /** 阶段一静默门槛(天):peripheral 低分节点连续静默满该天数才被自动弃用。 */ autoDeprecateAfterDays?: number; /** 阶段二反悔窗口(天):decay 弃用节点自 deprecated_at 起超过该天数后硬删;0 = 永不硬删。 */ purgeAfterDays?: number; } export interface GmConfig { dbPath: string; /** SQLite write-lock wait in milliseconds; omitted uses the shared store policy. */ dbBusyTimeoutMs?: number; compactTurnCount: number; /** Maximum query-matched memory nodes returned by one recall. */ recallMaxNodes: number; /** * Provider-calibrated cosine floor for automatic prompt injection. * Deliberately required by DEFAULT_CONFIG: ranked top-k alone always returns * a "nearest" memory even when no memory is actually relevant. */ semanticScoreThreshold?: number; /** Number of recent user turns kept as native question/final-answer endpoints on the host context surface. */ freshTurnCount: number; embedding?: EmbeddingConfig; llm?: { apiKey?: string; baseURL?: string; /** Alias used by OpenClaw and several OpenAI-compatible providers. */ baseUrl?: string; model?: string; /** Required only for direct Anthropic REST calls, whose protocol requires a response cap. */ maxTokens?: number; }; /** PageRank 阻尼系数 */ pagerankDamping: number; /** PageRank 迭代次数 */ pagerankIterations: number; /** * 知识提取的本地成本控制(trivial 轮预筛);未提供时仍启用内置词表的 * 默认预筛——判定见 src/extractor/turn-filter.ts。 */ extract?: { /** 追加的 trivial 词表(与内置词表合并,匹配前统一 normalize)。 */ trivialPrompts?: string[]; /** 清洗后长度阈值;默认 5。 */ trivialMaxChars?: number; }; /** * 遗忘曲线维护链覆盖段。缺省 = DEFAULT_DECAY_CONFIG(enabled/autoDeprecate 开、 * 30 天静默弃用、60 天硬删);维护链接线经 resolveDecayConfig 展开消费。 */ decay?: DecayOverrideConfig; } export const DEFAULT_CONFIG: GmConfig = { dbPath: "~/.openclaw/graph-memory.db", compactTurnCount: 6, recallMaxNodes: 6, // Automatic prompt injection optimizes for precision. On the existing // text-embedding-v4 20-turn corpus, 0.70 sits above the p90 different-turn // similarity (0.669) and near the same-turn median (0.721). Other embedding // providers can override this single documented policy value. semanticScoreThreshold: 0.70, freshTurnCount: 5, pagerankDamping: 0.85, pagerankIterations: 20, };