@ai-agent-forge/plugin-memory 0.88.18 → 0.88.19

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.
@@ -1 +1 @@
1
- {"version":3,"file":"capability.js","sourceRoot":"","sources":["../src/capability.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoFG;AACH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAQjC,OAAO,EAGN,+BAA+B,GAC/B,MAAM,yBAAyB,CAAC;AAEjC,2GAA2D;AAC3D,sFAAwC;AACxC,OAAO,EACN,uBAAuB,GAMvB,MAAM,yBAAyB,CAAC;AACjC,kGAAoD;AACpD,wFAA4D;AAC5D,+EAAmE;AACnE,kFAA0D;AAC1D,OAAO,EACN,qCAAqC,EACrC,6BAA6B,EAC7B,0BAA0B,EAC1B,uBAAuB,GACvB,MAAM,sBAAsB,CAAC;AAC9B,2FAAuD;AACvD,0FAAoE;AACpE,4FAAkE;AAClE,sFAAqC;AACrC,OAAO,EACN,8BAA8B,EAC9B,6BAA6B,EAC7B,yBAAyB,GACzB,MAAM,mBAAmB,CAAC;AAC3B,yFAAiE;AACjE,6FAAyD;AACzD,iFAAmE;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAIN,iBAAiB,EACjB,0BAA0B,EAC1B,wBAAwB,GACxB,MAAM,4BAA4B,CAAC;AACpC,gGAA0D;AAC1D,6CAA2B;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,wBAAwB,CAAC;AAE7E,OAAO,EAAE,4BAA4B,EAAE,MAAM,wBAAwB,CAAC;AACtE,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAA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CAAC,cAAc,IAAI,GAAG,CAAC,IAAI,EAAE,cAAc;KAClE,CAAC,CAAC;IAEH,MAAM,aAAa,GAAG;QACrB,gGAA8C;QAC9C,4FAAkC;QAClC,iEAA6D;QAC7D;YACC,EAAE,EAAE,4BAA4B;YAChC,IAAI,EAAE,qBAAqB;YAC3B,OAAO,EAAE,GAAG,EAAE,CAAC,gBAAgB,CAAC,OAAO,EAAE;SACzC;QACD,SAAS,CAAC,SAAS;QACnB,cAAc,CAAC,UAAU;QACzB,WAAW,CAAC,QAAQ;QACpB,WAAW,CAAC,UAAU;QACtB,WAAW,CAAC,UAAU;QACtB,WAAW,CAAC,aAAa;QACzB,WAAW,CAAC,cAAc;QAC1B,WAAW,CAAC,mBAAmB;QAC/B,KAAK,CAAC,cAAc;QACpB,KAAK,CAAC,kBAAkB;QACxB,GAAG,OAAO,CAAC,aAAa;KACxB,CAAC;IACF,OAAO;QACN,aAAa;QACb,gBAAgB,EAAE,KAAK,IAAI,EAAE,CAAC;YAC7B,MAAM,gBAAgB,CAAC,MAAM,EAAE,CAAC;QAAA,CAChC;QACD,WAAW,EAAE,GAAoC,EAAE,CAAC,gBAAgB,CAAC,KAAK,EAAE;QAC5E,sGAAkD;QAClD,eAAe,EAAE,GAAG,EAAE,CAAC,gBAAgB,CAAC,eAAe,EAAE;QACzD,QAAQ,EAAE,GAAG,EAAE,CAAC,gBAAgB,CAAC,OAAO,EAAE;KAC1C,CAAC;AAAA,CACF","sourcesContent":["/**\n * First-party builtin memory capability (统一修复轮 A, 方案系统设计 §6.1 + §11,\n * 方案实施计划 §11 A 路) — the model-facing write/recall/list/forget surface\n * over the M5 Memory Foundation.\n *\n * Every operation is suite-scoped by construction: the suiteId comes from the\n * session's suite binding entry (SUITE_SESSION_ENTRY_TYPE, written by the sdk\n * at session creation) and is NEVER a tool parameter, so the model cannot\n * widen or switch its memory domain (防越权). Sessions without a binding fall\n * back to the \"legacy\" domain with a diagnostic. Writes go through the\n * scheduler facade (observation → candidate → committed) plus a durable JSONL\n * ledger append (src/memory/ledger.ts, the store's persistent replica); recall\n * runs through the memory-recall-agent with the suiteId passthrough filter and\n * the egress gate; forget goes through the canonical purge gate\n * (user-immediate) and journal, physically rewriting the ledger (forget 后真\n * 物理删除).\n *\n * Domain resolution is LAZY, per tool call (统一修复轮 B1 复审修复): the sdk\n * appends the suite binding entry only after `new AgentSession` returns (the\n * constructor's synchronous runtime build already runs this factory), so a\n * factory-time resolution always saw an empty branch and every new session\n * fell back to the legacy domain. Instead, each tool handler resolves the\n * domain at call time — the binding entry is on the branch by then (creation\n * appends it; resumed sessions carry it in their history) — and the per-domain\n * ledger is created, loaded, and replayed into the store on the first call in\n * that domain (Map<domain, ledger> cache, no memoization of the domain\n * itself). The store stays one per-capability-instance singleton across\n * domains: the atom `suiteId` field carries the read boundary; the ledger is\n * only the per-domain durable replica.\n *\n * Concurrency envelope (统一修复轮 H1, #7 深度修复; WP-F 关洞修复): ledger\n * appends AND the forget path's full-file rewrite serialize competing\n * processes through the ledger's `.lock` sibling file (exclusive create +\n * poll, 5 s timeout, stale-lock stealing — src/memory/ledger.ts), and both\n * write paths run open → write → fsync → close, so a hard crash cannot lose\n * a write that returned to its caller. A lock timeout or IO/fsync failure\n * throws out of the tool handler, so the model sees the error instead of a\n * silently lost write. Remaining boundaries: the lock is atomic only on\n * local filesystems; a rewrite publishes the calling process's in-memory\n * view without merging rows another process appended after its last load\n * (the forget caller owns that reconciliation); fsync does not cover\n * directory entries, so a crash before rewrite's rename leaves the previous\n * file intact; an append whose fsync failed stays unacknowledged though it\n * may already be readable — the loader's duplicate tolerance covers an\n * unacknowledged retry.\n *\n * Global mode gate (2.4d6 S1, 记忆系统语义化重设计 §3): `memory.mode` is\n * `\"off\"` (default) | `\"light\"` | `\"full\"`; off means the whole memory family\n * is NOT registered (the suite membership skips the plugin; the factory\n * itself returns zero registrations for direct callers). light/full run an\n * enabling state machine (local checks → model load/download → smoke →\n * ready; failure → failed with a four-option action list and the effective\n * mode falls back to off for this instance).\n *\n * Semantic recall (2.4d6 S2, 设计 §4): memory_recall has exactly one\n * retrieval path — embed → KNN depth50 + FTS depth50 → RRF k=60 top20 →\n * cross-encoder rerank → store lookup (owner/suite/scope/expiry). The legacy\n * tag-wordform bridge (query-token → tag-facet anchors, recency fallback\n * page) is retired as a retrieval semantic; tags still ride the FTS body and\n * the memory_list management face. Degradation ladder (never thrown at the\n * model): rerank failure → RRF order; vector failure → FTS-only with\n * recency ordering; FTS/index failure → KNN-only; both channels down →\n * recency enumeration over the domain; total failure → degraded packet.\n * `memoryIdEquals`-style primary-key lookup survives as the exact-id fast\n * path (reference semantics, not retrieval).\n *\n * Semantic write merge (2.4d6 S3, 设计 §5 + 实施计划 S3 标定定版): in mode\n * \"full\" every memory_write probes the projection BEFORE the canonical commit\n * (embed + same-owner KNN top-5) because atoms are immutable — the outcome's\n * relations must ride the atom's one commit. Merge condition (calibrated on\n * bge-m3): cos ≥ 0.72, or 0.55 ≤ cos < 0.72 with a case-insensitive tag\n * overlap. A merge commits the NEW atom with a one-way `supersedes` relation\n * to the neighbor (the old entry keeps its memoryId and stays addressable via\n * primary-key lookup) while the projection upserts the new row and removes the\n * superseded one; startup reconciliation never re-adds superseded rows.\n * 0.55 ≤ cos < 0.72 without a tag overlap is the conflict band: both entries\n * stay, and the new atom carries one-way `conflict` relations. Below that (or\n * no neighbor): a plain new entry. bge-small-zh similarity distributions\n * overlap (标定: 余弦不可用作去重信号) → light mode never probes and stays\n * byte-identical to the pre-S3 behavior. Recall filters superseded entries\n * after the store lookup (only while their successor is among the candidates,\n * so forgetting the successor revives the old entry). The Foundation\n * (owner, observationId) idempotency is untouched: replays never consume a\n * probe outcome.\n */\nimport { join } from \"node:path\";\nimport type {\n\tMemoryCapabilityOverrideV1,\n\tMemoryModeV1,\n\tMemoryStorageComponentsV1,\n\tMemoryVectorComponentsOverrideV1,\n\tSessionArchiveHostV1,\n} from \"@agent-forge/plugin-sdk\";\nimport {\n\ttype CapabilityAPI,\n\ttype DisposableRegistration,\n\tEXPERIMENTAL_PUBLIC_API_VERSION,\n} from \"@agent-forge/plugin-sdk\";\n\n// 记忆公共契约的权威定义处已是 plugin-sdk(D-075 S4-4 第一批迁入);此处 re-export\n// 维持宿主历史导出面(宿主第二批收口后由宿主 re-export SDK)。\nexport {\n\tMEMORY_RECALL_TOOL_NAME,\n\ttype MemoryCapabilityOverrideV1,\n\ttype MemoryEnablingOverrideV1,\n\ttype MemoryModeV1,\n\ttype MemoryStorageComponentsV1,\n\ttype MemoryVectorComponentsOverrideV1,\n} from \"@agent-forge/plugin-sdk\";\n// 拆分战役 slice 1/3b: 征询持久化(enabling.ts 征询域)与向量常量/状态类型\n// (vector-channel.ts)随模块迁出,经 re-export 维持 capability.ts 的历史\n// 导出面(index.ts `export *` 与 entry.ts / inference-service-main.ts 的\n// 既有 import 不变;vector-channel.ts 不进 index.ts,slice 2 先例)。\nexport {\n\tMEMORY_AGENT_DIR_CONFIG_RELATIVE_PATH,\n\tMEMORY_CONSENT_DECLINED_VALUE,\n\twriteMemoryConsentDeclined,\n\twriteMemorySettingsMode,\n} from \"./memory/enabling.ts\";\n// 拆分战役 slice 7: auto-recall 注入标记/免责行随钩子面迁入 hooks.ts, 经\n// re-export 维持 capability.ts 的历史导出面 (index.ts `export *` 与既有 import\n// 不变; hooks.ts 本体不进 index.ts, recall-pipeline.ts 先例)。lessons 开关解析\n// 已随实时教训停用一并移除 (记忆归档与整理设计 §14 裁决 1)。\nexport {\n\tMEMORY_AUTO_RECALL_DEADLINE_MS,\n\tMEMORY_AUTO_RECALL_DISCLAIMER,\n\tMEMORY_AUTO_RECALL_MARKER,\n} from \"./memory/hooks.ts\";\n// 拆分战役 slice 4: MEMORY_TOOLS_GUIDE 随召回管线迁入 recall-pipeline.ts, 经\n// re-export 维持 capability.ts 的历史导出面 (宿主与测试的既有 import 不变;\n// recall-pipeline.ts 本体不进 index.ts, vector-channel.ts slice 2 先例)。\nexport { MEMORY_TOOLS_GUIDE } from \"./memory/recall-pipeline.ts\";\nexport {\n\ttype MemoryCapabilityStateV1,\n\ttype MemoryConsentNeededV1,\n\ttype MemoryEnablingFailureV1,\n\tVECTOR_DB_DIRNAME,\n\tVECTOR_MODEL_CACHE_DIRNAME,\n\tVECTOR_RERANKER_MODEL_ID,\n} from \"./memory/vector-channel.ts\";\n// 拆分战役 slice 5: 档位自动升级阈值随写入面迁入 write-face.ts, 经 re-export\n// 维持 capability.ts 的历史导出面。\nexport { MEMORY_TIER_UPGRADE_STORE_THRESHOLD } from \"./memory/write-face.ts\";\n\nimport { createMemoryCandidateMachine } from \"./memory/candidates.ts\";\nimport { createMemoryCommandFace } from \"./memory/command-face.ts\";\nimport { createMemoryCurator } from \"./memory/curator.ts\";\nimport { createMemoryEgressPolicy } from \"./memory/egress-policy.ts\";\nimport type { MemoryAtomV1 } from \"./memory/foundation.ts\";\nimport { createMemoryHooks } from \"./memory/hooks.ts\";\nimport { createDurableMemoryLedger, type DurableMemoryLedgerV1, scanOwnerLedgerMemoryIds } from \"./memory/ledger.ts\";\nimport { createMemoryLifecycleManager } from \"./memory/lifecycle.ts\";\nimport { createMemoryNetwork, createRelationDiffusionAdapter } from \"./memory/memory-network.ts\";\nimport { createPreferenceDisambiguator } from \"./memory/preference-disambiguator.ts\";\nimport { createPreferenceResolver } from \"./memory/preference-resolver.ts\";\nimport { createMemoryPurgeGate, createMemoryReplicaRegistry, type MemoryReplicaV1 } from \"./memory/purge.ts\";\nimport { createMemoryPurgeJournal } from \"./memory/purge-journal.ts\";\nimport { createMemoryRecallAgent } from \"./memory/recall-agent.ts\";\nimport { createMemoryRecallIndex } from \"./memory/recall-index.ts\";\nimport { createMemoryRecallPipeline } from \"./memory/recall-pipeline.ts\";\nimport { sweepExpiredMemories } from \"./memory/retention-sweep.ts\";\nimport { createMemoryScheduler } from \"./memory/scheduler.ts\";\nimport { createMemorySchedulerApi } from \"./memory/scheduler-api.ts\";\nimport { createFirstPartyRetentionRegistry, createMemoryStore } from \"./memory/store.ts\";\nimport { type SuiteMemoryDomainV1, suiteMemoryDomainName } from \"./memory/suite-memory.ts\";\nimport { MEMORY_CONTRACT_VERSION_V2 } from \"./memory/transfer.ts\";\nimport type { MemoryCapabilityStateV1, MemoryEnablingFailureV1 } from \"./memory/vector-channel.ts\";\nimport { createMemoryVectorChannel } from \"./memory/vector-channel.ts\";\nimport { createMemoryVectorProjection } from \"./memory/vector-projection.ts\";\nimport { createMemoryWriteFace, TAG_FACET_NAMESPACE } from \"./memory/write-face.ts\";\n\nexport const capabilityManifest = {\n\tid: \"agent-forge.builtin.memory\",\n\tversion: \"0.1.0\",\n\tapiVersion: EXPERIMENTAL_PUBLIC_API_VERSION,\n\trequiredCapabilities: [\"session\", \"events\", \"tools\"],\n\tprovides: [{ id: \"memory.scheduler\", version: 1, kind: \"service\" }],\n} as const;\n\n/**\n * 解析后的全局模式 (2.4d6 S1)。`invalidEnvValue` 非空 = 配置的环境值非法,\n * 已 fail-closed 回 off, 调用方负责以此输出一次 warn; `invalidSettingsValue`\n * 非空 = settings.json 的 `memory.mode` 非法, 同为 fail-closed off 并输出一次\n * 诊断; `legacyEnvUsed` = 模式由旧别名 `AGENT_FORGE_MEMORY_VECTOR` 决定 (兼容\n * 期: 仅当 `AGENT_FORGE_MEMORY_MODE` 与 settings 均未定档时生效, 一个发布周期\n * 后移除)。\n */\nexport interface MemoryModeResolutionV1 {\n\treadonly mode: MemoryModeV1;\n\treadonly invalidEnvValue?: string;\n\treadonly invalidSettingsValue?: string;\n\treadonly legacyEnvUsed?: boolean;\n}\n\nconst isMemoryModeV1 = (value: string): value is MemoryModeV1 =>\n\tvalue === \"off\" || value === \"light\" || value === \"full\";\n\n/**\n * memory.mode 解析 (2.4d6 S1)。优先级: context 显式值 → 环境变量\n * `AGENT_FORGE_MEMORY_MODE` → settings.json `memory.mode` (settingsMode 参, 持\n * 久配置面) → 旧别名 `AGENT_FORGE_MEMORY_VECTOR` (兼容期) → 默认 light\n * (2026-10-05 用户裁决翻转默认 off→light, 对齐主流编程助手开箱即用方向)。env 是\n * 临时覆盖、settings 是持久配置 (env > 文件, 沿用本仓 suite 解析先例)。任何\n * 非法配置值 fail-closed 为 off 并在结果中携带原值供调用方告警一次, 绝不静默\n * 改档或意外下载。\n */\nexport function resolveMemoryMode(\n\texplicitMode: string | undefined,\n\tenv: Readonly<Record<string, string | undefined>> = process.env,\n\tsettingsMode?: string,\n): MemoryModeResolutionV1 {\n\tif (explicitMode !== undefined) {\n\t\tif (isMemoryModeV1(explicitMode)) return { mode: explicitMode };\n\t\treturn { mode: \"off\", invalidEnvValue: explicitMode };\n\t}\n\tconst configured = env.AGENT_FORGE_MEMORY_MODE?.trim().toLowerCase();\n\tif (configured !== undefined && configured !== \"\") {\n\t\tif (isMemoryModeV1(configured)) return { mode: configured };\n\t\treturn { mode: \"off\", invalidEnvValue: configured };\n\t}\n\t// 持久配置面: settings.json memory.mode。设置但非法同样 fail-closed, 不再\n\t// 回落旧别名 (与非法 env 的先例一致)。\n\tconst fromSettings = settingsMode?.trim().toLowerCase();\n\tif (fromSettings !== undefined && fromSettings !== \"\") {\n\t\tif (isMemoryModeV1(fromSettings)) return { mode: fromSettings };\n\t\treturn { mode: \"off\", invalidSettingsValue: fromSettings };\n\t}\n\t// 兼容期别名: AGENT_FORGE_MEMORY_VECTOR (混合检索工程化的旧开关), 语义并入\n\t// AGENT_FORGE_MEMORY_MODE, 仅当新变量与 settings 均未定档时生效; 一个发布\n\t// 周期后删除。\n\tconst legacy = env.AGENT_FORGE_MEMORY_VECTOR?.trim().toLowerCase();\n\tif (legacy !== undefined && legacy !== \"\") {\n\t\tif (isMemoryModeV1(legacy)) return { mode: legacy, legacyEnvUsed: true };\n\t\treturn { mode: \"off\", invalidEnvValue: legacy, legacyEnvUsed: true };\n\t}\n\treturn { mode: \"light\" };\n}\n\n/** Host-provided factory context; provided by the host session assembly (sdk suite membership). */\nexport interface MemoryCapabilityContext {\n\t/** Agent home directory — roots the durable ledger under `<agentDir>/memory/`. */\n\treadonly agentDir: string;\n\t/**\n\t * 宿主已解析的 onnxruntime-node 入口绝对路径 (D-075 安装店重依赖可见性):\n\t * 安装店副本无 node_modules, 插件内 createRequire 解析不到; 宿主装载器把\n\t * hostDependencyPaths 注入 manifest config, entry 提取后经本字段传入。\n\t * 缺省 (源码/工作区直载) 走插件内双通道自解析。\n\t */\n\treadonly hostOnnxRuntimeEntryPath?: string;\n\t/** 同上——@lancedb/lancedb 入口路径 (向量索引运行时按绝对路径原生 import)。 */\n\treadonly hostLancedbEntryPath?: string;\n\t/** 同上——@huggingface/transformers 入口路径 (embedding/reranker 运行时用)。 */\n\treadonly hostTransformersEntryPath?: string;\n\t/**\n\t * 记忆全局档位 (2.4d6 S1)。缺省解析顺序: 本字段 → 环境变量\n\t * `AGENT_FORGE_MEMORY_MODE` → {@link MemoryCapabilityContext.memory.settingsMode}\n\t * → 旧别名 `AGENT_FORGE_MEMORY_VECTOR` (兼容期) → 默认 off (整个家族不注册)。\n\t * 装配方 (sdk) 可经本字段显式定档。\n\t */\n\treadonly memory?: {\n\t\treadonly mode?: MemoryModeV1;\n\t\t/**\n\t\t * settings.json `memory.mode` 的原样值 (持久配置面, 优先级低于 env);\n\t\t * 类型面只允许合法档位, 手改文件的非法值原样透传并由\n\t\t * {@link resolveMemoryMode} fail-closed 处理。\n\t\t */\n\t\treadonly settingsMode?: string;\n\t};\n\t/**\n\t * 测试专用注入 (架构宪法: deterministic mock AI 门禁)。经装配上下文携带时,\n\t * 装配方原样透传给工厂; 与 {@link createCapabilityWithVectorComponents}\n\t * 的第三参语义一致, 第三参优先。\n\t */\n\treadonly vectorComponents?: MemoryCapabilityOverrideV1;\n\t/**\n\t * 共享推理服务装配缝 (Slice B2, 记忆共享推理服务设计 §3.1/§3.3/§3.6)。\n\t * 缺省 (生产) = 真实路径: 模型在位时装配经 TCP loopback 走常驻服务,\n\t * 连不上则懒 spawn 插件 bin (`agent-forge-memory-inference`), 重连失败按\n\t * enabling failed 呈现 (裁决 A: 不回退本地装配)。测试注入替换对应环节\n\t * (deterministic 门禁): `port` 直连测试服务、`spawnImpl` 替换进程拉起、\n\t * `modelsInPlace` 声明模型在位 (跳过文件检查, 免写假权重文件)。\n\t * loadImpl enabling 缝与 vectorComponents 注入仍走本地装配路径 (既有语义)。\n\t */\n\treadonly inferenceService?: {\n\t\treadonly port?: number;\n\t\treadonly spawnImpl?: (\n\t\t\tagentDir: string,\n\t\t\tmode: \"light\" | \"full\",\n\t\t\tport: number,\n\t\t\t/** spawn 异步失败 (EACCES/ENOMEM 等) 的回调; 缺省实现经 child 'error' 事件馈入。 */\n\t\t\tonError?: (error: Error) => void,\n\t\t) => Promise<void>;\n\t\treadonly modelsInPlace?: boolean;\n\t};\n\t/**\n\t * 记忆底层组件注入 (扩展位盘点 A1/A2 的宿主装配通道): store/ledger 工厂与\n\t * 向量组件公共契约, 缺省成员走内置默认实现。装配方经\n\t * `CreateAgentSessionOptions.memoryCapability.storage` 携带。\n\t */\n\treadonly storage?: MemoryStorageComponentsV1;\n\t/**\n\t * 会话归档协调面 (记忆归档与整理设计 §4/§8): 整理器读归档会话条目与回写\n\t * curation 状态的唯一通道。缺省回落宿主服务 `api.host.sessionArchive`(生产\n\t * 装配路径);两者都缺席 = 宿主不开放归档,整理器的两个触发(归档事件观察与\n\t * 启动 sweep)都不注册,记忆家族其余能力不受影响。本字段同时是测试注入缝\n\t * (deterministic mock AI 门禁:curator 测试经它注入 fake archive)。\n\t */\n\treadonly sessionArchive?: SessionArchiveHostV1;\n}\n\nconst isVectorComponentsOverride = (\n\toverride: MemoryCapabilityOverrideV1,\n): override is MemoryVectorComponentsOverrideV1 => \"embedProvider\" in override && \"vectorIndex\" in override;\n\n/**\n * 默认档判定 (征询拒绝只抑制默认档): 显式值、env、settings、旧别名四层全部\n * 未定档时, 模式来自出厂默认档 (light)。与 resolveMemoryMode 的优先级链同构,\n * 不改 resolver 返回面。\n */\nexport function memoryModeSourceIsDefault(\n\texplicitMode: string | undefined,\n\tenv: Readonly<Record<string, string | undefined>>,\n\tsettingsMode?: string,\n): boolean {\n\treturn (\n\t\texplicitMode === undefined &&\n\t\t(env.AGENT_FORGE_MEMORY_MODE?.trim() ?? \"\") === \"\" &&\n\t\t(env.AGENT_FORGE_MEMORY_VECTOR?.trim() ?? \"\") === \"\" &&\n\t\t(settingsMode?.trim() ?? \"\") === \"\"\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\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * 双约定工具输入读取(对齐 subagent-delegate 的 objectInput):capability invoke\n * 面单参约定下第一参即输入(第二参是宿主注入的 toolExecutionContext),legacy 5 参\n * 约定(toolCallId 字符串打头)下输入在第二参。生产装配恒向 runtime invoke 面注入\n * toolExecutionContext 作为 execute 第二参(公共契约),因此\"第二参非 undefined 即\n * 输入\"的判定会把 context 误当输入(content/query 等读成 undefined)。改按形状判定:\n * 第一参是普通对象即取第一参,否则看第二参;两者皆非对象时返回空记录,交由各工具\n * 的字段断言报错。\n */\nfunction memoryToolInput(first: unknown, second: unknown): Record<string, unknown> {\n\tconst primary = isPlainRecord(first) ? first : second;\n\treturn isPlainRecord(primary) ? primary : {};\n}\n\n/** FNV-1a 32-bit — deterministic identity from the given value (code-memory 同构). */\nfunction identityHash(value: string): string {\n\tlet hash = 0x811c9dc5;\n\tfor (let index = 0; index < value.length; index += 1) {\n\t\thash ^= value.charCodeAt(index);\n\t\thash = Math.imul(hash, 0x01000193);\n\t}\n\treturn (hash >>> 0).toString(36);\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * Session protocol key of the suite binding entry (方案设计 §10.1). The value\n * mirrors the authoritative `SUITE_SESSION_ENTRY_TYPE` in\n * src/suites/suite-loader.ts — pinned by a deterministic test in\n * test/capabilities-builtin.test.ts. Declared locally so the capability module\n * graph stays free of the assembler's bundled-loader dependency chain.\n */\nconst SUITE_SESSION_ENTRY_TYPE = \"suite\";\n\n/**\n * Owner (isolation principal) of every atom this capability writes. The\n * Foundation owner is the store/facade isolation identity; this product ships\n * one local user per agentDir, so one stable owner id partitions the ledger\n * directory `<agentDir>/memory/<owner>/ledger-<suiteId|\"legacy\">.jsonl`.\n */\nexport const BUILTIN_MEMORY_OWNER = \"local-user\";\n\n/** Contract version written by this capability (@2 atoms carry suiteId). */\nconst MEMORY_CONTRACT_VERSION = MEMORY_CONTRACT_VERSION_V2;\n\n/**\n * Suite binding entry ids already warned about (统一修复轮终审 minor 3):\n * resolveSessionDomain runs on EVERY memory tool call, so without this\n * module-level set one malformed binding entry would repeat the warning on\n * each call and flood the log.\n */\nconst malformedBindingWarned = new Set<string>();\n\n/**\n * Resolves the session's suite binding domain from the branch entries: the\n * LAST suite entry wins (the sdk appends one at session creation). A binding\n * with a malformed payload counts as unbound — the legacy fallback is\n * fail-safe (its atoms are invisible to every real suite) and a diagnostic is\n * logged when the logger capability is available. Called per tool call —\n * never captured at factory time (统一修复轮 B1: the binding entry is appended\n * after the session constructor ran this factory).\n */\nfunction resolveSessionDomain(api: CapabilityAPI): SuiteMemoryDomainV1 {\n\tconst entries = api.session?.getBranchEntries() ?? [];\n\tfor (let index = entries.length - 1; index >= 0; index -= 1) {\n\t\tconst entry = entries[index];\n\t\tif (entry.type !== \"custom\" || entry.customType !== SUITE_SESSION_ENTRY_TYPE) continue;\n\t\tconst data = entry.data;\n\t\tconst suiteId = isPlainObject(data) ? data.suiteId : undefined;\n\t\tif (typeof suiteId === \"string\" && suiteId.trim() !== \"\") {\n\t\t\treturn { kind: \"suite\", suiteId };\n\t\t}\n\t\tif (!malformedBindingWarned.has(entry.id)) {\n\t\t\tmalformedBindingWarned.add(entry.id);\n\t\t\tapi.logger?.warn(\"suite binding entry has a malformed payload; falling back to the legacy memory domain\", {\n\t\t\t\tentryId: entry.id,\n\t\t\t});\n\t\t}\n\t\treturn { kind: \"legacy\" };\n\t}\n\treturn { kind: \"legacy\" };\n}\n\n/** Recency-first payload projection: unwraps the `{ statement }` payload convention. */\nfunction statementOf(payload: unknown): string {\n\tif (isPlainObject(payload) && typeof payload.statement === \"string\") return payload.statement;\n\treturn JSON.stringify(payload);\n}\n\n/** The egress gate re-derives statements as payload JSON; unwrap for the model face. */\nfunction unwrapEgressStatement(statement: string): string {\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(statement);\n\t\tif (isPlainObject(parsed) && typeof parsed.statement === \"string\") return parsed.statement;\n\t} catch {\n\t\t// Not payload JSON — surface it verbatim.\n\t}\n\treturn statement;\n}\n\nfunction tagFacetsOf(atom: MemoryAtomV1): string[] {\n\treturn atom.facets\n\t\t.filter((facet) => facet.namespace === TAG_FACET_NAMESPACE && facet.key === \"tag\")\n\t\t.map((facet) => facet.value);\n}\n\n/**\n * Creates the builtin memory capability: four tools (memory_write,\n * memory_recall, memory_list, memory_forget) over a per-session Foundation\n * stack whose durable replica is the per-domain JSONL ledger under\n * `<agentDir>/memory/<owner>/ledger-<domain>.jsonl`, resolved lazily at each\n * tool call (统一修复轮 B1).\n *\n * `memory.mode` gates the whole family (2.4d6 S1): a resolved mode of \"off\"\n * registers NOTHING (zero tools, zero commands, zero events) — the factory\n * returns an empty registration list and logs the one-line disabled\n * declaration. suite capability membership decides earlier at the assembly\n * level (设计 §3.2 \"禁用 = 不注册\").\n *\n * `override` is the test-only seam (deterministic mock AI 门禁): full vector\n * components skip the real transformers/lancedb assembly entirely; enabling\n * seams keep the real assembly but replace the transformers loader.\n */\nexport function createMemoryCapability(\n\tapi: CapabilityAPI,\n\tcontext: MemoryCapabilityContext,\n\toverride?: MemoryCapabilityOverrideV1,\n): readonly DisposableRegistration[] {\n\tconst harness = createMemoryCapabilityHarness(api, context, override);\n\treturn harness.registrations;\n}\n\n/** Test-only harness over the capability: registration list plus state-work hooks. */\nexport interface MemoryVectorCapabilityHarnessV1 {\n\treadonly registrations: readonly DisposableRegistration[];\n\t/** Resolves after every vector op queued so far (reconcile/upsert/purge) settled. */\n\tsettleVectorWork(): Promise<void>;\n\tvectorState(): \"off\" | MemoryCapabilityStateV1;\n\t/**\n\t * Resolves once the enabling attempt settles (immediately for injected\n\t * components): ready, or the structured failure (reason + action list).\n\t */\n\tenablingOutcome(): Promise<\"ready\" | MemoryEnablingFailureV1>;\n\t/**\n\t * 释放共享推理服务连接 (服务路径) 或本地向量索引 (本地装配路径)。幂等: 引用\n\t * 清空后二次调用为 no-op。同名注册项挂 registrations 首位——宿主反向逐个\n\t * dispose 时它最后执行 (先拆消费者、后关通道)。\n\t */\n\tteardown(): void;\n}\n\n/**\n * Test-only assembly variant: the capability with an injected override (full\n * vector components skip real assembly; enabling seams redirect the model\n * loader on the real path). Public tool names, schemas, and return shapes are\n * identical to {@link createMemoryCapability}.\n */\nexport function createCapabilityWithVectorComponents(\n\tapi: CapabilityAPI,\n\tcontext: MemoryCapabilityContext,\n\toverride: MemoryCapabilityOverrideV1,\n): MemoryVectorCapabilityHarnessV1 {\n\t// Tool-face test stubs hand-write partial CapabilityAPIs that predate the\n\t// D-071 auto-recall hook; default registerLoopHook to a no-op so those\n\t// tests keep exercising just the tool face. Real CapabilityAPIs always\n\t// carry the method (production path never hits this default) — the `in`\n\t// check is runtime-only because the stubs bypass the declared type.\n\tconst apiWithHooks: CapabilityAPI =\n\t\t\"registerLoopHook\" in api\n\t\t\t? api\n\t\t\t: Object.assign(Object.create(null) as CapabilityAPI, api, {\n\t\t\t\t\tregisterLoopHook: (): DisposableRegistration => ({\n\t\t\t\t\t\tid: \"test:noop-loop-hook\",\n\t\t\t\t\t\tkind: \"loop-hook\",\n\t\t\t\t\t\tdispose() {},\n\t\t\t\t\t}),\n\t\t\t\t});\n\treturn createMemoryCapabilityHarness(apiWithHooks, context, override);\n}\n\nfunction createMemoryCapabilityHarness(\n\tapi: CapabilityAPI,\n\tcontext: MemoryCapabilityContext,\n\toverride?: MemoryCapabilityOverrideV1,\n): MemoryVectorCapabilityHarnessV1 {\n\tassertNonEmptyString(context.agentDir, \"MemoryCapabilityContext.agentDir\");\n\tconst now = (): number => Date.now();\n\tconst sessionId = api.session?.getSessionId() ?? \"no-session\";\n\n\t// 全局档位解析 (2.4d6 S1): context 显式 → env → settings.json → 默认 off。\n\t// 非法 env/settings 值 fail-closed 回 off 并各告警一次; off = 家族整体不注册\n\t// (零工具零命令零事件)。\n\tconst modeResolution = resolveMemoryMode(context.memory?.mode, undefined, context.memory?.settingsMode);\n\tif (modeResolution.invalidEnvValue !== undefined) {\n\t\tapi.logger?.warn(\n\t\t\t`invalid AGENT_FORGE_MEMORY_MODE value \"${modeResolution.invalidEnvValue}\"; memory stays off (fail-closed)`,\n\t\t);\n\t}\n\tif (modeResolution.invalidSettingsValue !== undefined) {\n\t\tapi.logger?.warn(\n\t\t\t`invalid memory.mode setting \"${modeResolution.invalidSettingsValue}\"; memory stays off (fail-closed)`,\n\t\t);\n\t}\n\tif (modeResolution.mode === \"off\") {\n\t\tapi.logger?.info(\"memory disabled (mode=off)\");\n\t\treturn {\n\t\t\tregistrations: [],\n\t\t\tsettleVectorWork: async () => {},\n\t\t\tvectorState: () => \"off\",\n\t\t\tenablingOutcome: async () => \"ready\",\n\t\t\tteardown: () => {},\n\t\t};\n\t}\n\tconst memoryMode = modeResolution.mode;\n\tconst vectorComponentsOverride: MemoryCapabilityOverrideV1 | undefined =\n\t\toverride ?? context.vectorComponents ?? context.storage?.vectorComponents;\n\tconst injectedComponents =\n\t\tvectorComponentsOverride !== undefined && isVectorComponentsOverride(vectorComponentsOverride)\n\t\t\t? vectorComponentsOverride\n\t\t\t: undefined;\n\tconst enablingOverride =\n\t\tvectorComponentsOverride !== undefined && !isVectorComponentsOverride(vectorComponentsOverride)\n\t\t\t? vectorComponentsOverride\n\t\t\t: undefined;\n\n\t// Store: one per-capability-instance singleton. Atoms of every domain this\n\t// session touches live here together — the atom `suiteId` field carries the\n\t// read boundary (suite queries filter through it; the ledger is only the\n\t// per-domain durable replica). The injected storeFactory (扩展位 A1) replaces\n\t// the default store wholesale: the implementation owns retention semantics.\n\tconst retentionRegistry = createFirstPartyRetentionRegistry();\n\tconst store =\n\t\tcontext.storage?.storeFactory?.({\n\t\t\tagentDir: context.agentDir,\n\t\t\towner: BUILTIN_MEMORY_OWNER,\n\t\t\tnow,\n\t\t}) ?? createMemoryStore({ retentionRegistry, now });\n\n\t// Durable replica per domain, created and loaded lazily on the first tool\n\t// call in that domain (统一修复轮 B1 复审修复): the sdk appends the suite\n\t// binding entry only after the session constructor ran this factory, so the\n\t// domain (and with it the ledger to replay) is only known at call time.\n\t// Write identity is deterministic: observationId `memory_write:<sessionId>:<n>`\n\t// hashes into the memoryId. The counter is instance-local, so a resumed session\n\t// re-derives its floor from the replayed ledger (resolveDomain): a persisted\n\t// observationId of this session marks its sequence as taken — the store rejects\n\t// a regenerated memoryId (canonical atoms are immutable), which would fail every\n\t// replayed-sequence write after resume (write → dispose → resume → write).\n\tconst domainLedgers = new Map<string, DurableMemoryLedgerV1>();\n\tconst resolveDomain = (): {\n\t\treadonly domain: SuiteMemoryDomainV1;\n\t\treadonly domainName: string;\n\t\treadonly ledger: DurableMemoryLedgerV1;\n\t} => {\n\t\tconst domain = resolveSessionDomain(api);\n\t\tconst domainName = suiteMemoryDomainName(domain);\n\t\tlet ledger = domainLedgers.get(domainName);\n\t\tif (ledger === undefined) {\n\t\t\tledger =\n\t\t\t\tcontext.storage?.ledgerFactory?.({\n\t\t\t\t\tagentDir: context.agentDir,\n\t\t\t\t\towner: BUILTIN_MEMORY_OWNER,\n\t\t\t\t\tdomain: domainName,\n\t\t\t\t\tnow,\n\t\t\t\t}) ??\n\t\t\t\tcreateDurableMemoryLedger({\n\t\t\t\t\tpath: join(context.agentDir, \"memory\", BUILTIN_MEMORY_OWNER, `ledger-${domainName}.jsonl`),\n\t\t\t\t\tnow,\n\t\t\t\t});\n\t\t\tif (domain.kind === \"legacy\") {\n\t\t\t\tapi.logger?.info(\"session has no suite binding; memory falls back to the legacy domain\", {\n\t\t\t\t\tsessionId: api.session?.getSessionId() ?? \"unknown\",\n\t\t\t\t});\n\t\t\t}\n\t\t\t// First load in this domain: replay the durable atoms into the store.\n\t\t\t// Sequences persisted by earlier instances of this session raise the\n\t\t\t// write-sequence floor before any new write can regenerate their ids.\n\t\t\tconst replay = ledger.load();\n\t\t\tfor (const atom of replay.atoms) {\n\t\t\t\tconst persistedSequence = writeFace.writeSequenceOf(atom.observationId);\n\t\t\t\tif (persistedSequence !== undefined) writeFace.advanceWriteSequenceFloor(persistedSequence);\n\t\t\t\ttry {\n\t\t\t\t\tstore.commit(atom);\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// A ledger atom the current store cannot accept (e.g. an unregistered\n\t\t\t\t\t// retention mode) must not fail the session — skip with a diagnostic.\n\t\t\t\t\tapi.logger?.warn(\"memory ledger atom could not be replayed into the store\", {\n\t\t\t\t\t\tmemoryId: atom.memoryId,\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\tif (replay.corruptedLines > 0 || replay.duplicateSkipped > 0 || replay.unreadable) {\n\t\t\t\tapi.logger?.warn(\"memory ledger loaded with diagnostics\", {\n\t\t\t\t\tdomain: domainName,\n\t\t\t\t\tcorruptedLines: replay.corruptedLines,\n\t\t\t\t\tduplicateSkipped: replay.duplicateSkipped,\n\t\t\t\t\tunreadable: replay.unreadable,\n\t\t\t\t});\n\t\t\t}\n\t\t\tdomainLedgers.set(domainName, ledger);\n\t\t\t// 启动对账: 首个域的 ledger 重放完成后一次性触发 (fire-and-forget,\n\t\t\t// 不阻塞本工具调用; 失败只影响向量通道, 不影响锚点通道)。\n\t\t\tvectorProjection.reconcileOnce();\n\t\t\t// 机会式保留清扫 (M5, 记忆系统设计 §3.3): 首载重放完成后对本域已过期\n\t\t\t// 原子执行一次受控物理清理 (retention-expiry 授权, 最旧优先 ≤200 条,\n\t\t\t// ledger 重写 + 向量行删除 + store 逐出)。同步调用且 sweep 自吞错——\n\t\t\t// 装载绝不因清扫失败失败; 非干净结果只记一条有界 warn。\n\t\t\tconst sweepLedger = ledger;\n\t\t\tconst sweep = sweepExpiredMemories(\n\t\t\t\t{\n\t\t\t\t\tstore,\n\t\t\t\t\tpurgeGate,\n\t\t\t\t\tpurgeJournal,\n\t\t\t\t\tpurgeIndexReplica: vectorProjection.purgeMemories,\n\t\t\t\t\tpurgeCanonicalReplica: (memoryIds) => {\n\t\t\t\t\t\tconst purged = new Set(memoryIds);\n\t\t\t\t\t\tsweepLedger.rewrite(sweepLedger.atomsSnapshot().filter((atom) => !purged.has(atom.memoryId)));\n\t\t\t\t\t\tfor (const id of memoryIds) store.evict(id);\n\t\t\t\t\t},\n\t\t\t\t\tauthorizedBy: `${capabilityManifest.id}:retention-sweep`,\n\t\t\t\t\tnow,\n\t\t\t\t},\n\t\t\t\t{ owner: BUILTIN_MEMORY_OWNER, domain },\n\t\t\t);\n\t\t\tif (sweep.status === \"failed\" || sweep.status === \"purge_eligible\" || sweep.reason !== undefined) {\n\t\t\t\tapi.logger?.warn(\n\t\t\t\t\t\"memory retention sweep did not finish clean; expired atoms stay purge-eligible and are retried on the next domain load\",\n\t\t\t\t\t{\n\t\t\t\t\t\tdomain: domainName,\n\t\t\t\t\t\tstatus: sweep.status,\n\t\t\t\t\t\t...(sweep.reason === undefined ? {} : { reason: sweep.reason }),\n\t\t\t\t\t\t...(sweep.failedReplicas === undefined ? {} : { failedReplicas: sweep.failedReplicas }),\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn { domain, domainName, ledger };\n\t};\n\n\tconst machine = createMemoryCandidateMachine({ store, now });\n\tconst lifecycle = createMemoryLifecycleManager({\n\t\tpolicy: {\n\t\t\tpolicyVersion: \"lifecycle@1\",\n\t\t\thalfLifeMs: { session: 86_400_000, cycle: 604_800_000, \"long-term\": 2_592_000_000 },\n\t\t\tstaleAfterMs: { session: 172_800_000, cycle: 1_209_600_000, \"long-term\": 5_184_000_000 },\n\t\t\tarchiveAfterMs: { session: 604_800_000, cycle: 5_184_000_000, \"long-term\": 15_552_000_000 },\n\t\t\tbaselineAttention: 0.5,\n\t\t},\n\t\tnow,\n\t});\n\tconst scheduler = createMemoryScheduler({ now });\n\tscheduler.acquireForInstance({ instanceId: sessionId, owner: BUILTIN_MEMORY_OWNER });\n\t// 非工具召回路径设施 (2.4d6 S4 家族收口取证结论): 生产工具召回 (memory_recall\n\t// 工具与 auto-recall 钩子, 后者直连同一 recallExecute, D-071 自 sdk 迁入)\n\t// 只走 recallSemantically 语义管线; index → recallAgent →\n\t// schedulerApi.recall 这条链在本 capability 内不再被工具面调用 (schedulerApi\n\t// 的生产使用仅剩写入路径的 submitObservation/submitCandidate)。保留原因:\n\t// MemorySchedulerApiV1 facade 契约 (recall + egress 门)、recall-agent 与\n\t// recall-index 是公共 API (src/index.ts 导出) 和 memory-testkit 之上的测试\n\t// 设施 (scheduler-api / memory-suite-scope / coverage-branch-memory-recall\n\t// 等测试的直接消费者) — 有存续消费者, 非死代码。\n\tconst index = createMemoryRecallIndex({ store });\n\tconst recallAgent = createMemoryRecallAgent({\n\t\tscheduler,\n\t\tindex,\n\t\tpolicyDefaults: {\n\t\t\tcandidateBudget: 1000,\n\t\t\tmodelInspectionLimit: 20,\n\t\t\tfinalResultLimit: 20,\n\t\t\tmaxRelationHops: 2,\n\t\t\tmaxModelCalls: 3,\n\t\t\tmaxOutputTokens: 4000,\n\t\t\tmaxOutputBytes: 16_000,\n\t\t\tmaxRounds: 3,\n\t\t},\n\t\thostLimits: {\n\t\t\tcandidateBudget: 5000,\n\t\t\tmodelInspectionLimit: 100,\n\t\t\tfinalResultLimit: 100,\n\t\t\tmaxRelationHops: 5,\n\t\t\tmaxModelCalls: 10,\n\t\t\tmaxOutputTokens: 100_000,\n\t\t\tmaxOutputBytes: 1_000_000,\n\t\t\tmaxRounds: 10,\n\t\t},\n\t\tnow,\n\t});\n\tconst replicaRegistry = createMemoryReplicaRegistry();\n\treplicaRegistry.register({\n\t\treplicaId: \"memory-ledger\",\n\t\tkind: \"canonical\",\n\t\townerScope: BUILTIN_MEMORY_OWNER,\n\t\tcontractVersion: MEMORY_CONTRACT_VERSION,\n\t\thealthy: true,\n\t} satisfies MemoryReplicaV1);\n\t// 向量投影副本 (混合检索工程化, D-035): 恒注册 — purge 批次以向量索引确认为\n\t// 副本契约的一部分; 通道 off/disabled 时 index 分派为 no-op (索引不存在,\n\t// 无行可清), 行为见 vectorProjection.purgeMemories。\n\treplicaRegistry.register({\n\t\treplicaId: \"memory-vector-index\",\n\t\tkind: \"index\",\n\t\tcontractVersion: MEMORY_CONTRACT_VERSION,\n\t\townerScope: BUILTIN_MEMORY_OWNER,\n\t\thealthy: true,\n\t} satisfies MemoryReplicaV1);\n\tconst purgeGate = createMemoryPurgeGate({ registry: replicaRegistry, now });\n\tconst purgeJournal = createMemoryPurgeJournal();\n\tconst egressPolicy = createMemoryEgressPolicy({\n\t\tpolicyVersion: \"egress@1\",\n\t\tallowedSourceKinds: [\"tool\", \"entry\"],\n\t\tredactedPayloadFields: [],\n\t});\n\t// schedulerApi.recall 在生产工具面无调用点 (角色见上方\"非工具召回路径设施\"\n\t// 注释); 本 capability 的生产使用仅 submitObservation/submitCandidate (写入)。\n\tconst schedulerApi = createMemorySchedulerApi({\n\t\trecallAgent,\n\t\tmachine,\n\t\tlifecycle,\n\t\tpurgeGate,\n\t\tegressPolicy,\n\t\tfactInfoLookup: (memoryId) => {\n\t\t\tconst record = store.get(memoryId, { owner: BUILTIN_MEMORY_OWNER });\n\t\t\tif (!record) return undefined;\n\t\t\treturn {\n\t\t\t\tsourceRefs: record.atom.sourceRefs,\n\t\t\t\tpayload: record.atom.payload as Record<string, unknown>,\n\t\t\t};\n\t\t},\n\t});\n\t// Preference resolution/disambiguation over context-scoped recalls (2.4c/2.4d2):\n\t// stateless and deterministic — one instance per capability suffices.\n\tconst preferenceResolver = createPreferenceResolver();\n\tconst preferenceDisambiguator = createPreferenceDisambiguator();\n\t// Relation diffusion over the recall seeds (记忆网络接线, 2.4d4): a factory-\n\t// scoped deterministic network with one enabled one-hop adapter; disabled\n\t// adapters yield an explicit `disabled` result instead of silent degradation.\n\tconst memoryNetwork = createMemoryNetwork({\n\t\tadapters: [createRelationDiffusionAdapter({ maxHops: 1 })],\n\t});\n\n\t// ---- 语义召回通道状态机 (2.4d6 S1/S2; 拆分战役 slice 3b) ----\n\t// vectorEnsure 状态转换、装配分支 (服务/本地/下载/征询门) 与 dispose 闩锁\n\t// 已迁至 memory/vector-channel.ts: 共享闭包状态收拢为 channel 对象, 经 deps\n\t// 显式注入, 降级/投影经下方 vectorProjection (slice 3a) 上报。以下调用点\n\t// 全部薄委托。\n\tconst vectorChannelCtl = createMemoryVectorChannel({\n\t\tagentDir: context.agentDir,\n\t\tmemoryMode,\n\t\tlogger: api.logger,\n\t\thostOnnxRuntimeEntryPath: context.hostOnnxRuntimeEntryPath,\n\t\thostLancedbEntryPath: context.hostLancedbEntryPath,\n\t\thostTransformersEntryPath: context.hostTransformersEntryPath,\n\t\tinferenceServicePort: context.inferenceService?.port,\n\t\tinferenceServiceSpawnImpl: context.inferenceService?.spawnImpl,\n\t\tinferenceServiceModelsInPlace: context.inferenceService?.modelsInPlace,\n\t\tenablingOverride,\n\t\tinjectedComponents,\n\t\t// vectorProjection 声明在本对象之后; 委托箭头只在 download 运行期触达,\n\t\t// 与下方 supersededMemoryIds 依赖同构 (构造期不执行)。\n\t\tresetReconcile: () => vectorProjection.resetReconcile(),\n\t\treconcileOnce: () => vectorProjection.reconcileOnce(),\n\t});\n\n\t// 写入侧向量投影管线 (拆分战役 slice 3a): 串行队列、upsert/purge 埋点与启动\n\t// 对账搬至 memory/vector-projection.ts; 状态机归 memory/vector-channel.ts\n\t// (slice 3b), 投影经只读 deps 使用, degraded 转换经 markDegraded 回调上报。\n\tconst vectorProjection = createMemoryVectorProjection({\n\t\tvectorEnabled: () => vectorChannelCtl.enabled(),\n\t\tensureChannel: () => vectorChannelCtl.ensure(),\n\t\treadyChannel: () => vectorChannelCtl.readyChannel(),\n\t\tisChannelActive: () => {\n\t\t\tconst channelState = vectorChannelCtl.rawState();\n\t\t\treturn channelState === \"ready\" || channelState === \"degraded\";\n\t\t},\n\t\tisDisposed: () => vectorChannelCtl.isDisposed(),\n\t\t// 反向清理的跨进程守卫 (2026-10-07 终审): 只读扫描 owner 全部域账本的\n\t\t// memoryId 并集 (盘面扫描, 不触碰进程内 ledger 快照)。\n\t\trefreshCanonicalMemoryIds: () =>\n\t\t\tscanOwnerLedgerMemoryIds({ agentDir: context.agentDir, owner: BUILTIN_MEMORY_OWNER }),\n\t\tmarkDegraded: () => vectorChannelCtl.markDegraded(),\n\t\tlogger: api.logger,\n\t\towner: BUILTIN_MEMORY_OWNER,\n\t\tstore,\n\t\t// writeFace 声明在本对象之后; 委托箭头只在对账运行期触达 (构造期不执行)。\n\t\tsupersededMemoryIds: () => writeFace.supersededMemoryIds(),\n\t\tstatementOf,\n\t\ttagFacetsOf,\n\t});\n\n\t// ---- 写入面 (拆分战役 slice 5) ----\n\t// memory_write 工具、语义合并探测、写入 atom 构造与写后自动升档旁路已迁至\n\t// memory/write-face.ts: 写序计数/探测降级告警闩/升档闩归 write-face 工厂\n\t// 所有, 经 deps 显式注入; 状态机与写侧投影经对象只读消费。supersededMemoryIds\n\t// 供上方 vectorProjection 的对账 deps 消费 (构造期不执行, 依赖同构)。\n\tconst writeFace = createMemoryWriteFace({\n\t\tlogger: api.logger,\n\t\tregisterTool: (definition) => api.registerTool(definition),\n\t\tpublish: api.publish,\n\t\towner: BUILTIN_MEMORY_OWNER,\n\t\tsessionId,\n\t\tmanifest: capabilityManifest,\n\t\tcontractVersion: MEMORY_CONTRACT_VERSION,\n\t\tmemoryMode,\n\t\tagentDir: context.agentDir,\n\t\tnow,\n\t\tstore,\n\t\tschedulerApi,\n\t\tvectorProjection,\n\t\tvectorChannelCtl,\n\t\tresolveDomain,\n\t\tassertNonEmptyString,\n\t\tmemoryToolInput,\n\t\tidentityHash,\n\t\tstatementOf,\n\t\ttagFacetsOf,\n\t});\n\n\t// ---- 语义召回管线 (拆分战役 slice 4) ----\n\t// 双通道查询、RRF 融合、egress 门、语义召回与召回工具已迁至\n\t// memory/recall-pipeline.ts: 状态机经 vectorChannelCtl 只读面消费\n\t// (warming/ensure/征询/失败/degraded), 写侧投影的读侧等待经 settleProjection,\n\t// capability 模块级纯函数经 deps 注入避免双头定义。recallTool 进 registrations,\n\t// recallExecute 同时被钩子面 (slice 7) 直连。\n\tconst recallPipeline = createMemoryRecallPipeline({\n\t\tlogger: api.logger,\n\t\towner: BUILTIN_MEMORY_OWNER,\n\t\tsessionId,\n\t\tstore,\n\t\tresolveDomain,\n\t\tegressPolicy,\n\t\tpreferenceResolver,\n\t\tpreferenceDisambiguator,\n\t\tmemoryNetwork,\n\t\twarming: () => vectorChannelCtl.warming(),\n\t\tensureChannel: () => vectorChannelCtl.ensure(),\n\t\tdeclined: () => vectorChannelCtl.declined(),\n\t\tconsentAsk: () => vectorChannelCtl.consentAsk(),\n\t\tfailure: () => vectorChannelCtl.failure(),\n\t\trawState: () => vectorChannelCtl.rawState(),\n\t\tmarkDegraded: () => vectorChannelCtl.markDegraded(),\n\t\trecoverDegraded: () => vectorChannelCtl.recoverDegraded(),\n\t\tsettleProjection: () => vectorProjection.settle(),\n\t\tmemoryToolInput,\n\t\tassertNonEmptyString,\n\t\tisPlainObject,\n\t\tidentityHash,\n\t\tstatementOf,\n\t\tunwrapEgressStatement,\n\t\tregisterTool: (definition) => api.registerTool(definition),\n\t});\n\n\t// ---- 命令面 (拆分战役 slice 6) ----\n\t// memory_list/forget 工具、/memory 与 /promote 命令、memory_enable 征询执行\n\t// 面与 memory.scheduler 声明已迁至 memory/command-face.ts: 列表/删除/晋升/\n\t// 征询的命令执行面经 deps 显式注入, decline/download 仍薄委托 vectorChannelCtl\n\t// (slice 3b 先例); 升档声明状态经 writeFace 的只读面消费。\n\tconst commandFace = createMemoryCommandFace({\n\t\tregisterTool: (definition) => api.registerTool(definition),\n\t\tregisterCommand: (definition) => api.registerCommand(definition),\n\t\tpublish: api.publish,\n\t\tcapabilities: api.capabilities,\n\t\towner: BUILTIN_MEMORY_OWNER,\n\t\tsessionId,\n\t\tmanifest: capabilityManifest,\n\t\tagentDir: context.agentDir,\n\t\tmemoryMode,\n\t\tnow,\n\t\tstore,\n\t\tpurgeGate,\n\t\tpurgeJournal,\n\t\tvectorProjection,\n\t\tvectorChannelCtl,\n\t\tresolveDomain,\n\t\tassertNonEmptyString,\n\t\tmemoryToolInput,\n\t\tstatementOf,\n\t\tunwrapEgressStatement,\n\t\ttierUpgradePending: writeFace.tierUpgradePending,\n\t\tclearTierUpgrade: writeFace.clearTierUpgrade,\n\t});\n\n\t// ---- 注入钩子 (拆分战役 slice 7) ----\n\t// auto-recall 与 assistant 偏好卡已迁至 memory/hooks.ts: 钩子经 api 注册面\n\t// 订阅 (loop hook), 召回执行闭包经 deps 注入。bash 失败教训沉淀已停用\n\t// (记忆归档与整理设计 §14 裁决 1), 其职责由归档整理器承担。\n\tconst hooks = createMemoryHooks({\n\t\tlogger: api.logger,\n\t\tregisterLoopHook: api.registerLoopHook,\n\t\tsession: api.session,\n\t\towner: BUILTIN_MEMORY_OWNER,\n\t\tagentDir: context.agentDir,\n\t\tnow,\n\t\tisPlainObject,\n\t\tresolveSessionDomain: () => resolveSessionDomain(api),\n\t\trecallExecute: recallPipeline.recallExecute,\n\t\tvectorChannelCtl,\n\t});\n\n\t// ---- 归档整理器 (记忆归档与整理设计 §5-§7) ----\n\t// 归档即后台整理: session.archived 事件观察 + 启动 sweep 两个触发, 提交、\n\t// 幂等、journal 与暂停/续跑语义归 memory/curator.ts。宿主未开放归档面\n\t// (context 与 api.host 都无 sessionArchive) 时两个触发都不注册。\n\tconst curator = createMemoryCurator({\n\t\tapi,\n\t\tagentDir: context.agentDir,\n\t\towner: BUILTIN_MEMORY_OWNER,\n\t\tnow,\n\t\tmanifest: capabilityManifest,\n\t\tstore,\n\t\tresolveDomain,\n\t\tvectorProjection,\n\t\tidentityHash,\n\t\tsessionArchive: context.sessionArchive ?? api.host?.sessionArchive,\n\t});\n\n\tconst registrations = [\n\t\t// 首位 = 宿主反向 dispose 时的末位: 先拆工具/命令/钩子等消费者, 最后关\n\t\t// 底层通道, 避免消费者在通道已关后仍触发向量操作报错。释放本体\n\t\t// (capabilityTeardown, slice 3b) 在 memory/vector-channel.ts。\n\t\t{\n\t\t\tid: \"memory:capability-teardown\",\n\t\t\tkind: \"capability-teardown\",\n\t\t\tdispose: () => vectorChannelCtl.dispose(),\n\t\t},\n\t\twriteFace.writeTool,\n\t\trecallPipeline.recallTool,\n\t\tcommandFace.listTool,\n\t\tcommandFace.forgetTool,\n\t\tcommandFace.enableTool,\n\t\tcommandFace.memoryCommand,\n\t\tcommandFace.promoteCommand,\n\t\tcommandFace.schedulerCapability,\n\t\thooks.autoRecallHook,\n\t\thooks.preferenceCardHook,\n\t\t...curator.registrations,\n\t];\n\treturn {\n\t\tregistrations,\n\t\tsettleVectorWork: async () => {\n\t\t\tawait vectorProjection.settle();\n\t\t},\n\t\tvectorState: (): \"off\" | MemoryCapabilityStateV1 => vectorChannelCtl.state(),\n\t\t// 触发惰性 enabling (已注入组件时已就绪) 并等待其落定: ready 或结构化失败。\n\t\tenablingOutcome: () => vectorChannelCtl.enablingOutcome(),\n\t\tteardown: () => vectorChannelCtl.dispose(),\n\t};\n}\n"]}
1
+ {"version":3,"file":"capability.js","sourceRoot":"","sources":["../src/capability.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoFG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AACtC,OAAO,EAAE,IAA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ACpB,WAAW,CAAC,UAAU;QACtB,WAAW,CAAC,UAAU;QACtB,WAAW,CAAC,aAAa;QACzB,WAAW,CAAC,cAAc;QAC1B,WAAW,CAAC,mBAAmB;QAC/B,KAAK,CAAC,cAAc;QACpB,KAAK,CAAC,kBAAkB;QACxB,GAAG,OAAO,CAAC,aAAa;KACxB,CAAC;IACF,OAAO;QACN,aAAa;QACb,gBAAgB,EAAE,KAAK,IAAI,EAAE,CAAC;YAC7B,MAAM,gBAAgB,CAAC,MAAM,EAAE,CAAC;QAAA,CAChC;QACD,WAAW,EAAE,GAAoC,EAAE,CAAC,gBAAgB,CAAC,KAAK,EAAE;QAC5E,sGAAkD;QAClD,eAAe,EAAE,GAAG,EAAE,CAAC,gBAAgB,CAAC,eAAe,EAAE;QACzD,QAAQ,EAAE,GAAG,EAAE,CAAC,gBAAgB,CAAC,OAAO,EAAE;KAC1C,CAAC;AAAA,CACF","sourcesContent":["/**\n * First-party builtin memory capability (统一修复轮 A, 方案系统设计 §6.1 + §11,\n * 方案实施计划 §11 A 路) — the model-facing write/recall/list/forget surface\n * over the M5 Memory Foundation.\n *\n * Every operation is suite-scoped by construction: the suiteId comes from the\n * session's suite binding entry (SUITE_SESSION_ENTRY_TYPE, written by the sdk\n * at session creation) and is NEVER a tool parameter, so the model cannot\n * widen or switch its memory domain (防越权). Sessions without a binding fall\n * back to the \"legacy\" domain with a diagnostic. Writes go through the\n * scheduler facade (observation → candidate → committed) plus a durable JSONL\n * ledger append (src/memory/ledger.ts, the store's persistent replica); recall\n * runs through the memory-recall-agent with the suiteId passthrough filter and\n * the egress gate; forget goes through the canonical purge gate\n * (user-immediate) and journal, physically rewriting the ledger (forget 后真\n * 物理删除).\n *\n * Domain resolution is LAZY, per tool call (统一修复轮 B1 复审修复): the sdk\n * appends the suite binding entry only after `new AgentSession` returns (the\n * constructor's synchronous runtime build already runs this factory), so a\n * factory-time resolution always saw an empty branch and every new session\n * fell back to the legacy domain. Instead, each tool handler resolves the\n * domain at call time — the binding entry is on the branch by then (creation\n * appends it; resumed sessions carry it in their history) — and the per-domain\n * ledger is created, loaded, and replayed into the store on the first call in\n * that domain (Map<domain, ledger> cache, no memoization of the domain\n * itself). The store stays one per-capability-instance singleton across\n * domains: the atom `suiteId` field carries the read boundary; the ledger is\n * only the per-domain durable replica.\n *\n * Concurrency envelope (统一修复轮 H1, #7 深度修复; WP-F 关洞修复): ledger\n * appends AND the forget path's full-file rewrite serialize competing\n * processes through the ledger's `.lock` sibling file (exclusive create +\n * poll, 5 s timeout, stale-lock stealing — src/memory/ledger.ts), and both\n * write paths run open → write → fsync → close, so a hard crash cannot lose\n * a write that returned to its caller. A lock timeout or IO/fsync failure\n * throws out of the tool handler, so the model sees the error instead of a\n * silently lost write. Remaining boundaries: the lock is atomic only on\n * local filesystems; a rewrite publishes the calling process's in-memory\n * view without merging rows another process appended after its last load\n * (the forget caller owns that reconciliation); fsync does not cover\n * directory entries, so a crash before rewrite's rename leaves the previous\n * file intact; an append whose fsync failed stays unacknowledged though it\n * may already be readable — the loader's duplicate tolerance covers an\n * unacknowledged retry.\n *\n * Global mode gate (2.4d6 S1, 记忆系统语义化重设计 §3): `memory.mode` is\n * `\"off\"` (default) | `\"light\"` | `\"full\"`; off means the whole memory family\n * is NOT registered (the suite membership skips the plugin; the factory\n * itself returns zero registrations for direct callers). light/full run an\n * enabling state machine (local checks → model load/download → smoke →\n * ready; failure → failed with a four-option action list and the effective\n * mode falls back to off for this instance).\n *\n * Semantic recall (2.4d6 S2, 设计 §4): memory_recall has exactly one\n * retrieval path — embed → KNN depth50 + FTS depth50 → RRF k=60 top20 →\n * cross-encoder rerank → store lookup (owner/suite/scope/expiry). The legacy\n * tag-wordform bridge (query-token → tag-facet anchors, recency fallback\n * page) is retired as a retrieval semantic; tags still ride the FTS body and\n * the memory_list management face. Degradation ladder (never thrown at the\n * model): rerank failure → RRF order; vector failure → FTS-only with\n * recency ordering; FTS/index failure → KNN-only; both channels down →\n * recency enumeration over the domain; total failure → degraded packet.\n * `memoryIdEquals`-style primary-key lookup survives as the exact-id fast\n * path (reference semantics, not retrieval).\n *\n * Semantic write merge (2.4d6 S3, 设计 §5 + 实施计划 S3 标定定版): in mode\n * \"full\" every memory_write probes the projection BEFORE the canonical commit\n * (embed + same-owner KNN top-5) because atoms are immutable — the outcome's\n * relations must ride the atom's one commit. Merge condition (calibrated on\n * bge-m3): cos ≥ 0.72, or 0.55 ≤ cos < 0.72 with a case-insensitive tag\n * overlap. A merge commits the NEW atom with a one-way `supersedes` relation\n * to the neighbor (the old entry keeps its memoryId and stays addressable via\n * primary-key lookup) while the projection upserts the new row and removes the\n * superseded one; startup reconciliation never re-adds superseded rows.\n * 0.55 ≤ cos < 0.72 without a tag overlap is the conflict band: both entries\n * stay, and the new atom carries one-way `conflict` relations. Below that (or\n * no neighbor): a plain new entry. bge-small-zh similarity distributions\n * overlap (标定: 余弦不可用作去重信号) → light mode never probes and stays\n * byte-identical to the pre-S3 behavior. Recall filters superseded entries\n * after the store lookup (only while their successor is among the candidates,\n * so forgetting the successor revives the old entry). The Foundation\n * (owner, observationId) idempotency is untouched: replays never consume a\n * probe outcome.\n */\nimport { readdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type {\n\tMemoryCapabilityOverrideV1,\n\tMemoryModeV1,\n\tMemoryStorageComponentsV1,\n\tMemoryVectorComponentsOverrideV1,\n\tSessionArchiveHostV1,\n} from \"@agent-forge/plugin-sdk\";\nimport {\n\ttype CapabilityAPI,\n\ttype DisposableRegistration,\n\tEXPERIMENTAL_PUBLIC_API_VERSION,\n} from \"@agent-forge/plugin-sdk\";\n\n// 记忆公共契约的权威定义处已是 plugin-sdk(D-075 S4-4 第一批迁入);此处 re-export\n// 维持宿主历史导出面(宿主第二批收口后由宿主 re-export SDK)。\nexport {\n\tMEMORY_RECALL_TOOL_NAME,\n\ttype MemoryCapabilityOverrideV1,\n\ttype MemoryEnablingOverrideV1,\n\ttype MemoryModeV1,\n\ttype MemoryStorageComponentsV1,\n\ttype MemoryVectorComponentsOverrideV1,\n} from \"@agent-forge/plugin-sdk\";\n// 拆分战役 slice 1/3b: 征询持久化(enabling.ts 征询域)与向量常量/状态类型\n// (vector-channel.ts)随模块迁出,经 re-export 维持 capability.ts 的历史\n// 导出面(index.ts `export *` 与 entry.ts / inference-service-main.ts 的\n// 既有 import 不变;vector-channel.ts 不进 index.ts,slice 2 先例)。\nexport {\n\tMEMORY_AGENT_DIR_CONFIG_RELATIVE_PATH,\n\tMEMORY_CONSENT_DECLINED_VALUE,\n\twriteMemoryConsentDeclined,\n\twriteMemorySettingsMode,\n} from \"./memory/enabling.ts\";\n// 拆分战役 slice 7: auto-recall 注入标记/免责行随钩子面迁入 hooks.ts, 经\n// re-export 维持 capability.ts 的历史导出面 (index.ts `export *` 与既有 import\n// 不变; hooks.ts 本体不进 index.ts, recall-pipeline.ts 先例)。lessons 开关解析\n// 已随实时教训停用一并移除 (记忆归档与整理设计 §14 裁决 1)。\nexport {\n\tMEMORY_AUTO_RECALL_DEADLINE_MS,\n\tMEMORY_AUTO_RECALL_DISCLAIMER,\n\tMEMORY_AUTO_RECALL_MARKER,\n} from \"./memory/hooks.ts\";\n// 拆分战役 slice 4: MEMORY_TOOLS_GUIDE 随召回管线迁入 recall-pipeline.ts, 经\n// re-export 维持 capability.ts 的历史导出面 (宿主与测试的既有 import 不变;\n// recall-pipeline.ts 本体不进 index.ts, vector-channel.ts slice 2 先例)。\nexport { MEMORY_TOOLS_GUIDE } from \"./memory/recall-pipeline.ts\";\nexport {\n\ttype MemoryCapabilityStateV1,\n\ttype MemoryConsentNeededV1,\n\ttype MemoryEnablingFailureV1,\n\tVECTOR_DB_DIRNAME,\n\tVECTOR_MODEL_CACHE_DIRNAME,\n\tVECTOR_RERANKER_MODEL_ID,\n} from \"./memory/vector-channel.ts\";\n// 拆分战役 slice 5: 档位自动升级阈值随写入面迁入 write-face.ts, 经 re-export\n// 维持 capability.ts 的历史导出面。\nexport { MEMORY_TIER_UPGRADE_STORE_THRESHOLD } from \"./memory/write-face.ts\";\n\nimport { createMemoryCandidateMachine } from \"./memory/candidates.ts\";\nimport { createMemoryCommandFace } from \"./memory/command-face.ts\";\nimport { createMemoryCurator } from \"./memory/curator.ts\";\nimport { createMemoryEgressPolicy } from \"./memory/egress-policy.ts\";\nimport type { MemoryAtomV1 } from \"./memory/foundation.ts\";\nimport { createMemoryHooks } from \"./memory/hooks.ts\";\nimport { createDurableMemoryLedger, type DurableMemoryLedgerV1, scanOwnerLedgerMemoryIds } from \"./memory/ledger.ts\";\nimport { createMemoryLifecycleManager } from \"./memory/lifecycle.ts\";\nimport { createMemoryNetwork, createRelationDiffusionAdapter } from \"./memory/memory-network.ts\";\nimport { createPreferenceDisambiguator } from \"./memory/preference-disambiguator.ts\";\nimport { createPreferenceResolver } from \"./memory/preference-resolver.ts\";\nimport { createMemoryPurgeGate, createMemoryReplicaRegistry, type MemoryReplicaV1 } from \"./memory/purge.ts\";\nimport { createMemoryPurgeJournal } from \"./memory/purge-journal.ts\";\nimport { createMemoryRecallAgent } from \"./memory/recall-agent.ts\";\nimport { createMemoryRecallIndex } from \"./memory/recall-index.ts\";\nimport { createMemoryRecallPipeline } from \"./memory/recall-pipeline.ts\";\nimport { sweepExpiredMemories } from \"./memory/retention-sweep.ts\";\nimport { createMemoryScheduler } from \"./memory/scheduler.ts\";\nimport { createMemorySchedulerApi } from \"./memory/scheduler-api.ts\";\nimport { createFirstPartyRetentionRegistry, createMemoryStore } from \"./memory/store.ts\";\nimport { type SuiteMemoryDomainV1, suiteMemoryDomainName } from \"./memory/suite-memory.ts\";\nimport { MEMORY_CONTRACT_VERSION_V2 } from \"./memory/transfer.ts\";\nimport type { MemoryCapabilityStateV1, MemoryEnablingFailureV1 } from \"./memory/vector-channel.ts\";\nimport { createMemoryVectorChannel } from \"./memory/vector-channel.ts\";\nimport { createMemoryVectorProjection } from \"./memory/vector-projection.ts\";\nimport { createMemoryWriteFace, TAG_FACET_NAMESPACE } from \"./memory/write-face.ts\";\n\nexport const capabilityManifest = {\n\tid: \"agent-forge.builtin.memory\",\n\tversion: \"0.1.0\",\n\tapiVersion: EXPERIMENTAL_PUBLIC_API_VERSION,\n\trequiredCapabilities: [\"session\", \"events\", \"tools\"],\n\tprovides: [{ id: \"memory.scheduler\", version: 1, kind: \"service\" }],\n} as const;\n\n/**\n * 解析后的全局模式 (2.4d6 S1)。`invalidEnvValue` 非空 = 配置的环境值非法,\n * 已 fail-closed 回 off, 调用方负责以此输出一次 warn; `invalidSettingsValue`\n * 非空 = settings.json 的 `memory.mode` 非法, 同为 fail-closed off 并输出一次\n * 诊断; `legacyEnvUsed` = 模式由旧别名 `AGENT_FORGE_MEMORY_VECTOR` 决定 (兼容\n * 期: 仅当 `AGENT_FORGE_MEMORY_MODE` 与 settings 均未定档时生效, 一个发布周期\n * 后移除)。\n */\nexport interface MemoryModeResolutionV1 {\n\treadonly mode: MemoryModeV1;\n\treadonly invalidEnvValue?: string;\n\treadonly invalidSettingsValue?: string;\n\treadonly legacyEnvUsed?: boolean;\n}\n\nconst isMemoryModeV1 = (value: string): value is MemoryModeV1 =>\n\tvalue === \"off\" || value === \"light\" || value === \"full\";\n\n/**\n * memory.mode 解析 (2.4d6 S1)。优先级: context 显式值 → 环境变量\n * `AGENT_FORGE_MEMORY_MODE` → settings.json `memory.mode` (settingsMode 参, 持\n * 久配置面) → 旧别名 `AGENT_FORGE_MEMORY_VECTOR` (兼容期) → 默认 light\n * (2026-10-05 用户裁决翻转默认 off→light, 对齐主流编程助手开箱即用方向)。env 是\n * 临时覆盖、settings 是持久配置 (env > 文件, 沿用本仓 suite 解析先例)。任何\n * 非法配置值 fail-closed 为 off 并在结果中携带原值供调用方告警一次, 绝不静默\n * 改档或意外下载。\n */\nexport function resolveMemoryMode(\n\texplicitMode: string | undefined,\n\tenv: Readonly<Record<string, string | undefined>> = process.env,\n\tsettingsMode?: string,\n): MemoryModeResolutionV1 {\n\tif (explicitMode !== undefined) {\n\t\tif (isMemoryModeV1(explicitMode)) return { mode: explicitMode };\n\t\treturn { mode: \"off\", invalidEnvValue: explicitMode };\n\t}\n\tconst configured = env.AGENT_FORGE_MEMORY_MODE?.trim().toLowerCase();\n\tif (configured !== undefined && configured !== \"\") {\n\t\tif (isMemoryModeV1(configured)) return { mode: configured };\n\t\treturn { mode: \"off\", invalidEnvValue: configured };\n\t}\n\t// 持久配置面: settings.json memory.mode。设置但非法同样 fail-closed, 不再\n\t// 回落旧别名 (与非法 env 的先例一致)。\n\tconst fromSettings = settingsMode?.trim().toLowerCase();\n\tif (fromSettings !== undefined && fromSettings !== \"\") {\n\t\tif (isMemoryModeV1(fromSettings)) return { mode: fromSettings };\n\t\treturn { mode: \"off\", invalidSettingsValue: fromSettings };\n\t}\n\t// 兼容期别名: AGENT_FORGE_MEMORY_VECTOR (混合检索工程化的旧开关), 语义并入\n\t// AGENT_FORGE_MEMORY_MODE, 仅当新变量与 settings 均未定档时生效; 一个发布\n\t// 周期后删除。\n\tconst legacy = env.AGENT_FORGE_MEMORY_VECTOR?.trim().toLowerCase();\n\tif (legacy !== undefined && legacy !== \"\") {\n\t\tif (isMemoryModeV1(legacy)) return { mode: legacy, legacyEnvUsed: true };\n\t\treturn { mode: \"off\", invalidEnvValue: legacy, legacyEnvUsed: true };\n\t}\n\treturn { mode: \"light\" };\n}\n\n/** Host-provided factory context; provided by the host session assembly (sdk suite membership). */\nexport interface MemoryCapabilityContext {\n\t/** Agent home directory — roots the durable ledger under `<agentDir>/memory/`. */\n\treadonly agentDir: string;\n\t/**\n\t * 宿主已解析的 onnxruntime-node 入口绝对路径 (D-075 安装店重依赖可见性):\n\t * 安装店副本无 node_modules, 插件内 createRequire 解析不到; 宿主装载器把\n\t * hostDependencyPaths 注入 manifest config, entry 提取后经本字段传入。\n\t * 缺省 (源码/工作区直载) 走插件内双通道自解析。\n\t */\n\treadonly hostOnnxRuntimeEntryPath?: string;\n\t/** 同上——@lancedb/lancedb 入口路径 (向量索引运行时按绝对路径原生 import)。 */\n\treadonly hostLancedbEntryPath?: string;\n\t/** 同上——@huggingface/transformers 入口路径 (embedding/reranker 运行时用)。 */\n\treadonly hostTransformersEntryPath?: string;\n\t/**\n\t * 记忆全局档位 (2.4d6 S1)。缺省解析顺序: 本字段 → 环境变量\n\t * `AGENT_FORGE_MEMORY_MODE` → {@link MemoryCapabilityContext.memory.settingsMode}\n\t * → 旧别名 `AGENT_FORGE_MEMORY_VECTOR` (兼容期) → 默认 off (整个家族不注册)。\n\t * 装配方 (sdk) 可经本字段显式定档。\n\t */\n\treadonly memory?: {\n\t\treadonly mode?: MemoryModeV1;\n\t\t/**\n\t\t * settings.json `memory.mode` 的原样值 (持久配置面, 优先级低于 env);\n\t\t * 类型面只允许合法档位, 手改文件的非法值原样透传并由\n\t\t * {@link resolveMemoryMode} fail-closed 处理。\n\t\t */\n\t\treadonly settingsMode?: string;\n\t};\n\t/**\n\t * 测试专用注入 (架构宪法: deterministic mock AI 门禁)。经装配上下文携带时,\n\t * 装配方原样透传给工厂; 与 {@link createCapabilityWithVectorComponents}\n\t * 的第三参语义一致, 第三参优先。\n\t */\n\treadonly vectorComponents?: MemoryCapabilityOverrideV1;\n\t/**\n\t * 共享推理服务装配缝 (Slice B2, 记忆共享推理服务设计 §3.1/§3.3/§3.6)。\n\t * 缺省 (生产) = 真实路径: 模型在位时装配经 TCP loopback 走常驻服务,\n\t * 连不上则懒 spawn 插件 bin (`agent-forge-memory-inference`), 重连失败按\n\t * enabling failed 呈现 (裁决 A: 不回退本地装配)。测试注入替换对应环节\n\t * (deterministic 门禁): `port` 直连测试服务、`spawnImpl` 替换进程拉起、\n\t * `modelsInPlace` 声明模型在位 (跳过文件检查, 免写假权重文件)。\n\t * loadImpl enabling 缝与 vectorComponents 注入仍走本地装配路径 (既有语义)。\n\t */\n\treadonly inferenceService?: {\n\t\treadonly port?: number;\n\t\treadonly spawnImpl?: (\n\t\t\tagentDir: string,\n\t\t\tmode: \"light\" | \"full\",\n\t\t\tport: number,\n\t\t\t/** spawn 异步失败 (EACCES/ENOMEM 等) 的回调; 缺省实现经 child 'error' 事件馈入。 */\n\t\t\tonError?: (error: Error) => void,\n\t\t) => Promise<void>;\n\t\treadonly modelsInPlace?: boolean;\n\t};\n\t/**\n\t * 记忆底层组件注入 (扩展位盘点 A1/A2 的宿主装配通道): store/ledger 工厂与\n\t * 向量组件公共契约, 缺省成员走内置默认实现。装配方经\n\t * `CreateAgentSessionOptions.memoryCapability.storage` 携带。\n\t */\n\treadonly storage?: MemoryStorageComponentsV1;\n\t/**\n\t * 会话归档协调面 (记忆归档与整理设计 §4/§8): 整理器读归档会话条目与回写\n\t * curation 状态的唯一通道。缺省回落宿主服务 `api.host.sessionArchive`(生产\n\t * 装配路径);两者都缺席 = 宿主不开放归档,整理器的两个触发(归档事件观察与\n\t * 启动 sweep)都不注册,记忆家族其余能力不受影响。本字段同时是测试注入缝\n\t * (deterministic mock AI 门禁:curator 测试经它注入 fake archive)。\n\t */\n\treadonly sessionArchive?: SessionArchiveHostV1;\n}\n\nconst isVectorComponentsOverride = (\n\toverride: MemoryCapabilityOverrideV1,\n): override is MemoryVectorComponentsOverrideV1 => \"embedProvider\" in override && \"vectorIndex\" in override;\n\n/**\n * 默认档判定 (征询拒绝只抑制默认档): 显式值、env、settings、旧别名四层全部\n * 未定档时, 模式来自出厂默认档 (light)。与 resolveMemoryMode 的优先级链同构,\n * 不改 resolver 返回面。\n */\nexport function memoryModeSourceIsDefault(\n\texplicitMode: string | undefined,\n\tenv: Readonly<Record<string, string | undefined>>,\n\tsettingsMode?: string,\n): boolean {\n\treturn (\n\t\texplicitMode === undefined &&\n\t\t(env.AGENT_FORGE_MEMORY_MODE?.trim() ?? \"\") === \"\" &&\n\t\t(env.AGENT_FORGE_MEMORY_VECTOR?.trim() ?? \"\") === \"\" &&\n\t\t(settingsMode?.trim() ?? \"\") === \"\"\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\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * 双约定工具输入读取(对齐 subagent-delegate 的 objectInput):capability invoke\n * 面单参约定下第一参即输入(第二参是宿主注入的 toolExecutionContext),legacy 5 参\n * 约定(toolCallId 字符串打头)下输入在第二参。生产装配恒向 runtime invoke 面注入\n * toolExecutionContext 作为 execute 第二参(公共契约),因此\"第二参非 undefined 即\n * 输入\"的判定会把 context 误当输入(content/query 等读成 undefined)。改按形状判定:\n * 第一参是普通对象即取第一参,否则看第二参;两者皆非对象时返回空记录,交由各工具\n * 的字段断言报错。\n */\nfunction memoryToolInput(first: unknown, second: unknown): Record<string, unknown> {\n\tconst primary = isPlainRecord(first) ? first : second;\n\treturn isPlainRecord(primary) ? primary : {};\n}\n\n/** FNV-1a 32-bit — deterministic identity from the given value (code-memory 同构). */\nfunction identityHash(value: string): string {\n\tlet hash = 0x811c9dc5;\n\tfor (let index = 0; index < value.length; index += 1) {\n\t\thash ^= value.charCodeAt(index);\n\t\thash = Math.imul(hash, 0x01000193);\n\t}\n\treturn (hash >>> 0).toString(36);\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * Session protocol key of the suite binding entry (方案设计 §10.1). The value\n * mirrors the authoritative `SUITE_SESSION_ENTRY_TYPE` in\n * src/suites/suite-loader.ts — pinned by a deterministic test in\n * test/capabilities-builtin.test.ts. Declared locally so the capability module\n * graph stays free of the assembler's bundled-loader dependency chain.\n */\nconst SUITE_SESSION_ENTRY_TYPE = \"suite\";\n\n/**\n * Owner (isolation principal) of every atom this capability writes. The\n * Foundation owner is the store/facade isolation identity; this product ships\n * one local user per agentDir, so one stable owner id partitions the ledger\n * directory `<agentDir>/memory/<owner>/ledger-<suiteId|\"legacy\">.jsonl`.\n */\nexport const BUILTIN_MEMORY_OWNER = \"local-user\";\n\n/** Contract version written by this capability (@2 atoms carry suiteId). */\nconst MEMORY_CONTRACT_VERSION = MEMORY_CONTRACT_VERSION_V2;\n\n/**\n * Suite binding entry ids already warned about (统一修复轮终审 minor 3):\n * resolveSessionDomain runs on EVERY memory tool call, so without this\n * module-level set one malformed binding entry would repeat the warning on\n * each call and flood the log.\n */\nconst malformedBindingWarned = new Set<string>();\n\n/**\n * Resolves the session's suite binding domain from the branch entries: the\n * LAST suite entry wins (the sdk appends one at session creation). A binding\n * with a malformed payload counts as unbound — the legacy fallback is\n * fail-safe (its atoms are invisible to every real suite) and a diagnostic is\n * logged when the logger capability is available. Called per tool call —\n * never captured at factory time (统一修复轮 B1: the binding entry is appended\n * after the session constructor ran this factory).\n */\nfunction resolveSessionDomain(api: CapabilityAPI): SuiteMemoryDomainV1 {\n\tconst entries = api.session?.getBranchEntries() ?? [];\n\tfor (let index = entries.length - 1; index >= 0; index -= 1) {\n\t\tconst entry = entries[index];\n\t\tif (entry.type !== \"custom\" || entry.customType !== SUITE_SESSION_ENTRY_TYPE) continue;\n\t\tconst data = entry.data;\n\t\tconst suiteId = isPlainObject(data) ? data.suiteId : undefined;\n\t\tif (typeof suiteId === \"string\" && suiteId.trim() !== \"\") {\n\t\t\treturn { kind: \"suite\", suiteId };\n\t\t}\n\t\tif (!malformedBindingWarned.has(entry.id)) {\n\t\t\tmalformedBindingWarned.add(entry.id);\n\t\t\tapi.logger?.warn(\"suite binding entry has a malformed payload; falling back to the legacy memory domain\", {\n\t\t\t\tentryId: entry.id,\n\t\t\t});\n\t\t}\n\t\treturn { kind: \"legacy\" };\n\t}\n\treturn { kind: \"legacy\" };\n}\n\n/** Recency-first payload projection: unwraps the `{ statement }` payload convention. */\nfunction statementOf(payload: unknown): string {\n\tif (isPlainObject(payload) && typeof payload.statement === \"string\") return payload.statement;\n\treturn JSON.stringify(payload);\n}\n\n/** The egress gate re-derives statements as payload JSON; unwrap for the model face. */\nfunction unwrapEgressStatement(statement: string): string {\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(statement);\n\t\tif (isPlainObject(parsed) && typeof parsed.statement === \"string\") return parsed.statement;\n\t} catch {\n\t\t// Not payload JSON — surface it verbatim.\n\t}\n\treturn statement;\n}\n\nfunction tagFacetsOf(atom: MemoryAtomV1): string[] {\n\treturn atom.facets\n\t\t.filter((facet) => facet.namespace === TAG_FACET_NAMESPACE && facet.key === \"tag\")\n\t\t.map((facet) => facet.value);\n}\n\n/**\n * Creates the builtin memory capability: four tools (memory_write,\n * memory_recall, memory_list, memory_forget) over a per-session Foundation\n * stack whose durable replica is the per-domain JSONL ledger under\n * `<agentDir>/memory/<owner>/ledger-<domain>.jsonl`, resolved lazily at each\n * tool call (统一修复轮 B1).\n *\n * `memory.mode` gates the whole family (2.4d6 S1): a resolved mode of \"off\"\n * registers NOTHING (zero tools, zero commands, zero events) — the factory\n * returns an empty registration list and logs the one-line disabled\n * declaration. suite capability membership decides earlier at the assembly\n * level (设计 §3.2 \"禁用 = 不注册\").\n *\n * `override` is the test-only seam (deterministic mock AI 门禁): full vector\n * components skip the real transformers/lancedb assembly entirely; enabling\n * seams keep the real assembly but replace the transformers loader.\n */\nexport function createMemoryCapability(\n\tapi: CapabilityAPI,\n\tcontext: MemoryCapabilityContext,\n\toverride?: MemoryCapabilityOverrideV1,\n): readonly DisposableRegistration[] {\n\tconst harness = createMemoryCapabilityHarness(api, context, override);\n\treturn harness.registrations;\n}\n\n/** Test-only harness over the capability: registration list plus state-work hooks. */\nexport interface MemoryVectorCapabilityHarnessV1 {\n\treadonly registrations: readonly DisposableRegistration[];\n\t/** Resolves after every vector op queued so far (reconcile/upsert/purge) settled. */\n\tsettleVectorWork(): Promise<void>;\n\tvectorState(): \"off\" | MemoryCapabilityStateV1;\n\t/**\n\t * Resolves once the enabling attempt settles (immediately for injected\n\t * components): ready, or the structured failure (reason + action list).\n\t */\n\tenablingOutcome(): Promise<\"ready\" | MemoryEnablingFailureV1>;\n\t/**\n\t * 释放共享推理服务连接 (服务路径) 或本地向量索引 (本地装配路径)。幂等: 引用\n\t * 清空后二次调用为 no-op。同名注册项挂 registrations 首位——宿主反向逐个\n\t * dispose 时它最后执行 (先拆消费者、后关通道)。\n\t */\n\tteardown(): void;\n}\n\n/**\n * Test-only assembly variant: the capability with an injected override (full\n * vector components skip real assembly; enabling seams redirect the model\n * loader on the real path). Public tool names, schemas, and return shapes are\n * identical to {@link createMemoryCapability}.\n */\nexport function createCapabilityWithVectorComponents(\n\tapi: CapabilityAPI,\n\tcontext: MemoryCapabilityContext,\n\toverride: MemoryCapabilityOverrideV1,\n): MemoryVectorCapabilityHarnessV1 {\n\t// Tool-face test stubs hand-write partial CapabilityAPIs that predate the\n\t// D-071 auto-recall hook; default registerLoopHook to a no-op so those\n\t// tests keep exercising just the tool face. Real CapabilityAPIs always\n\t// carry the method (production path never hits this default) — the `in`\n\t// check is runtime-only because the stubs bypass the declared type.\n\tconst apiWithHooks: CapabilityAPI =\n\t\t\"registerLoopHook\" in api\n\t\t\t? api\n\t\t\t: Object.assign(Object.create(null) as CapabilityAPI, api, {\n\t\t\t\t\tregisterLoopHook: (): DisposableRegistration => ({\n\t\t\t\t\t\tid: \"test:noop-loop-hook\",\n\t\t\t\t\t\tkind: \"loop-hook\",\n\t\t\t\t\t\tdispose() {},\n\t\t\t\t\t}),\n\t\t\t\t});\n\treturn createMemoryCapabilityHarness(apiWithHooks, context, override);\n}\n\nfunction createMemoryCapabilityHarness(\n\tapi: CapabilityAPI,\n\tcontext: MemoryCapabilityContext,\n\toverride?: MemoryCapabilityOverrideV1,\n): MemoryVectorCapabilityHarnessV1 {\n\tassertNonEmptyString(context.agentDir, \"MemoryCapabilityContext.agentDir\");\n\tconst now = (): number => Date.now();\n\tconst sessionId = api.session?.getSessionId() ?? \"no-session\";\n\n\t// 全局档位解析 (2.4d6 S1): context 显式 → env → settings.json → 默认 off。\n\t// 非法 env/settings 值 fail-closed 回 off 并各告警一次; off = 家族整体不注册\n\t// (零工具零命令零事件)。\n\tconst modeResolution = resolveMemoryMode(context.memory?.mode, undefined, context.memory?.settingsMode);\n\tif (modeResolution.invalidEnvValue !== undefined) {\n\t\tapi.logger?.warn(\n\t\t\t`invalid AGENT_FORGE_MEMORY_MODE value \"${modeResolution.invalidEnvValue}\"; memory stays off (fail-closed)`,\n\t\t);\n\t}\n\tif (modeResolution.invalidSettingsValue !== undefined) {\n\t\tapi.logger?.warn(\n\t\t\t`invalid memory.mode setting \"${modeResolution.invalidSettingsValue}\"; memory stays off (fail-closed)`,\n\t\t);\n\t}\n\tif (modeResolution.mode === \"off\") {\n\t\tapi.logger?.info(\"memory disabled (mode=off)\");\n\t\treturn {\n\t\t\tregistrations: [],\n\t\t\tsettleVectorWork: async () => {},\n\t\t\tvectorState: () => \"off\",\n\t\t\tenablingOutcome: async () => \"ready\",\n\t\t\tteardown: () => {},\n\t\t};\n\t}\n\tconst memoryMode = modeResolution.mode;\n\tconst vectorComponentsOverride: MemoryCapabilityOverrideV1 | undefined =\n\t\toverride ?? context.vectorComponents ?? context.storage?.vectorComponents;\n\tconst injectedComponents =\n\t\tvectorComponentsOverride !== undefined && isVectorComponentsOverride(vectorComponentsOverride)\n\t\t\t? vectorComponentsOverride\n\t\t\t: undefined;\n\tconst enablingOverride =\n\t\tvectorComponentsOverride !== undefined && !isVectorComponentsOverride(vectorComponentsOverride)\n\t\t\t? vectorComponentsOverride\n\t\t\t: undefined;\n\n\t// Store: one per-capability-instance singleton. Atoms of every domain this\n\t// session touches live here together — the atom `suiteId` field carries the\n\t// read boundary (suite queries filter through it; the ledger is only the\n\t// per-domain durable replica). The injected storeFactory (扩展位 A1) replaces\n\t// the default store wholesale: the implementation owns retention semantics.\n\tconst retentionRegistry = createFirstPartyRetentionRegistry();\n\tconst store =\n\t\tcontext.storage?.storeFactory?.({\n\t\t\tagentDir: context.agentDir,\n\t\t\towner: BUILTIN_MEMORY_OWNER,\n\t\t\tnow,\n\t\t}) ?? createMemoryStore({ retentionRegistry, now });\n\n\t// Durable replica per domain, created and loaded lazily on the first tool\n\t// call in that domain (统一修复轮 B1 复审修复): the sdk appends the suite\n\t// binding entry only after the session constructor ran this factory, so the\n\t// domain (and with it the ledger to replay) is only known at call time.\n\t// Write identity is deterministic: observationId `memory_write:<sessionId>:<n>`\n\t// hashes into the memoryId. The counter is instance-local, so a resumed session\n\t// re-derives its floor from the replayed ledger (resolveDomain): a persisted\n\t// observationId of this session marks its sequence as taken — the store rejects\n\t// a regenerated memoryId (canonical atoms are immutable), which would fail every\n\t// replayed-sequence write after resume (write → dispose → resume → write).\n\tconst domainLedgers = new Map<string, DurableMemoryLedgerV1>();\n\t/**\n\t * Seed the write-sequence floor from every domain ledger in this owner\n\t * directory, not just the domain being loaded. The observationId carries no\n\t * domain component, so per-domain floors can collide (legacy fallback after a\n\t * branch cut reused the first coding write's sequence and memoryId, and the\n\t * projection overwrote that coding row).\n\t */\n\tconst seedWriteSequenceFloorFromAllDomains = (): void => {\n\t\tconst dir = join(context.agentDir, \"memory\", BUILTIN_MEMORY_OWNER);\n\t\tlet names: readonly string[];\n\t\ttry {\n\t\t\tnames = readdirSync(dir);\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tfor (const name of names) {\n\t\t\tif (!name.startsWith(\"ledger-\") || !name.endsWith(\".jsonl\")) continue;\n\t\t\tconst path = join(dir, name);\n\t\t\ttry {\n\t\t\t\tconst replay = createDurableMemoryLedger({ path, now }).load();\n\t\t\t\tfor (const atom of replay.atoms) {\n\t\t\t\t\tconst sequence = writeFace.writeSequenceOf(atom.observationId);\n\t\t\t\t\tif (sequence !== undefined) writeFace.advanceWriteSequenceFloor(sequence);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tapi.logger?.warn(\"memory ledger sequence floor scan failed; a new write may reuse a sequence\", {\n\t\t\t\t\tpath,\n\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t};\n\tconst resolveDomain = (): {\n\t\treadonly domain: SuiteMemoryDomainV1;\n\t\treadonly domainName: string;\n\t\treadonly ledger: DurableMemoryLedgerV1;\n\t} => {\n\t\tconst domain = resolveSessionDomain(api);\n\t\tconst domainName = suiteMemoryDomainName(domain);\n\t\tlet ledger = domainLedgers.get(domainName);\n\t\tif (ledger === undefined) {\n\t\t\tledger =\n\t\t\t\tcontext.storage?.ledgerFactory?.({\n\t\t\t\t\tagentDir: context.agentDir,\n\t\t\t\t\towner: BUILTIN_MEMORY_OWNER,\n\t\t\t\t\tdomain: domainName,\n\t\t\t\t\tnow,\n\t\t\t\t}) ??\n\t\t\t\tcreateDurableMemoryLedger({\n\t\t\t\t\tpath: join(context.agentDir, \"memory\", BUILTIN_MEMORY_OWNER, `ledger-${domainName}.jsonl`),\n\t\t\t\t\tnow,\n\t\t\t\t});\n\t\t\tif (domain.kind === \"legacy\") {\n\t\t\t\tapi.logger?.info(\"session has no suite binding; memory falls back to the legacy domain\", {\n\t\t\t\t\tsessionId: api.session?.getSessionId() ?? \"unknown\",\n\t\t\t\t});\n\t\t\t}\n\t\t\t// First load in this domain: replay the durable atoms into the store.\n\t\t\t// Sequences persisted by earlier instances of this session raise the\n\t\t\t// write-sequence floor before any new write can regenerate their ids.\n\t\t\t// Scan every domain first: observationIds are shared across domains.\n\t\t\tseedWriteSequenceFloorFromAllDomains();\n\t\t\tconst replay = ledger.load();\n\t\t\tfor (const atom of replay.atoms) {\n\t\t\t\tconst persistedSequence = writeFace.writeSequenceOf(atom.observationId);\n\t\t\t\tif (persistedSequence !== undefined) writeFace.advanceWriteSequenceFloor(persistedSequence);\n\t\t\t\ttry {\n\t\t\t\t\tstore.commit(atom);\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// A ledger atom the current store cannot accept (e.g. an unregistered\n\t\t\t\t\t// retention mode) must not fail the session — skip with a diagnostic.\n\t\t\t\t\tapi.logger?.warn(\"memory ledger atom could not be replayed into the store\", {\n\t\t\t\t\t\tmemoryId: atom.memoryId,\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\tif (replay.corruptedLines > 0 || replay.duplicateSkipped > 0 || replay.unreadable) {\n\t\t\t\tapi.logger?.warn(\"memory ledger loaded with diagnostics\", {\n\t\t\t\t\tdomain: domainName,\n\t\t\t\t\tcorruptedLines: replay.corruptedLines,\n\t\t\t\t\tduplicateSkipped: replay.duplicateSkipped,\n\t\t\t\t\tunreadable: replay.unreadable,\n\t\t\t\t});\n\t\t\t}\n\t\t\tdomainLedgers.set(domainName, ledger);\n\t\t\t// 启动对账: 首个域的 ledger 重放完成后一次性触发 (fire-and-forget,\n\t\t\t// 不阻塞本工具调用; 失败只影响向量通道, 不影响锚点通道)。\n\t\t\tvectorProjection.reconcileOnce();\n\t\t\t// 机会式保留清扫 (M5, 记忆系统设计 §3.3): 首载重放完成后对本域已过期\n\t\t\t// 原子执行一次受控物理清理 (retention-expiry 授权, 最旧优先 ≤200 条,\n\t\t\t// ledger 重写 + 向量行删除 + store 逐出)。同步调用且 sweep 自吞错——\n\t\t\t// 装载绝不因清扫失败失败; 非干净结果只记一条有界 warn。\n\t\t\tconst sweepLedger = ledger;\n\t\t\tconst sweep = sweepExpiredMemories(\n\t\t\t\t{\n\t\t\t\t\tstore,\n\t\t\t\t\tpurgeGate,\n\t\t\t\t\tpurgeJournal,\n\t\t\t\t\tpurgeIndexReplica: vectorProjection.purgeMemories,\n\t\t\t\t\tpurgeCanonicalReplica: (memoryIds) => {\n\t\t\t\t\t\tconst purged = new Set(memoryIds);\n\t\t\t\t\t\tsweepLedger.rewrite(sweepLedger.atomsSnapshot().filter((atom) => !purged.has(atom.memoryId)));\n\t\t\t\t\t\tfor (const id of memoryIds) store.evict(id);\n\t\t\t\t\t},\n\t\t\t\t\tauthorizedBy: `${capabilityManifest.id}:retention-sweep`,\n\t\t\t\t\tnow,\n\t\t\t\t},\n\t\t\t\t{ owner: BUILTIN_MEMORY_OWNER, domain },\n\t\t\t);\n\t\t\tif (sweep.status === \"failed\" || sweep.status === \"purge_eligible\" || sweep.reason !== undefined) {\n\t\t\t\tapi.logger?.warn(\n\t\t\t\t\t\"memory retention sweep did not finish clean; expired atoms stay purge-eligible and are retried on the next domain load\",\n\t\t\t\t\t{\n\t\t\t\t\t\tdomain: domainName,\n\t\t\t\t\t\tstatus: sweep.status,\n\t\t\t\t\t\t...(sweep.reason === undefined ? {} : { reason: sweep.reason }),\n\t\t\t\t\t\t...(sweep.failedReplicas === undefined ? {} : { failedReplicas: sweep.failedReplicas }),\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn { domain, domainName, ledger };\n\t};\n\n\tconst machine = createMemoryCandidateMachine({ store, now });\n\tconst lifecycle = createMemoryLifecycleManager({\n\t\tpolicy: {\n\t\t\tpolicyVersion: \"lifecycle@1\",\n\t\t\thalfLifeMs: { session: 86_400_000, cycle: 604_800_000, \"long-term\": 2_592_000_000 },\n\t\t\tstaleAfterMs: { session: 172_800_000, cycle: 1_209_600_000, \"long-term\": 5_184_000_000 },\n\t\t\tarchiveAfterMs: { session: 604_800_000, cycle: 5_184_000_000, \"long-term\": 15_552_000_000 },\n\t\t\tbaselineAttention: 0.5,\n\t\t},\n\t\tnow,\n\t});\n\tconst scheduler = createMemoryScheduler({ now });\n\tscheduler.acquireForInstance({ instanceId: sessionId, owner: BUILTIN_MEMORY_OWNER });\n\t// 非工具召回路径设施 (2.4d6 S4 家族收口取证结论): 生产工具召回 (memory_recall\n\t// 工具与 auto-recall 钩子, 后者直连同一 recallExecute, D-071 自 sdk 迁入)\n\t// 只走 recallSemantically 语义管线; index → recallAgent →\n\t// schedulerApi.recall 这条链在本 capability 内不再被工具面调用 (schedulerApi\n\t// 的生产使用仅剩写入路径的 submitObservation/submitCandidate)。保留原因:\n\t// MemorySchedulerApiV1 facade 契约 (recall + egress 门)、recall-agent 与\n\t// recall-index 是公共 API (src/index.ts 导出) 和 memory-testkit 之上的测试\n\t// 设施 (scheduler-api / memory-suite-scope / coverage-branch-memory-recall\n\t// 等测试的直接消费者) — 有存续消费者, 非死代码。\n\tconst index = createMemoryRecallIndex({ store });\n\tconst recallAgent = createMemoryRecallAgent({\n\t\tscheduler,\n\t\tindex,\n\t\tpolicyDefaults: {\n\t\t\tcandidateBudget: 1000,\n\t\t\tmodelInspectionLimit: 20,\n\t\t\tfinalResultLimit: 20,\n\t\t\tmaxRelationHops: 2,\n\t\t\tmaxModelCalls: 3,\n\t\t\tmaxOutputTokens: 4000,\n\t\t\tmaxOutputBytes: 16_000,\n\t\t\tmaxRounds: 3,\n\t\t},\n\t\thostLimits: {\n\t\t\tcandidateBudget: 5000,\n\t\t\tmodelInspectionLimit: 100,\n\t\t\tfinalResultLimit: 100,\n\t\t\tmaxRelationHops: 5,\n\t\t\tmaxModelCalls: 10,\n\t\t\tmaxOutputTokens: 100_000,\n\t\t\tmaxOutputBytes: 1_000_000,\n\t\t\tmaxRounds: 10,\n\t\t},\n\t\tnow,\n\t});\n\tconst replicaRegistry = createMemoryReplicaRegistry();\n\treplicaRegistry.register({\n\t\treplicaId: \"memory-ledger\",\n\t\tkind: \"canonical\",\n\t\townerScope: BUILTIN_MEMORY_OWNER,\n\t\tcontractVersion: MEMORY_CONTRACT_VERSION,\n\t\thealthy: true,\n\t} satisfies MemoryReplicaV1);\n\t// 向量投影副本 (混合检索工程化, D-035): 恒注册 — purge 批次以向量索引确认为\n\t// 副本契约的一部分; 通道 off/disabled 时 index 分派为 no-op (索引不存在,\n\t// 无行可清), 行为见 vectorProjection.purgeMemories。\n\treplicaRegistry.register({\n\t\treplicaId: \"memory-vector-index\",\n\t\tkind: \"index\",\n\t\tcontractVersion: MEMORY_CONTRACT_VERSION,\n\t\townerScope: BUILTIN_MEMORY_OWNER,\n\t\thealthy: true,\n\t} satisfies MemoryReplicaV1);\n\tconst purgeGate = createMemoryPurgeGate({ registry: replicaRegistry, now });\n\tconst purgeJournal = createMemoryPurgeJournal();\n\tconst egressPolicy = createMemoryEgressPolicy({\n\t\tpolicyVersion: \"egress@1\",\n\t\tallowedSourceKinds: [\"tool\", \"entry\"],\n\t\tredactedPayloadFields: [],\n\t});\n\t// schedulerApi.recall 在生产工具面无调用点 (角色见上方\"非工具召回路径设施\"\n\t// 注释); 本 capability 的生产使用仅 submitObservation/submitCandidate (写入)。\n\tconst schedulerApi = createMemorySchedulerApi({\n\t\trecallAgent,\n\t\tmachine,\n\t\tlifecycle,\n\t\tpurgeGate,\n\t\tegressPolicy,\n\t\tfactInfoLookup: (memoryId) => {\n\t\t\tconst record = store.get(memoryId, { owner: BUILTIN_MEMORY_OWNER });\n\t\t\tif (!record) return undefined;\n\t\t\treturn {\n\t\t\t\tsourceRefs: record.atom.sourceRefs,\n\t\t\t\tpayload: record.atom.payload as Record<string, unknown>,\n\t\t\t};\n\t\t},\n\t});\n\t// Preference resolution/disambiguation over context-scoped recalls (2.4c/2.4d2):\n\t// stateless and deterministic — one instance per capability suffices.\n\tconst preferenceResolver = createPreferenceResolver();\n\tconst preferenceDisambiguator = createPreferenceDisambiguator();\n\t// Relation diffusion over the recall seeds (记忆网络接线, 2.4d4): a factory-\n\t// scoped deterministic network with one enabled one-hop adapter; disabled\n\t// adapters yield an explicit `disabled` result instead of silent degradation.\n\tconst memoryNetwork = createMemoryNetwork({\n\t\tadapters: [createRelationDiffusionAdapter({ maxHops: 1 })],\n\t});\n\n\t// ---- 语义召回通道状态机 (2.4d6 S1/S2; 拆分战役 slice 3b) ----\n\t// vectorEnsure 状态转换、装配分支 (服务/本地/下载/征询门) 与 dispose 闩锁\n\t// 已迁至 memory/vector-channel.ts: 共享闭包状态收拢为 channel 对象, 经 deps\n\t// 显式注入, 降级/投影经下方 vectorProjection (slice 3a) 上报。以下调用点\n\t// 全部薄委托。\n\tconst vectorChannelCtl = createMemoryVectorChannel({\n\t\tagentDir: context.agentDir,\n\t\tmemoryMode,\n\t\tlogger: api.logger,\n\t\thostOnnxRuntimeEntryPath: context.hostOnnxRuntimeEntryPath,\n\t\thostLancedbEntryPath: context.hostLancedbEntryPath,\n\t\thostTransformersEntryPath: context.hostTransformersEntryPath,\n\t\tinferenceServicePort: context.inferenceService?.port,\n\t\tinferenceServiceSpawnImpl: context.inferenceService?.spawnImpl,\n\t\tinferenceServiceModelsInPlace: context.inferenceService?.modelsInPlace,\n\t\tenablingOverride,\n\t\tinjectedComponents,\n\t\t// vectorProjection 声明在本对象之后; 委托箭头只在 download 运行期触达,\n\t\t// 与下方 supersededMemoryIds 依赖同构 (构造期不执行)。\n\t\tresetReconcile: () => vectorProjection.resetReconcile(),\n\t\treconcileOnce: () => vectorProjection.reconcileOnce(),\n\t});\n\n\t// 写入侧向量投影管线 (拆分战役 slice 3a): 串行队列、upsert/purge 埋点与启动\n\t// 对账搬至 memory/vector-projection.ts; 状态机归 memory/vector-channel.ts\n\t// (slice 3b), 投影经只读 deps 使用, degraded 转换经 markDegraded 回调上报。\n\tconst vectorProjection = createMemoryVectorProjection({\n\t\tvectorEnabled: () => vectorChannelCtl.enabled(),\n\t\tensureChannel: () => vectorChannelCtl.ensure(),\n\t\treadyChannel: () => vectorChannelCtl.readyChannel(),\n\t\tisChannelActive: () => {\n\t\t\tconst channelState = vectorChannelCtl.rawState();\n\t\t\treturn channelState === \"ready\" || channelState === \"degraded\";\n\t\t},\n\t\tisDisposed: () => vectorChannelCtl.isDisposed(),\n\t\t// 反向清理的跨进程守卫 (2026-10-07 终审): 只读扫描 owner 全部域账本的\n\t\t// memoryId 并集 (盘面扫描, 不触碰进程内 ledger 快照)。\n\t\trefreshCanonicalMemoryIds: () =>\n\t\t\tscanOwnerLedgerMemoryIds({ agentDir: context.agentDir, owner: BUILTIN_MEMORY_OWNER }),\n\t\tmarkDegraded: () => vectorChannelCtl.markDegraded(),\n\t\tlogger: api.logger,\n\t\towner: BUILTIN_MEMORY_OWNER,\n\t\tstore,\n\t\t// writeFace 声明在本对象之后; 委托箭头只在对账运行期触达 (构造期不执行)。\n\t\tsupersededMemoryIds: () => writeFace.supersededMemoryIds(),\n\t\tstatementOf,\n\t\ttagFacetsOf,\n\t});\n\n\t// ---- 写入面 (拆分战役 slice 5) ----\n\t// memory_write 工具、语义合并探测、写入 atom 构造与写后自动升档旁路已迁至\n\t// memory/write-face.ts: 写序计数/探测降级告警闩/升档闩归 write-face 工厂\n\t// 所有, 经 deps 显式注入; 状态机与写侧投影经对象只读消费。supersededMemoryIds\n\t// 供上方 vectorProjection 的对账 deps 消费 (构造期不执行, 依赖同构)。\n\tconst writeFace = createMemoryWriteFace({\n\t\tlogger: api.logger,\n\t\tregisterTool: (definition) => api.registerTool(definition),\n\t\tpublish: api.publish,\n\t\towner: BUILTIN_MEMORY_OWNER,\n\t\tsessionId,\n\t\tmanifest: capabilityManifest,\n\t\tcontractVersion: MEMORY_CONTRACT_VERSION,\n\t\tmemoryMode,\n\t\tagentDir: context.agentDir,\n\t\tnow,\n\t\tstore,\n\t\tschedulerApi,\n\t\tvectorProjection,\n\t\tvectorChannelCtl,\n\t\tresolveDomain,\n\t\tassertNonEmptyString,\n\t\tmemoryToolInput,\n\t\tidentityHash,\n\t\tstatementOf,\n\t\ttagFacetsOf,\n\t});\n\n\t// ---- 语义召回管线 (拆分战役 slice 4) ----\n\t// 双通道查询、RRF 融合、egress 门、语义召回与召回工具已迁至\n\t// memory/recall-pipeline.ts: 状态机经 vectorChannelCtl 只读面消费\n\t// (warming/ensure/征询/失败/degraded), 写侧投影的读侧等待经 settleProjection,\n\t// capability 模块级纯函数经 deps 注入避免双头定义。recallTool 进 registrations,\n\t// recallExecute 同时被钩子面 (slice 7) 直连。\n\tconst recallPipeline = createMemoryRecallPipeline({\n\t\tlogger: api.logger,\n\t\towner: BUILTIN_MEMORY_OWNER,\n\t\tsessionId,\n\t\tstore,\n\t\tresolveDomain,\n\t\tegressPolicy,\n\t\tpreferenceResolver,\n\t\tpreferenceDisambiguator,\n\t\tmemoryNetwork,\n\t\twarming: () => vectorChannelCtl.warming(),\n\t\tensureChannel: () => vectorChannelCtl.ensure(),\n\t\tdeclined: () => vectorChannelCtl.declined(),\n\t\tconsentAsk: () => vectorChannelCtl.consentAsk(),\n\t\tfailure: () => vectorChannelCtl.failure(),\n\t\trawState: () => vectorChannelCtl.rawState(),\n\t\tmarkDegraded: () => vectorChannelCtl.markDegraded(),\n\t\trecoverDegraded: () => vectorChannelCtl.recoverDegraded(),\n\t\tsettleProjection: () => vectorProjection.settle(),\n\t\tmemoryToolInput,\n\t\tassertNonEmptyString,\n\t\tisPlainObject,\n\t\tidentityHash,\n\t\tstatementOf,\n\t\tunwrapEgressStatement,\n\t\tregisterTool: (definition) => api.registerTool(definition),\n\t});\n\n\t// ---- 命令面 (拆分战役 slice 6) ----\n\t// memory_list/forget 工具、/memory 与 /promote 命令、memory_enable 征询执行\n\t// 面与 memory.scheduler 声明已迁至 memory/command-face.ts: 列表/删除/晋升/\n\t// 征询的命令执行面经 deps 显式注入, decline/download 仍薄委托 vectorChannelCtl\n\t// (slice 3b 先例); 升档声明状态经 writeFace 的只读面消费。\n\tconst commandFace = createMemoryCommandFace({\n\t\tregisterTool: (definition) => api.registerTool(definition),\n\t\tregisterCommand: (definition) => api.registerCommand(definition),\n\t\tpublish: api.publish,\n\t\tcapabilities: api.capabilities,\n\t\towner: BUILTIN_MEMORY_OWNER,\n\t\tsessionId,\n\t\tmanifest: capabilityManifest,\n\t\tagentDir: context.agentDir,\n\t\tmemoryMode,\n\t\tnow,\n\t\tstore,\n\t\tpurgeGate,\n\t\tpurgeJournal,\n\t\tvectorProjection,\n\t\tvectorChannelCtl,\n\t\tresolveDomain,\n\t\tassertNonEmptyString,\n\t\tmemoryToolInput,\n\t\tstatementOf,\n\t\tunwrapEgressStatement,\n\t\ttierUpgradePending: writeFace.tierUpgradePending,\n\t\tclearTierUpgrade: writeFace.clearTierUpgrade,\n\t});\n\n\t// ---- 注入钩子 (拆分战役 slice 7) ----\n\t// auto-recall 与 assistant 偏好卡已迁至 memory/hooks.ts: 钩子经 api 注册面\n\t// 订阅 (loop hook), 召回执行闭包经 deps 注入。bash 失败教训沉淀已停用\n\t// (记忆归档与整理设计 §14 裁决 1), 其职责由归档整理器承担。\n\tconst hooks = createMemoryHooks({\n\t\tlogger: api.logger,\n\t\tregisterLoopHook: api.registerLoopHook,\n\t\tsession: api.session,\n\t\towner: BUILTIN_MEMORY_OWNER,\n\t\tagentDir: context.agentDir,\n\t\tnow,\n\t\tisPlainObject,\n\t\tresolveSessionDomain: () => resolveSessionDomain(api),\n\t\trecallExecute: recallPipeline.recallExecute,\n\t\tvectorChannelCtl,\n\t});\n\n\t// ---- 归档整理器 (记忆归档与整理设计 §5-§7) ----\n\t// 归档即后台整理: session.archived 事件观察 + 启动 sweep 两个触发, 提交、\n\t// 幂等、journal 与暂停/续跑语义归 memory/curator.ts。宿主未开放归档面\n\t// (context 与 api.host 都无 sessionArchive) 时两个触发都不注册。\n\tconst curator = createMemoryCurator({\n\t\tapi,\n\t\tagentDir: context.agentDir,\n\t\towner: BUILTIN_MEMORY_OWNER,\n\t\tnow,\n\t\tmanifest: capabilityManifest,\n\t\tstore,\n\t\tresolveDomain,\n\t\tvectorProjection,\n\t\tidentityHash,\n\t\tsessionArchive: context.sessionArchive ?? api.host?.sessionArchive,\n\t});\n\n\tconst registrations = [\n\t\t// 首位 = 宿主反向 dispose 时的末位: 先拆工具/命令/钩子等消费者, 最后关\n\t\t// 底层通道, 避免消费者在通道已关后仍触发向量操作报错。释放本体\n\t\t// (capabilityTeardown, slice 3b) 在 memory/vector-channel.ts。\n\t\t{\n\t\t\tid: \"memory:capability-teardown\",\n\t\t\tkind: \"capability-teardown\",\n\t\t\tdispose: () => vectorChannelCtl.dispose(),\n\t\t},\n\t\twriteFace.writeTool,\n\t\trecallPipeline.recallTool,\n\t\tcommandFace.listTool,\n\t\tcommandFace.forgetTool,\n\t\tcommandFace.enableTool,\n\t\tcommandFace.memoryCommand,\n\t\tcommandFace.promoteCommand,\n\t\tcommandFace.schedulerCapability,\n\t\thooks.autoRecallHook,\n\t\thooks.preferenceCardHook,\n\t\t...curator.registrations,\n\t];\n\treturn {\n\t\tregistrations,\n\t\tsettleVectorWork: async () => {\n\t\t\tawait vectorProjection.settle();\n\t\t},\n\t\tvectorState: (): \"off\" | MemoryCapabilityStateV1 => vectorChannelCtl.state(),\n\t\t// 触发惰性 enabling (已注入组件时已就绪) 并等待其落定: ready 或结构化失败。\n\t\tenablingOutcome: () => vectorChannelCtl.enablingOutcome(),\n\t\tteardown: () => vectorChannelCtl.dispose(),\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"recall-pipeline.d.ts","sourceRoot":"","sources":["../../src/memory/recall-pipeline.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,aAAa,EAAE,sBAAsB,EAAa,MAAM,yBAAyB,CAAC;AAGhG,OAAO,KAAK,EAA0B,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAE3F,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,KAAK,EAA4B,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACrF,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC/E,OAAO,KAAK,EAAuB,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAE1F,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,EAAsB,KAAK,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACjF,OAAO,KAAK,EAAE,uBAAuB,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAEhH,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAEpE;;;;;GAKG;AACH,eAAO,MAAM,kBAAkB,4gBACie,CAAC;AA0EjgB;;;;;GAKG;AACH,MAAM,WAAW,0BAA0B;IAC1C,wFAAoD;IACpD,QAAQ,CAAC,MAAM,EAAE,aAAa,CAAC,QAAQ,C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D,QAAQ,CAAC,gBAAgB,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;IAElD,QAAQ,CAAC,eAAe,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,KAAK,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACvF,QAAQ,CAAC,oBAAoB,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,KAAK,IAAI,MAAM,CAAC;IAC1F,QAAQ,CAAC,aAAa,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC7E,QAAQ,CAAC,YAAY,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAC;IACjD,QAAQ,CAAC,WAAW,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,MAAM,CAAC;IACnD,QAAQ,CAAC,qBAAqB,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,MAAM,CAAC;IAC9D,uFAAyD;IACzD,QAAQ,CAAC,YAAY,EAAE,aAAa,CAAC,cAAc,CAAC,CAAC;CACrD;AAED,uFAA6C;AAC7C,MAAM,WAAW,sBAAsB;IACtC,yEAAyD;IACzD,QAAQ,CAAC,UAAU,EAAE,sBAAsB,CAAC;IAC5C,wGAA4E;IAC5E,QAAQ,CAAC,aAAa,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,OAAO,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;CAC/E;AAED,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,0BAA0B,GAAG,sBAAsB,CAksBnG","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"]}
1
+ {"version":3,"file":"recall-pipeline.d.ts","sourceRoot":"","sources":["../../src/memory/recall-pipeline.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,aAAa,EAAE,sBAAsB,EAAa,MAAM,yBAAyB,CAAC;AAGhG,OAAO,KAAK,EAA0B,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAE3F,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,KAAK,EAA4B,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACrF,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC/E,OAAO,KAAK,EAAuB,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAE1F,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,EAAsB,KAAK,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACjF,OAAO,KAAK,EAAE,uBAAuB,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAEhH,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAEpE;;;;;G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 召回管线(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// Domain visibility (P4): an empty result must not read as \"no memories\"\n\t\t\t// when the session fell back to the isolated legacy domain.\n\t\t\tdomain: domain.kind === \"suite\" ? domain.suiteId : \"legacy\",\n\t\t\t...(domain.kind === \"legacy\"\n\t\t\t\t? {\n\t\t\t\t\t\twarning:\n\t\t\t\t\t\t\t\"this session has no suite binding on its current branch; memory is using the isolated legacy domain (suite memories are not visible)\",\n\t\t\t\t\t}\n\t\t\t\t: {}),\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"]}
@@ -644,6 +644,14 @@ export function createMemoryRecallPipeline(deps) {
644
644
  return {
645
645
  status: finalFacts.length === 0 ? "empty" : "completed",
646
646
  facts: finalFacts,
647
+ // Domain visibility (P4): an empty result must not read as "no memories"
648
+ // when the session fell back to the isolated legacy domain.
649
+ domain: domain.kind === "suite" ? domain.suiteId : "legacy",
650
+ ...(domain.kind === "legacy"
651
+ ? {
652
+ warning: "this session has no suite binding on its current branch; memory is using the isolated legacy domain (suite memories are not visible)",
653
+ }
654
+ : {}),
647
655
  ...(outcome.degraded === undefined ? {} : { degraded: outcome.degraded }),
648
656
  ...(resolvedConflicts.length > 0 ? { conflicts: resolvedConflicts } : {}),
649
657
  ...(domain.kind === "suite" ? { suiteFilter: outcome.suiteFilter } : {}),