/** * graph-memory — 图谱维护 * * By: adoresever * Email: Wywelljob@gmail.com * * 调用时机:session_end * * 执行顺序: * 0. 遗忘曲线评分 + tier 写回(分页批 500;fail-soft) * 0.5 遗忘曲线两阶段生命周期:静默 ≥30 天自动弃用(断联,可复活)→ * 到期 >60 天硬删(两步各自独立 fail-soft;详见 docs/decay.md) * 1. 全局 PageRank(基线分数写入 DB,供 topNodes 兜底用) * 2. 社区检测(重新划分知识域) * * 注意:个性化 PPR 不在这里跑,它在 recall 时实时计算。 * 0/0.5 先于排名/社区执行,让后续步骤基于最新 tier 集合运算;自动弃用 * 的断联发生在图结构缓存重建之前,后续步骤读到的是断联后的图。 */ import { DatabaseSync, type DatabaseSyncInstance } from "../store/sqlite.ts"; import type { DecayOverrideConfig, GmConfig } from "../types.ts"; import { computeGlobalPageRank, invalidateGraphCache, type GlobalPageRankResult } from "./pagerank.ts"; import { detectCommunities, detectNavigationCommunities, type CommunityResult } from "./community.ts"; import { detectDuplicates, type DuplicatePair } from "./dedup.ts"; import { DEFAULT_DECAY_CONFIG, MS_PER_DAY, decideTierTransition, normalizeImportance, scoreNode, shouldAutoDeprecate, type DecayConfig, type NodeTier, } from "./decay.ts"; import { DECAY_BATCH_SIZE, applyDecayBatch, getAllDecayCandidates, markDeprecatedByDecay, purgeDeprecatedBefore, } from "../store/store.ts"; /** 阶段一静默门槛:tier=peripheral 且低分的节点需连续静默满该天数才被自动弃用。 */ export const AUTO_DEPRECATE_SILENCE_DAYS = 30; /** 阶段二反悔窗口:decay 弃用节点自 deprecated_at 起超过该天数后硬删。 */ export const PURGE_AFTER_DAYS = 60; /** * 展开 cfg.decay 覆盖段为 runDecaySteps 的运行时衰减配置:未提供的字段 * 逐字段回退默认——时间窗回退模块常量(AUTO_DEPRECATE_SILENCE_DAYS / * PURGE_AFTER_DAYS,与 DEFAULT_DECAY_CONFIG 对齐由 test/decay-maintenance.test.ts * 钉死防双源漂移),开关回退 DEFAULT_DECAY_CONFIG(enabled/autoDeprecate 默认开)。 * 显式配置原样生效,含 purgeAfterDays=0(永不硬删)与 enabled=false(总开关)。 */ export function resolveDecayConfig(override?: DecayOverrideConfig): DecayConfig { return { ...DEFAULT_DECAY_CONFIG, autoDeprecateAfterDays: AUTO_DEPRECATE_SILENCE_DAYS, purgeAfterDays: PURGE_AFTER_DAYS, ...(override?.enabled !== undefined ? { enabled: override.enabled } : {}), ...(override?.autoDeprecate !== undefined ? { autoDeprecate: override.autoDeprecate } : {}), ...(override?.autoDeprecateAfterDays !== undefined ? { autoDeprecateAfterDays: override.autoDeprecateAfterDays } : {}), ...(override?.purgeAfterDays !== undefined ? { purgeAfterDays: override.purgeAfterDays } : {}), }; } export interface MaintenanceResult { /** * 遗忘曲线维护链计数(steps 0/0.5)。三步各自 fail-soft:单步失败只记 * 日志、不否定其余步骤,计数只反映实际落库的部分。 * computed — 本轮完成评分并写回的节点数(分页批提交后累计; * fail-forward 部分成功时只计已提交批) * deprecated — 本轮被遗忘曲线自动弃用(断联 + deprecated_by='decay') * 的节点数(markDeprecatedByDecay 返回 void,本侧事后核对取数) * purged — 本轮到期硬删的 decay 弃用节点数 */ decay?: { computed: number; deprecated: number; purged: number }; pagerank: GlobalPageRankResult; community: CommunityResult; navigationCommunity: CommunityResult; /** * 向量近重复检测 dry-run 报告(Task 14)。纯读:detectDuplicates 不写库, * 仅返回 DuplicatePair[] 供用户经 gm_merge 确认执行(R1 裁决:不自动合并)。 * fail-soft:检测异常时 pairs=[],不阻断维护链——检测恒跑,字段必填。 */ dedup: { pairs: DuplicatePair[] }; durationMs: number; } /** 事后核对:ids 中现已被遗忘曲线弃用(status='deprecated' 且 deprecated_by='decay')的节点数。 */ function countDecayDeprecated(db: DatabaseSyncInstance, ids: string[]): number { let count = 0; for (let i = 0; i < ids.length; i += DECAY_BATCH_SIZE) { const slice = ids.slice(i, i + DECAY_BATCH_SIZE); const placeholders = slice.map(() => "?").join(","); const row = db.prepare( `SELECT COUNT(*) AS n FROM gm_nodes WHERE id IN (${placeholders}) AND status='deprecated' AND deprecated_by='decay'`, ).get(...slice) as any; count += Number(row?.n ?? 0); } return count; } /** * 遗忘曲线三步(PR #69 applyDecay 的 SQLite 编排形态;公式见 docs/decay.md)。 * 每步独立 try/catch:失败只落日志,绝不炸掉整轮维护,下一周期重试。 * * 本函数与宿主形态零耦合(只依赖 store 层 + decay 纯函数),除 OpenClaw 维护链 * (runMaintenance 头部)外,也被 DSH 适配器的维护 tick 复用(dsh.ts),使 * 遗忘曲线门控在两种宿主形态下都真实执行。衰减配置由可选的 decay 覆盖段 * (GmConfig.decay)经 resolveDecayConfig 展开;未配置 = 默认策略。 */ export function runDecaySteps( db: DatabaseSyncInstance, now: number, decay?: DecayOverrideConfig, ): { computed: number; deprecated: number; purged: number } { const result = { computed: 0, deprecated: 0, purged: 0 }; const autoDeprecateIds: string[] = []; const DECAY_CFG = resolveDecayConfig(decay); // step 0:评分 + tier 写回。两遍分页扫描:先取全局 maxPagerank(importance // 归一化基准,PR 语义),再逐批"评分 + 写回",单批内存与单事务停顿均以 500 为界。 // 硬契约:getAllDecayCandidates 裸调用只回前 500,offset += limit 直到返回 < limit。 try { if (DECAY_CFG.enabled) { let maxPagerank = 0.0001; // PR floor:空图/全零分时避免归一化除零 for (let offset = 0; ; offset += DECAY_BATCH_SIZE) { const batch = getAllDecayCandidates(db, { offset, limit: DECAY_BATCH_SIZE }); for (const node of batch) { if (node.pagerank > maxPagerank) maxPagerank = node.pagerank; } if (batch.length < DECAY_BATCH_SIZE) break; } for (let offset = 0; ; offset += DECAY_BATCH_SIZE) { const batch = getAllDecayCandidates(db, { offset, limit: DECAY_BATCH_SIZE }); if (batch.length === 0) break; const updates: Array<{ id: string; tier: NodeTier; decayScore: number; decayComputedAt: number; }> = []; const batchDeprecateIds: string[] = []; for (const node of batch) { const tier = node.tier as NodeTier; // DecayCandidate.tier: string → NodeTier(读取层已归一哨兵值) const score = scoreNode({ ...node, tier }, maxPagerank, now, DECAY_CFG); const importance = normalizeImportance(node.pagerank, maxPagerank); // PR applyDecay 编排语义:先 decideTierTransition 得 finalTier,再以 // 转换后的层级判定 shouldAutoDeprecate——本轮刚降到 peripheral 的老节点即刻参与阶段一。 const nextTier = decideTierTransition({ ...node, tier }, score, importance, DECAY_CFG, now); const finalTier = nextTier ?? tier; if (shouldAutoDeprecate({ ...node, tier: finalTier }, score, DECAY_CFG, now)) { batchDeprecateIds.push(node.id); } updates.push({ id: node.id, tier: finalTier, decayScore: score.composite, decayComputedAt: now }); } applyDecayBatch(db, updates); // 写回确认后才并入弃用候选:tier 写失败的批不做不可逆断联(对齐 PR // "写事务失败则弃用不执行";applyDecayBatch fail-forward 时只弃用已提交批)。 autoDeprecateIds.push(...batchDeprecateIds); result.computed += batch.length; if (batch.length < DECAY_BATCH_SIZE) break; } } } catch (error) { console.error(`[graph-memory] decay 评分写回失败(fail-soft,维护链其余步骤继续):`, error); } // step 0.5a:阶段一自动弃用——静默 ≥AUTO_DEPRECATE_SILENCE_DAYS 的 peripheral // 低分节点断联 + 标记 deprecated_by='decay'(新引用/重提取可复活,见 R3 裁决)。 try { if (autoDeprecateIds.length > 0) { markDeprecatedByDecay(db, autoDeprecateIds, now); // markDeprecatedByDecay 返回 void(本地裁剪;PR 返回计数),计数由编排层 // 事后核对:候选扫描时均为 active、node:sqlite 同步无并发写, // 故"现为 decay 弃用"的数量即本次标记数。 result.deprecated = countDecayDeprecated(db, autoDeprecateIds); } } catch (error) { console.error(`[graph-memory] decay 自动弃用失败(fail-soft,维护链其余步骤继续):`, error); } // step 0.5b:阶段二到期硬删。独立于 enabled(PR 语义:弃用清理不随衰减总开关 // 停摆);本地 store 裁决只删 deprecated_by='decay',manual/merge 留给用户。 // purgeAfterDays=0 表示永不硬删(PR 在 purge 侧处理 0,本地守卫在调用侧)。 // 注意读 DECAY_CFG.purgeAfterDays(cfg.decay 覆盖生效点)而非模块常量。 try { if (DECAY_CFG.purgeAfterDays > 0) { result.purged = purgeDeprecatedBefore(db, now - DECAY_CFG.purgeAfterDays * MS_PER_DAY); } } catch (error) { console.error(`[graph-memory] decay 到期清理失败(fail-soft,维护链其余步骤继续):`, error); } return result; } export async function runMaintenance(db: DatabaseSyncInstance, cfg: GmConfig): Promise { const start = Date.now(); // 0 / 0.5. 遗忘曲线三步(fail-soft;断联/硬删先落地,后续步骤基于最新图运算) invalidateGraphCache(db); const decay = runDecaySteps(db, start, cfg?.decay); // 1. 全局 PageRank(基线) const pagerankResult = computeGlobalPageRank(db, cfg); // 2. 社区检测 const communityResult = detectCommunities(db); const navigationCommunityResult = detectNavigationCommunities(db); // 3. 向量近重复检测(dry-run 报告,纯读不自动合并;须在社区检测后跑, // 使 community_id 已写回——同社区配对依赖该列)。fail-soft。 let dedupPairs: DuplicatePair[] = []; try { dedupPairs = detectDuplicates(db); } catch (error) { console.error(`[graph-memory] dedup 检测失败(fail-soft,仅报告,不阻断维护链):`, error); } return { decay, pagerank: pagerankResult, community: communityResult, navigationCommunity: navigationCommunityResult, dedup: { pairs: dedupPairs }, durationMs: Date.now() - start, }; }