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

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":"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,CAAC,CAAC;IACzC,2DAAmD;IACnD,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,kEAAwD;IACxD,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,uFAAiE;IACjE,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC;IAC9B,+FAAiE;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AAQ,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,CA2sBnG","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// 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"]}
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,qB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ED,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,0BAA0B,GAAG,sBAAsB,CA2sBnG","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({\n\t\t\tdescription: \"Maximum number of memories to return (1-100, default 5)\",\n\t\t\tminimum: 1,\n\t\t\tmaximum: 100,\n\t\t}),\n\t),\n\tcontext: Type.Optional(\n\t\tType.Object(\n\t\t\t{\n\t\t\t\tscenes: Type.Optional(\n\t\t\t\t\tType.Array(Type.String(), {\n\t\t\t\t\t\tdescription: \"Scene tags of the current task, used to resolve preferences by scope\",\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t\tprojects: Type.Optional(\n\t\t\t\t\tType.Array(Type.String(), {\n\t\t\t\t\t\tdescription: \"Project identifiers of the current task, used to resolve preferences by scope\",\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t\ttasks: Type.Optional(\n\t\t\t\t\tType.Array(Type.String(), {\n\t\t\t\t\t\tdescription: \"Task or goal identifiers of the current task, used to resolve preferences by scope\",\n\t\t\t\t\t}),\n\t\t\t\t),\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"]}
@@ -37,11 +37,21 @@ const recallSchema = Type.Object({
37
37
  query: Type.String({
38
38
  description: "Natural-language query; recall fuses semantic (vector) and full-text (BM25) matching and reranks the result. An exact memoryId retrieves that memory directly",
39
39
  }),
40
- limit: Type.Optional(Type.Integer({ description: "Maximum number of memories to return (1-100)", minimum: 1, maximum: 100 })),
40
+ limit: Type.Optional(Type.Integer({
41
+ description: "Maximum number of memories to return (1-100, default 5)",
42
+ minimum: 1,
43
+ maximum: 100,
44
+ })),
41
45
  context: Type.Optional(Type.Object({
42
- scenes: Type.Optional(Type.Array(Type.String())),
43
- projects: Type.Optional(Type.Array(Type.String())),
44
- tasks: Type.Optional(Type.Array(Type.String())),
46
+ scenes: Type.Optional(Type.Array(Type.String(), {
47
+ description: "Scene tags of the current task, used to resolve preferences by scope",
48
+ })),
49
+ projects: Type.Optional(Type.Array(Type.String(), {
50
+ description: "Project identifiers of the current task, used to resolve preferences by scope",
51
+ })),
52
+ tasks: Type.Optional(Type.Array(Type.String(), {
53
+ description: "Task or goal identifiers of the current task, used to resolve preferences by scope",
54
+ })),
45
55
  }, {
46
56
  description: "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)",
47
57
  })),
@@ -1 +1 @@
1
- {"version":3,"file":"recall-pipeline.js","sourceRoot":"","sources":["../../src/memory/recall-pipeline.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAS/B,OAAO,EAAE,kBAAkB,EAA4B,MAAM,mBAAmB,CAAC;AAKjF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAC9B,mgBAA+f,CAAC;AAEjgB,MAAM,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qEAAmE;YACnE,oDAAoD;YACpD,GAAG,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC;gBACrB,CAAC,CAAC;oBACA,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;wBACpC,QAAQ,EAAE,SAAS,CAAC,QAAQ;wBAC5B,YAAY,EAAE,SAAS,CAAC,YAAY;wBACpC,GAAG,EAAE,SAAS,CAAC,GAAG;wBAClB,MAAM,EAAE,SAAS,CAAC,MAAM;wBACxB,GAAG,EAAE,SAAS,CAAC,GAAG;qBAClB,CAAC,CAAC;iBACH;gBACF,CAAC,CAAC,EAAE,CAAC;YACN,GAAG,CAAC,mBAAmB,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,mBAAmB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC3D,CAAC;IAAA,CACF,CAAC;IACF,MAAM,UAAU,GAAG,IAAI,CAAC,YAAY,CAAC;QACpC,IAAI,EAAE,uBAAuB;QAC7B,KAAK,EAAE,iBAAiB;QACxB,gBAAgB,EAAE,CAAC,kBAAkB,CAAC;QACtC,WAAW,EACV,kUAAgU;QACjU,UAAU,EAAE,YAAY;QACxB,OAAO,EAAE,aAAa;KACtB,CAAC,CAAC;IAEH,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,CAAC;AAAA,CACrC","sourcesContent":["/**\n * 召回管线(capability 拆分战役 slice 4):双通道查询、RRF 融合、egress 门、语义召回与召回工具。状态机经 vectorChannel 只读面消费, 降级经回调上报\n */\nimport type { CapabilityAPI, DisposableRegistration, JsonValue } from \"@agent-forge/plugin-sdk\";\nimport { MEMORY_RECALL_TOOL_NAME } from \"@agent-forge/plugin-sdk\";\nimport { Type } from \"typebox\";\nimport type { MemoryEgressFactInfoV1, MemoryEgressPolicyGateV1 } from \"./egress-policy.ts\";\nimport type { MemoryAtomV1, MemoryPreferenceEnvelopeV1, MemorySuiteFilterStatsV1 } from \"./foundation.ts\";\nimport type { DurableMemoryLedgerV1 } from \"./ledger.ts\";\nimport type { MemoryNetworkExpansionV1, MemoryNetworkV1 } from \"./memory-network.ts\";\nimport type { PreferenceDisambiguatorV1 } from \"./preference-disambiguator.ts\";\nimport type { PreferenceContextV1, PreferenceResolverV1 } from \"./preference-resolver.ts\";\nimport type { MemoryRecallPacketV1 } from \"./recall-packet.ts\";\nimport type { MemoryStoreV1 } from \"./store.ts\";\nimport { listDomainMemories, type SuiteMemoryDomainV1 } from \"./suite-memory.ts\";\nimport type { MemoryCapabilityStateV1, MemoryConsentAskV1, MemoryEnablingFailureV1 } from \"./vector-channel.ts\";\nimport type { MemoryVectorHitV1 } from \"./vector-index.ts\";\nimport type { ActiveVectorChannelV1 } from \"./vector-projection.ts\";\n\n/**\n * Memory tools guide(记忆 runtime 注入面,原 system-prompt.ts MEMORY_TOOL_GUIDE,\n * D-071 迁移):the model-facing hint that the persistent memory tools exist.\n * It rides memory_recall's promptGuidelines so the text lives with the plugin\n * that owns the tools (宪法 §3) and renders whenever the tool face is active.\n */\nexport const MEMORY_TOOLS_GUIDE =\n\t\"Memory: You have persistent memory tools (memory_write, memory_recall, memory_list, memory_forget). Use memory_recall only when past decisions, preferences, or project facts are actually relevant to the current question — not on every turn. Use memory_write only for facts the user explicitly stated or that a tool/test verified; never save your own inferences or guesses as facts, and declare the honest evidence class. memory_forget only files a forget request — deletion happens after the user confirms it.\";\n\nconst DEFAULT_RECALL_LIMIT = 5;\n\n/** Bounded supplementary relation references per recall (记忆网络接线). */\nconst MAX_RELATED_REFS = 20;\n\n/** FTS / KNN 通道各自取回深度 (定版管线: depth 50)。 */\nconst HYBRID_CHANNEL_DEPTH = 50;\n/** RRF 常数, 与 vector-index 组件 queryFts 打分口径一致。 */\nconst HYBRID_RRF_K = 60;\n/** 融合候选池上限 (定版管线: top20 → 精排 → top limit)。 */\nconst HYBRID_FUSION_POOL = 20;\n\ninterface MemoryFact {\n\treadonly memoryId: string;\n\treadonly statement: string;\n\treadonly confidence: number;\n}\n\n/**\n * 三通道 RRF 融合 (定版管线): `score(id) += 1/(k + rank + 1)` 对各通道排名累加,\n * 取 top {@link HYBRID_FUSION_POOL}。分数并列时以 memoryId 升序打破, 保证确定性。\n */\nfunction rrfFuseRankings(rankings: readonly (readonly string[])[]): readonly string[] {\n\tconst scores = new Map<string, number>();\n\tfor (const ranking of rankings) {\n\t\tfor (const [rank, memoryId] of ranking.entries()) {\n\t\t\tscores.set(memoryId, (scores.get(memoryId) ?? 0) + 1 / (HYBRID_RRF_K + rank + 1));\n\t\t}\n\t}\n\treturn [...scores.entries()]\n\t\t.sort((left, right) => right[1] - left[1] || (left[0] < right[0] ? -1 : 1))\n\t\t.map(([memoryId]) => memoryId)\n\t\t.slice(0, HYBRID_FUSION_POOL);\n}\n\n/** One unresolvably competing preference, surfaced verbatim instead of a silent pick. */\ninterface RecallConflictV1 {\n\treadonly subject: MemoryPreferenceEnvelopeV1[\"subject\"];\n\treadonly key: string;\n\treadonly candidates: readonly {\n\t\treadonly memoryId: string;\n\t\treadonly statement: string;\n\t\treadonly value: JsonValue;\n\t\treadonly evidenceClass: MemoryPreferenceEnvelopeV1[\"evidence\"][\"class\"];\n\t\treadonly confidence: number;\n\t}[];\n\treadonly explanation: readonly string[];\n}\n\nconst recallSchema = Type.Object({\n\tquery: Type.String({\n\t\tdescription:\n\t\t\t\"Natural-language query; recall fuses semantic (vector) and full-text (BM25) matching and reranks the result. An exact memoryId retrieves that memory directly\",\n\t}),\n\tlimit: Type.Optional(\n\t\tType.Integer({ description: \"Maximum number of memories to return (1-100)\", minimum: 1, maximum: 100 }),\n\t),\n\tcontext: Type.Optional(\n\t\tType.Object(\n\t\t\t{\n\t\t\t\tscenes: Type.Optional(Type.Array(Type.String())),\n\t\t\t\tprojects: Type.Optional(Type.Array(Type.String())),\n\t\t\t\ttasks: Type.Optional(Type.Array(Type.String())),\n\t\t\t},\n\t\t\t{\n\t\t\t\tdescription:\n\t\t\t\t\t\"Current scope context; when present, recalled preferences are resolved against it (out-of-scope preferences drop, competing values resolve by scope specificity or surface as explicit conflicts)\",\n\t\t\t},\n\t\t),\n\t),\n});\n\n/**\n * 召回管线对 capability 闭包的显式依赖视图 (slice 4): 逐项来自\n * createMemoryCapabilityHarness 的闭包捕获核实。状态机 (vectorChannelCtl) 与\n * 写侧投影 (vectorProjection) 归 capability 装配所有, 本模块经只读回调消费与\n * 上报, 不持有任何状态机变量; capability 模块级纯函数经 deps 注入避免双头定义。\n */\nexport interface MemoryRecallPipelineDepsV1 {\n\t/** capability 日志面 (api.logger): 通道降级/增强失败的结构化日志。 */\n\treadonly logger: CapabilityAPI[\"logger\"];\n\t/** 检索行 owner (capability.BUILTIN_MEMORY_OWNER)。 */\n\treadonly owner: string;\n\t/** 会话 id (harness sessionId): egress operationId 组成。 */\n\treadonly sessionId: string;\n\t/** canonical store (per-capability 单例): store 回查与增强段 atom 读取。 */\n\treadonly store: MemoryStoreV1;\n\t/** 域解析 (capability.resolveDomain): 每次 recall 调用时惰性解析 (B1 语义)。 */\n\treadonly resolveDomain: () => {\n\t\treadonly domain: SuiteMemoryDomainV1;\n\t\treadonly domainName: string;\n\t\treadonly ledger: DurableMemoryLedgerV1;\n\t};\n\t/** egress 门 (capability.egressPolicy): 与旧锚点 packet 同一 gate。 */\n\treadonly egressPolicy: MemoryEgressPolicyGateV1;\n\t/** context-scoped 偏好解析 (2.4c/2.4d2)。 */\n\treadonly preferenceResolver: PreferenceResolverV1;\n\t/** 未决偏好的确定性消歧 (2.4c/2.4d2)。 */\n\treadonly preferenceDisambiguator: PreferenceDisambiguatorV1;\n\t/** 关系扩散 (记忆网络接线): recall 种子的一跳扩展。 */\n\treadonly memoryNetwork: MemoryNetworkV1;\n\t// ---- vectorChannel 只读面 (slice 3b 的 vectorChannelCtl, 状态机归其所有) ----\n\t/** warming 守卫: 后台预热在途且未拒绝时 recall 零等待返回 unavailable。 */\n\treadonly warming: () => boolean;\n\t/** 惰性装配 (vectorEnsure 单飞语义原样保留): undefined = 通道不可用。 */\n\treadonly ensureChannel: () => Promise<ActiveVectorChannelV1 | undefined>;\n\t/** 征询拒绝标记 (declined): recall 按模式关闭对待。 */\n\treadonly declined: () => boolean;\n\t/** 待征询信息 (consent-required): recall 返回征询话术包。 */\n\treadonly consentAsk: () => MemoryConsentAskV1 | undefined;\n\t/** enabling 结构化失败 (原因 + 行动清单, 设计 §3.2)。 */\n\treadonly failure: () => MemoryEnablingFailureV1 | undefined;\n\t/** 通道原始状态 (未做 declined 投影): packet 的 state 字段来源。 */\n\treadonly rawState: () => MemoryCapabilityStateV1;\n\t/** 运行期故障的 degraded 转换回调 (状态转换语义归状态机)。 */\n\treadonly markDegraded: () => void;\n\t/** 全通成功的 degraded 自愈回调。 */\n\treadonly recoverDegraded: () => void;\n\t// ---- 写侧投影 (slice 3a 的 vectorProjection) ----\n\t/** 读侧 FIFO 等待 (await vectorQueue): 保写入→召回次序。 */\n\treadonly settleProjection: () => Promise<unknown>;\n\t// ---- capability 模块级纯函数 (留守方, 经 deps 注入避免双头定义) ----\n\treadonly memoryToolInput: (first: unknown, second: unknown) => Record<string, unknown>;\n\treadonly assertNonEmptyString: (value: unknown, label: string) => asserts value is string;\n\treadonly isPlainObject: (value: unknown) => value is Record<string, unknown>;\n\treadonly identityHash: (value: string) => string;\n\treadonly statementOf: (payload: unknown) => string;\n\treadonly unwrapEgressStatement: (statement: string) => string;\n\t/** 工具注册面 (api.registerTool): memory_recall 经同一公共通道注册。 */\n\treadonly registerTool: CapabilityAPI[\"registerTool\"];\n}\n\n/** 召回管线工厂产物: 工具注册项 + auto-recall 直连的执行闭包。 */\nexport interface MemoryRecallPipelineV1 {\n\t/** memory_recall 工具注册项 (capability registrations 收集)。 */\n\treadonly recallTool: DisposableRegistration;\n\t/** 召回执行闭包 (原 recallExecute): autoRecallBlock (留守, slice 7) 直连同一 execute。 */\n\treadonly recallExecute: (first: unknown, second?: unknown) => Promise<unknown>;\n}\n\nexport function createMemoryRecallPipeline(deps: MemoryRecallPipelineDepsV1): MemoryRecallPipelineV1 {\n\t/**\n\t * 语义召回管线 (2.4d6 S2, 设计 §4) — 唯一检索路径: embed(查询, light 加 BGE\n\t * 前缀) → KNN depth50 + FTS depth50 → RRF k=60 top20 → 精排 → store 回查\n\t * (owner/suite/scope/过期, 单一可见性路径, 不足 limit 不回填)。降级层级\n\t * (2026-10-05 裁决 A「宁漏勿错」, 每次降级一条结构化日志, 状态转 degraded\n\t * 可自愈): 精排失败 → RRF 序 + degraded 标记 (不闩锁, 下次重试); 向量失败\n\t * (embed/KNN) → FTS-only + degraded; FTS 失败 → KNN-only + degraded;\n\t * 双通道皆败 → unavailable (语义召回不可用, memory_list 仍是列表入口;\n\t * recency 枚举兜底已移除 — 语义查询返回\"最近的几条\"是对查询语义的错答)。\n\t * degraded 标记对显式召回可见; auto-recall 见标记零注入。\n\t */\n\n\t/** 一次语义召回的中间候选: atom + 融合/降级序位 (精排并列打破用)。 */\n\tinterface RecallCandidateV1 {\n\t\treadonly atom: MemoryAtomV1;\n\t\treadonly position: number;\n\t}\n\n\t/** 出线事实行 (含精排可选分): score 缺席 = 该路径未产生精排分。 */\n\tinterface ScoredRecallFactV1 {\n\t\treadonly memoryId: string;\n\t\treadonly statement: string;\n\t\treadonly confidence: number;\n\t\treadonly position: number;\n\t\treadonly score?: number;\n\t}\n\n\ttype SemanticRecallOutcomeV1 =\n\t\t| {\n\t\t\t\treadonly kind: \"served\";\n\t\t\t\treadonly facts: readonly MemoryFact[];\n\t\t\t\treadonly candidateCount: number;\n\t\t\t\treadonly suiteFilter: MemorySuiteFilterStatsV1;\n\t\t\t\t/**\n\t\t\t\t * 降级原因短语 (2026-10-05 裁决 A「宁漏勿错」): 存在即本次结果未经\n\t\t\t\t * 精排打分。显式召回照常服务并携带该标记 (模型可见); auto-recall\n\t\t\t\t * 见标记零注入。\n\t\t\t\t */\n\t\t\t\treadonly degraded?: string;\n\t\t }\n\t\t| { readonly kind: \"blocked\"; readonly reason: string }\n\t\t| { readonly kind: \"unavailable\"; readonly message: string };\n\n\t/** recency 排序 (occurredAt 降序, memoryId 升序打破并列 — 与 recall index 同口径)。 */\n\tconst recencyOrdered = (entries: readonly RecallCandidateV1[]): readonly RecallCandidateV1[] =>\n\t\t[...entries]\n\t\t\t.sort(\n\t\t\t\t(left, right) =>\n\t\t\t\t\tDate.parse(right.atom.occurredAt) - Date.parse(left.atom.occurredAt) ||\n\t\t\t\t\t(left.atom.memoryId < right.atom.memoryId ? -1 : 1),\n\t\t\t)\n\t\t\t.map((entry, position) => ({ atom: entry.atom, position }));\n\n\t/**\n\t * superseded 过滤 (S3-B, store 回查后 / 精排前): 被某条在场候选的 supersedes\n\t * 关系指向的旧条目不再出线 — 合并后同义查询只出新条目。\"新条目在场\"以候选\n\t * 集为界: 继任条目被遗忘 (purge/过期) 后其关系随之消失, 旧条目自然恢复出线。\n\t * memoryId 主键直查不经此过滤 (引用不失效), memory_list 管理面不过滤\n\t * (nothing silently dropped — 用户可显式 forget 旧条目)。\n\t */\n\tconst filterSupersededCandidates = (candidates: readonly RecallCandidateV1[]): readonly RecallCandidateV1[] => {\n\t\tconst superseded = new Set<string>();\n\t\tfor (const entry of candidates) {\n\t\t\tfor (const relation of entry.atom.relations) {\n\t\t\t\tif (relation.kind === \"supersedes\" && relation.targetMemoryId !== undefined) {\n\t\t\t\t\tsuperseded.add(relation.targetMemoryId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (superseded.size === 0) return candidates;\n\t\treturn candidates.filter((entry) => !superseded.has(entry.atom.memoryId));\n\t};\n\n\t/**\n\t * store 回查 (正确性关键): 候选 id 逐条走与旧锚点通道相同的可见性单一路径\n\t * (owner + suite 读边界 + 过期, 单一路径); suite 场景下不可见 id 按 legacy/\n\t * 外套件区分计数 (suiteFilter 可观测), 不可见者丢弃且不回填 (诚实分页)。\n\t */\n\tconst lookupCandidates = (\n\t\trankedIds: readonly (readonly [memoryId: string, position: number])[],\n\t\tsuiteId: string | undefined,\n\t): { readonly candidates: readonly RecallCandidateV1[]; readonly suiteFilter: MemorySuiteFilterStatsV1 } => {\n\t\tconst candidates: RecallCandidateV1[] = [];\n\t\tlet legacySkipped = 0;\n\t\tlet foreignSuiteSkipped = 0;\n\t\tfor (const [memoryId, position] of rankedIds) {\n\t\t\tconst record = deps.store.get(memoryId, {\n\t\t\t\towner: deps.owner,\n\t\t\t\t...(suiteId === undefined ? {} : { suiteId }),\n\t\t\t});\n\t\t\tif (record !== undefined) {\n\t\t\t\tcandidates.push({ atom: record.atom, position });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (suiteId !== undefined) {\n\t\t\t\tconst unfiltered = deps.store.get(memoryId, { owner: deps.owner });\n\t\t\t\tif (unfiltered !== undefined) {\n\t\t\t\t\tif (unfiltered.atom.suiteId === undefined) legacySkipped += 1;\n\t\t\t\t\telse foreignSuiteSkipped += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn { candidates, suiteFilter: { legacySkipped, foreignSuiteSkipped } };\n\t};\n\n\t/**\n\t * egress 门重放 (设计 §11 MUST run): 对最终候选统一执行, 与旧锚点 packet 同\n\t * 一 gate、同一 factInfo 来源 (store); blocked 即 fail-closed, 该次 recall\n\t * 返回 failed packet (来源未登记的事实永不越过出界面)。\n\t */\n\tconst egressGate = (candidates: readonly RecallCandidateV1[]) => {\n\t\tconst factInfo: Record<string, MemoryEgressFactInfoV1 | undefined> = {};\n\t\tfor (const entry of candidates) {\n\t\t\tfactInfo[entry.atom.memoryId] = {\n\t\t\t\tsourceRefs: entry.atom.sourceRefs,\n\t\t\t\tpayload: entry.atom.payload as Record<string, unknown>,\n\t\t\t};\n\t\t}\n\t\treturn deps.egressPolicy.apply(\n\t\t\t{\n\t\t\t\toperationId: `memory_recall:${deps.sessionId}:${deps.identityHash(candidates.map((entry) => entry.atom.memoryId).join(\"\\u0000\"))}`,\n\t\t\t\tstatus: \"completed\",\n\t\t\t\tfacts: candidates.map((entry) => ({\n\t\t\t\t\tmemoryId: entry.atom.memoryId,\n\t\t\t\t\tcontentRevision: entry.atom.contentRevision,\n\t\t\t\t\tstatement: JSON.stringify(entry.atom.payload),\n\t\t\t\t\tconfidence: entry.atom.confidence,\n\t\t\t\t})),\n\t\t\t\tqueryPlan: { lookupUsed: false, filtersApplied: [], scorerVersion: \"semantic-rrf@1\" },\n\t\t\t\tattempts: 0,\n\t\t\t\tnarrowingHints: [],\n\t\t\t\tomittedCount: 0,\n\t\t\t\ttruncated: false,\n\t\t\t\ttruncationScope: \"none\",\n\t\t\t\tbudget: {\n\t\t\t\t\tcandidateBudget: 0,\n\t\t\t\t\tmodelInspectionLimit: 0,\n\t\t\t\t\tfinalResultLimit: 0,\n\t\t\t\t\tused: { candidateCount: 0, modelInspectedCount: 0, finalResultCount: 0 },\n\t\t\t\t},\n\t\t\t} satisfies MemoryRecallPacketV1,\n\t\t\tfactInfo,\n\t\t);\n\t};\n\n\tconst recallSemantically = async (input: {\n\t\treadonly query: string;\n\t\treadonly domain: SuiteMemoryDomainV1;\n\t\treadonly limit: number;\n\t\t/**\n\t\t * 自动召回质量门槛 (错误教训与召回质量护栏设计 §2.1, 内部执行缝):\n\t\t * memory_recall 工具 schema 不含该参数, 显式召回行为不变; auto-recall\n\t\t * 钩子经内部闭包恒传。仅精排实际产生 score 且过门槛的候选保留 (裁决 A\n\t\t * 收紧: 无 score 候选一律丢弃)。\n\t\t */\n\t\treadonly minScore?: number;\n\t}): Promise<SemanticRecallOutcomeV1> => {\n\t\t// 后台预热不阻塞读侧 (2026-10-05 流程裁决「后台预热、不阻塞提问」):\n\t\t// 下载/加载进行中时 recall 直接返回 warming 不可用包, 不等待 vectorQueue\n\t\t// (队列此时可能正背着启动对账或下载任务) 与 ensure 单飞。\n\t\tif (deps.warming()) {\n\t\t\treturn {\n\t\t\t\tkind: \"unavailable\",\n\t\t\t\tmessage: \"memory models are loading in the background; recall becomes available once they are ready\",\n\t\t\t};\n\t\t}\n\t\t// 读侧先等写侧队列在调用时刻已入队的部分 (待处理的投影写入 + 启动对账\n\t\t// 已入队的块), 保证写入→召回 FIFO: 本调用之前提交的写入其投影先落地,\n\t\t// 不与后台对账/埋点竞态。启动对账的分块自续 (RECONCILE_CHUNK_UPSERTS)\n\t\t// 在块完成时才入队下一块, 未入队的后续块不阻塞本次召回——未回填条目由\n\t\t// store 回查与 memory_list 兜底, 残行由后续对账继续补齐。\n\t\tawait deps.settleProjection();\n\t\tconst channel = await deps.ensureChannel();\n\t\tif (channel === undefined) {\n\t\t\tif (deps.declined()) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"unavailable\",\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t\"memory was declined on this machine — set memory.mode (light|full) in settings.json and restart the session to re-enable\",\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst consentAsk = deps.consentAsk();\n\t\t\tif (consentAsk !== undefined) {\n\t\t\t\treturn { kind: \"unavailable\", message: consentAsk.message };\n\t\t\t}\n\t\t\tconst failure = deps.failure();\n\t\t\treturn {\n\t\t\t\tkind: \"unavailable\",\n\t\t\t\tmessage:\n\t\t\t\t\tfailure === undefined\n\t\t\t\t\t\t? `memory channel is unavailable (state=${deps.rawState()})`\n\t\t\t\t\t\t: `memory enabling failed: ${failure.reason} — actions: ${failure.actions.join(\" | \")}`,\n\t\t\t};\n\t\t}\n\t\tconst suiteId = input.domain.kind === \"suite\" ? input.domain.suiteId : undefined;\n\t\tlet vectorFailed = false;\n\t\tlet ftsFailed = false;\n\t\tlet knnHits: readonly MemoryVectorHitV1[] | undefined;\n\t\tlet ftsHits: readonly MemoryVectorHitV1[] | undefined;\n\t\ttry {\n\t\t\tconst [queryVector] = await channel.embed.embed([channel.queryPrefix + input.query]);\n\t\t\tknnHits = await channel.index.queryKnn(queryVector, {\n\t\t\t\towner: deps.owner,\n\t\t\t\tlimit: HYBRID_CHANNEL_DEPTH,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tvectorFailed = true;\n\t\t\tdeps.logger?.warn(\"memory recall degraded: the vector channel failed; continuing on the FTS channel\", {\n\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t});\n\t\t}\n\t\ttry {\n\t\t\tftsHits = await channel.index.queryFts(input.query, {\n\t\t\t\towner: deps.owner,\n\t\t\t\tlimit: HYBRID_CHANNEL_DEPTH,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tftsFailed = true;\n\t\t\tdeps.logger?.warn(\"memory recall degraded: the FTS channel failed\", {\n\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t});\n\t\t}\n\n\t\tlet candidates: readonly RecallCandidateV1[];\n\t\tlet suiteFilter: MemorySuiteFilterStatsV1 = { legacySkipped: 0, foreignSuiteSkipped: 0 };\n\t\tlet channelDegraded = false;\n\t\t// 裁决 A: 降级原因短语, 透出到工具结果的 degraded 字段 (无精排分数路径)。\n\t\tlet degradedReason: string | undefined;\n\t\tif (!vectorFailed && !ftsFailed && knnHits !== undefined && ftsHits !== undefined) {\n\t\t\t// 主路径: 双通道 RRF k=60 融合 top20。\n\t\t\tconst pool = rrfFuseRankings([ftsHits.map((hit) => hit.memoryId), knnHits.map((hit) => hit.memoryId)]);\n\t\t\tconst lookup = lookupCandidates(\n\t\t\t\tpool.map((memoryId, position) => [memoryId, position] as const),\n\t\t\t\tsuiteId,\n\t\t\t);\n\t\t\tcandidates = lookup.candidates;\n\t\t\tsuiteFilter = lookup.suiteFilter;\n\t\t} else if (ftsHits !== undefined) {\n\t\t\t// 向量失败: FTS-only + recency 排序。\n\t\t\tchannelDegraded = true;\n\t\t\tdegradedReason = \"vector channel failed; full-text-only results, not reranked\";\n\t\t\tconst lookup = lookupCandidates(\n\t\t\t\tftsHits.map((hit, position) => [hit.memoryId, position] as const),\n\t\t\t\tsuiteId,\n\t\t\t);\n\t\t\tcandidates = recencyOrdered(lookup.candidates);\n\t\t\tsuiteFilter = lookup.suiteFilter;\n\t\t} else if (knnHits !== undefined) {\n\t\t\t// FTS 失败: KNN-only + recency 排序 (对称降级)。\n\t\t\tchannelDegraded = true;\n\t\t\tdegradedReason = \"FTS channel failed; vector-only results, not reranked\";\n\t\t\tconst lookup = lookupCandidates(\n\t\t\t\tknnHits.map((hit, position) => [hit.memoryId, position] as const),\n\t\t\t\tsuiteId,\n\t\t\t);\n\t\t\tcandidates = recencyOrdered(lookup.candidates);\n\t\t\tsuiteFilter = lookup.suiteFilter;\n\t\t} else {\n\t\t\t// 双通道皆败 = 语义召回能力不可用 (2026-10-05 裁决 A): 显式召回返回\n\t\t\t// 结构化 unavailable (memory_list 仍是列表入口), recency 枚举兜底从\n\t\t\t// 语义召回路径移除 — 语义查询返回\"最近的几条\"是对查询语义的错答。\n\t\t\tdeps.markDegraded();\n\t\t\tdeps.logger?.warn(\"memory recall unavailable: both the vector and FTS channels failed\");\n\t\t\treturn {\n\t\t\t\tkind: \"unavailable\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"memory recall is unavailable (both retrieval channels failed); use memory_list to enumerate this suite's memories\",\n\t\t\t};\n\t\t}\n\t\t// 运行期通道故障 → degraded (可自愈: 下一次全通 recall 回 ready)。\n\t\tif (channelDegraded) deps.markDegraded();\n\t\telse deps.recoverDegraded();\n\n\t\t// superseded 过滤 (S3-B): 回查后、egress/精排前 (主路径与全部降级路径\n\t\t// 统一收敛于此 — 被继任的旧条目任何通道都不再出线)。\n\t\tcandidates = filterSupersededCandidates(candidates);\n\n\t\tif (candidates.length === 0) {\n\t\t\treturn {\n\t\t\t\tkind: \"served\",\n\t\t\t\tfacts: [],\n\t\t\t\tcandidateCount: 0,\n\t\t\t\tsuiteFilter,\n\t\t\t\t...(degradedReason === undefined ? {} : { degraded: degradedReason }),\n\t\t\t};\n\t\t}\n\t\tconst egressOutcome = egressGate(candidates);\n\t\tif (egressOutcome.status === \"blocked\") return { kind: \"blocked\", reason: egressOutcome.reason };\n\t\tconst statementByMemoryId = new Map(egressOutcome.packet.facts.map((fact) => [fact.memoryId, fact.statement]));\n\t\tlet ordered: readonly ScoredRecallFactV1[] = candidates.map((entry) => ({\n\t\t\tmemoryId: entry.atom.memoryId,\n\t\t\tstatement: deps.unwrapEgressStatement(statementByMemoryId.get(entry.atom.memoryId) ?? \"\"),\n\t\t\tconfidence: entry.atom.confidence,\n\t\t\tposition: entry.position,\n\t\t}));\n\t\t// 精排 (仅主融合路径: 降级页的排序即其降级语义)。reranker 不可用或调用\n\t\t// 失败 → 保持 RRF 序并携带 degraded 标记; 调用失败不闩锁 (裁决 A: 下一次\n\t\t// 召回重试, 与组件层加载重试语义对齐), 每次失败记一条结构化日志。\n\t\tconst reranker = channel.reranker;\n\t\tif (!channelDegraded && reranker !== undefined) {\n\t\t\ttry {\n\t\t\t\tconst scores = await reranker.rerank(\n\t\t\t\t\tinput.query,\n\t\t\t\t\tordered.map((fact) => fact.statement),\n\t\t\t\t);\n\t\t\t\tordered = ordered\n\t\t\t\t\t.map((fact, position) => ({ ...fact, score: scores[position] }))\n\t\t\t\t\t.sort((left, right) => (right.score ?? 0) - (left.score ?? 0) || left.position - right.position);\n\t\t\t} catch (error) {\n\t\t\t\tdegradedReason ??= \"reranker failed; RRF order without rerank scores\";\n\t\t\t\tdeps.logger?.warn(\n\t\t\t\t\t\"memory reranker failed; recall serves the RRF order this round and retries the next recall\",\n\t\t\t\t\t{\n\t\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\t// minScore 门槛 (§2.1, 裁决 A 收紧): 仅精排实际产生 score 且过门槛的候选\n\t\t// 参与过滤后结果 (无 score 的候选一律丢弃, 不再放行); 过滤先于 limit 截取。\n\t\t// minScore 只经 auto-recall 内部闭包传入, auto-recall 另按 degraded 标记\n\t\t// 零注入, 双保险钉住\"注入 ⟹ 全部条目有分且过门槛\"。\n\t\tconst minScore = input.minScore;\n\t\tconst eligible =\n\t\t\tminScore === undefined\n\t\t\t\t? ordered\n\t\t\t\t: ordered.filter((fact) => fact.score !== undefined && fact.score >= minScore);\n\t\treturn {\n\t\t\tkind: \"served\",\n\t\t\tfacts: eligible\n\t\t\t\t.slice(0, input.limit)\n\t\t\t\t.map(({ memoryId, statement, confidence }) => ({ memoryId, statement, confidence })),\n\t\t\tcandidateCount: ordered.length,\n\t\t\tsuiteFilter,\n\t\t\t...(degradedReason === undefined ? {} : { degraded: degradedReason }),\n\t\t};\n\t};\n\n\t/**\n\t * Context-scoped preference post-processing over the recalled facts: preference\n\t * atoms compete per (subject, key); the resolver drops out-of-scope preferences\n\t * and deterministically ranks the rest, and an unconfirmed ranking goes through\n\t * the scope-specificity disambiguator. Whatever remains unresolvable is\n\t * returned as an explicit conflict block — the recall never silently picks\n\t * between competing stored values. Non-preference facts pass through untouched.\n\t */\n\tfunction applyPreferenceContext(input: {\n\t\treadonly facts: readonly MemoryFact[];\n\t\treadonly context: PreferenceContextV1;\n\t\treadonly resolver: PreferenceResolverV1;\n\t\treadonly disambiguator: PreferenceDisambiguatorV1;\n\t\treadonly atomOf: (memoryId: string) => MemoryAtomV1 | undefined;\n\t}): { readonly facts: readonly MemoryFact[]; readonly conflicts: readonly RecallConflictV1[] } {\n\t\tconst { facts, context, resolver, disambiguator, atomOf } = input;\n\t\tconst preferenceAtoms: MemoryAtomV1[] = [];\n\t\tconst atomsByGroup = new Map<string, MemoryAtomV1[]>();\n\t\tconst preferenceMemoryIds = new Set<string>();\n\t\tfor (const fact of facts) {\n\t\t\tconst atom = atomOf(fact.memoryId);\n\t\t\tif (atom === undefined || atom.memoryKind !== \"preference\" || atom.preference === undefined) continue;\n\t\t\tpreferenceMemoryIds.add(fact.memoryId);\n\t\t\tpreferenceAtoms.push(atom);\n\t\t\tconst groupKey = `${atom.preference.subject}\\u0000${atom.preference.key}`;\n\t\t\tconst group = atomsByGroup.get(groupKey) ?? [];\n\t\t\tgroup.push(atom);\n\t\t\tatomsByGroup.set(groupKey, group);\n\t\t}\n\t\tif (preferenceMemoryIds.size === 0) return { facts, conflicts: [] };\n\n\t\tconst keptMemoryIds = new Set<string>();\n\t\tconst conflicts: RecallConflictV1[] = [];\n\t\tfor (const decision of resolver.resolve(preferenceAtoms, context)) {\n\t\t\tconst groupAtoms = atomsByGroup.get(`${decision.subject}\\u0000${decision.key}`) ?? [];\n\t\t\tif (decision.status === \"applied\") {\n\t\t\t\tif (decision.winnerMemoryId === undefined) {\n\t\t\t\t\tthrow new Error(`applied preference decision without a winnerMemoryId: ${JSON.stringify(decision)}`);\n\t\t\t\t}\n\t\t\t\tkeptMemoryIds.add(decision.winnerMemoryId);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (decision.status === \"instruction_override\") {\n\t\t\t\t// No stored fact survives a current-instruction override (this slice has\n\t\t\t\t// no input source for currentInstructions, so the branch stays inert).\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (decision.status === \"conflict_unconfirmed\") {\n\t\t\t\tconst outcome = disambiguator.disambiguate(\n\t\t\t\t\tgroupAtoms.map((atom) => ({\n\t\t\t\t\t\tmemoryId: atom.memoryId,\n\t\t\t\t\t\tpreferredValue: atom.preference!.preferredValue,\n\t\t\t\t\t\tscope: atom.preference!.scope,\n\t\t\t\t\t\tevidenceClass: atom.preference!.evidence.class,\n\t\t\t\t\t\tapplicabilityConfidence: atom.preference!.applicabilityConfidence,\n\t\t\t\t\t})),\n\t\t\t\t\tcontext,\n\t\t\t\t);\n\t\t\t\tif (outcome.status === \"resolved\") {\n\t\t\t\t\tkeptMemoryIds.add(outcome.winnerMemoryId);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconflicts.push({\n\t\t\t\t\tsubject: decision.subject,\n\t\t\t\t\tkey: decision.key,\n\t\t\t\t\tcandidates: groupAtoms.map((atom) => {\n\t\t\t\t\t\tconst preference = atom.preference!;\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tmemoryId: atom.memoryId,\n\t\t\t\t\t\t\tstatement: deps.unwrapEgressStatement(deps.statementOf(atom.payload)),\n\t\t\t\t\t\t\tvalue: preference.preferredValue,\n\t\t\t\t\t\t\tevidenceClass: preference.evidence.class,\n\t\t\t\t\t\t\tconfidence: preference.applicabilityConfidence,\n\t\t\t\t\t\t};\n\t\t\t\t\t}),\n\t\t\t\t\texplanation: [...outcome.explanation],\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow new Error(`unexpected preference decision status: ${JSON.stringify(decision)}`);\n\t\t}\n\n\t\treturn {\n\t\t\tfacts: facts.filter((fact) => !preferenceMemoryIds.has(fact.memoryId) || keptMemoryIds.has(fact.memoryId)),\n\t\t\tconflicts,\n\t\t};\n\t}\n\n\t/**\n\t * Parses the optional recall context (scenes/projects/tasks) into a preference\n\t * resolution context. Returns undefined when absent so the no-context recall\n\t * path stays byte-identical to the pre-disambiguation behavior.\n\t */\n\tfunction parseRecallContext(value: unknown): PreferenceContextV1 | undefined {\n\t\tif (value === undefined) return undefined;\n\t\tif (!deps.isPlainObject(value)) throw new Error(\"context must be an object\");\n\t\tconst stringArray = (field: \"scenes\" | \"projects\" | \"tasks\"): readonly string[] | undefined => {\n\t\t\tconst entries: unknown = value[field];\n\t\t\tif (entries === undefined) return undefined;\n\t\t\tif (!Array.isArray(entries)) throw new Error(`context.${field} must be an array of strings`);\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (typeof entry !== \"string\") throw new Error(`context.${field} entries must be strings`);\n\t\t\t}\n\t\t\treturn entries;\n\t\t};\n\t\tconst scenes = stringArray(\"scenes\");\n\t\tconst projects = stringArray(\"projects\");\n\t\tconst tasks = stringArray(\"tasks\");\n\t\treturn {\n\t\t\t...(scenes === undefined ? {} : { scenes }),\n\t\t\t...(projects === undefined ? {} : { projects }),\n\t\t\t...(tasks === undefined ? {} : { tasks }),\n\t\t};\n\t}\n\n\t// 提取为具名闭包: 除模型工具面外, 下方的 auto-recall 钩子直接调用同一 execute\n\t// (单参输入约定, memoryToolInput 取第一参), 不经 runtime.invokeTool —— 钩子\n\t// 随插件注册/卸载, 与工具面同生命周期, 替换工具面不会重接自动召回。\n\tconst recallExecute = async (first: unknown, second?: unknown): Promise<unknown> => {\n\t\tconst input = deps.memoryToolInput(first, second);\n\t\tdeps.assertNonEmptyString(input.query, \"query\");\n\t\tconst rawLimit: unknown = input.limit;\n\t\tconst limit =\n\t\t\trawLimit === undefined\n\t\t\t\t? DEFAULT_RECALL_LIMIT\n\t\t\t\t: ((): number => {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\ttypeof rawLimit !== \"number\" ||\n\t\t\t\t\t\t\t!Number.isSafeInteger(rawLimit) ||\n\t\t\t\t\t\t\trawLimit < 1 ||\n\t\t\t\t\t\t\trawLimit > 100\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthrow new Error(\"limit must be an integer between 1 and 100\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn rawLimit;\n\t\t\t\t\t})();\n\t\t// 内部执行缝 (§2.1): auto-recall 闭包经本字段恒传质量门槛; memory_recall\n\t\t// 工具 schema 不含该参数 (工具面恒 undefined), 显式召回行为不变。\n\t\tconst rawMinScore: unknown = input.minScore;\n\t\tconst minScore =\n\t\t\trawMinScore === undefined\n\t\t\t\t? undefined\n\t\t\t\t: ((): number => {\n\t\t\t\t\t\tif (typeof rawMinScore !== \"number\" || !Number.isFinite(rawMinScore)) {\n\t\t\t\t\t\t\tthrow new Error(\"minScore must be a finite number\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn rawMinScore;\n\t\t\t\t\t})();\n\t\tconst context = parseRecallContext(input.context);\n\t\tconst { domain } = deps.resolveDomain();\n\n\t\t// enabling 失败 = 本实例终态 (mode 记录回退 off): 记忆工具返回携带原因\n\t\t// 与五选一行动清单的不可用 packet (设计 §3.2 硬性要求), 不再重试。\n\t\tif (deps.rawState() === \"failed\") {\n\t\t\tconst failure = deps.failure() ?? { reason: \"memory enabling failed\", actions: [] as const };\n\t\t\treturn {\n\t\t\t\tstatus: \"unavailable\",\n\t\t\t\tstate: \"failed\",\n\t\t\t\tfacts: [] as MemoryFact[],\n\t\t\t\terror: `memory enabling failed: ${failure.reason}`,\n\t\t\t\tactions: failure.actions,\n\t\t\t};\n\t\t}\n\t\t// 征询门早退 (2026-10-05 用户裁决): 拒绝 = 本实例按模式关闭对待; 待征询 =\n\t\t// 返回带行动清单的 consent-required packet (后续 recall 不再反复探测文件)。\n\t\tif (deps.declined()) {\n\t\t\treturn {\n\t\t\t\tstatus: \"unavailable\",\n\t\t\t\tstate: \"off\",\n\t\t\t\tfacts: [] as MemoryFact[],\n\t\t\t\terror: \"memory was declined on this machine — set memory.mode (light|full) in settings.json and restart the session to re-enable\",\n\t\t\t\tactions: [] as const,\n\t\t\t};\n\t\t}\n\t\tconst consentAsk = deps.consentAsk();\n\t\tif (consentAsk !== undefined) {\n\t\t\treturn {\n\t\t\t\tstatus: \"unavailable\",\n\t\t\t\tstate: \"consent-required\",\n\t\t\t\tfacts: [] as MemoryFact[],\n\t\t\t\terror: consentAsk.message,\n\t\t\t\tactions: consentAsk.actions,\n\t\t\t};\n\t\t}\n\n\t\t// 主键快路径 (memoryIdEquals 语义保留, 幂等/引用而非检索): query 恰为本\n\t\t// 域可见 memoryId 时直接取该条, 不依赖向量通道 (enabling 期间也可用)。\n\t\tlet outcome: SemanticRecallOutcomeV1;\n\t\tconst directRecord = deps.store.get(input.query.trim(), {\n\t\t\towner: deps.owner,\n\t\t\t...(domain.kind === \"suite\" ? { suiteId: domain.suiteId } : {}),\n\t\t});\n\t\tif (directRecord !== undefined) {\n\t\t\tconst gate = egressGate([{ atom: directRecord.atom, position: 0 }]);\n\t\t\tif (gate.status === \"blocked\") {\n\t\t\t\treturn { status: \"failed\", facts: [] as MemoryFact[], error: `egress blocked: ${gate.reason}` };\n\t\t\t}\n\t\t\tconst statementByMemoryId = new Map(gate.packet.facts.map((fact) => [fact.memoryId, fact.statement]));\n\t\t\toutcome = {\n\t\t\t\tkind: \"served\",\n\t\t\t\tfacts: [\n\t\t\t\t\t{\n\t\t\t\t\t\tmemoryId: directRecord.atom.memoryId,\n\t\t\t\t\t\tstatement: deps.unwrapEgressStatement(statementByMemoryId.get(directRecord.atom.memoryId) ?? \"\"),\n\t\t\t\t\t\tconfidence: directRecord.atom.confidence,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tcandidateCount: 1,\n\t\t\t\tsuiteFilter: { legacySkipped: 0, foreignSuiteSkipped: 0 },\n\t\t\t\t// 裁决 A 缝隙收口 (2026-10-05 复审后用户裁决「修复」): 直查是引用\n\t\t\t\t// 语义、未经精排 — 显式召回如实带标记, auto-recall 见标记零注入\n\t\t\t\t// (此前用户消息恰为 memoryId 时会绕过质量门注入该条)。\n\t\t\t\tdegraded: \"primary-key direct lookup (reference semantics, not reranked)\",\n\t\t\t};\n\t\t} else {\n\t\t\ttry {\n\t\t\t\toutcome = await recallSemantically({\n\t\t\t\t\tquery: input.query,\n\t\t\t\t\tdomain,\n\t\t\t\t\tlimit,\n\t\t\t\t\t...(minScore === undefined ? {} : { minScore }),\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\t// 意外异常 (管线 throw) → degraded packet: 结构化返回, 不抛给模型。\n\t\t\t\tdeps.markDegraded();\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tdeps.logger?.warn(\"memory recall degraded: the recall pipeline threw; returning a degraded packet\", {\n\t\t\t\t\terror: message,\n\t\t\t\t});\n\t\t\t\treturn { status: \"failed\", facts: [] as MemoryFact[], error: message };\n\t\t\t}\n\t\t}\n\t\tif (outcome.kind === \"blocked\") {\n\t\t\treturn { status: \"failed\", facts: [] as MemoryFact[], error: `egress blocked: ${outcome.reason}` };\n\t\t}\n\t\tif (outcome.kind === \"unavailable\") {\n\t\t\t// 首次调用即在装配中途失败时, vectorState 在本调用内才翻成 failed —\n\t\t\t// 这里同样必须携带 enabling 失败的原因 + 行动清单 (设计 §3.2 硬性\n\t\t\t// 要求: 终态的第一份可见 packet 就是完整的), 不等下一次调用补。\n\t\t\t// (vectorState 是可变闭包状态, 语义检索内部会改写它, 入口预检的\n\t\t\t// 收窄在此处不成立 — 经函数边界读取以如实表达。)\n\t\t\tconst stateAtEgress = (): MemoryCapabilityStateV1 => deps.rawState();\n\t\t\tconst failureAtEgress = deps.failure();\n\t\t\tconst consentAskAtEgress = deps.consentAsk();\n\t\t\tif (stateAtEgress() === \"failed\" && failureAtEgress !== undefined) {\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"unavailable\",\n\t\t\t\t\tstate: \"failed\",\n\t\t\t\t\tfacts: [] as MemoryFact[],\n\t\t\t\t\terror: `memory enabling failed: ${failureAtEgress.reason}`,\n\t\t\t\t\tactions: failureAtEgress.actions,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstatus: \"unavailable\",\n\t\t\t\tstate: stateAtEgress(),\n\t\t\t\tfacts: [] as MemoryFact[],\n\t\t\t\terror: outcome.message,\n\t\t\t\t...(stateAtEgress() === \"consent-required\" && consentAskAtEgress !== undefined\n\t\t\t\t\t? { actions: consentAskAtEgress.actions }\n\t\t\t\t\t: {}),\n\t\t\t};\n\t\t}\n\t\tconst facts = outcome.facts;\n\t\t// 增强段 (偏好消歧 + 关系扩散) 是增量元数据面: 内部抛错不得砸穿工具面\n\t\t// (结构化失败契约), 也不吞掉整个召回 — 降级为基础事实 + 一条结构化 warn。\n\t\tconst { finalFacts, resolvedConflicts, related, relatedOmittedCount } = await (async () => {\n\t\t\ttry {\n\t\t\t\tconst resolved =\n\t\t\t\t\tcontext === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: applyPreferenceContext({\n\t\t\t\t\t\t\t\tfacts,\n\t\t\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t\t\tresolver: deps.preferenceResolver,\n\t\t\t\t\t\t\t\tdisambiguator: deps.preferenceDisambiguator,\n\t\t\t\t\t\t\t\tatomOf: (memoryId) => deps.store.get(memoryId, { owner: deps.owner })?.atom,\n\t\t\t\t\t\t\t});\n\t\t\t\t// 偏好消歧先于关系扩散: the diffusion seeds are the atoms the user\n\t\t\t\t// actually sees — preference facts dropped by the conflict resolution\n\t\t\t\t// never diffuse their relations.\n\t\t\t\tconst baseFacts = resolved === undefined ? facts : resolved.facts;\n\t\t\t\tconst seeds: MemoryAtomV1[] = [];\n\t\t\t\tfor (const fact of baseFacts) {\n\t\t\t\t\tconst atom = deps.store.get(fact.memoryId, { owner: deps.owner })?.atom;\n\t\t\t\t\tif (atom !== undefined) seeds.push(atom);\n\t\t\t\t}\n\t\t\t\t// The traversal graph is the recall domain's visible atom set (same\n\t\t\t\t// suite read boundary). Diffusion targets outside this set are dropped,\n\t\t\t\t// so relations never leak across suites.\n\t\t\t\tconst domainMemoryIds = new Set<string>();\n\t\t\t\tconst graph: MemoryAtomV1[] = [];\n\t\t\t\tfor (const entry of listDomainMemories({ store: deps.store }, { owner: deps.owner, domain }).entries) {\n\t\t\t\t\tdomainMemoryIds.add(entry.memoryId);\n\t\t\t\t\tconst atom = deps.store.get(entry.memoryId, { owner: deps.owner })?.atom;\n\t\t\t\t\tif (atom !== undefined) graph.push(atom);\n\t\t\t\t}\n\t\t\t\tconst related: MemoryNetworkExpansionV1[] = [];\n\t\t\t\tlet relatedOmittedCount = 0;\n\t\t\t\tconst seenRelatedMemoryIds = new Set<string>();\n\t\t\t\tfor (const adapterResult of deps.memoryNetwork.expand({ seeds, graph })) {\n\t\t\t\t\tif (adapterResult.status !== \"completed\") continue;\n\t\t\t\t\tfor (const expansion of adapterResult.related) {\n\t\t\t\t\t\tif (!domainMemoryIds.has(expansion.memoryId)) continue;\n\t\t\t\t\t\tif (seenRelatedMemoryIds.has(expansion.memoryId)) continue;\n\t\t\t\t\t\tseenRelatedMemoryIds.add(expansion.memoryId);\n\t\t\t\t\t\tif (related.length >= MAX_RELATED_REFS) {\n\t\t\t\t\t\t\trelatedOmittedCount += 1;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\trelated.push(expansion);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tfinalFacts: baseFacts,\n\t\t\t\t\tresolvedConflicts: resolved === undefined ? [] : resolved.conflicts,\n\t\t\t\t\trelated,\n\t\t\t\t\trelatedOmittedCount,\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tdeps.logger?.warn(\n\t\t\t\t\t\"memory recall enhancement failed; serving the base facts without preference resolution and related references\",\n\t\t\t\t\t{ error: error instanceof Error ? error.message : String(error) },\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tfinalFacts: facts,\n\t\t\t\t\tresolvedConflicts: [],\n\t\t\t\t\trelated: [] as MemoryNetworkExpansionV1[],\n\t\t\t\t\trelatedOmittedCount: 0,\n\t\t\t\t};\n\t\t\t}\n\t\t})();\n\t\treturn {\n\t\t\tstatus: finalFacts.length === 0 ? \"empty\" : \"completed\",\n\t\t\tfacts: finalFacts,\n\t\t\t// 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"]}
1
+ {"version":3,"file":"recall-pipeline.js","sourceRoot":"","sources":["../../src/memory/recall-pipeline.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAS/B,OAAO,EAAE,kBAAkB,EAA4B,MAAM,mBAAmB,CAAC;AAKjF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAC9B,mgBAA+f,CAAC;AAEjgB,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAE/B,iFAAqE;AACrE,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAE5B,qEAA2C;AAC3C,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAChC,yEAAiD;AACjD,MAAM,YAAY,GAAG,EAAE,CAAC;AACxB,8EAA8C;AAC9C,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAQ9B;;;GAGG;AACH,SAAS,eAAe,CAAC,QAAwC,EAAqB;IACrF,MAAM,MAAM,GAAG,IAAI,GAAG,EAAkB,CAAC;IACz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AAY;wBACpC,GAAG,EAAE,SAAS,CAAC,GAAG;wBAClB,MAAM,EAAE,SAAS,CAAC,MAAM;wBACxB,GAAG,EAAE,SAAS,CAAC,GAAG;qBAClB,CAAC,CAAC;iBACH;gBACF,CAAC,CAAC,EAAE,CAAC;YACN,GAAG,CAAC,mBAAmB,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,mBAAmB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC3D,CAAC;IAAA,CACF,CAAC;IACF,MAAM,UAAU,GAAG,IAAI,CAAC,YAAY,CAAC;QACpC,IAAI,EAAE,uBAAuB;QAC7B,KAAK,EAAE,iBAAiB;QACxB,gBAAgB,EAAE,CAAC,kBAAkB,CAAC;QACtC,WAAW,EACV,kUAAgU;QACjU,UAAU,EAAE,YAAY;QACxB,OAAO,EAAE,aAAa;KACtB,CAAC,CAAC;IAEH,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,CAAC;AAAA,CACrC","sourcesContent":["/**\n * 召回管线(capability 拆分战役 slice 4):双通道查询、RRF 融合、egress 门、语义召回与召回工具。状态机经 vectorChannel 只读面消费, 降级经回调上报\n */\nimport type { CapabilityAPI, DisposableRegistration, JsonValue } from \"@agent-forge/plugin-sdk\";\nimport { MEMORY_RECALL_TOOL_NAME } from \"@agent-forge/plugin-sdk\";\nimport { Type } from \"typebox\";\nimport type { MemoryEgressFactInfoV1, MemoryEgressPolicyGateV1 } from \"./egress-policy.ts\";\nimport type { MemoryAtomV1, MemoryPreferenceEnvelopeV1, MemorySuiteFilterStatsV1 } from \"./foundation.ts\";\nimport type { DurableMemoryLedgerV1 } from \"./ledger.ts\";\nimport type { MemoryNetworkExpansionV1, MemoryNetworkV1 } from \"./memory-network.ts\";\nimport type { PreferenceDisambiguatorV1 } from \"./preference-disambiguator.ts\";\nimport type { PreferenceContextV1, PreferenceResolverV1 } from \"./preference-resolver.ts\";\nimport type { MemoryRecallPacketV1 } from \"./recall-packet.ts\";\nimport type { MemoryStoreV1 } from \"./store.ts\";\nimport { listDomainMemories, type SuiteMemoryDomainV1 } from \"./suite-memory.ts\";\nimport type { MemoryCapabilityStateV1, MemoryConsentAskV1, MemoryEnablingFailureV1 } from \"./vector-channel.ts\";\nimport type { MemoryVectorHitV1 } from \"./vector-index.ts\";\nimport type { ActiveVectorChannelV1 } from \"./vector-projection.ts\";\n\n/**\n * Memory tools guide(记忆 runtime 注入面,原 system-prompt.ts MEMORY_TOOL_GUIDE,\n * D-071 迁移):the model-facing hint that the persistent memory tools exist.\n * It rides memory_recall's promptGuidelines so the text lives with the plugin\n * that owns the tools (宪法 §3) and renders whenever the tool face is active.\n */\nexport const MEMORY_TOOLS_GUIDE =\n\t\"Memory: You have persistent memory tools (memory_write, memory_recall, memory_list, memory_forget). Use memory_recall only when past decisions, preferences, or project facts are actually relevant to the current question — not on every turn. Use memory_write only for facts the user explicitly stated or that a tool/test verified; never save your own inferences or guesses as facts, and declare the honest evidence class. memory_forget only files a forget request — deletion happens after the user confirms it.\";\n\nconst DEFAULT_RECALL_LIMIT = 5;\n\n/** Bounded supplementary relation references per recall (记忆网络接线). */\nconst MAX_RELATED_REFS = 20;\n\n/** FTS / KNN 通道各自取回深度 (定版管线: depth 50)。 */\nconst HYBRID_CHANNEL_DEPTH = 50;\n/** RRF 常数, 与 vector-index 组件 queryFts 打分口径一致。 */\nconst HYBRID_RRF_K = 60;\n/** 融合候选池上限 (定版管线: top20 → 精排 → top limit)。 */\nconst HYBRID_FUSION_POOL = 20;\n\ninterface MemoryFact {\n\treadonly memoryId: string;\n\treadonly statement: string;\n\treadonly confidence: number;\n}\n\n/**\n * 三通道 RRF 融合 (定版管线): `score(id) += 1/(k + rank + 1)` 对各通道排名累加,\n * 取 top {@link HYBRID_FUSION_POOL}。分数并列时以 memoryId 升序打破, 保证确定性。\n */\nfunction rrfFuseRankings(rankings: readonly (readonly string[])[]): readonly string[] {\n\tconst scores = new Map<string, number>();\n\tfor (const ranking of rankings) {\n\t\tfor (const [rank, memoryId] of ranking.entries()) {\n\t\t\tscores.set(memoryId, (scores.get(memoryId) ?? 0) + 1 / (HYBRID_RRF_K + rank + 1));\n\t\t}\n\t}\n\treturn [...scores.entries()]\n\t\t.sort((left, right) => right[1] - left[1] || (left[0] < right[0] ? -1 : 1))\n\t\t.map(([memoryId]) => memoryId)\n\t\t.slice(0, HYBRID_FUSION_POOL);\n}\n\n/** One unresolvably competing preference, surfaced verbatim instead of a silent pick. */\ninterface RecallConflictV1 {\n\treadonly subject: MemoryPreferenceEnvelopeV1[\"subject\"];\n\treadonly key: string;\n\treadonly candidates: readonly {\n\t\treadonly memoryId: string;\n\t\treadonly statement: string;\n\t\treadonly value: JsonValue;\n\t\treadonly evidenceClass: MemoryPreferenceEnvelopeV1[\"evidence\"][\"class\"];\n\t\treadonly confidence: number;\n\t}[];\n\treadonly explanation: readonly string[];\n}\n\nconst recallSchema = Type.Object({\n\tquery: Type.String({\n\t\tdescription:\n\t\t\t\"Natural-language query; recall fuses semantic (vector) and full-text (BM25) matching and reranks the result. An exact memoryId retrieves that memory directly\",\n\t}),\n\tlimit: Type.Optional(\n\t\tType.Integer({\n\t\t\tdescription: \"Maximum number of memories to return (1-100, default 5)\",\n\t\t\tminimum: 1,\n\t\t\tmaximum: 100,\n\t\t}),\n\t),\n\tcontext: Type.Optional(\n\t\tType.Object(\n\t\t\t{\n\t\t\t\tscenes: Type.Optional(\n\t\t\t\t\tType.Array(Type.String(), {\n\t\t\t\t\t\tdescription: \"Scene tags of the current task, used to resolve preferences by scope\",\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t\tprojects: Type.Optional(\n\t\t\t\t\tType.Array(Type.String(), {\n\t\t\t\t\t\tdescription: \"Project identifiers of the current task, used to resolve preferences by scope\",\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t\ttasks: Type.Optional(\n\t\t\t\t\tType.Array(Type.String(), {\n\t\t\t\t\t\tdescription: \"Task or goal identifiers of the current task, used to resolve preferences by scope\",\n\t\t\t\t\t}),\n\t\t\t\t),\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"]}