@ai-agent-forge/plugin-memory 0.88.0 → 0.88.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -4
- package/agent-forge.json +1 -1
- package/bin/agent-forge-memory-inference.js +8 -0
- package/dist/capability.d.ts +42 -59
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +263 -2055
- package/dist/capability.js.map +1 -1
- package/dist/entry.d.ts +11 -0
- package/dist/entry.d.ts.map +1 -1
- package/dist/entry.js +38 -2
- package/dist/entry.js.map +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -1
- package/dist/inference-bin.d.ts +21 -0
- package/dist/inference-bin.d.ts.map +1 -0
- package/dist/inference-bin.js +85 -0
- package/dist/inference-bin.js.map +1 -0
- package/dist/memory/command-face.d.ts +86 -0
- package/dist/memory/command-face.d.ts.map +1 -0
- package/dist/memory/command-face.js +377 -0
- package/dist/memory/command-face.js.map +1 -0
- package/dist/memory/embedding-provider.d.ts.map +1 -1
- package/dist/memory/embedding-provider.js +14 -2
- package/dist/memory/embedding-provider.js.map +1 -1
- package/dist/memory/embedding-reranker.d.ts.map +1 -1
- package/dist/memory/embedding-reranker.js +14 -2
- package/dist/memory/embedding-reranker.js.map +1 -1
- package/dist/memory/enabling.d.ts +104 -0
- package/dist/memory/enabling.d.ts.map +1 -0
- package/dist/memory/enabling.js +321 -0
- package/dist/memory/enabling.js.map +1 -0
- package/dist/memory/hooks.d.ts +110 -0
- package/dist/memory/hooks.d.ts.map +1 -0
- package/dist/memory/hooks.js +478 -0
- package/dist/memory/hooks.js.map +1 -0
- package/dist/memory/inference-channel.d.ts +33 -0
- package/dist/memory/inference-channel.d.ts.map +1 -0
- package/dist/memory/inference-channel.js +101 -0
- package/dist/memory/inference-channel.js.map +1 -0
- package/dist/memory/inference-client.d.ts +25 -0
- package/dist/memory/inference-client.d.ts.map +1 -0
- package/dist/memory/inference-client.js +216 -0
- package/dist/memory/inference-client.js.map +1 -0
- package/dist/memory/inference-protocol.d.ts +95 -0
- package/dist/memory/inference-protocol.d.ts.map +1 -0
- package/dist/memory/inference-protocol.js +27 -0
- package/dist/memory/inference-protocol.js.map +1 -0
- package/dist/memory/inference-server.d.ts +70 -0
- package/dist/memory/inference-server.d.ts.map +1 -0
- package/dist/memory/inference-server.js +395 -0
- package/dist/memory/inference-server.js.map +1 -0
- package/dist/memory/inference-service-main.d.ts +31 -0
- package/dist/memory/inference-service-main.d.ts.map +1 -0
- package/dist/memory/inference-service-main.js +89 -0
- package/dist/memory/inference-service-main.js.map +1 -0
- package/dist/memory/ledger.d.ts +15 -0
- package/dist/memory/ledger.d.ts.map +1 -1
- package/dist/memory/ledger.js +35 -2
- package/dist/memory/ledger.js.map +1 -1
- package/dist/memory/model-cache-hygiene.d.ts +10 -0
- package/dist/memory/model-cache-hygiene.d.ts.map +1 -1
- package/dist/memory/model-cache-hygiene.js +15 -0
- package/dist/memory/model-cache-hygiene.js.map +1 -1
- package/dist/memory/preference-promotion.d.ts +0 -14
- package/dist/memory/preference-promotion.d.ts.map +1 -1
- package/dist/memory/preference-promotion.js +17 -0
- package/dist/memory/preference-promotion.js.map +1 -1
- package/dist/memory/recall-pipeline.d.ts +85 -0
- package/dist/memory/recall-pipeline.d.ts.map +1 -0
- package/dist/memory/recall-pipeline.js +678 -0
- package/dist/memory/recall-pipeline.js.map +1 -0
- package/dist/memory/retention-sweep.d.ts +59 -0
- package/dist/memory/retention-sweep.d.ts.map +1 -0
- package/dist/memory/retention-sweep.js +103 -0
- package/dist/memory/retention-sweep.js.map +1 -0
- package/dist/memory/store.d.ts +17 -2
- package/dist/memory/store.d.ts.map +1 -1
- package/dist/memory/store.js +18 -2
- package/dist/memory/store.js.map +1 -1
- package/dist/memory/vector-channel.d.ts +120 -0
- package/dist/memory/vector-channel.d.ts.map +1 -0
- package/dist/memory/vector-channel.js +495 -0
- package/dist/memory/vector-channel.js.map +1 -0
- package/dist/memory/vector-projection.d.ts +87 -0
- package/dist/memory/vector-projection.d.ts.map +1 -0
- package/dist/memory/vector-projection.js +215 -0
- package/dist/memory/vector-projection.js.map +1 -0
- package/dist/memory/write-face.d.ts +128 -0
- package/dist/memory/write-face.d.ts.map +1 -0
- package/dist/memory/write-face.js +504 -0
- package/dist/memory/write-face.js.map +1 -0
- package/dist/testing/memory-testkit.d.ts +2 -0
- package/dist/testing/memory-testkit.d.ts.map +1 -1
- package/dist/testing/memory-testkit.js +1 -0
- package/dist/testing/memory-testkit.js.map +1 -1
- package/package.json +7 -3
- package/plugin.json +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recall-pipeline.js","sourceRoot":"","sources":["../../src/memory/recall-pipeline.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAS/B,OAAO,EAAE,kBAAkB,EAA4B,MAAM,mBAAmB,CAAC;AAKjF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAC9B,mgBAA+f,CAAC;AAEjgB,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAE/B,iFAAqE;AACrE,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAE5B,qEAA2C;AAC3C,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAChC,yEAAiD;AACjD,MAAM,YAAY,GAAG,EAAE,CAAC;AACxB,8EAA8C;AAC9C,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAQ9B;;;GAGG;AACH,SAAS,eAAe,CAAC,QAAwC,EAAqB;IACrF,MAAM,MAAM,GAAG,IAAI,GAAG,EAAkB,CAAC;IACzC,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAChC,KAAK,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,OAAO,CAAC,OAAO,EAAE,EAA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AAO,EAAE,aAAa;KACtB,CAAC,CAAC;IAEH,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,CAAC;AAAA,CACrC","sourcesContent":["/**\n * 召回管线(capability 拆分战役 slice 4):双通道查询、RRF 融合、egress 门、语义召回与召回工具。状态机经 vectorChannel 只读面消费, 降级经回调上报\n */\nimport type { CapabilityAPI, DisposableRegistration, JsonValue } from \"@agent-forge/plugin-sdk\";\nimport { MEMORY_RECALL_TOOL_NAME } from \"@agent-forge/plugin-sdk\";\nimport { Type } from \"typebox\";\nimport type { MemoryEgressFactInfoV1, MemoryEgressPolicyGateV1 } from \"./egress-policy.ts\";\nimport type { MemoryAtomV1, MemoryPreferenceEnvelopeV1, MemorySuiteFilterStatsV1 } from \"./foundation.ts\";\nimport type { DurableMemoryLedgerV1 } from \"./ledger.ts\";\nimport type { MemoryNetworkExpansionV1, MemoryNetworkV1 } from \"./memory-network.ts\";\nimport type { PreferenceDisambiguatorV1 } from \"./preference-disambiguator.ts\";\nimport type { PreferenceContextV1, PreferenceResolverV1 } from \"./preference-resolver.ts\";\nimport type { MemoryRecallPacketV1 } from \"./recall-packet.ts\";\nimport type { MemoryStoreV1 } from \"./store.ts\";\nimport { listDomainMemories, type SuiteMemoryDomainV1 } from \"./suite-memory.ts\";\nimport type { MemoryCapabilityStateV1, MemoryConsentAskV1, MemoryEnablingFailureV1 } from \"./vector-channel.ts\";\nimport type { MemoryVectorHitV1 } from \"./vector-index.ts\";\nimport type { ActiveVectorChannelV1 } from \"./vector-projection.ts\";\n\n/**\n * Memory tools guide(记忆 runtime 注入面,原 system-prompt.ts MEMORY_TOOL_GUIDE,\n * D-071 迁移):the model-facing hint that the persistent memory tools exist.\n * It rides memory_recall's promptGuidelines so the text lives with the plugin\n * that owns the tools (宪法 §3) and renders whenever the tool face is active.\n */\nexport const MEMORY_TOOLS_GUIDE =\n\t\"Memory: You have persistent memory tools (memory_write, memory_recall, memory_list, memory_forget). Use memory_recall only when past decisions, preferences, or project facts are actually relevant to the current question — not on every turn. Use memory_write only for facts the user explicitly stated or that a tool/test verified; never save your own inferences or guesses as facts, and declare the honest evidence class. memory_forget only files a forget request — deletion happens after the user confirms it.\";\n\nconst DEFAULT_RECALL_LIMIT = 5;\n\n/** Bounded supplementary relation references per recall (记忆网络接线). */\nconst MAX_RELATED_REFS = 20;\n\n/** FTS / KNN 通道各自取回深度 (定版管线: depth 50)。 */\nconst HYBRID_CHANNEL_DEPTH = 50;\n/** RRF 常数, 与 vector-index 组件 queryFts 打分口径一致。 */\nconst HYBRID_RRF_K = 60;\n/** 融合候选池上限 (定版管线: top20 → 精排 → top limit)。 */\nconst HYBRID_FUSION_POOL = 20;\n\ninterface MemoryFact {\n\treadonly memoryId: string;\n\treadonly statement: string;\n\treadonly confidence: number;\n}\n\n/**\n * 三通道 RRF 融合 (定版管线): `score(id) += 1/(k + rank + 1)` 对各通道排名累加,\n * 取 top {@link HYBRID_FUSION_POOL}。分数并列时以 memoryId 升序打破, 保证确定性。\n */\nfunction rrfFuseRankings(rankings: readonly (readonly string[])[]): readonly string[] {\n\tconst scores = new Map<string, number>();\n\tfor (const ranking of rankings) {\n\t\tfor (const [rank, memoryId] of ranking.entries()) {\n\t\t\tscores.set(memoryId, (scores.get(memoryId) ?? 0) + 1 / (HYBRID_RRF_K + rank + 1));\n\t\t}\n\t}\n\treturn [...scores.entries()]\n\t\t.sort((left, right) => right[1] - left[1] || (left[0] < right[0] ? -1 : 1))\n\t\t.map(([memoryId]) => memoryId)\n\t\t.slice(0, HYBRID_FUSION_POOL);\n}\n\n/** One unresolvably competing preference, surfaced verbatim instead of a silent pick. */\ninterface RecallConflictV1 {\n\treadonly subject: MemoryPreferenceEnvelopeV1[\"subject\"];\n\treadonly key: string;\n\treadonly candidates: readonly {\n\t\treadonly memoryId: string;\n\t\treadonly statement: string;\n\t\treadonly value: JsonValue;\n\t\treadonly evidenceClass: MemoryPreferenceEnvelopeV1[\"evidence\"][\"class\"];\n\t\treadonly confidence: number;\n\t}[];\n\treadonly explanation: readonly string[];\n}\n\nconst recallSchema = Type.Object({\n\tquery: Type.String({\n\t\tdescription:\n\t\t\t\"Natural-language query; recall fuses semantic (vector) and full-text (BM25) matching and reranks the result. An exact memoryId retrieves that memory directly\",\n\t}),\n\tlimit: Type.Optional(\n\t\tType.Integer({ description: \"Maximum number of memories to return (1-100)\", minimum: 1, maximum: 100 }),\n\t),\n\tcontext: Type.Optional(\n\t\tType.Object(\n\t\t\t{\n\t\t\t\tscenes: Type.Optional(Type.Array(Type.String())),\n\t\t\t\tprojects: Type.Optional(Type.Array(Type.String())),\n\t\t\t\ttasks: Type.Optional(Type.Array(Type.String())),\n\t\t\t},\n\t\t\t{\n\t\t\t\tdescription:\n\t\t\t\t\t\"Current scope context; when present, recalled preferences are resolved against it (out-of-scope preferences drop, competing values resolve by scope specificity or surface as explicit conflicts)\",\n\t\t\t},\n\t\t),\n\t),\n});\n\n/**\n * 召回管线对 capability 闭包的显式依赖视图 (slice 4): 逐项来自\n * createMemoryCapabilityHarness 的闭包捕获核实。状态机 (vectorChannelCtl) 与\n * 写侧投影 (vectorProjection) 归 capability 装配所有, 本模块经只读回调消费与\n * 上报, 不持有任何状态机变量; capability 模块级纯函数经 deps 注入避免双头定义。\n */\nexport interface MemoryRecallPipelineDepsV1 {\n\t/** capability 日志面 (api.logger): 通道降级/增强失败的结构化日志。 */\n\treadonly logger: CapabilityAPI[\"logger\"];\n\t/** 检索行 owner (capability.BUILTIN_MEMORY_OWNER)。 */\n\treadonly owner: string;\n\t/** 会话 id (harness sessionId): egress operationId 组成。 */\n\treadonly sessionId: string;\n\t/** canonical store (per-capability 单例): store 回查与增强段 atom 读取。 */\n\treadonly store: MemoryStoreV1;\n\t/** 域解析 (capability.resolveDomain): 每次 recall 调用时惰性解析 (B1 语义)。 */\n\treadonly resolveDomain: () => {\n\t\treadonly domain: SuiteMemoryDomainV1;\n\t\treadonly domainName: string;\n\t\treadonly ledger: DurableMemoryLedgerV1;\n\t};\n\t/** egress 门 (capability.egressPolicy): 与旧锚点 packet 同一 gate。 */\n\treadonly egressPolicy: MemoryEgressPolicyGateV1;\n\t/** context-scoped 偏好解析 (2.4c/2.4d2)。 */\n\treadonly preferenceResolver: PreferenceResolverV1;\n\t/** 未决偏好的确定性消歧 (2.4c/2.4d2)。 */\n\treadonly preferenceDisambiguator: PreferenceDisambiguatorV1;\n\t/** 关系扩散 (记忆网络接线): recall 种子的一跳扩展。 */\n\treadonly memoryNetwork: MemoryNetworkV1;\n\t// ---- vectorChannel 只读面 (slice 3b 的 vectorChannelCtl, 状态机归其所有) ----\n\t/** warming 守卫: 后台预热在途且未拒绝时 recall 零等待返回 unavailable。 */\n\treadonly warming: () => boolean;\n\t/** 惰性装配 (vectorEnsure 单飞语义原样保留): undefined = 通道不可用。 */\n\treadonly ensureChannel: () => Promise<ActiveVectorChannelV1 | undefined>;\n\t/** 征询拒绝标记 (declined): recall 按模式关闭对待。 */\n\treadonly declined: () => boolean;\n\t/** 待征询信息 (consent-required): recall 返回征询话术包。 */\n\treadonly consentAsk: () => MemoryConsentAskV1 | undefined;\n\t/** enabling 结构化失败 (原因 + 行动清单, 设计 §3.2)。 */\n\treadonly failure: () => MemoryEnablingFailureV1 | undefined;\n\t/** 通道原始状态 (未做 declined 投影): packet 的 state 字段来源。 */\n\treadonly rawState: () => MemoryCapabilityStateV1;\n\t/** 运行期故障的 degraded 转换回调 (状态转换语义归状态机)。 */\n\treadonly markDegraded: () => void;\n\t/** 全通成功的 degraded 自愈回调。 */\n\treadonly recoverDegraded: () => void;\n\t// ---- 写侧投影 (slice 3a 的 vectorProjection) ----\n\t/** 读侧 FIFO 等待 (await vectorQueue): 保写入→召回次序。 */\n\treadonly settleProjection: () => Promise<unknown>;\n\t// ---- capability 模块级纯函数 (留守方, 经 deps 注入避免双头定义) ----\n\treadonly memoryToolInput: (first: unknown, second: unknown) => Record<string, unknown>;\n\treadonly assertNonEmptyString: (value: unknown, label: string) => asserts value is string;\n\treadonly isPlainObject: (value: unknown) => value is Record<string, unknown>;\n\treadonly identityHash: (value: string) => string;\n\treadonly statementOf: (payload: unknown) => string;\n\treadonly unwrapEgressStatement: (statement: string) => string;\n\t/** 工具注册面 (api.registerTool): memory_recall 经同一公共通道注册。 */\n\treadonly registerTool: CapabilityAPI[\"registerTool\"];\n}\n\n/** 召回管线工厂产物: 工具注册项 + auto-recall 直连的执行闭包。 */\nexport interface MemoryRecallPipelineV1 {\n\t/** memory_recall 工具注册项 (capability registrations 收集)。 */\n\treadonly recallTool: DisposableRegistration;\n\t/** 召回执行闭包 (原 recallExecute): autoRecallBlock (留守, slice 7) 直连同一 execute。 */\n\treadonly recallExecute: (first: unknown, second?: unknown) => Promise<unknown>;\n}\n\nexport function createMemoryRecallPipeline(deps: MemoryRecallPipelineDepsV1): MemoryRecallPipelineV1 {\n\t/**\n\t * 语义召回管线 (2.4d6 S2, 设计 §4) — 唯一检索路径: embed(查询, light 加 BGE\n\t * 前缀) → KNN depth50 + FTS depth50 → RRF k=60 top20 → 精排 → store 回查\n\t * (owner/suite/scope/过期, 单一可见性路径, 不足 limit 不回填)。降级层级\n\t * (2026-10-05 裁决 A「宁漏勿错」, 每次降级一条结构化日志, 状态转 degraded\n\t * 可自愈): 精排失败 → RRF 序 + degraded 标记 (不闩锁, 下次重试); 向量失败\n\t * (embed/KNN) → FTS-only + degraded; FTS 失败 → KNN-only + degraded;\n\t * 双通道皆败 → unavailable (语义召回不可用, memory_list 仍是列表入口;\n\t * recency 枚举兜底已移除 — 语义查询返回\"最近的几条\"是对查询语义的错答)。\n\t * degraded 标记对显式召回可见; auto-recall 见标记零注入。\n\t */\n\n\t/** 一次语义召回的中间候选: atom + 融合/降级序位 (精排并列打破用)。 */\n\tinterface RecallCandidateV1 {\n\t\treadonly atom: MemoryAtomV1;\n\t\treadonly position: number;\n\t}\n\n\t/** 出线事实行 (含精排可选分): score 缺席 = 该路径未产生精排分。 */\n\tinterface ScoredRecallFactV1 {\n\t\treadonly memoryId: string;\n\t\treadonly statement: string;\n\t\treadonly confidence: number;\n\t\treadonly position: number;\n\t\treadonly score?: number;\n\t}\n\n\ttype SemanticRecallOutcomeV1 =\n\t\t| {\n\t\t\t\treadonly kind: \"served\";\n\t\t\t\treadonly facts: readonly MemoryFact[];\n\t\t\t\treadonly candidateCount: number;\n\t\t\t\treadonly suiteFilter: MemorySuiteFilterStatsV1;\n\t\t\t\t/**\n\t\t\t\t * 降级原因短语 (2026-10-05 裁决 A「宁漏勿错」): 存在即本次结果未经\n\t\t\t\t * 精排打分。显式召回照常服务并携带该标记 (模型可见); auto-recall\n\t\t\t\t * 见标记零注入。\n\t\t\t\t */\n\t\t\t\treadonly degraded?: string;\n\t\t }\n\t\t| { readonly kind: \"blocked\"; readonly reason: string }\n\t\t| { readonly kind: \"unavailable\"; readonly message: string };\n\n\t/** recency 排序 (occurredAt 降序, memoryId 升序打破并列 — 与 recall index 同口径)。 */\n\tconst recencyOrdered = (entries: readonly RecallCandidateV1[]): readonly RecallCandidateV1[] =>\n\t\t[...entries]\n\t\t\t.sort(\n\t\t\t\t(left, right) =>\n\t\t\t\t\tDate.parse(right.atom.occurredAt) - Date.parse(left.atom.occurredAt) ||\n\t\t\t\t\t(left.atom.memoryId < right.atom.memoryId ? -1 : 1),\n\t\t\t)\n\t\t\t.map((entry, position) => ({ atom: entry.atom, position }));\n\n\t/**\n\t * superseded 过滤 (S3-B, store 回查后 / 精排前): 被某条在场候选的 supersedes\n\t * 关系指向的旧条目不再出线 — 合并后同义查询只出新条目。\"新条目在场\"以候选\n\t * 集为界: 继任条目被遗忘 (purge/过期) 后其关系随之消失, 旧条目自然恢复出线。\n\t * memoryId 主键直查不经此过滤 (引用不失效), memory_list 管理面不过滤\n\t * (nothing silently dropped — 用户可显式 forget 旧条目)。\n\t */\n\tconst filterSupersededCandidates = (candidates: readonly RecallCandidateV1[]): readonly RecallCandidateV1[] => {\n\t\tconst superseded = new Set<string>();\n\t\tfor (const entry of candidates) {\n\t\t\tfor (const relation of entry.atom.relations) {\n\t\t\t\tif (relation.kind === \"supersedes\" && relation.targetMemoryId !== undefined) {\n\t\t\t\t\tsuperseded.add(relation.targetMemoryId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (superseded.size === 0) return candidates;\n\t\treturn candidates.filter((entry) => !superseded.has(entry.atom.memoryId));\n\t};\n\n\t/**\n\t * store 回查 (正确性关键): 候选 id 逐条走与旧锚点通道相同的可见性单一路径\n\t * (owner + suite 读边界 + 过期, 单一路径); suite 场景下不可见 id 按 legacy/\n\t * 外套件区分计数 (suiteFilter 可观测), 不可见者丢弃且不回填 (诚实分页)。\n\t */\n\tconst lookupCandidates = (\n\t\trankedIds: readonly (readonly [memoryId: string, position: number])[],\n\t\tsuiteId: string | undefined,\n\t): { readonly candidates: readonly RecallCandidateV1[]; readonly suiteFilter: MemorySuiteFilterStatsV1 } => {\n\t\tconst candidates: RecallCandidateV1[] = [];\n\t\tlet legacySkipped = 0;\n\t\tlet foreignSuiteSkipped = 0;\n\t\tfor (const [memoryId, position] of rankedIds) {\n\t\t\tconst record = deps.store.get(memoryId, {\n\t\t\t\towner: deps.owner,\n\t\t\t\t...(suiteId === undefined ? {} : { suiteId }),\n\t\t\t});\n\t\t\tif (record !== undefined) {\n\t\t\t\tcandidates.push({ atom: record.atom, position });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (suiteId !== undefined) {\n\t\t\t\tconst unfiltered = deps.store.get(memoryId, { owner: deps.owner });\n\t\t\t\tif (unfiltered !== undefined) {\n\t\t\t\t\tif (unfiltered.atom.suiteId === undefined) legacySkipped += 1;\n\t\t\t\t\telse foreignSuiteSkipped += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn { candidates, suiteFilter: { legacySkipped, foreignSuiteSkipped } };\n\t};\n\n\t/**\n\t * egress 门重放 (设计 §11 MUST run): 对最终候选统一执行, 与旧锚点 packet 同\n\t * 一 gate、同一 factInfo 来源 (store); blocked 即 fail-closed, 该次 recall\n\t * 返回 failed packet (来源未登记的事实永不越过出界面)。\n\t */\n\tconst egressGate = (candidates: readonly RecallCandidateV1[]) => {\n\t\tconst factInfo: Record<string, MemoryEgressFactInfoV1 | undefined> = {};\n\t\tfor (const entry of candidates) {\n\t\t\tfactInfo[entry.atom.memoryId] = {\n\t\t\t\tsourceRefs: entry.atom.sourceRefs,\n\t\t\t\tpayload: entry.atom.payload as Record<string, unknown>,\n\t\t\t};\n\t\t}\n\t\treturn deps.egressPolicy.apply(\n\t\t\t{\n\t\t\t\toperationId: `memory_recall:${deps.sessionId}:${deps.identityHash(candidates.map((entry) => entry.atom.memoryId).join(\"\\u0000\"))}`,\n\t\t\t\tstatus: \"completed\",\n\t\t\t\tfacts: candidates.map((entry) => ({\n\t\t\t\t\tmemoryId: entry.atom.memoryId,\n\t\t\t\t\tcontentRevision: entry.atom.contentRevision,\n\t\t\t\t\tstatement: JSON.stringify(entry.atom.payload),\n\t\t\t\t\tconfidence: entry.atom.confidence,\n\t\t\t\t})),\n\t\t\t\tqueryPlan: { lookupUsed: false, filtersApplied: [], scorerVersion: \"semantic-rrf@1\" },\n\t\t\t\tattempts: 0,\n\t\t\t\tnarrowingHints: [],\n\t\t\t\tomittedCount: 0,\n\t\t\t\ttruncated: false,\n\t\t\t\ttruncationScope: \"none\",\n\t\t\t\tbudget: {\n\t\t\t\t\tcandidateBudget: 0,\n\t\t\t\t\tmodelInspectionLimit: 0,\n\t\t\t\t\tfinalResultLimit: 0,\n\t\t\t\t\tused: { candidateCount: 0, modelInspectedCount: 0, finalResultCount: 0 },\n\t\t\t\t},\n\t\t\t} satisfies MemoryRecallPacketV1,\n\t\t\tfactInfo,\n\t\t);\n\t};\n\n\tconst recallSemantically = async (input: {\n\t\treadonly query: string;\n\t\treadonly domain: SuiteMemoryDomainV1;\n\t\treadonly limit: number;\n\t\t/**\n\t\t * 自动召回质量门槛 (错误教训与召回质量护栏设计 §2.1, 内部执行缝):\n\t\t * memory_recall 工具 schema 不含该参数, 显式召回行为不变; auto-recall\n\t\t * 钩子经内部闭包恒传。仅精排实际产生 score 且过门槛的候选保留 (裁决 A\n\t\t * 收紧: 无 score 候选一律丢弃)。\n\t\t */\n\t\treadonly minScore?: number;\n\t}): Promise<SemanticRecallOutcomeV1> => {\n\t\t// 后台预热不阻塞读侧 (2026-10-05 流程裁决「后台预热、不阻塞提问」):\n\t\t// 下载/加载进行中时 recall 直接返回 warming 不可用包, 不等待 vectorQueue\n\t\t// (队列此时可能正背着启动对账或下载任务) 与 ensure 单飞。\n\t\tif (deps.warming()) {\n\t\t\treturn {\n\t\t\t\tkind: \"unavailable\",\n\t\t\t\tmessage: \"memory models are loading in the background; recall becomes available once they are ready\",\n\t\t\t};\n\t\t}\n\t\t// 读侧先等写侧队列在调用时刻已入队的部分 (待处理的投影写入 + 启动对账\n\t\t// 已入队的块), 保证写入→召回 FIFO: 本调用之前提交的写入其投影先落地,\n\t\t// 不与后台对账/埋点竞态。启动对账的分块自续 (RECONCILE_CHUNK_UPSERTS)\n\t\t// 在块完成时才入队下一块, 未入队的后续块不阻塞本次召回——未回填条目由\n\t\t// store 回查与 memory_list 兜底, 残行由后续对账继续补齐。\n\t\tawait deps.settleProjection();\n\t\tconst channel = await deps.ensureChannel();\n\t\tif (channel === undefined) {\n\t\t\tif (deps.declined()) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"unavailable\",\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t\"memory was declined on this machine — set memory.mode (light|full) in settings.json and restart the session to re-enable\",\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst consentAsk = deps.consentAsk();\n\t\t\tif (consentAsk !== undefined) {\n\t\t\t\treturn { kind: \"unavailable\", message: consentAsk.message };\n\t\t\t}\n\t\t\tconst failure = deps.failure();\n\t\t\treturn {\n\t\t\t\tkind: \"unavailable\",\n\t\t\t\tmessage:\n\t\t\t\t\tfailure === undefined\n\t\t\t\t\t\t? `memory channel is unavailable (state=${deps.rawState()})`\n\t\t\t\t\t\t: `memory enabling failed: ${failure.reason} — actions: ${failure.actions.join(\" | \")}`,\n\t\t\t};\n\t\t}\n\t\tconst suiteId = input.domain.kind === \"suite\" ? input.domain.suiteId : undefined;\n\t\tlet vectorFailed = false;\n\t\tlet ftsFailed = false;\n\t\tlet knnHits: readonly MemoryVectorHitV1[] | undefined;\n\t\tlet ftsHits: readonly MemoryVectorHitV1[] | undefined;\n\t\ttry {\n\t\t\tconst [queryVector] = await channel.embed.embed([channel.queryPrefix + input.query]);\n\t\t\tknnHits = await channel.index.queryKnn(queryVector, {\n\t\t\t\towner: deps.owner,\n\t\t\t\tlimit: HYBRID_CHANNEL_DEPTH,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tvectorFailed = true;\n\t\t\tdeps.logger?.warn(\"memory recall degraded: the vector channel failed; continuing on the FTS channel\", {\n\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t});\n\t\t}\n\t\ttry {\n\t\t\tftsHits = await channel.index.queryFts(input.query, {\n\t\t\t\towner: deps.owner,\n\t\t\t\tlimit: HYBRID_CHANNEL_DEPTH,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tftsFailed = true;\n\t\t\tdeps.logger?.warn(\"memory recall degraded: the FTS channel failed\", {\n\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t});\n\t\t}\n\n\t\tlet candidates: readonly RecallCandidateV1[];\n\t\tlet suiteFilter: MemorySuiteFilterStatsV1 = { legacySkipped: 0, foreignSuiteSkipped: 0 };\n\t\tlet channelDegraded = false;\n\t\t// 裁决 A: 降级原因短语, 透出到工具结果的 degraded 字段 (无精排分数路径)。\n\t\tlet degradedReason: string | undefined;\n\t\tif (!vectorFailed && !ftsFailed && knnHits !== undefined && ftsHits !== undefined) {\n\t\t\t// 主路径: 双通道 RRF k=60 融合 top20。\n\t\t\tconst pool = rrfFuseRankings([ftsHits.map((hit) => hit.memoryId), knnHits.map((hit) => hit.memoryId)]);\n\t\t\tconst lookup = lookupCandidates(\n\t\t\t\tpool.map((memoryId, position) => [memoryId, position] as const),\n\t\t\t\tsuiteId,\n\t\t\t);\n\t\t\tcandidates = lookup.candidates;\n\t\t\tsuiteFilter = lookup.suiteFilter;\n\t\t} else if (ftsHits !== undefined) {\n\t\t\t// 向量失败: FTS-only + recency 排序。\n\t\t\tchannelDegraded = true;\n\t\t\tdegradedReason = \"vector channel failed; full-text-only results, not reranked\";\n\t\t\tconst lookup = lookupCandidates(\n\t\t\t\tftsHits.map((hit, position) => [hit.memoryId, position] as const),\n\t\t\t\tsuiteId,\n\t\t\t);\n\t\t\tcandidates = recencyOrdered(lookup.candidates);\n\t\t\tsuiteFilter = lookup.suiteFilter;\n\t\t} else if (knnHits !== undefined) {\n\t\t\t// FTS 失败: KNN-only + recency 排序 (对称降级)。\n\t\t\tchannelDegraded = true;\n\t\t\tdegradedReason = \"FTS channel failed; vector-only results, not reranked\";\n\t\t\tconst lookup = lookupCandidates(\n\t\t\t\tknnHits.map((hit, position) => [hit.memoryId, position] as const),\n\t\t\t\tsuiteId,\n\t\t\t);\n\t\t\tcandidates = recencyOrdered(lookup.candidates);\n\t\t\tsuiteFilter = lookup.suiteFilter;\n\t\t} else {\n\t\t\t// 双通道皆败 = 语义召回能力不可用 (2026-10-05 裁决 A): 显式召回返回\n\t\t\t// 结构化 unavailable (memory_list 仍是列表入口), recency 枚举兜底从\n\t\t\t// 语义召回路径移除 — 语义查询返回\"最近的几条\"是对查询语义的错答。\n\t\t\tdeps.markDegraded();\n\t\t\tdeps.logger?.warn(\"memory recall unavailable: both the vector and FTS channels failed\");\n\t\t\treturn {\n\t\t\t\tkind: \"unavailable\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"memory recall is unavailable (both retrieval channels failed); use memory_list to enumerate this suite's memories\",\n\t\t\t};\n\t\t}\n\t\t// 运行期通道故障 → degraded (可自愈: 下一次全通 recall 回 ready)。\n\t\tif (channelDegraded) deps.markDegraded();\n\t\telse deps.recoverDegraded();\n\n\t\t// superseded 过滤 (S3-B): 回查后、egress/精排前 (主路径与全部降级路径\n\t\t// 统一收敛于此 — 被继任的旧条目任何通道都不再出线)。\n\t\tcandidates = filterSupersededCandidates(candidates);\n\n\t\tif (candidates.length === 0) {\n\t\t\treturn {\n\t\t\t\tkind: \"served\",\n\t\t\t\tfacts: [],\n\t\t\t\tcandidateCount: 0,\n\t\t\t\tsuiteFilter,\n\t\t\t\t...(degradedReason === undefined ? {} : { degraded: degradedReason }),\n\t\t\t};\n\t\t}\n\t\tconst egressOutcome = egressGate(candidates);\n\t\tif (egressOutcome.status === \"blocked\") return { kind: \"blocked\", reason: egressOutcome.reason };\n\t\tconst statementByMemoryId = new Map(egressOutcome.packet.facts.map((fact) => [fact.memoryId, fact.statement]));\n\t\tlet ordered: readonly ScoredRecallFactV1[] = candidates.map((entry) => ({\n\t\t\tmemoryId: entry.atom.memoryId,\n\t\t\tstatement: deps.unwrapEgressStatement(statementByMemoryId.get(entry.atom.memoryId) ?? \"\"),\n\t\t\tconfidence: entry.atom.confidence,\n\t\t\tposition: entry.position,\n\t\t}));\n\t\t// 精排 (仅主融合路径: 降级页的排序即其降级语义)。reranker 不可用或调用\n\t\t// 失败 → 保持 RRF 序并携带 degraded 标记; 调用失败不闩锁 (裁决 A: 下一次\n\t\t// 召回重试, 与组件层加载重试语义对齐), 每次失败记一条结构化日志。\n\t\tconst reranker = channel.reranker;\n\t\tif (!channelDegraded && reranker !== undefined) {\n\t\t\ttry {\n\t\t\t\tconst scores = await reranker.rerank(\n\t\t\t\t\tinput.query,\n\t\t\t\t\tordered.map((fact) => fact.statement),\n\t\t\t\t);\n\t\t\t\tordered = ordered\n\t\t\t\t\t.map((fact, position) => ({ ...fact, score: scores[position] }))\n\t\t\t\t\t.sort((left, right) => (right.score ?? 0) - (left.score ?? 0) || left.position - right.position);\n\t\t\t} catch (error) {\n\t\t\t\tdegradedReason ??= \"reranker failed; RRF order without rerank scores\";\n\t\t\t\tdeps.logger?.warn(\n\t\t\t\t\t\"memory reranker failed; recall serves the RRF order this round and retries the next recall\",\n\t\t\t\t\t{\n\t\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\t// minScore 门槛 (§2.1, 裁决 A 收紧): 仅精排实际产生 score 且过门槛的候选\n\t\t// 参与过滤后结果 (无 score 的候选一律丢弃, 不再放行); 过滤先于 limit 截取。\n\t\t// minScore 只经 auto-recall 内部闭包传入, auto-recall 另按 degraded 标记\n\t\t// 零注入, 双保险钉住\"注入 ⟹ 全部条目有分且过门槛\"。\n\t\tconst minScore = input.minScore;\n\t\tconst eligible =\n\t\t\tminScore === undefined\n\t\t\t\t? ordered\n\t\t\t\t: ordered.filter((fact) => fact.score !== undefined && fact.score >= minScore);\n\t\treturn {\n\t\t\tkind: \"served\",\n\t\t\tfacts: eligible\n\t\t\t\t.slice(0, input.limit)\n\t\t\t\t.map(({ memoryId, statement, confidence }) => ({ memoryId, statement, confidence })),\n\t\t\tcandidateCount: ordered.length,\n\t\t\tsuiteFilter,\n\t\t\t...(degradedReason === undefined ? {} : { degraded: degradedReason }),\n\t\t};\n\t};\n\n\t/**\n\t * Context-scoped preference post-processing over the recalled facts: preference\n\t * atoms compete per (subject, key); the resolver drops out-of-scope preferences\n\t * and deterministically ranks the rest, and an unconfirmed ranking goes through\n\t * the scope-specificity disambiguator. Whatever remains unresolvable is\n\t * returned as an explicit conflict block — the recall never silently picks\n\t * between competing stored values. Non-preference facts pass through untouched.\n\t */\n\tfunction applyPreferenceContext(input: {\n\t\treadonly facts: readonly MemoryFact[];\n\t\treadonly context: PreferenceContextV1;\n\t\treadonly resolver: PreferenceResolverV1;\n\t\treadonly disambiguator: PreferenceDisambiguatorV1;\n\t\treadonly atomOf: (memoryId: string) => MemoryAtomV1 | undefined;\n\t}): { readonly facts: readonly MemoryFact[]; readonly conflicts: readonly RecallConflictV1[] } {\n\t\tconst { facts, context, resolver, disambiguator, atomOf } = input;\n\t\tconst preferenceAtoms: MemoryAtomV1[] = [];\n\t\tconst atomsByGroup = new Map<string, MemoryAtomV1[]>();\n\t\tconst preferenceMemoryIds = new Set<string>();\n\t\tfor (const fact of facts) {\n\t\t\tconst atom = atomOf(fact.memoryId);\n\t\t\tif (atom === undefined || atom.memoryKind !== \"preference\" || atom.preference === undefined) continue;\n\t\t\tpreferenceMemoryIds.add(fact.memoryId);\n\t\t\tpreferenceAtoms.push(atom);\n\t\t\tconst groupKey = `${atom.preference.subject}\\u0000${atom.preference.key}`;\n\t\t\tconst group = atomsByGroup.get(groupKey) ?? [];\n\t\t\tgroup.push(atom);\n\t\t\tatomsByGroup.set(groupKey, group);\n\t\t}\n\t\tif (preferenceMemoryIds.size === 0) return { facts, conflicts: [] };\n\n\t\tconst keptMemoryIds = new Set<string>();\n\t\tconst conflicts: RecallConflictV1[] = [];\n\t\tfor (const decision of resolver.resolve(preferenceAtoms, context)) {\n\t\t\tconst groupAtoms = atomsByGroup.get(`${decision.subject}\\u0000${decision.key}`) ?? [];\n\t\t\tif (decision.status === \"applied\") {\n\t\t\t\tif (decision.winnerMemoryId === undefined) {\n\t\t\t\t\tthrow new Error(`applied preference decision without a winnerMemoryId: ${JSON.stringify(decision)}`);\n\t\t\t\t}\n\t\t\t\tkeptMemoryIds.add(decision.winnerMemoryId);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (decision.status === \"instruction_override\") {\n\t\t\t\t// No stored fact survives a current-instruction override (this slice has\n\t\t\t\t// no input source for currentInstructions, so the branch stays inert).\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (decision.status === \"conflict_unconfirmed\") {\n\t\t\t\tconst outcome = disambiguator.disambiguate(\n\t\t\t\t\tgroupAtoms.map((atom) => ({\n\t\t\t\t\t\tmemoryId: atom.memoryId,\n\t\t\t\t\t\tpreferredValue: atom.preference!.preferredValue,\n\t\t\t\t\t\tscope: atom.preference!.scope,\n\t\t\t\t\t\tevidenceClass: atom.preference!.evidence.class,\n\t\t\t\t\t\tapplicabilityConfidence: atom.preference!.applicabilityConfidence,\n\t\t\t\t\t})),\n\t\t\t\t\tcontext,\n\t\t\t\t);\n\t\t\t\tif (outcome.status === \"resolved\") {\n\t\t\t\t\tkeptMemoryIds.add(outcome.winnerMemoryId);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconflicts.push({\n\t\t\t\t\tsubject: decision.subject,\n\t\t\t\t\tkey: decision.key,\n\t\t\t\t\tcandidates: groupAtoms.map((atom) => {\n\t\t\t\t\t\tconst preference = atom.preference!;\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tmemoryId: atom.memoryId,\n\t\t\t\t\t\t\tstatement: deps.unwrapEgressStatement(deps.statementOf(atom.payload)),\n\t\t\t\t\t\t\tvalue: preference.preferredValue,\n\t\t\t\t\t\t\tevidenceClass: preference.evidence.class,\n\t\t\t\t\t\t\tconfidence: preference.applicabilityConfidence,\n\t\t\t\t\t\t};\n\t\t\t\t\t}),\n\t\t\t\t\texplanation: [...outcome.explanation],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow new Error(`unexpected preference decision status: ${JSON.stringify(decision)}`);\n\t\t}\n\n\t\treturn {\n\t\t\tfacts: facts.filter((fact) => !preferenceMemoryIds.has(fact.memoryId) || keptMemoryIds.has(fact.memoryId)),\n\t\t\tconflicts,\n\t\t};\n\t}\n\n\t/**\n\t * Parses the optional recall context (scenes/projects/tasks) into a preference\n\t * resolution context. Returns undefined when absent so the no-context recall\n\t * path stays byte-identical to the pre-disambiguation behavior.\n\t */\n\tfunction parseRecallContext(value: unknown): PreferenceContextV1 | undefined {\n\t\tif (value === undefined) return undefined;\n\t\tif (!deps.isPlainObject(value)) throw new Error(\"context must be an object\");\n\t\tconst stringArray = (field: \"scenes\" | \"projects\" | \"tasks\"): readonly string[] | undefined => {\n\t\t\tconst entries: unknown = value[field];\n\t\t\tif (entries === undefined) return undefined;\n\t\t\tif (!Array.isArray(entries)) throw new Error(`context.${field} must be an array of strings`);\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (typeof entry !== \"string\") throw new Error(`context.${field} entries must be strings`);\n\t\t\t}\n\t\t\treturn entries;\n\t\t};\n\t\tconst scenes = stringArray(\"scenes\");\n\t\tconst projects = stringArray(\"projects\");\n\t\tconst tasks = stringArray(\"tasks\");\n\t\treturn {\n\t\t\t...(scenes === undefined ? {} : { scenes }),\n\t\t\t...(projects === undefined ? {} : { projects }),\n\t\t\t...(tasks === undefined ? {} : { tasks }),\n\t\t};\n\t}\n\n\t// 提取为具名闭包: 除模型工具面外, 下方的 auto-recall 钩子直接调用同一 execute\n\t// (单参输入约定, memoryToolInput 取第一参), 不经 runtime.invokeTool —— 钩子\n\t// 随插件注册/卸载, 与工具面同生命周期, 替换工具面不会重接自动召回。\n\tconst recallExecute = async (first: unknown, second?: unknown): Promise<unknown> => {\n\t\tconst input = deps.memoryToolInput(first, second);\n\t\tdeps.assertNonEmptyString(input.query, \"query\");\n\t\tconst rawLimit: unknown = input.limit;\n\t\tconst limit =\n\t\t\trawLimit === undefined\n\t\t\t\t? DEFAULT_RECALL_LIMIT\n\t\t\t\t: ((): number => {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\ttypeof rawLimit !== \"number\" ||\n\t\t\t\t\t\t\t!Number.isSafeInteger(rawLimit) ||\n\t\t\t\t\t\t\trawLimit < 1 ||\n\t\t\t\t\t\t\trawLimit > 100\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthrow new Error(\"limit must be an integer between 1 and 100\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn rawLimit;\n\t\t\t\t\t})();\n\t\t// 内部执行缝 (§2.1): auto-recall 闭包经本字段恒传质量门槛; memory_recall\n\t\t// 工具 schema 不含该参数 (工具面恒 undefined), 显式召回行为不变。\n\t\tconst rawMinScore: unknown = input.minScore;\n\t\tconst minScore =\n\t\t\trawMinScore === undefined\n\t\t\t\t? undefined\n\t\t\t\t: ((): number => {\n\t\t\t\t\t\tif (typeof rawMinScore !== \"number\" || !Number.isFinite(rawMinScore)) {\n\t\t\t\t\t\t\tthrow new Error(\"minScore must be a finite number\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn rawMinScore;\n\t\t\t\t\t})();\n\t\tconst context = parseRecallContext(input.context);\n\t\tconst { domain } = deps.resolveDomain();\n\n\t\t// enabling 失败 = 本实例终态 (mode 记录回退 off): 记忆工具返回携带原因\n\t\t// 与五选一行动清单的不可用 packet (设计 §3.2 硬性要求), 不再重试。\n\t\tif (deps.rawState() === \"failed\") {\n\t\t\tconst failure = deps.failure() ?? { reason: \"memory enabling failed\", actions: [] as const };\n\t\t\treturn {\n\t\t\t\tstatus: \"unavailable\",\n\t\t\t\tstate: \"failed\",\n\t\t\t\tfacts: [] as MemoryFact[],\n\t\t\t\terror: `memory enabling failed: ${failure.reason}`,\n\t\t\t\tactions: failure.actions,\n\t\t\t};\n\t\t}\n\t\t// 征询门早退 (2026-10-05 用户裁决): 拒绝 = 本实例按模式关闭对待; 待征询 =\n\t\t// 返回带行动清单的 consent-required packet (后续 recall 不再反复探测文件)。\n\t\tif (deps.declined()) {\n\t\t\treturn {\n\t\t\t\tstatus: \"unavailable\",\n\t\t\t\tstate: \"off\",\n\t\t\t\tfacts: [] as MemoryFact[],\n\t\t\t\terror: \"memory was declined on this machine — set memory.mode (light|full) in settings.json and restart the session to re-enable\",\n\t\t\t\tactions: [] as const,\n\t\t\t};\n\t\t}\n\t\tconst consentAsk = deps.consentAsk();\n\t\tif (consentAsk !== undefined) {\n\t\t\treturn {\n\t\t\t\tstatus: \"unavailable\",\n\t\t\t\tstate: \"consent-required\",\n\t\t\t\tfacts: [] as MemoryFact[],\n\t\t\t\terror: consentAsk.message,\n\t\t\t\tactions: consentAsk.actions,\n\t\t\t};\n\t\t}\n\n\t\t// 主键快路径 (memoryIdEquals 语义保留, 幂等/引用而非检索): query 恰为本\n\t\t// 域可见 memoryId 时直接取该条, 不依赖向量通道 (enabling 期间也可用)。\n\t\tlet outcome: SemanticRecallOutcomeV1;\n\t\tconst directRecord = deps.store.get(input.query.trim(), {\n\t\t\towner: deps.owner,\n\t\t\t...(domain.kind === \"suite\" ? { suiteId: domain.suiteId } : {}),\n\t\t});\n\t\tif (directRecord !== undefined) {\n\t\t\tconst gate = egressGate([{ atom: directRecord.atom, position: 0 }]);\n\t\t\tif (gate.status === \"blocked\") {\n\t\t\t\treturn { status: \"failed\", facts: [] as MemoryFact[], error: `egress blocked: ${gate.reason}` };\n\t\t\t}\n\t\t\tconst statementByMemoryId = new Map(gate.packet.facts.map((fact) => [fact.memoryId, fact.statement]));\n\t\t\toutcome = {\n\t\t\t\tkind: \"served\",\n\t\t\t\tfacts: [\n\t\t\t\t\t{\n\t\t\t\t\t\tmemoryId: directRecord.atom.memoryId,\n\t\t\t\t\t\tstatement: deps.unwrapEgressStatement(statementByMemoryId.get(directRecord.atom.memoryId) ?? \"\"),\n\t\t\t\t\t\tconfidence: directRecord.atom.confidence,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tcandidateCount: 1,\n\t\t\t\tsuiteFilter: { legacySkipped: 0, foreignSuiteSkipped: 0 },\n\t\t\t\t// 裁决 A 缝隙收口 (2026-10-05 复审后用户裁决「修复」): 直查是引用\n\t\t\t\t// 语义、未经精排 — 显式召回如实带标记, auto-recall 见标记零注入\n\t\t\t\t// (此前用户消息恰为 memoryId 时会绕过质量门注入该条)。\n\t\t\t\tdegraded: \"primary-key direct lookup (reference semantics, not reranked)\",\n\t\t\t};\n\t\t} else {\n\t\t\ttry {\n\t\t\t\toutcome = await recallSemantically({\n\t\t\t\t\tquery: input.query,\n\t\t\t\t\tdomain,\n\t\t\t\t\tlimit,\n\t\t\t\t\t...(minScore === undefined ? {} : { minScore }),\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\t// 意外异常 (管线 throw) → degraded packet: 结构化返回, 不抛给模型。\n\t\t\t\tdeps.markDegraded();\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tdeps.logger?.warn(\"memory recall degraded: the recall pipeline threw; returning a degraded packet\", {\n\t\t\t\t\terror: message,\n\t\t\t\t});\n\t\t\t\treturn { status: \"failed\", facts: [] as MemoryFact[], error: message };\n\t\t\t}\n\t\t}\n\t\tif (outcome.kind === \"blocked\") {\n\t\t\treturn { status: \"failed\", facts: [] as MemoryFact[], error: `egress blocked: ${outcome.reason}` };\n\t\t}\n\t\tif (outcome.kind === \"unavailable\") {\n\t\t\t// 首次调用即在装配中途失败时, vectorState 在本调用内才翻成 failed —\n\t\t\t// 这里同样必须携带 enabling 失败的原因 + 行动清单 (设计 §3.2 硬性\n\t\t\t// 要求: 终态的第一份可见 packet 就是完整的), 不等下一次调用补。\n\t\t\t// (vectorState 是可变闭包状态, 语义检索内部会改写它, 入口预检的\n\t\t\t// 收窄在此处不成立 — 经函数边界读取以如实表达。)\n\t\t\tconst stateAtEgress = (): MemoryCapabilityStateV1 => deps.rawState();\n\t\t\tconst failureAtEgress = deps.failure();\n\t\t\tconst consentAskAtEgress = deps.consentAsk();\n\t\t\tif (stateAtEgress() === \"failed\" && failureAtEgress !== undefined) {\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"unavailable\",\n\t\t\t\t\tstate: \"failed\",\n\t\t\t\t\tfacts: [] as MemoryFact[],\n\t\t\t\t\terror: `memory enabling failed: ${failureAtEgress.reason}`,\n\t\t\t\t\tactions: failureAtEgress.actions,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstatus: \"unavailable\",\n\t\t\t\tstate: stateAtEgress(),\n\t\t\t\tfacts: [] as MemoryFact[],\n\t\t\t\terror: outcome.message,\n\t\t\t\t...(stateAtEgress() === \"consent-required\" && consentAskAtEgress !== undefined\n\t\t\t\t\t? { actions: consentAskAtEgress.actions }\n\t\t\t\t\t: {}),\n\t\t\t};\n\t\t}\n\t\tconst facts = outcome.facts;\n\t\t// 增强段 (偏好消歧 + 关系扩散) 是增量元数据面: 内部抛错不得砸穿工具面\n\t\t// (结构化失败契约), 也不吞掉整个召回 — 降级为基础事实 + 一条结构化 warn。\n\t\tconst { finalFacts, resolvedConflicts, related, relatedOmittedCount } = await (async () => {\n\t\t\ttry {\n\t\t\t\tconst resolved =\n\t\t\t\t\tcontext === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: applyPreferenceContext({\n\t\t\t\t\t\t\t\tfacts,\n\t\t\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t\t\tresolver: deps.preferenceResolver,\n\t\t\t\t\t\t\t\tdisambiguator: deps.preferenceDisambiguator,\n\t\t\t\t\t\t\t\tatomOf: (memoryId) => deps.store.get(memoryId, { owner: deps.owner })?.atom,\n\t\t\t\t\t\t\t});\n\t\t\t\t// 偏好消歧先于关系扩散: the diffusion seeds are the atoms the user\n\t\t\t\t// actually sees — preference facts dropped by the conflict resolution\n\t\t\t\t// never diffuse their relations.\n\t\t\t\tconst baseFacts = resolved === undefined ? facts : resolved.facts;\n\t\t\t\tconst seeds: MemoryAtomV1[] = [];\n\t\t\t\tfor (const fact of baseFacts) {\n\t\t\t\t\tconst atom = deps.store.get(fact.memoryId, { owner: deps.owner })?.atom;\n\t\t\t\t\tif (atom !== undefined) seeds.push(atom);\n\t\t\t\t}\n\t\t\t\t// The traversal graph is the recall domain's visible atom set (same\n\t\t\t\t// suite read boundary). Diffusion targets outside this set are dropped,\n\t\t\t\t// so relations never leak across suites.\n\t\t\t\tconst domainMemoryIds = new Set<string>();\n\t\t\t\tconst graph: MemoryAtomV1[] = [];\n\t\t\t\tfor (const entry of listDomainMemories({ store: deps.store }, { owner: deps.owner, domain }).entries) {\n\t\t\t\t\tdomainMemoryIds.add(entry.memoryId);\n\t\t\t\t\tconst atom = deps.store.get(entry.memoryId, { owner: deps.owner })?.atom;\n\t\t\t\t\tif (atom !== undefined) graph.push(atom);\n\t\t\t\t}\n\t\t\t\tconst related: MemoryNetworkExpansionV1[] = [];\n\t\t\t\tlet relatedOmittedCount = 0;\n\t\t\t\tconst seenRelatedMemoryIds = new Set<string>();\n\t\t\t\tfor (const adapterResult of deps.memoryNetwork.expand({ seeds, graph })) {\n\t\t\t\t\tif (adapterResult.status !== \"completed\") continue;\n\t\t\t\t\tfor (const expansion of adapterResult.related) {\n\t\t\t\t\t\tif (!domainMemoryIds.has(expansion.memoryId)) continue;\n\t\t\t\t\t\tif (seenRelatedMemoryIds.has(expansion.memoryId)) continue;\n\t\t\t\t\t\tseenRelatedMemoryIds.add(expansion.memoryId);\n\t\t\t\t\t\tif (related.length >= MAX_RELATED_REFS) {\n\t\t\t\t\t\t\trelatedOmittedCount += 1;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\trelated.push(expansion);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tfinalFacts: baseFacts,\n\t\t\t\t\tresolvedConflicts: resolved === undefined ? [] : resolved.conflicts,\n\t\t\t\t\trelated,\n\t\t\t\t\trelatedOmittedCount,\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tdeps.logger?.warn(\n\t\t\t\t\t\"memory recall enhancement failed; serving the base facts without preference resolution and related references\",\n\t\t\t\t\t{ error: error instanceof Error ? error.message : String(error) },\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tfinalFacts: facts,\n\t\t\t\t\tresolvedConflicts: [],\n\t\t\t\t\trelated: [] as MemoryNetworkExpansionV1[],\n\t\t\t\t\trelatedOmittedCount: 0,\n\t\t\t\t};\n\t\t\t}\n\t\t})();\n\t\treturn {\n\t\t\tstatus: finalFacts.length === 0 ? \"empty\" : \"completed\",\n\t\t\tfacts: finalFacts,\n\t\t\t...(outcome.degraded === undefined ? {} : { degraded: outcome.degraded }),\n\t\t\t...(resolvedConflicts.length > 0 ? { conflicts: resolvedConflicts } : {}),\n\t\t\t...(domain.kind === \"suite\" ? { suiteFilter: outcome.suiteFilter } : {}),\n\t\t\tomittedCount: Math.max(0, outcome.candidateCount - finalFacts.length),\n\t\t\ttruncated: false,\n\t\t\t// References only — no statement/payload egress; the model fetches\n\t\t\t// content via memory_list or another memory_recall.\n\t\t\t...(related.length > 0\n\t\t\t\t? {\n\t\t\t\t\t\trelated: related.map((expansion) => ({\n\t\t\t\t\t\t\tmemoryId: expansion.memoryId,\n\t\t\t\t\t\t\trelationKind: expansion.relationKind,\n\t\t\t\t\t\t\thop: expansion.hop,\n\t\t\t\t\t\t\tweight: expansion.weight,\n\t\t\t\t\t\t\tvia: expansion.via,\n\t\t\t\t\t\t})),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(relatedOmittedCount > 0 ? { relatedOmittedCount } : {}),\n\t\t};\n\t};\n\tconst recallTool = deps.registerTool({\n\t\tname: MEMORY_RECALL_TOOL_NAME,\n\t\tlabel: \"Recall memories\",\n\t\tpromptGuidelines: [MEMORY_TOOLS_GUIDE],\n\t\tdescription:\n\t\t\t\"Search this suite's durable memories with semantic recall: vector and full-text channels fuse (RRF) and the result is reranked; an exact memoryId retrieves that memory directly; the result may include related memory references (ids and relation metadata only — recall or list a referenced memory again for its content)\",\n\t\tparameters: recallSchema,\n\t\texecute: recallExecute,\n\t});\n\n\treturn { recallTool, recallExecute };\n}\n"]}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { MemoryPurgeGateV1 } from "./purge.ts";
|
|
2
|
+
import type { MemoryPurgeJournalV1 } from "./purge-journal.ts";
|
|
3
|
+
import type { MemoryStoreV1 } from "./store.ts";
|
|
4
|
+
import { type SuiteMemoryDomainV1 } from "./suite-memory.ts";
|
|
5
|
+
/**
|
|
6
|
+
* 单批清扫的过期原子上限(最旧优先取前 N 条;超出部分留给下一轮 sweep——
|
|
7
|
+
* 批量物理清理的对标口径,与 codex PRUNE_BATCH_SIZE 同量级)。
|
|
8
|
+
*/
|
|
9
|
+
export declare const MEMORY_RETENTION_SWEEP_BATCH_LIMIT = 200;
|
|
10
|
+
export interface MemoryRetentionSweepDepsV1 {
|
|
11
|
+
/** canonical store(过期判定的唯一权威,经可选 listExpired 枚举)。 */
|
|
12
|
+
readonly store: MemoryStoreV1;
|
|
13
|
+
readonly purgeGate: MemoryPurgeGateV1;
|
|
14
|
+
readonly purgeJournal: MemoryPurgeJournalV1;
|
|
15
|
+
/**
|
|
16
|
+
* canonical 副本清除回调(capability 装配注入:当前域 ledger.rewrite 去掉
|
|
17
|
+
* 批次原子 + store.evict)。必须幂等——purge_eligible 重试会重跑它。
|
|
18
|
+
*/
|
|
19
|
+
readonly purgeCanonicalReplica: (memoryIds: readonly string[]) => void;
|
|
20
|
+
/**
|
|
21
|
+
* index 副本(向量投影)清除回调;缺省 undefined 时 index 分派为 no-op 且
|
|
22
|
+
* 不报错——与 suite-memory 门面同语义(向量通道未装配时索引里无行可清)。
|
|
23
|
+
*/
|
|
24
|
+
readonly purgeIndexReplica?: (memoryIds: readonly string[]) => void;
|
|
25
|
+
/** 授权主体(authorizationRef.issuedBy 与批次 authorizedBy),capability 传入 manifest 派生串。 */
|
|
26
|
+
readonly authorizedBy: string;
|
|
27
|
+
readonly now?: () => number;
|
|
28
|
+
}
|
|
29
|
+
export interface MemoryRetentionSweepResultV1 {
|
|
30
|
+
/**
|
|
31
|
+
* `completed` / `purge_eligible`:purge 门语义原样(barrier 全确认 / 部分
|
|
32
|
+
* 失败待幂等重试)。`failed`:授权或执行链抛错(错误原文在 `reason`,批次
|
|
33
|
+
* 状态未知但不阻塞调用方,可重试)。`skipped`:本域没有过期原子,或注入
|
|
34
|
+
* store 未提供过期枚举(`reason` 说明,绝不猜写过期集)。
|
|
35
|
+
*/
|
|
36
|
+
readonly status: "completed" | "purge_eligible" | "failed" | "skipped";
|
|
37
|
+
/** skipped/failed 的原因;干净结果无此字段。 */
|
|
38
|
+
readonly reason?: string;
|
|
39
|
+
readonly batchId?: string;
|
|
40
|
+
/** 本批授权的 memoryIds(completed = 已物理清理;purge_eligible = 待重试)。 */
|
|
41
|
+
readonly memoryIds: readonly string[];
|
|
42
|
+
readonly confirmedReplicas?: readonly string[];
|
|
43
|
+
readonly failedReplicas?: readonly {
|
|
44
|
+
readonly replicaId: string;
|
|
45
|
+
readonly error: string;
|
|
46
|
+
}[];
|
|
47
|
+
/** 本批之后仍过期的本域原子数(下一轮 sweep 继续);枚举未完成时缺省。 */
|
|
48
|
+
readonly remainingExpired?: number;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Runs one retention-sweep batch over the owner's expired records in `domain`.
|
|
52
|
+
* Never throws — every failure surfaces as a structured summary (see
|
|
53
|
+
* {@link MemoryRetentionSweepResultV1.status}).
|
|
54
|
+
*/
|
|
55
|
+
export declare function sweepExpiredMemories(deps: MemoryRetentionSweepDepsV1, input: {
|
|
56
|
+
readonly owner: string;
|
|
57
|
+
readonly domain: SuiteMemoryDomainV1;
|
|
58
|
+
}): MemoryRetentionSweepResultV1;
|
|
59
|
+
//# sourceMappingURL=retention-sweep.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"retention-sweep.d.ts","sourceRoot":"","sources":["../../src/memory/retention-sweep.ts"],"names":[],"mappings":"AA4BA,OAAO,KAAK,EAAiC,iBAAiB,EAAmB,MAAM,YAAY,CAAC;AACpG,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,EAAE,KAAK,mBAAmB,EAAyB,MAAM,mBAAmB,CAAC;AAEpF;;;GAGG;AACH,eAAO,MAAM,kCAAkC,MAAM,CAAC;AAEtD,MAAM,WAAW,0BAA0B;IAC1C,yFAAqD;IACrD,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC;IAC9B,QAAQ,CAAC,SAAS,EAAE,iBAAiB,CAAC;IACtC,QAAQ,CAAC,YAAY,EAAE,oBAAoB,CAAC;IAC5C;;;OAGG;IACH,QAAQ,CAAC,qBAAqB,EAAE,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,KAAK,IAAI,CAAC;IACvE;;;OAGG;IACH,QAAQ,CAAC,iBAAiB,CAAC,EAAE,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,KAAK,IAAI,CAAC;IACpE,mHAAmF;IACnF,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,4BAA4B;IAC5C;;;;;OAKG;IACH,QAAQ,CAAC,MAAM,EAAE,WAAW,GAAG,gBAAgB,GAAG,QAAQ,GAAG,SAAS,CAAC;IACvE,6DAAmC;IACnC,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,iGAA+D;IAC/D,QAAQ,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,QAAQ,CAAC,iBAAiB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC/C,QAAQ,CAAC,cAAc,CAAC,EAAE,SAAS;QAAE,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC5F,wGAA4C;IAC5C,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;CACnC;AAYD;;;;GAIG;AACH,wBAAgB,oBAAoB,CACnC,IAAI,EAAE,0BAA0B,EAChC,KAAK,EAAE;IAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,mBAAmB,CAAA;CAAE,GACrE,4BAA4B,CA6E9B","sourcesContent":["/**\n * 机会式保留清扫 (retention sweep, 记忆系统设计 §3.3 的第一方落地) — the\n * automatic arm of the controlled physical purge.\n *\n * 过期 (`purgeAt <= now`) 在 store 里只是逻辑失效:recall 不可见,ledger 行、\n * 向量投影行与 store 条目全部保留。本模块在每个会话的每个域首载重放完成后被\n * capability.resolveDomain 调用一次:从 store 枚举已过期的本域原子,最旧优先\n * 取至多 {@link MEMORY_RETENTION_SWEEP_BATCH_LIMIT} 条,以 `retention-expiry`\n * 授权(purge.ts:该 mode 不需要额外引用)走既有 purge 门(authorizeBatch →\n * executeBatch → journal → barrier),副本分派与 suite-memory 的\n * executePurgeBatch 同链同语义:index 副本 → 向量投影清除回调,canonical 副本\n * → 注入回调(当前域 ledger 重写 + store 逐出)。无定时器——触发点只有首载\n * 重放完成这一条路径,写路径不挂。\n *\n * 域成员判定与 forgetDomainMemory 同判据(atom.suiteId 匹配 / legacy 为\n * undefined):canonical 副本是按域分文件的 JSONL ledger,批次只授权\"其持久\n * 行就在本次回调可重写的这份 ledger 里\"的原子——跨域原子留给各自域的装载\n * sweep,绝不产生\"store 已逐出、重启重放又复活\"的窗口。\n *\n * 失败语义:副本级失败由 purge 门兜住(批次保持 `purge_eligible`,结构化\n * failedReplicas,幂等可重试——下一轮 sweep 会把仍过期的原子重新授权清理,\n * batchId 也可直接经门重试);授权/执行链抛错被本模块吞掉并转为 `failed`\n * 摘要。本模块绝不向调用方抛错,会话/域装载绝不因清扫失败失败;调用点只把\n * 非干净摘要记一条有界 warn。\n *\n * deps 全部显式注入,无模块级可变状态。\n */\nimport type { MemoryAtomV1 } from \"./foundation.ts\";\nimport type { MemoryPurgeAuthorizationRefV1, MemoryPurgeGateV1, MemoryReplicaV1 } from \"./purge.ts\";\nimport type { MemoryPurgeJournalV1 } from \"./purge-journal.ts\";\nimport type { MemoryStoreV1 } from \"./store.ts\";\nimport { type SuiteMemoryDomainV1, suiteMemoryDomainName } from \"./suite-memory.ts\";\n\n/**\n * 单批清扫的过期原子上限(最旧优先取前 N 条;超出部分留给下一轮 sweep——\n * 批量物理清理的对标口径,与 codex PRUNE_BATCH_SIZE 同量级)。\n */\nexport const MEMORY_RETENTION_SWEEP_BATCH_LIMIT = 200;\n\nexport interface MemoryRetentionSweepDepsV1 {\n\t/** canonical store(过期判定的唯一权威,经可选 listExpired 枚举)。 */\n\treadonly store: MemoryStoreV1;\n\treadonly purgeGate: MemoryPurgeGateV1;\n\treadonly purgeJournal: MemoryPurgeJournalV1;\n\t/**\n\t * canonical 副本清除回调(capability 装配注入:当前域 ledger.rewrite 去掉\n\t * 批次原子 + store.evict)。必须幂等——purge_eligible 重试会重跑它。\n\t */\n\treadonly purgeCanonicalReplica: (memoryIds: readonly string[]) => void;\n\t/**\n\t * index 副本(向量投影)清除回调;缺省 undefined 时 index 分派为 no-op 且\n\t * 不报错——与 suite-memory 门面同语义(向量通道未装配时索引里无行可清)。\n\t */\n\treadonly purgeIndexReplica?: (memoryIds: readonly string[]) => void;\n\t/** 授权主体(authorizationRef.issuedBy 与批次 authorizedBy),capability 传入 manifest 派生串。 */\n\treadonly authorizedBy: string;\n\treadonly now?: () => number;\n}\n\nexport interface MemoryRetentionSweepResultV1 {\n\t/**\n\t * `completed` / `purge_eligible`:purge 门语义原样(barrier 全确认 / 部分\n\t * 失败待幂等重试)。`failed`:授权或执行链抛错(错误原文在 `reason`,批次\n\t * 状态未知但不阻塞调用方,可重试)。`skipped`:本域没有过期原子,或注入\n\t * store 未提供过期枚举(`reason` 说明,绝不猜写过期集)。\n\t */\n\treadonly status: \"completed\" | \"purge_eligible\" | \"failed\" | \"skipped\";\n\t/** skipped/failed 的原因;干净结果无此字段。 */\n\treadonly reason?: string;\n\treadonly batchId?: string;\n\t/** 本批授权的 memoryIds(completed = 已物理清理;purge_eligible = 待重试)。 */\n\treadonly memoryIds: readonly string[];\n\treadonly confirmedReplicas?: readonly string[];\n\treadonly failedReplicas?: readonly { readonly replicaId: string; readonly error: string }[];\n\t/** 本批之后仍过期的本域原子数(下一轮 sweep 继续);枚举未完成时缺省。 */\n\treadonly remainingExpired?: number;\n}\n\n/** 域成员判定(与 suite-memory.isDomainMember 同判据):成员资格,不是读边界。 */\nfunction isDomainMember(atom: MemoryAtomV1, domain: SuiteMemoryDomainV1): boolean {\n\tif (domain.kind === \"legacy\") return atom.suiteId === undefined;\n\treturn atom.suiteId === domain.suiteId;\n}\n\nfunction assertNonEmptyString(value: unknown, label: string): asserts value is string {\n\tif (typeof value !== \"string\" || value.trim() === \"\") throw new Error(`${label} must be a non-empty string`);\n}\n\n/**\n * Runs one retention-sweep batch over the owner's expired records in `domain`.\n * Never throws — every failure surfaces as a structured summary (see\n * {@link MemoryRetentionSweepResultV1.status}).\n */\nexport function sweepExpiredMemories(\n\tdeps: MemoryRetentionSweepDepsV1,\n\tinput: { readonly owner: string; readonly domain: SuiteMemoryDomainV1 },\n): MemoryRetentionSweepResultV1 {\n\tconst memoryIds: string[] = [];\n\ttry {\n\t\tassertNonEmptyString(input.owner, \"sweepExpiredMemories owner\");\n\t\tassertNonEmptyString(deps.authorizedBy, \"sweepExpiredMemories authorizedBy\");\n\t\tconst now = deps.now ?? (() => Date.now());\n\t\tconst expired = deps.store.listExpired?.({ owner: input.owner });\n\t\tif (expired === undefined) {\n\t\t\treturn Object.freeze({\n\t\t\t\tstatus: \"skipped\",\n\t\t\t\treason: \"store does not expose expired-record enumeration (listExpired); sweep refuses to guess\",\n\t\t\t\tmemoryIds: Object.freeze([]),\n\t\t\t});\n\t\t}\n\t\tconst members = expired\n\t\t\t.filter((record) => isDomainMember(record.atom, input.domain))\n\t\t\t.sort((left, right) => left.storeRevision - right.storeRevision);\n\t\tif (members.length === 0) {\n\t\t\treturn Object.freeze({ status: \"skipped\", memoryIds: Object.freeze([]), remainingExpired: 0 });\n\t\t}\n\t\tconst batchRecords = members.slice(0, MEMORY_RETENTION_SWEEP_BATCH_LIMIT);\n\t\tfor (const record of batchRecords) memoryIds.push(record.atom.memoryId);\n\t\tconst batch = deps.purgeGate.authorizeBatch({\n\t\t\tmemoryIds,\n\t\t\treason: `retention-sweep:${suiteMemoryDomainName(input.domain)}`,\n\t\t\tauthorizedBy: deps.authorizedBy,\n\t\t\tauthorizationRef: {\n\t\t\t\tmode: \"retention-expiry\",\n\t\t\t\tissuedAt: now(),\n\t\t\t\tissuedBy: deps.authorizedBy,\n\t\t\t} satisfies MemoryPurgeAuthorizationRefV1,\n\t\t});\n\t\tdeps.purgeJournal.authorize({\n\t\t\tbatchId: batch.batchId,\n\t\t\tmemoryIds: batch.memoryIds,\n\t\t\treplicas: batch.replicas,\n\t\t\tauthorizedBy: batch.authorizedBy,\n\t\t\treason: batch.reason,\n\t\t\tat: now(),\n\t\t});\n\t\t// 副本分派与 suite-memory.executePurgeBatch 同链:index → 向量投影回调\n\t\t// (缺省 no-op 确认),其余 → canonical 回调。副本契约要求 purge 幂等\n\t\t// 可重试;门会兜住副本级失败并保持批次 purge_eligible。\n\t\tconst outcome = deps.purgeGate.executeBatch(batch.batchId, (replica: MemoryReplicaV1, ids) => {\n\t\t\tif (replica.kind === \"index\") {\n\t\t\t\tif (deps.purgeIndexReplica === undefined) return;\n\t\t\t\tdeps.purgeIndexReplica(ids);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdeps.purgeCanonicalReplica(ids);\n\t\t});\n\t\t// Journal confirmations are idempotent per (batchId, replicaId); replays\n\t\t// from a retry never double-count.\n\t\tfor (const replica of outcome.replicas) {\n\t\t\tif (outcome.confirmedReplicas?.includes(replica.replicaId)) {\n\t\t\t\tdeps.purgeJournal.confirmReplica({ batchId: batch.batchId, replicaId: replica.replicaId, at: now() });\n\t\t\t}\n\t\t}\n\t\tif (outcome.state === \"completed\") {\n\t\t\tdeps.purgeJournal.complete({ batchId: batch.batchId, at: now() });\n\t\t}\n\t\treturn Object.freeze({\n\t\t\tstatus: outcome.state as \"completed\" | \"purge_eligible\",\n\t\t\tbatchId: batch.batchId,\n\t\t\tmemoryIds: Object.freeze([...memoryIds]),\n\t\t\tconfirmedReplicas: Object.freeze([...(outcome.confirmedReplicas ?? [])]),\n\t\t\t...(outcome.failedReplicas === undefined ? {} : { failedReplicas: outcome.failedReplicas }),\n\t\t\tremainingExpired: members.length - batchRecords.length,\n\t\t});\n\t} catch (error) {\n\t\t// 吞错契约:清扫绝不向调用方抛错,装载绝不因清扫失败失败。\n\t\treturn Object.freeze({\n\t\t\tstatus: \"failed\",\n\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\tmemoryIds: Object.freeze([...memoryIds]),\n\t\t});\n\t}\n}\n"]}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { suiteMemoryDomainName } from "./suite-memory.js";
|
|
2
|
+
/**
|
|
3
|
+
* 单批清扫的过期原子上限(最旧优先取前 N 条;超出部分留给下一轮 sweep——
|
|
4
|
+
* 批量物理清理的对标口径,与 codex PRUNE_BATCH_SIZE 同量级)。
|
|
5
|
+
*/
|
|
6
|
+
export const MEMORY_RETENTION_SWEEP_BATCH_LIMIT = 200;
|
|
7
|
+
/** 域成员判定(与 suite-memory.isDomainMember 同判据):成员资格,不是读边界。 */
|
|
8
|
+
function isDomainMember(atom, domain) {
|
|
9
|
+
if (domain.kind === "legacy")
|
|
10
|
+
return atom.suiteId === undefined;
|
|
11
|
+
return atom.suiteId === domain.suiteId;
|
|
12
|
+
}
|
|
13
|
+
function assertNonEmptyString(value, label) {
|
|
14
|
+
if (typeof value !== "string" || value.trim() === "")
|
|
15
|
+
throw new Error(`${label} must be a non-empty string`);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Runs one retention-sweep batch over the owner's expired records in `domain`.
|
|
19
|
+
* Never throws — every failure surfaces as a structured summary (see
|
|
20
|
+
* {@link MemoryRetentionSweepResultV1.status}).
|
|
21
|
+
*/
|
|
22
|
+
export function sweepExpiredMemories(deps, input) {
|
|
23
|
+
const memoryIds = [];
|
|
24
|
+
try {
|
|
25
|
+
assertNonEmptyString(input.owner, "sweepExpiredMemories owner");
|
|
26
|
+
assertNonEmptyString(deps.authorizedBy, "sweepExpiredMemories authorizedBy");
|
|
27
|
+
const now = deps.now ?? (() => Date.now());
|
|
28
|
+
const expired = deps.store.listExpired?.({ owner: input.owner });
|
|
29
|
+
if (expired === undefined) {
|
|
30
|
+
return Object.freeze({
|
|
31
|
+
status: "skipped",
|
|
32
|
+
reason: "store does not expose expired-record enumeration (listExpired); sweep refuses to guess",
|
|
33
|
+
memoryIds: Object.freeze([]),
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
const members = expired
|
|
37
|
+
.filter((record) => isDomainMember(record.atom, input.domain))
|
|
38
|
+
.sort((left, right) => left.storeRevision - right.storeRevision);
|
|
39
|
+
if (members.length === 0) {
|
|
40
|
+
return Object.freeze({ status: "skipped", memoryIds: Object.freeze([]), remainingExpired: 0 });
|
|
41
|
+
}
|
|
42
|
+
const batchRecords = members.slice(0, MEMORY_RETENTION_SWEEP_BATCH_LIMIT);
|
|
43
|
+
for (const record of batchRecords)
|
|
44
|
+
memoryIds.push(record.atom.memoryId);
|
|
45
|
+
const batch = deps.purgeGate.authorizeBatch({
|
|
46
|
+
memoryIds,
|
|
47
|
+
reason: `retention-sweep:${suiteMemoryDomainName(input.domain)}`,
|
|
48
|
+
authorizedBy: deps.authorizedBy,
|
|
49
|
+
authorizationRef: {
|
|
50
|
+
mode: "retention-expiry",
|
|
51
|
+
issuedAt: now(),
|
|
52
|
+
issuedBy: deps.authorizedBy,
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
deps.purgeJournal.authorize({
|
|
56
|
+
batchId: batch.batchId,
|
|
57
|
+
memoryIds: batch.memoryIds,
|
|
58
|
+
replicas: batch.replicas,
|
|
59
|
+
authorizedBy: batch.authorizedBy,
|
|
60
|
+
reason: batch.reason,
|
|
61
|
+
at: now(),
|
|
62
|
+
});
|
|
63
|
+
// 副本分派与 suite-memory.executePurgeBatch 同链:index → 向量投影回调
|
|
64
|
+
// (缺省 no-op 确认),其余 → canonical 回调。副本契约要求 purge 幂等
|
|
65
|
+
// 可重试;门会兜住副本级失败并保持批次 purge_eligible。
|
|
66
|
+
const outcome = deps.purgeGate.executeBatch(batch.batchId, (replica, ids) => {
|
|
67
|
+
if (replica.kind === "index") {
|
|
68
|
+
if (deps.purgeIndexReplica === undefined)
|
|
69
|
+
return;
|
|
70
|
+
deps.purgeIndexReplica(ids);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
deps.purgeCanonicalReplica(ids);
|
|
74
|
+
});
|
|
75
|
+
// Journal confirmations are idempotent per (batchId, replicaId); replays
|
|
76
|
+
// from a retry never double-count.
|
|
77
|
+
for (const replica of outcome.replicas) {
|
|
78
|
+
if (outcome.confirmedReplicas?.includes(replica.replicaId)) {
|
|
79
|
+
deps.purgeJournal.confirmReplica({ batchId: batch.batchId, replicaId: replica.replicaId, at: now() });
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (outcome.state === "completed") {
|
|
83
|
+
deps.purgeJournal.complete({ batchId: batch.batchId, at: now() });
|
|
84
|
+
}
|
|
85
|
+
return Object.freeze({
|
|
86
|
+
status: outcome.state,
|
|
87
|
+
batchId: batch.batchId,
|
|
88
|
+
memoryIds: Object.freeze([...memoryIds]),
|
|
89
|
+
confirmedReplicas: Object.freeze([...(outcome.confirmedReplicas ?? [])]),
|
|
90
|
+
...(outcome.failedReplicas === undefined ? {} : { failedReplicas: outcome.failedReplicas }),
|
|
91
|
+
remainingExpired: members.length - batchRecords.length,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
// 吞错契约:清扫绝不向调用方抛错,装载绝不因清扫失败失败。
|
|
96
|
+
return Object.freeze({
|
|
97
|
+
status: "failed",
|
|
98
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
99
|
+
memoryIds: Object.freeze([...memoryIds]),
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
//# sourceMappingURL=retention-sweep.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"retention-sweep.js","sourceRoot":"","sources":["../../src/memory/retention-sweep.ts"],"names":[],"mappings":"AA+BA,OAAO,EAA4B,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAEpF;;;GAGG;AACH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,OAAO,CAAC,iBAAiB,IAAI,EAAE,CAAC,CAAC,CAAC;YACxE,GAAG,CAAC,OAAO,CAAC,cAAc,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,OAAO,CAAC,cAAc,EAAE,CAAC;YAC3F,gBAAgB,EAAE,OAAO,CAAC,MAAM,GAAG,YAAY,CAAC,MAAM;SACtD,CAAC,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,uFAA+B;QAC/B,OAAO,MAAM,CAAC,MAAM,CAAC;YACpB,MAAM,EAAE,QAAQ;YAChB,MAAM,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;YAC9D,SAAS,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC;SACxC,CAAC,CAAC;IACJ,CAAC;AAAA,CACD","sourcesContent":["/**\n * 机会式保留清扫 (retention sweep, 记忆系统设计 §3.3 的第一方落地) — the\n * automatic arm of the controlled physical purge.\n *\n * 过期 (`purgeAt <= now`) 在 store 里只是逻辑失效:recall 不可见,ledger 行、\n * 向量投影行与 store 条目全部保留。本模块在每个会话的每个域首载重放完成后被\n * capability.resolveDomain 调用一次:从 store 枚举已过期的本域原子,最旧优先\n * 取至多 {@link MEMORY_RETENTION_SWEEP_BATCH_LIMIT} 条,以 `retention-expiry`\n * 授权(purge.ts:该 mode 不需要额外引用)走既有 purge 门(authorizeBatch →\n * executeBatch → journal → barrier),副本分派与 suite-memory 的\n * executePurgeBatch 同链同语义:index 副本 → 向量投影清除回调,canonical 副本\n * → 注入回调(当前域 ledger 重写 + store 逐出)。无定时器——触发点只有首载\n * 重放完成这一条路径,写路径不挂。\n *\n * 域成员判定与 forgetDomainMemory 同判据(atom.suiteId 匹配 / legacy 为\n * undefined):canonical 副本是按域分文件的 JSONL ledger,批次只授权\"其持久\n * 行就在本次回调可重写的这份 ledger 里\"的原子——跨域原子留给各自域的装载\n * sweep,绝不产生\"store 已逐出、重启重放又复活\"的窗口。\n *\n * 失败语义:副本级失败由 purge 门兜住(批次保持 `purge_eligible`,结构化\n * failedReplicas,幂等可重试——下一轮 sweep 会把仍过期的原子重新授权清理,\n * batchId 也可直接经门重试);授权/执行链抛错被本模块吞掉并转为 `failed`\n * 摘要。本模块绝不向调用方抛错,会话/域装载绝不因清扫失败失败;调用点只把\n * 非干净摘要记一条有界 warn。\n *\n * deps 全部显式注入,无模块级可变状态。\n */\nimport type { MemoryAtomV1 } from \"./foundation.ts\";\nimport type { MemoryPurgeAuthorizationRefV1, MemoryPurgeGateV1, MemoryReplicaV1 } from \"./purge.ts\";\nimport type { MemoryPurgeJournalV1 } from \"./purge-journal.ts\";\nimport type { MemoryStoreV1 } from \"./store.ts\";\nimport { type SuiteMemoryDomainV1, suiteMemoryDomainName } from \"./suite-memory.ts\";\n\n/**\n * 单批清扫的过期原子上限(最旧优先取前 N 条;超出部分留给下一轮 sweep——\n * 批量物理清理的对标口径,与 codex PRUNE_BATCH_SIZE 同量级)。\n */\nexport const MEMORY_RETENTION_SWEEP_BATCH_LIMIT = 200;\n\nexport interface MemoryRetentionSweepDepsV1 {\n\t/** canonical store(过期判定的唯一权威,经可选 listExpired 枚举)。 */\n\treadonly store: MemoryStoreV1;\n\treadonly purgeGate: MemoryPurgeGateV1;\n\treadonly purgeJournal: MemoryPurgeJournalV1;\n\t/**\n\t * canonical 副本清除回调(capability 装配注入:当前域 ledger.rewrite 去掉\n\t * 批次原子 + store.evict)。必须幂等——purge_eligible 重试会重跑它。\n\t */\n\treadonly purgeCanonicalReplica: (memoryIds: readonly string[]) => void;\n\t/**\n\t * index 副本(向量投影)清除回调;缺省 undefined 时 index 分派为 no-op 且\n\t * 不报错——与 suite-memory 门面同语义(向量通道未装配时索引里无行可清)。\n\t */\n\treadonly purgeIndexReplica?: (memoryIds: readonly string[]) => void;\n\t/** 授权主体(authorizationRef.issuedBy 与批次 authorizedBy),capability 传入 manifest 派生串。 */\n\treadonly authorizedBy: string;\n\treadonly now?: () => number;\n}\n\nexport interface MemoryRetentionSweepResultV1 {\n\t/**\n\t * `completed` / `purge_eligible`:purge 门语义原样(barrier 全确认 / 部分\n\t * 失败待幂等重试)。`failed`:授权或执行链抛错(错误原文在 `reason`,批次\n\t * 状态未知但不阻塞调用方,可重试)。`skipped`:本域没有过期原子,或注入\n\t * store 未提供过期枚举(`reason` 说明,绝不猜写过期集)。\n\t */\n\treadonly status: \"completed\" | \"purge_eligible\" | \"failed\" | \"skipped\";\n\t/** skipped/failed 的原因;干净结果无此字段。 */\n\treadonly reason?: string;\n\treadonly batchId?: string;\n\t/** 本批授权的 memoryIds(completed = 已物理清理;purge_eligible = 待重试)。 */\n\treadonly memoryIds: readonly string[];\n\treadonly confirmedReplicas?: readonly string[];\n\treadonly failedReplicas?: readonly { readonly replicaId: string; readonly error: string }[];\n\t/** 本批之后仍过期的本域原子数(下一轮 sweep 继续);枚举未完成时缺省。 */\n\treadonly remainingExpired?: number;\n}\n\n/** 域成员判定(与 suite-memory.isDomainMember 同判据):成员资格,不是读边界。 */\nfunction isDomainMember(atom: MemoryAtomV1, domain: SuiteMemoryDomainV1): boolean {\n\tif (domain.kind === \"legacy\") return atom.suiteId === undefined;\n\treturn atom.suiteId === domain.suiteId;\n}\n\nfunction assertNonEmptyString(value: unknown, label: string): asserts value is string {\n\tif (typeof value !== \"string\" || value.trim() === \"\") throw new Error(`${label} must be a non-empty string`);\n}\n\n/**\n * Runs one retention-sweep batch over the owner's expired records in `domain`.\n * Never throws — every failure surfaces as a structured summary (see\n * {@link MemoryRetentionSweepResultV1.status}).\n */\nexport function sweepExpiredMemories(\n\tdeps: MemoryRetentionSweepDepsV1,\n\tinput: { readonly owner: string; readonly domain: SuiteMemoryDomainV1 },\n): MemoryRetentionSweepResultV1 {\n\tconst memoryIds: string[] = [];\n\ttry {\n\t\tassertNonEmptyString(input.owner, \"sweepExpiredMemories owner\");\n\t\tassertNonEmptyString(deps.authorizedBy, \"sweepExpiredMemories authorizedBy\");\n\t\tconst now = deps.now ?? (() => Date.now());\n\t\tconst expired = deps.store.listExpired?.({ owner: input.owner });\n\t\tif (expired === undefined) {\n\t\t\treturn Object.freeze({\n\t\t\t\tstatus: \"skipped\",\n\t\t\t\treason: \"store does not expose expired-record enumeration (listExpired); sweep refuses to guess\",\n\t\t\t\tmemoryIds: Object.freeze([]),\n\t\t\t});\n\t\t}\n\t\tconst members = expired\n\t\t\t.filter((record) => isDomainMember(record.atom, input.domain))\n\t\t\t.sort((left, right) => left.storeRevision - right.storeRevision);\n\t\tif (members.length === 0) {\n\t\t\treturn Object.freeze({ status: \"skipped\", memoryIds: Object.freeze([]), remainingExpired: 0 });\n\t\t}\n\t\tconst batchRecords = members.slice(0, MEMORY_RETENTION_SWEEP_BATCH_LIMIT);\n\t\tfor (const record of batchRecords) memoryIds.push(record.atom.memoryId);\n\t\tconst batch = deps.purgeGate.authorizeBatch({\n\t\t\tmemoryIds,\n\t\t\treason: `retention-sweep:${suiteMemoryDomainName(input.domain)}`,\n\t\t\tauthorizedBy: deps.authorizedBy,\n\t\t\tauthorizationRef: {\n\t\t\t\tmode: \"retention-expiry\",\n\t\t\t\tissuedAt: now(),\n\t\t\t\tissuedBy: deps.authorizedBy,\n\t\t\t} satisfies MemoryPurgeAuthorizationRefV1,\n\t\t});\n\t\tdeps.purgeJournal.authorize({\n\t\t\tbatchId: batch.batchId,\n\t\t\tmemoryIds: batch.memoryIds,\n\t\t\treplicas: batch.replicas,\n\t\t\tauthorizedBy: batch.authorizedBy,\n\t\t\treason: batch.reason,\n\t\t\tat: now(),\n\t\t});\n\t\t// 副本分派与 suite-memory.executePurgeBatch 同链:index → 向量投影回调\n\t\t// (缺省 no-op 确认),其余 → canonical 回调。副本契约要求 purge 幂等\n\t\t// 可重试;门会兜住副本级失败并保持批次 purge_eligible。\n\t\tconst outcome = deps.purgeGate.executeBatch(batch.batchId, (replica: MemoryReplicaV1, ids) => {\n\t\t\tif (replica.kind === \"index\") {\n\t\t\t\tif (deps.purgeIndexReplica === undefined) return;\n\t\t\t\tdeps.purgeIndexReplica(ids);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdeps.purgeCanonicalReplica(ids);\n\t\t});\n\t\t// Journal confirmations are idempotent per (batchId, replicaId); replays\n\t\t// from a retry never double-count.\n\t\tfor (const replica of outcome.replicas) {\n\t\t\tif (outcome.confirmedReplicas?.includes(replica.replicaId)) {\n\t\t\t\tdeps.purgeJournal.confirmReplica({ batchId: batch.batchId, replicaId: replica.replicaId, at: now() });\n\t\t\t}\n\t\t}\n\t\tif (outcome.state === \"completed\") {\n\t\t\tdeps.purgeJournal.complete({ batchId: batch.batchId, at: now() });\n\t\t}\n\t\treturn Object.freeze({\n\t\t\tstatus: outcome.state as \"completed\" | \"purge_eligible\",\n\t\t\tbatchId: batch.batchId,\n\t\t\tmemoryIds: Object.freeze([...memoryIds]),\n\t\t\tconfirmedReplicas: Object.freeze([...(outcome.confirmedReplicas ?? [])]),\n\t\t\t...(outcome.failedReplicas === undefined ? {} : { failedReplicas: outcome.failedReplicas }),\n\t\t\tremainingExpired: members.length - batchRecords.length,\n\t\t});\n\t} catch (error) {\n\t\t// 吞错契约:清扫绝不向调用方抛错,装载绝不因清扫失败失败。\n\t\treturn Object.freeze({\n\t\t\tstatus: \"failed\",\n\t\t\treason: error instanceof Error ? error.message : String(error),\n\t\t\tmemoryIds: Object.freeze([...memoryIds]),\n\t\t});\n\t}\n}\n"]}
|
package/dist/memory/store.d.ts
CHANGED
|
@@ -6,8 +6,12 @@
|
|
|
6
6
|
* long-term); retention decides how long it stays recallable. Retention mode
|
|
7
7
|
* IDs are opaque strings resolved through a versioned registry provided by the
|
|
8
8
|
* Profile — the Foundation never hardcodes business durations. Expired records
|
|
9
|
-
* lose recall eligibility but are NOT physically purged here
|
|
10
|
-
* is the controlled
|
|
9
|
+
* lose recall eligibility but are NOT physically purged here — the store never
|
|
10
|
+
* self-purges. The physical purge is the controlled gate driven by the
|
|
11
|
+
* retention sweep (src/memory/retention-sweep.ts, 记忆系统设计 §3.3), which
|
|
12
|
+
* enumerates expired records through {@link MemoryStoreV1.listExpired} and
|
|
13
|
+
* destroys the replicas via the purge gate's injected callbacks (ledger
|
|
14
|
+
* rewrite + vector row deletion + store evict).
|
|
11
15
|
*/
|
|
12
16
|
import type { JsonValue } from "@agent-forge/plugin-sdk";
|
|
13
17
|
import type { MemoryAtomV1, MemoryScopeV1, MemorySuiteFilterStatsV1 } from "./foundation.ts";
|
|
@@ -78,6 +82,17 @@ export interface MemoryStoreV1 {
|
|
|
78
82
|
get(memoryId: string, query: MemoryStoreQuery): CommittedMemoryV1 | undefined;
|
|
79
83
|
/** Lists active records owned by `query.owner`, optionally narrowed to one scope. */
|
|
80
84
|
list(query: MemoryStoreQuery, scope?: MemoryScopeV1): readonly CommittedMemoryV1[];
|
|
85
|
+
/**
|
|
86
|
+
* Lists EXPIRED records owned by `query.owner`, oldest first (store
|
|
87
|
+
* revision ascending) — the read-only enumeration the retention sweep
|
|
88
|
+
* batches from (the store's expiry predicate is the single authority; the
|
|
89
|
+
* sweep never re-derives expiry). Expiry precedes the suite read boundary
|
|
90
|
+
* (an expired record is expired in every suite); records without `purgeAt`
|
|
91
|
+
* (`permanent`) never appear. Optional: replacement stores injected
|
|
92
|
+
* through the SDK storage seam may omit it — the sweep then skips
|
|
93
|
+
* explicitly instead of guessing.
|
|
94
|
+
*/
|
|
95
|
+
listExpired?(query: MemoryStoreQuery): readonly CommittedMemoryV1[];
|
|
81
96
|
/**
|
|
82
97
|
* Suite-scoped listing with skip diagnostics: returns the records visible
|
|
83
98
|
* in `query.suiteId` plus how many legacy and foreign-suite records were
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/memory/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK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,iBAAiB,EAAE,uBAAuB,CAAC;IACpD,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CAC5B,GAAG,aAAa,CAgIhB","sourcesContent":["/**\n * Memory Foundation — three-scope store with revisions, TTL, and retention\n * inputs (1C.1b).\n *\n * Scope decides which partition a committed atom belongs to (session / cycle /\n * long-term); retention decides how long it stays recallable. Retention mode\n * IDs are opaque strings resolved through a versioned registry provided by the\n * Profile — the Foundation never hardcodes business durations. Expired records\n * lose recall eligibility but are NOT physically purged here (physical purge\n * is the controlled 1C.6d gate).\n */\n\nimport type { JsonValue } from \"@agent-forge/plugin-sdk\";\nimport type { MemoryAtomV1, MemoryScopeV1, MemorySuiteFilterStatsV1 } from \"./foundation.ts\";\nimport { memorySuiteVisibility, validateMemoryAtomV1 } from \"./foundation.ts\";\n\n/** One retention mode published by a Profile's retention-mode registry. */\nexport interface RetentionModeDefinitionV1 {\n\treadonly id: string;\n\t/** Recall duration in ms. Absent = no expiry (e.g. `permanent`). */\n\treadonly durationMs?: number;\n\treadonly autoPurge: boolean;\n}\n\n/** Versioned retention-mode registry snapshot. */\nexport interface RetentionModeRegistryV1 {\n\treadonly policyVersion: string;\n\treadonly modes: readonly RetentionModeDefinitionV1[];\n\tget(id: string): RetentionModeDefinitionV1 | undefined;\n}\n\n/** Validates a retention-mode registry: parseable, finite, non-negative, unique, traceable. */\nexport function validateRetentionModeRegistry(value: unknown): RetentionModeRegistryV1 {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n\t\tthrow new Error(\"Retention mode registry must be a plain object\");\n\t}\n\tconst record = value as Record<string, unknown>;\n\tassertNonEmptyString(record.policyVersion, \"Retention mode registry.policyVersion\");\n\tif (!Array.isArray(record.modes) || record.modes.length === 0) {\n\t\tthrow new Error(\"Retention mode registry.modes must be a non-empty array\");\n\t}\n\tconst seen = new Set<string>();\n\tconst modes: RetentionModeDefinitionV1[] = record.modes.map((item, index) => {\n\t\tconst label = `Retention mode[${index}]`;\n\t\tif (item === null || typeof item !== \"object\" || Array.isArray(item)) {\n\t\t\tthrow new Error(`${label} must be a plain object`);\n\t\t}\n\t\tconst entry = item as Record<string, unknown>;\n\t\tassertNonEmptyString(entry.id, `${label}.id`);\n\t\tif (seen.has(entry.id)) throw new Error(`${label} duplicates id: ${entry.id}`);\n\t\tseen.add(entry.id);\n\t\tif (typeof entry.autoPurge !== \"boolean\") throw new Error(`${label}.autoPurge must be boolean`);\n\t\tif (entry.durationMs !== undefined) {\n\t\t\tif (typeof entry.durationMs !== \"number\" || !Number.isSafeInteger(entry.durationMs) || entry.durationMs <= 0) {\n\t\t\t\tthrow new Error(`${label}.durationMs must be a positive safe integer`);\n\t\t\t}\n\t\t}\n\t\treturn Object.freeze({\n\t\t\tid: entry.id,\n\t\t\t...(entry.durationMs === undefined ? {} : { durationMs: entry.durationMs }),\n\t\t\tautoPurge: entry.autoPurge,\n\t\t});\n\t});\n\treturn Object.freeze({\n\t\tpolicyVersion: record.policyVersion,\n\t\tmodes: Object.freeze(modes),\n\t\tget(id: string) {\n\t\t\treturn modes.find((mode) => mode.id === id);\n\t\t},\n\t});\n}\n\nfunction assertNonEmptyString(value: unknown, label: string): asserts value is string {\n\tif (typeof value !== \"string\" || value.trim().length === 0) throw new Error(`${label} must be a non-empty string`);\n}\n\n/** First-party default registry (short/standard/long/permanent). Durations live here, not in Foundation logic. */\nexport function createFirstPartyRetentionRegistry(): RetentionModeRegistryV1 {\n\tconst DAY = 24 * 60 * 60 * 1000;\n\treturn validateRetentionModeRegistry({\n\t\tpolicyVersion: \"retention@1\",\n\t\tmodes: [\n\t\t\t{ id: \"short\", durationMs: 7 * DAY, autoPurge: true },\n\t\t\t{ id: \"standard\", durationMs: 30 * DAY, autoPurge: true },\n\t\t\t{ id: \"long\", durationMs: 365 * DAY, autoPurge: true },\n\t\t\t{ id: \"permanent\", autoPurge: false },\n\t\t],\n\t});\n}\n\nexport interface MemoryStoreCommitOptions {\n\t/** Overrides the atom's retentionMode id at commit time (policy-selected). */\n\treadonly retentionModeId?: string;\n}\n\n/** A committed atom plus the store-assigned bookkeeping facts. */\nexport interface CommittedMemoryV1<TPayload extends JsonValue = JsonValue> {\n\treadonly atom: MemoryAtomV1<TPayload>;\n\t/** Monotonic across the whole store. */\n\treadonly storeRevision: number;\n\t/** Monotonic within the atom's scope partition. */\n\treadonly scopeRevision: number;\n\treadonly committedAt: number;\n\t/** Recall deadline computed from the retention registry. Absent = no expiry. */\n\treadonly purgeAt?: number;\n\treadonly retentionModeId: string;\n}\n\nexport interface MemoryStoreQuery {\n\treadonly owner: string;\n\t/**\n\t * Suite-scoped read boundary (方案系统设计 §6.1/§11). When set, only atoms\n\t * whose suiteId equals this value — plus explicitly promoted user-default\n\t * preferences — are visible; legacy (suiteId-less) atoms are skipped\n\t * fail-safe. When absent, no suite filtering happens (suite-unscoped read).\n\t */\n\treadonly suiteId?: string;\n}\n\nexport interface MemoryStoreStats {\n\treadonly active: number;\n\treadonly expired: number;\n\treadonly byScope: Readonly<Record<MemoryScopeV1, { active: number; expired: number }>>;\n}\n\n/** Result of {@link MemoryStoreV1.listForSuite}: visible records plus skip counters. */\nexport interface MemoryStoreSuitePageV1 {\n\treadonly records: readonly CommittedMemoryV1[];\n\t/** Excluded-record counters for the suite read boundary (设计 §11). */\n\treadonly filter: MemorySuiteFilterStatsV1;\n}\n\nexport interface MemoryStoreV1 {\n\tcommit(atom: MemoryAtomV1, options?: MemoryStoreCommitOptions): CommittedMemoryV1;\n\t/**\n\t * Returns the record only when unexpired, owned by `query.owner`, and —\n\t * when `query.suiteId` is set — visible in that suite (legacy atoms are\n\t * invisible to every suite).\n\t */\n\tget(memoryId: string, query: MemoryStoreQuery): CommittedMemoryV1 | undefined;\n\t/** Lists active records owned by `query.owner`, optionally narrowed to one scope. */\n\tlist(query: MemoryStoreQuery, scope?: MemoryScopeV1): readonly CommittedMemoryV1[];\n\t/**\n\t * Suite-scoped listing with skip diagnostics: returns the records visible\n\t * in `query.suiteId` plus how many legacy and foreign-suite records were\n\t * excluded (expired records are excluded before the suite filter and are\n\t * not counted here).\n\t */\n\tlistForSuite(query: MemoryStoreQuery & { readonly suiteId: string }, scope?: MemoryScopeV1): MemoryStoreSuitePageV1;\n\tstats(): MemoryStoreStats;\n\t/**\n\t * Physically removes one record from the canonical in-memory ledger — the\n\t * store-side arm of the controlled purge gate (设计 §3.3: only the purge\n\t * flow may destroy committed atoms). Call it exclusively from the purge\n\t * path (suite memory facade / scheduler purge); ordinary business code\n\t * never evicts. Returns true when the record existed. Expired-then-evicted\n\t * and unexpired records are removed alike; a restart replay cannot\n\t * resurrect an evicted atom once the durable replica is rewritten.\n\t */\n\tevict(memoryId: string): boolean;\n}\n\n/** Creates a deterministic three-scope Foundation store. Expired records lose recall but stay ledgered. */\nexport function createMemoryStore(options: {\n\treadonly retentionRegistry: RetentionModeRegistryV1;\n\treadonly now?: () => number;\n}): MemoryStoreV1 {\n\tconst registry = options.retentionRegistry;\n\tconst now = options.now ?? (() => Date.now());\n\tconst records = new Map<string, CommittedMemoryV1>();\n\tlet storeRevision = 0;\n\tconst scopeRevisions = new Map<MemoryScopeV1, number>();\n\n\tconst isExpired = (record: CommittedMemoryV1): boolean => record.purgeAt !== undefined && record.purgeAt <= now();\n\n\tconst requireOwner = (query: MemoryStoreQuery): string => {\n\t\tif (query === null || typeof query !== \"object\" || typeof query.owner !== \"string\" || query.owner.trim() === \"\") {\n\t\t\tthrow new Error(\"Memory store query requires an owner\");\n\t\t}\n\t\tif (query.suiteId !== undefined && (typeof query.suiteId !== \"string\" || query.suiteId.trim() === \"\")) {\n\t\t\tthrow new Error(\"Memory store query requires a non-empty suiteId when filtering by suite\");\n\t\t}\n\t\treturn query.owner;\n\t};\n\n\t/** Suite read boundary: `undefined` query.suiteId means no suite filtering. */\n\tconst isVisibleInSuite = (atom: MemoryAtomV1, suiteId: string | undefined): boolean =>\n\t\tsuiteId === undefined || memorySuiteVisibility(atom, suiteId) === \"visible\";\n\n\treturn {\n\t\tcommit(atom, commitOptions) {\n\t\t\tconst validated = validateMemoryAtomV1(atom);\n\t\t\t// Canonical atoms are immutable once committed (设计 §4): a second\n\t\t\t// commit with the same memoryId is a caller bug and must fail\n\t\t\t// explicitly instead of silently overwriting verified facts.\n\t\t\tif (records.has(validated.memoryId)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Memory already committed: ${validated.memoryId} (canonical atoms are immutable; use the candidate machine for dedupe)`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst modeId = commitOptions?.retentionModeId ?? validated.retentionMode;\n\t\t\tconst mode = registry.get(modeId);\n\t\t\tif (!mode) throw new Error(`Retention mode is not registered: ${modeId}`);\n\t\t\tstoreRevision += 1;\n\t\t\tconst scopeRevision = (scopeRevisions.get(validated.scope) ?? 0) + 1;\n\t\t\tscopeRevisions.set(validated.scope, scopeRevision);\n\t\t\tconst committedAt = now();\n\t\t\tconst committed: CommittedMemoryV1 = Object.freeze({\n\t\t\t\tatom: validated,\n\t\t\t\tstoreRevision,\n\t\t\t\tscopeRevision,\n\t\t\t\tcommittedAt,\n\t\t\t\t...(mode.durationMs === undefined ? {} : { purgeAt: committedAt + mode.durationMs }),\n\t\t\t\tretentionModeId: mode.id,\n\t\t\t});\n\t\t\trecords.set(validated.memoryId, committed);\n\t\t\treturn committed;\n\t\t},\n\t\tget(memoryId, query) {\n\t\t\tconst owner = requireOwner(query);\n\t\t\tconst record = records.get(memoryId);\n\t\t\tif (!record) return undefined;\n\t\t\tif (record.atom.owner !== owner) return undefined;\n\t\t\tif (!isVisibleInSuite(record.atom, query.suiteId)) return undefined;\n\t\t\tif (isExpired(record)) return undefined;\n\t\t\treturn record;\n\t\t},\n\t\tlist(query, scope) {\n\t\t\tconst owner = requireOwner(query);\n\t\t\tconst results: CommittedMemoryV1[] = [];\n\t\t\tfor (const record of records.values()) {\n\t\t\t\tif (record.atom.owner !== owner) continue;\n\t\t\t\tif (scope !== undefined && record.atom.scope !== scope) continue;\n\t\t\t\tif (!isVisibleInSuite(record.atom, query.suiteId)) continue;\n\t\t\t\tif (isExpired(record)) continue;\n\t\t\t\tresults.push(record);\n\t\t\t}\n\t\t\treturn Object.freeze(results.sort((left, right) => left.storeRevision - right.storeRevision));\n\t\t},\n\t\tlistForSuite(query, scope) {\n\t\t\trequireOwner(query);\n\t\t\tconst suiteId = query.suiteId;\n\t\t\tconst results: CommittedMemoryV1[] = [];\n\t\t\tlet legacySkipped = 0;\n\t\t\tlet foreignSuiteSkipped = 0;\n\t\t\tfor (const record of records.values()) {\n\t\t\t\tif (record.atom.owner !== query.owner) continue;\n\t\t\t\tif (scope !== undefined && record.atom.scope !== scope) continue;\n\t\t\t\tif (isExpired(record)) continue;\n\t\t\t\tconst visibility = memorySuiteVisibility(record.atom, suiteId);\n\t\t\t\tif (visibility === \"legacy\") {\n\t\t\t\t\tlegacySkipped += 1;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (visibility === \"foreign-suite\") {\n\t\t\t\t\tforeignSuiteSkipped += 1;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tresults.push(record);\n\t\t\t}\n\t\t\tresults.sort((left, right) => left.storeRevision - right.storeRevision);\n\t\t\treturn Object.freeze({\n\t\t\t\trecords: Object.freeze(results),\n\t\t\t\tfilter: Object.freeze({ legacySkipped, foreignSuiteSkipped }),\n\t\t\t});\n\t\t},\n\t\tstats() {\n\t\t\tconst bucket = () => ({ active: 0, expired: 0 });\n\t\t\tconst byScope: Record<MemoryScopeV1, { active: number; expired: number }> = {\n\t\t\t\tsession: bucket(),\n\t\t\t\tcycle: bucket(),\n\t\t\t\t\"long-term\": bucket(),\n\t\t\t};\n\t\t\tlet active = 0;\n\t\t\tlet expired = 0;\n\t\t\tfor (const record of records.values()) {\n\t\t\t\tconst target = byScope[record.atom.scope];\n\t\t\t\tif (isExpired(record)) {\n\t\t\t\t\texpired += 1;\n\t\t\t\t\ttarget.expired += 1;\n\t\t\t\t} else {\n\t\t\t\t\tactive += 1;\n\t\t\t\t\ttarget.active += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { active, expired, byScope: Object.freeze(byScope) };\n\t\t},\n\t\tevict(memoryId) {\n\t\t\tif (typeof memoryId !== \"string\" || memoryId.trim() === \"\") {\n\t\t\t\tthrow new Error(\"Memory store evict requires a memoryId\");\n\t\t\t}\n\t\t\treturn records.delete(memoryId);\n\t\t},\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/memory/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AACzD,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAG7F,2EAA2E;AAC3E,MAAM,WAAW,yBAAyB;IACzC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,oEAAoE;IACpE,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;CAC5B;AAED,kDAAkD;AAClD,MAAM,WAAW,uBAAuB;IACvC,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,KAAK,EAAE,SAAS,yBAAyB,EAAE,CAAC;IACrD,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,yBAAyB,GAAG,SAAS,CAAC;CACvD;AAED,+FAA+F;AAC/F,wBAAgB,6BAA6B,CAAC,KAAK,EAAE,OAAO,GAAG,uBAAuB,CAsCrF;AAMD,kHAAkH;AAClH,wBAAgB,iCAAiC,IAAI,uBAAuB,CAW3E;AAED,MAAM,WAAW,wBAAwB;IACxC,8EAA8E;IAC9E,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;CAClC;AAED,kEAAkE;AAClE,MAAM,WAAW,iBAAiB,CAAC,QAAQ,SAAS,SA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E,aAAa,GAAG,SAAS,iBAAiB,EAAE,CAAC;IACnF;;;;;;;;;OASG;IACH,WAAW,CAAC,CAAC,KAAK,EAAE,gBAAgB,GAAG,SAAS,iBAAiB,EAAE,CAAC;IACpE;;;;;OAKG;IACH,YAAY,CAAC,KAAK,EAAE,gBAAgB,GAAG;QAAE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;KAAE,EAAE,KAAK,CAAC,EAAE,aAAa,GAAG,sBAAsB,CAAC;IACpH,KAAK,IAAI,gBAAgB,CAAC;IAC1B;;;;;;;;OAQG;IACH,KAAK,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC;CACjC;AAED,2GAA2G;AAC3G,wBAAgB,iBAAiB,CAAC,OAAO,EAAE;IAC1C,QAAQ,CAAC,iBAAiB,EAAE,uBAAuB,CAAC;IACpD,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CAC5B,GAAG,aAAa,CA0IhB","sourcesContent":["/**\n * Memory Foundation — three-scope store with revisions, TTL, and retention\n * inputs (1C.1b).\n *\n * Scope decides which partition a committed atom belongs to (session / cycle /\n * long-term); retention decides how long it stays recallable. Retention mode\n * IDs are opaque strings resolved through a versioned registry provided by the\n * Profile — the Foundation never hardcodes business durations. Expired records\n * lose recall eligibility but are NOT physically purged here — the store never\n * self-purges. The physical purge is the controlled gate driven by the\n * retention sweep (src/memory/retention-sweep.ts, 记忆系统设计 §3.3), which\n * enumerates expired records through {@link MemoryStoreV1.listExpired} and\n * destroys the replicas via the purge gate's injected callbacks (ledger\n * rewrite + vector row deletion + store evict).\n */\n\nimport type { JsonValue } from \"@agent-forge/plugin-sdk\";\nimport type { MemoryAtomV1, MemoryScopeV1, MemorySuiteFilterStatsV1 } from \"./foundation.ts\";\nimport { memorySuiteVisibility, validateMemoryAtomV1 } from \"./foundation.ts\";\n\n/** One retention mode published by a Profile's retention-mode registry. */\nexport interface RetentionModeDefinitionV1 {\n\treadonly id: string;\n\t/** Recall duration in ms. Absent = no expiry (e.g. `permanent`). */\n\treadonly durationMs?: number;\n\treadonly autoPurge: boolean;\n}\n\n/** Versioned retention-mode registry snapshot. */\nexport interface RetentionModeRegistryV1 {\n\treadonly policyVersion: string;\n\treadonly modes: readonly RetentionModeDefinitionV1[];\n\tget(id: string): RetentionModeDefinitionV1 | undefined;\n}\n\n/** Validates a retention-mode registry: parseable, finite, non-negative, unique, traceable. */\nexport function validateRetentionModeRegistry(value: unknown): RetentionModeRegistryV1 {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n\t\tthrow new Error(\"Retention mode registry must be a plain object\");\n\t}\n\tconst record = value as Record<string, unknown>;\n\tassertNonEmptyString(record.policyVersion, \"Retention mode registry.policyVersion\");\n\tif (!Array.isArray(record.modes) || record.modes.length === 0) {\n\t\tthrow new Error(\"Retention mode registry.modes must be a non-empty array\");\n\t}\n\tconst seen = new Set<string>();\n\tconst modes: RetentionModeDefinitionV1[] = record.modes.map((item, index) => {\n\t\tconst label = `Retention mode[${index}]`;\n\t\tif (item === null || typeof item !== \"object\" || Array.isArray(item)) {\n\t\t\tthrow new Error(`${label} must be a plain object`);\n\t\t}\n\t\tconst entry = item as Record<string, unknown>;\n\t\tassertNonEmptyString(entry.id, `${label}.id`);\n\t\tif (seen.has(entry.id)) throw new Error(`${label} duplicates id: ${entry.id}`);\n\t\tseen.add(entry.id);\n\t\tif (typeof entry.autoPurge !== \"boolean\") throw new Error(`${label}.autoPurge must be boolean`);\n\t\tif (entry.durationMs !== undefined) {\n\t\t\tif (typeof entry.durationMs !== \"number\" || !Number.isSafeInteger(entry.durationMs) || entry.durationMs <= 0) {\n\t\t\t\tthrow new Error(`${label}.durationMs must be a positive safe integer`);\n\t\t\t}\n\t\t}\n\t\treturn Object.freeze({\n\t\t\tid: entry.id,\n\t\t\t...(entry.durationMs === undefined ? {} : { durationMs: entry.durationMs }),\n\t\t\tautoPurge: entry.autoPurge,\n\t\t});\n\t});\n\treturn Object.freeze({\n\t\tpolicyVersion: record.policyVersion,\n\t\tmodes: Object.freeze(modes),\n\t\tget(id: string) {\n\t\t\treturn modes.find((mode) => mode.id === id);\n\t\t},\n\t});\n}\n\nfunction assertNonEmptyString(value: unknown, label: string): asserts value is string {\n\tif (typeof value !== \"string\" || value.trim().length === 0) throw new Error(`${label} must be a non-empty string`);\n}\n\n/** First-party default registry (short/standard/long/permanent). Durations live here, not in Foundation logic. */\nexport function createFirstPartyRetentionRegistry(): RetentionModeRegistryV1 {\n\tconst DAY = 24 * 60 * 60 * 1000;\n\treturn validateRetentionModeRegistry({\n\t\tpolicyVersion: \"retention@1\",\n\t\tmodes: [\n\t\t\t{ id: \"short\", durationMs: 7 * DAY, autoPurge: true },\n\t\t\t{ id: \"standard\", durationMs: 30 * DAY, autoPurge: true },\n\t\t\t{ id: \"long\", durationMs: 365 * DAY, autoPurge: true },\n\t\t\t{ id: \"permanent\", autoPurge: false },\n\t\t],\n\t});\n}\n\nexport interface MemoryStoreCommitOptions {\n\t/** Overrides the atom's retentionMode id at commit time (policy-selected). */\n\treadonly retentionModeId?: string;\n}\n\n/** A committed atom plus the store-assigned bookkeeping facts. */\nexport interface CommittedMemoryV1<TPayload extends JsonValue = JsonValue> {\n\treadonly atom: MemoryAtomV1<TPayload>;\n\t/** Monotonic across the whole store. */\n\treadonly storeRevision: number;\n\t/** Monotonic within the atom's scope partition. */\n\treadonly scopeRevision: number;\n\treadonly committedAt: number;\n\t/** Recall deadline computed from the retention registry. Absent = no expiry. */\n\treadonly purgeAt?: number;\n\treadonly retentionModeId: string;\n}\n\nexport interface MemoryStoreQuery {\n\treadonly owner: string;\n\t/**\n\t * Suite-scoped read boundary (方案系统设计 §6.1/§11). When set, only atoms\n\t * whose suiteId equals this value — plus explicitly promoted user-default\n\t * preferences — are visible; legacy (suiteId-less) atoms are skipped\n\t * fail-safe. When absent, no suite filtering happens (suite-unscoped read).\n\t */\n\treadonly suiteId?: string;\n}\n\nexport interface MemoryStoreStats {\n\treadonly active: number;\n\treadonly expired: number;\n\treadonly byScope: Readonly<Record<MemoryScopeV1, { active: number; expired: number }>>;\n}\n\n/** Result of {@link MemoryStoreV1.listForSuite}: visible records plus skip counters. */\nexport interface MemoryStoreSuitePageV1 {\n\treadonly records: readonly CommittedMemoryV1[];\n\t/** Excluded-record counters for the suite read boundary (设计 §11). */\n\treadonly filter: MemorySuiteFilterStatsV1;\n}\n\nexport interface MemoryStoreV1 {\n\tcommit(atom: MemoryAtomV1, options?: MemoryStoreCommitOptions): CommittedMemoryV1;\n\t/**\n\t * Returns the record only when unexpired, owned by `query.owner`, and —\n\t * when `query.suiteId` is set — visible in that suite (legacy atoms are\n\t * invisible to every suite).\n\t */\n\tget(memoryId: string, query: MemoryStoreQuery): CommittedMemoryV1 | undefined;\n\t/** Lists active records owned by `query.owner`, optionally narrowed to one scope. */\n\tlist(query: MemoryStoreQuery, scope?: MemoryScopeV1): readonly CommittedMemoryV1[];\n\t/**\n\t * Lists EXPIRED records owned by `query.owner`, oldest first (store\n\t * revision ascending) — the read-only enumeration the retention sweep\n\t * batches from (the store's expiry predicate is the single authority; the\n\t * sweep never re-derives expiry). Expiry precedes the suite read boundary\n\t * (an expired record is expired in every suite); records without `purgeAt`\n\t * (`permanent`) never appear. Optional: replacement stores injected\n\t * through the SDK storage seam may omit it — the sweep then skips\n\t * explicitly instead of guessing.\n\t */\n\tlistExpired?(query: MemoryStoreQuery): readonly CommittedMemoryV1[];\n\t/**\n\t * Suite-scoped listing with skip diagnostics: returns the records visible\n\t * in `query.suiteId` plus how many legacy and foreign-suite records were\n\t * excluded (expired records are excluded before the suite filter and are\n\t * not counted here).\n\t */\n\tlistForSuite(query: MemoryStoreQuery & { readonly suiteId: string }, scope?: MemoryScopeV1): MemoryStoreSuitePageV1;\n\tstats(): MemoryStoreStats;\n\t/**\n\t * Physically removes one record from the canonical in-memory ledger — the\n\t * store-side arm of the controlled purge gate (设计 §3.3: only the purge\n\t * flow may destroy committed atoms). Call it exclusively from the purge\n\t * path (suite memory facade / scheduler purge); ordinary business code\n\t * never evicts. Returns true when the record existed. Expired-then-evicted\n\t * and unexpired records are removed alike; a restart replay cannot\n\t * resurrect an evicted atom once the durable replica is rewritten.\n\t */\n\tevict(memoryId: string): boolean;\n}\n\n/** Creates a deterministic three-scope Foundation store. Expired records lose recall but stay ledgered. */\nexport function createMemoryStore(options: {\n\treadonly retentionRegistry: RetentionModeRegistryV1;\n\treadonly now?: () => number;\n}): MemoryStoreV1 {\n\tconst registry = options.retentionRegistry;\n\tconst now = options.now ?? (() => Date.now());\n\tconst records = new Map<string, CommittedMemoryV1>();\n\tlet storeRevision = 0;\n\tconst scopeRevisions = new Map<MemoryScopeV1, number>();\n\n\tconst isExpired = (record: CommittedMemoryV1): boolean => record.purgeAt !== undefined && record.purgeAt <= now();\n\n\tconst requireOwner = (query: MemoryStoreQuery): string => {\n\t\tif (query === null || typeof query !== \"object\" || typeof query.owner !== \"string\" || query.owner.trim() === \"\") {\n\t\t\tthrow new Error(\"Memory store query requires an owner\");\n\t\t}\n\t\tif (query.suiteId !== undefined && (typeof query.suiteId !== \"string\" || query.suiteId.trim() === \"\")) {\n\t\t\tthrow new Error(\"Memory store query requires a non-empty suiteId when filtering by suite\");\n\t\t}\n\t\treturn query.owner;\n\t};\n\n\t/** Suite read boundary: `undefined` query.suiteId means no suite filtering. */\n\tconst isVisibleInSuite = (atom: MemoryAtomV1, suiteId: string | undefined): boolean =>\n\t\tsuiteId === undefined || memorySuiteVisibility(atom, suiteId) === \"visible\";\n\n\treturn {\n\t\tcommit(atom, commitOptions) {\n\t\t\tconst validated = validateMemoryAtomV1(atom);\n\t\t\t// Canonical atoms are immutable once committed (设计 §4): a second\n\t\t\t// commit with the same memoryId is a caller bug and must fail\n\t\t\t// explicitly instead of silently overwriting verified facts.\n\t\t\tif (records.has(validated.memoryId)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Memory already committed: ${validated.memoryId} (canonical atoms are immutable; use the candidate machine for dedupe)`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst modeId = commitOptions?.retentionModeId ?? validated.retentionMode;\n\t\t\tconst mode = registry.get(modeId);\n\t\t\tif (!mode) throw new Error(`Retention mode is not registered: ${modeId}`);\n\t\t\tstoreRevision += 1;\n\t\t\tconst scopeRevision = (scopeRevisions.get(validated.scope) ?? 0) + 1;\n\t\t\tscopeRevisions.set(validated.scope, scopeRevision);\n\t\t\tconst committedAt = now();\n\t\t\tconst committed: CommittedMemoryV1 = Object.freeze({\n\t\t\t\tatom: validated,\n\t\t\t\tstoreRevision,\n\t\t\t\tscopeRevision,\n\t\t\t\tcommittedAt,\n\t\t\t\t...(mode.durationMs === undefined ? {} : { purgeAt: committedAt + mode.durationMs }),\n\t\t\t\tretentionModeId: mode.id,\n\t\t\t});\n\t\t\trecords.set(validated.memoryId, committed);\n\t\t\treturn committed;\n\t\t},\n\t\tget(memoryId, query) {\n\t\t\tconst owner = requireOwner(query);\n\t\t\tconst record = records.get(memoryId);\n\t\t\tif (!record) return undefined;\n\t\t\tif (record.atom.owner !== owner) return undefined;\n\t\t\tif (!isVisibleInSuite(record.atom, query.suiteId)) return undefined;\n\t\t\tif (isExpired(record)) return undefined;\n\t\t\treturn record;\n\t\t},\n\t\tlist(query, scope) {\n\t\t\tconst owner = requireOwner(query);\n\t\t\tconst results: CommittedMemoryV1[] = [];\n\t\t\tfor (const record of records.values()) {\n\t\t\t\tif (record.atom.owner !== owner) continue;\n\t\t\t\tif (scope !== undefined && record.atom.scope !== scope) continue;\n\t\t\t\tif (!isVisibleInSuite(record.atom, query.suiteId)) continue;\n\t\t\t\tif (isExpired(record)) continue;\n\t\t\t\tresults.push(record);\n\t\t\t}\n\t\t\treturn Object.freeze(results.sort((left, right) => left.storeRevision - right.storeRevision));\n\t\t},\n\t\tlistExpired(query) {\n\t\t\tconst owner = requireOwner(query);\n\t\t\tconst results: CommittedMemoryV1[] = [];\n\t\t\tfor (const record of records.values()) {\n\t\t\t\tif (record.atom.owner !== owner) continue;\n\t\t\t\tif (!isExpired(record)) continue;\n\t\t\t\tresults.push(record);\n\t\t\t}\n\t\t\treturn Object.freeze(results.sort((left, right) => left.storeRevision - right.storeRevision));\n\t\t},\n\t\tlistForSuite(query, scope) {\n\t\t\trequireOwner(query);\n\t\t\tconst suiteId = query.suiteId;\n\t\t\tconst results: CommittedMemoryV1[] = [];\n\t\t\tlet legacySkipped = 0;\n\t\t\tlet foreignSuiteSkipped = 0;\n\t\t\tfor (const record of records.values()) {\n\t\t\t\tif (record.atom.owner !== query.owner) continue;\n\t\t\t\tif (scope !== undefined && record.atom.scope !== scope) continue;\n\t\t\t\tif (isExpired(record)) continue;\n\t\t\t\tconst visibility = memorySuiteVisibility(record.atom, suiteId);\n\t\t\t\tif (visibility === \"legacy\") {\n\t\t\t\t\tlegacySkipped += 1;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (visibility === \"foreign-suite\") {\n\t\t\t\t\tforeignSuiteSkipped += 1;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tresults.push(record);\n\t\t\t}\n\t\t\tresults.sort((left, right) => left.storeRevision - right.storeRevision);\n\t\t\treturn Object.freeze({\n\t\t\t\trecords: Object.freeze(results),\n\t\t\t\tfilter: Object.freeze({ legacySkipped, foreignSuiteSkipped }),\n\t\t\t});\n\t\t},\n\t\tstats() {\n\t\t\tconst bucket = () => ({ active: 0, expired: 0 });\n\t\t\tconst byScope: Record<MemoryScopeV1, { active: number; expired: number }> = {\n\t\t\t\tsession: bucket(),\n\t\t\t\tcycle: bucket(),\n\t\t\t\t\"long-term\": bucket(),\n\t\t\t};\n\t\t\tlet active = 0;\n\t\t\tlet expired = 0;\n\t\t\tfor (const record of records.values()) {\n\t\t\t\tconst target = byScope[record.atom.scope];\n\t\t\t\tif (isExpired(record)) {\n\t\t\t\t\texpired += 1;\n\t\t\t\t\ttarget.expired += 1;\n\t\t\t\t} else {\n\t\t\t\t\tactive += 1;\n\t\t\t\t\ttarget.active += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { active, expired, byScope: Object.freeze(byScope) };\n\t\t},\n\t\tevict(memoryId) {\n\t\t\tif (typeof memoryId !== \"string\" || memoryId.trim() === \"\") {\n\t\t\t\tthrow new Error(\"Memory store evict requires a memoryId\");\n\t\t\t}\n\t\t\treturn records.delete(memoryId);\n\t\t},\n\t};\n}\n"]}
|
package/dist/memory/store.js
CHANGED
|
@@ -6,8 +6,12 @@
|
|
|
6
6
|
* long-term); retention decides how long it stays recallable. Retention mode
|
|
7
7
|
* IDs are opaque strings resolved through a versioned registry provided by the
|
|
8
8
|
* Profile — the Foundation never hardcodes business durations. Expired records
|
|
9
|
-
* lose recall eligibility but are NOT physically purged here
|
|
10
|
-
* is the controlled
|
|
9
|
+
* lose recall eligibility but are NOT physically purged here — the store never
|
|
10
|
+
* self-purges. The physical purge is the controlled gate driven by the
|
|
11
|
+
* retention sweep (src/memory/retention-sweep.ts, 记忆系统设计 §3.3), which
|
|
12
|
+
* enumerates expired records through {@link MemoryStoreV1.listExpired} and
|
|
13
|
+
* destroys the replicas via the purge gate's injected callbacks (ledger
|
|
14
|
+
* rewrite + vector row deletion + store evict).
|
|
11
15
|
*/
|
|
12
16
|
import { memorySuiteVisibility, validateMemoryAtomV1 } from "./foundation.js";
|
|
13
17
|
/** Validates a retention-mode registry: parseable, finite, non-negative, unique, traceable. */
|
|
@@ -145,6 +149,18 @@ export function createMemoryStore(options) {
|
|
|
145
149
|
}
|
|
146
150
|
return Object.freeze(results.sort((left, right) => left.storeRevision - right.storeRevision));
|
|
147
151
|
},
|
|
152
|
+
listExpired(query) {
|
|
153
|
+
const owner = requireOwner(query);
|
|
154
|
+
const results = [];
|
|
155
|
+
for (const record of records.values()) {
|
|
156
|
+
if (record.atom.owner !== owner)
|
|
157
|
+
continue;
|
|
158
|
+
if (!isExpired(record))
|
|
159
|
+
continue;
|
|
160
|
+
results.push(record);
|
|
161
|
+
}
|
|
162
|
+
return Object.freeze(results.sort((left, right) => left.storeRevision - right.storeRevision));
|
|
163
|
+
},
|
|
148
164
|
listForSuite(query, scope) {
|
|
149
165
|
requireOwner(query);
|
|
150
166
|
const suiteId = query.suiteId;
|