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