@ai-agent-forge/plugin-memory 0.88.0 → 0.88.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +10 -4
  2. package/agent-forge.json +1 -1
  3. package/bin/agent-forge-memory-inference.js +8 -0
  4. package/dist/capability.d.ts +42 -59
  5. package/dist/capability.d.ts.map +1 -1
  6. package/dist/capability.js +263 -2055
  7. package/dist/capability.js.map +1 -1
  8. package/dist/entry.d.ts +11 -0
  9. package/dist/entry.d.ts.map +1 -1
  10. package/dist/entry.js +38 -2
  11. package/dist/entry.js.map +1 -1
  12. package/dist/index.d.ts +5 -0
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +7 -0
  15. package/dist/index.js.map +1 -1
  16. package/dist/inference-bin.d.ts +21 -0
  17. package/dist/inference-bin.d.ts.map +1 -0
  18. package/dist/inference-bin.js +85 -0
  19. package/dist/inference-bin.js.map +1 -0
  20. package/dist/memory/command-face.d.ts +86 -0
  21. package/dist/memory/command-face.d.ts.map +1 -0
  22. package/dist/memory/command-face.js +377 -0
  23. package/dist/memory/command-face.js.map +1 -0
  24. package/dist/memory/embedding-provider.d.ts.map +1 -1
  25. package/dist/memory/embedding-provider.js +14 -2
  26. package/dist/memory/embedding-provider.js.map +1 -1
  27. package/dist/memory/embedding-reranker.d.ts.map +1 -1
  28. package/dist/memory/embedding-reranker.js +14 -2
  29. package/dist/memory/embedding-reranker.js.map +1 -1
  30. package/dist/memory/enabling.d.ts +104 -0
  31. package/dist/memory/enabling.d.ts.map +1 -0
  32. package/dist/memory/enabling.js +321 -0
  33. package/dist/memory/enabling.js.map +1 -0
  34. package/dist/memory/hooks.d.ts +110 -0
  35. package/dist/memory/hooks.d.ts.map +1 -0
  36. package/dist/memory/hooks.js +478 -0
  37. package/dist/memory/hooks.js.map +1 -0
  38. package/dist/memory/inference-channel.d.ts +33 -0
  39. package/dist/memory/inference-channel.d.ts.map +1 -0
  40. package/dist/memory/inference-channel.js +101 -0
  41. package/dist/memory/inference-channel.js.map +1 -0
  42. package/dist/memory/inference-client.d.ts +25 -0
  43. package/dist/memory/inference-client.d.ts.map +1 -0
  44. package/dist/memory/inference-client.js +216 -0
  45. package/dist/memory/inference-client.js.map +1 -0
  46. package/dist/memory/inference-protocol.d.ts +95 -0
  47. package/dist/memory/inference-protocol.d.ts.map +1 -0
  48. package/dist/memory/inference-protocol.js +27 -0
  49. package/dist/memory/inference-protocol.js.map +1 -0
  50. package/dist/memory/inference-server.d.ts +70 -0
  51. package/dist/memory/inference-server.d.ts.map +1 -0
  52. package/dist/memory/inference-server.js +395 -0
  53. package/dist/memory/inference-server.js.map +1 -0
  54. package/dist/memory/inference-service-main.d.ts +31 -0
  55. package/dist/memory/inference-service-main.d.ts.map +1 -0
  56. package/dist/memory/inference-service-main.js +89 -0
  57. package/dist/memory/inference-service-main.js.map +1 -0
  58. package/dist/memory/ledger.d.ts +15 -0
  59. package/dist/memory/ledger.d.ts.map +1 -1
  60. package/dist/memory/ledger.js +35 -2
  61. package/dist/memory/ledger.js.map +1 -1
  62. package/dist/memory/model-cache-hygiene.d.ts +10 -0
  63. package/dist/memory/model-cache-hygiene.d.ts.map +1 -1
  64. package/dist/memory/model-cache-hygiene.js +15 -0
  65. package/dist/memory/model-cache-hygiene.js.map +1 -1
  66. package/dist/memory/preference-promotion.d.ts +0 -14
  67. package/dist/memory/preference-promotion.d.ts.map +1 -1
  68. package/dist/memory/preference-promotion.js +17 -0
  69. package/dist/memory/preference-promotion.js.map +1 -1
  70. package/dist/memory/recall-pipeline.d.ts +85 -0
  71. package/dist/memory/recall-pipeline.d.ts.map +1 -0
  72. package/dist/memory/recall-pipeline.js +678 -0
  73. package/dist/memory/recall-pipeline.js.map +1 -0
  74. package/dist/memory/retention-sweep.d.ts +59 -0
  75. package/dist/memory/retention-sweep.d.ts.map +1 -0
  76. package/dist/memory/retention-sweep.js +103 -0
  77. package/dist/memory/retention-sweep.js.map +1 -0
  78. package/dist/memory/store.d.ts +17 -2
  79. package/dist/memory/store.d.ts.map +1 -1
  80. package/dist/memory/store.js +18 -2
  81. package/dist/memory/store.js.map +1 -1
  82. package/dist/memory/vector-channel.d.ts +120 -0
  83. package/dist/memory/vector-channel.d.ts.map +1 -0
  84. package/dist/memory/vector-channel.js +495 -0
  85. package/dist/memory/vector-channel.js.map +1 -0
  86. package/dist/memory/vector-projection.d.ts +87 -0
  87. package/dist/memory/vector-projection.d.ts.map +1 -0
  88. package/dist/memory/vector-projection.js +215 -0
  89. package/dist/memory/vector-projection.js.map +1 -0
  90. package/dist/memory/write-face.d.ts +128 -0
  91. package/dist/memory/write-face.d.ts.map +1 -0
  92. package/dist/memory/write-face.js +504 -0
  93. package/dist/memory/write-face.js.map +1 -0
  94. package/dist/testing/memory-testkit.d.ts +2 -0
  95. package/dist/testing/memory-testkit.d.ts.map +1 -1
  96. package/dist/testing/memory-testkit.js +1 -0
  97. package/dist/testing/memory-testkit.js.map +1 -1
  98. package/package.json +7 -3
  99. package/plugin.json +1 -1
@@ -0,0 +1,377 @@
1
+ import { Type } from "typebox";
2
+ import { writeMemorySettingsMode } from "./enabling.js";
3
+ import { promotePreferenceToUserDefault } from "./preference-promotion.js";
4
+ import { forgetDomainMemory, listDomainMemories, } from "./suite-memory.js";
5
+ import { EVENT_TYPE } from "./write-face.js";
6
+ const DEFAULT_LIST_LIMIT = 20;
7
+ const listSchema = Type.Object({
8
+ limit: Type.Optional(Type.Integer({ description: "Maximum number of entries to list (1-100)", minimum: 1, maximum: 100 })),
9
+ });
10
+ const forgetSchema = Type.Object({
11
+ memoryId: Type.String({
12
+ description: "The memoryId of the memory to forget, as returned by memory_write or memory_list",
13
+ }),
14
+ });
15
+ const enableSchema = Type.Object({
16
+ action: Type.Union([Type.Literal("download"), Type.Literal("decline"), Type.Literal("retry")], {
17
+ description: '"download" / "retry" run the one-time model download (retry re-runs after a failure); "decline" persists memory off for this machine',
18
+ }),
19
+ });
20
+ /** Canonical memoryId of the promoted copy of one preference (promotePreferenceToUserDefault suffix). */
21
+ const userDefaultMemoryId = (memoryId) => `${memoryId}-user-default`;
22
+ export function createMemoryCommandFace(deps) {
23
+ const { registerTool, registerCommand, publish, capabilities, owner, sessionId, agentDir, memoryMode, now, store, purgeGate, purgeJournal, vectorProjection, vectorChannelCtl, resolveDomain, memoryToolInput, statementOf, unwrapEgressStatement, tierUpgradePending, clearTierUpgrade, } = deps;
24
+ const { manifest: capabilityManifest } = deps;
25
+ /** Recency-first payload projection: unwraps the `{ statement }` payload convention. */
26
+ function entryToToolEntry(entry) {
27
+ return {
28
+ memoryId: entry.memoryId,
29
+ kind: entry.memoryKind,
30
+ statement: statementOf(entry.payload),
31
+ occurredAt: entry.occurredAt,
32
+ ...(entry.preference === undefined
33
+ ? {}
34
+ : {
35
+ preference: {
36
+ subject: entry.preference.subject,
37
+ key: entry.preference.key,
38
+ scopeLevel: entry.preference.scopeLevel,
39
+ crossSuiteVisible: entry.preference.crossSuiteVisible,
40
+ },
41
+ }),
42
+ };
43
+ }
44
+ const listTool = registerTool({
45
+ name: "memory_list",
46
+ label: "List memories",
47
+ description: "List this suite's durable memories (the explicit management surface for personal data)",
48
+ parameters: listSchema,
49
+ execute: async (first, second) => {
50
+ const input = memoryToolInput(first, second);
51
+ const rawLimit = input.limit;
52
+ const limit = rawLimit === undefined
53
+ ? DEFAULT_LIST_LIMIT
54
+ : (() => {
55
+ if (typeof rawLimit !== "number" ||
56
+ !Number.isSafeInteger(rawLimit) ||
57
+ rawLimit < 1 ||
58
+ rawLimit > 100) {
59
+ throw new Error("limit must be an integer between 1 and 100");
60
+ }
61
+ return rawLimit;
62
+ })();
63
+ const { domain } = resolveDomain();
64
+ const page = listDomainMemories({ store }, { owner, domain });
65
+ return {
66
+ domain: page.domain,
67
+ entries: page.entries.slice(0, limit).map(entryToToolEntry),
68
+ total: page.entries.length,
69
+ preferenceCount: page.preferenceCount,
70
+ factCount: page.factCount,
71
+ filter: page.filter,
72
+ };
73
+ },
74
+ });
75
+ /**
76
+ * 物理删除唯一生产入口 (诚实化设计 §2, 2026-10-05 裁决): 用户命令链
77
+ * `/memory forget <id> confirm`。授权引用由命令分发构造 (structured
78
+ * confirmationRef `memory-forget-command:<session>:<memoryId>:confirmed`),
79
+ * 模型工具面不再签发 user-immediate 授权 (记忆系统设计 :997 — 授权不能由
80
+ * 模型生成)。
81
+ */
82
+ const purgeMemoryViaUserCommand = (memoryId) => {
83
+ const { domain, ledger } = resolveDomain();
84
+ const authorizationRef = {
85
+ mode: "user-immediate",
86
+ issuedAt: now(),
87
+ issuedBy: `${capabilityManifest.id}:/memory-forget-confirm`,
88
+ confirmationRef: `memory-forget-command:${sessionId}:${memoryId}:confirmed`,
89
+ };
90
+ return forgetDomainMemory({
91
+ store,
92
+ purgeGate,
93
+ purgeJournal,
94
+ // index 副本分派 (混合检索工程化): canonical 走下方原回调, 向量投影由
95
+ // suite-memory 的 executePurgeBatch 按副本路由到这里。
96
+ purgeIndexReplica: vectorProjection.purgeMemories,
97
+ now,
98
+ }, {
99
+ owner,
100
+ domain,
101
+ memoryId,
102
+ authorizedBy: `${capabilityManifest.id}:memory-forget-command`,
103
+ authorizationRef,
104
+ }, (memoryIds) => {
105
+ const purged = new Set(memoryIds);
106
+ // Physical replica purge: rewrite the durable ledger without the
107
+ // purged atoms, then evict them from the in-memory store so the
108
+ // running process cannot recall them either (both idempotent for
109
+ // purge_eligible retries).
110
+ ledger.rewrite(ledger.atomsSnapshot().filter((atom) => !purged.has(atom.memoryId)));
111
+ for (const id of memoryIds)
112
+ store.evict(id);
113
+ });
114
+ };
115
+ const forgetTool = registerTool({
116
+ name: "memory_forget",
117
+ label: "File a forget request",
118
+ description: "File a request to forget one memory of this suite by memoryId. This tool never deletes anything — physical deletion is user-only: the user confirms via /memory forget <memoryId> confirm",
119
+ parameters: forgetSchema,
120
+ execute: async (first, second) => {
121
+ const input = memoryToolInput(first, second);
122
+ deps.assertNonEmptyString(input.memoryId, "memoryId");
123
+ const { domain, domainName } = resolveDomain();
124
+ const unscoped = store.get(input.memoryId, { owner });
125
+ if (unscoped === undefined) {
126
+ return { status: "not_found", memoryId: input.memoryId };
127
+ }
128
+ // 域成员判定与 forgetDomainMemory 同判据 (suiteId 匹配 / legacy 为
129
+ // undefined): 请求面同样拒绝外域 id — 模型连"请求遗忘"都不能指向别的域。
130
+ const isMember = domain.kind === "suite" ? unscoped.atom.suiteId === domain.suiteId : unscoped.atom.suiteId === undefined;
131
+ if (!isMember) {
132
+ return { status: "foreign_domain", memoryId: input.memoryId };
133
+ }
134
+ // 请求的登记价值由返回文本承载 (转告用户确认命令); 无进程内状态 —
135
+ // 重复请求幂等 (同一提示再次返回)。
136
+ return {
137
+ status: "requested",
138
+ memoryId: input.memoryId,
139
+ request: `Forget request filed for "${unwrapEgressStatement(statementOf(unscoped.atom.payload))}" in domain ${domainName}. ` +
140
+ `Nothing is deleted yet — tell the user to confirm the deletion with: /memory forget ${input.memoryId} confirm`,
141
+ };
142
+ },
143
+ });
144
+ /**
145
+ * /promote (偏好晋升触发, B2; 2026-10-05 诚实化裁决起两步确认): the production
146
+ * caller of {@link promotePreferenceToUserDefault}. Promotes one of THIS
147
+ * session's preferences to the user-default scope: the promoted canonical atom
148
+ * is appended to the session domain's durable ledger and committed to the
149
+ * store, so every suite's preference-card read (which applies the suite read
150
+ * boundary across all of the owner's ledgers) sees it from now on. The
151
+ * original atom is never rewritten. Promotion is an irreversible cross-suite
152
+ * authorization face, so the first run only shows the target and asks the
153
+ * user to re-run with `confirm`. Errors (unknown id, non-preference, already
154
+ * promoted) surface as error results, never as thrown failures — a slash
155
+ * command must not crash the host.
156
+ */
157
+ const promoteCommand = registerCommand({
158
+ name: "promote",
159
+ description: "Promote a memory preference to the user-default scope (visible in every suite; two-step — re-run with confirm)",
160
+ argumentHint: "<memoryId> [confirm]",
161
+ execute: async (args) => {
162
+ const tokens = args.trim().split(/\s+/).filter(Boolean);
163
+ const memoryId = tokens[0] ?? "";
164
+ const confirmed = tokens[1] === "confirm";
165
+ if (memoryId === "" || tokens.length > 2 || (tokens[1] !== undefined && !confirmed)) {
166
+ return {
167
+ status: "error",
168
+ message: "Usage: /promote <memoryId> [confirm] — run memory_list for this suite's memory ids",
169
+ };
170
+ }
171
+ const record = store.get(memoryId, { owner });
172
+ if (!record) {
173
+ return {
174
+ status: "error",
175
+ message: `No memory found with id ${memoryId}; run memory_list for this suite's memory ids`,
176
+ };
177
+ }
178
+ const atom = record.atom;
179
+ if (atom.memoryKind !== "preference" || atom.preference === undefined) {
180
+ return {
181
+ status: "error",
182
+ message: `${memoryId} is a fact, not a preference; only preferences can be promoted`,
183
+ };
184
+ }
185
+ if (store.get(userDefaultMemoryId(memoryId), { owner }) !== undefined) {
186
+ return {
187
+ status: "error",
188
+ message: `Preference ${memoryId} is already promoted to the user-default scope`,
189
+ };
190
+ }
191
+ if (!confirmed) {
192
+ return {
193
+ status: "success",
194
+ message: `Promotion target: "${unwrapEgressStatement(statementOf(atom.payload))}"\n` +
195
+ "This makes the preference visible in EVERY suite (user-default scope, permanent). Nothing is promoted yet — re-run to confirm:\n" +
196
+ `/promote ${memoryId} confirm`,
197
+ };
198
+ }
199
+ try {
200
+ const promoted = promotePreferenceToUserDefault({
201
+ atom,
202
+ authorizedBy: "user:/promote",
203
+ confirmedAt: new Date(now()).toISOString(),
204
+ });
205
+ const { domainName, ledger } = resolveDomain();
206
+ ledger.append(promoted);
207
+ store.commit(promoted);
208
+ // 向量投影埋点: 与 memory_write 同一异步旁路 (失败不阻塞命令返回)。
209
+ vectorProjection.upsertAtom(promoted);
210
+ return {
211
+ status: "success",
212
+ message: `Promoted "${unwrapEgressStatement(statementOf(promoted.payload))}" to the user-default scope; it is now visible in every suite`,
213
+ data: { memoryId: promoted.memoryId, sourceMemoryId: memoryId, domain: domainName },
214
+ };
215
+ }
216
+ catch (error) {
217
+ return { status: "error", message: error instanceof Error ? error.message : String(error) };
218
+ }
219
+ },
220
+ });
221
+ // memory.scheduler@1 plugin capability (宪法 §3 显式声明面): a declarative
222
+ // marker only — the scheduler enforcement itself (per-instance single
223
+ // lease, acquired above) stays carried by the host builtin implementation.
224
+ // The declaration anchors "this suite's memory scheduling is provided by
225
+ // this plugin" so the code Profile assembly check (requiresMemoryScheduler)
226
+ // and third-party replacement detection have an explicit surface:
227
+ // list()-visible, a same-id double provide fails explicitly (no override
228
+ // priority), and after dispose a replacement provider can take the id.
229
+ const schedulerCapability = capabilities.provide({ id: "memory.scheduler", version: 1, kind: "service" }, () => Object.freeze({
230
+ id: "memory.scheduler",
231
+ version: 1,
232
+ owner: "agent-forge.builtin.memory",
233
+ leaseScope: "per-agent-instance",
234
+ }));
235
+ // ---- 征询门执行面 (2026-10-05 用户裁决「首次使用征询、拒绝/失败可跳过」) ----
236
+ // memory_enable 是 consent-required / failed 态的唯一下载入口: consentGranted
237
+ // 只在这里置位, recall/auto-recall 永不触发下载。decline 同时持久化
238
+ // (writeMemoryConsentDeclined), 只抑制默认档——用户显式设置 memory.mode 后
239
+ // 下次启用会在首次使用时再次走到征询门。
240
+ // ---- 记忆模型下载控制面 (2026-10-05 流程裁决「后台预热、不阻塞提问」) ----
241
+ // 生产入口 (交互模式会话绑定后) 经公共工具面调用 memory_enable download
242
+ // 触发后台预热; 命令面 /memory off|retry 是用户的直接出口。decline/download
243
+ // 核心在 memory/vector-channel.ts (slice 3b), 工具与命令面经
244
+ // vectorChannelCtl.decline()/download() 薄委托; decline 持久化只抑制默认档。
245
+ const memoryStatusLine = () => {
246
+ // pending 尾巴只对仍有效的升档声明 (declined 分支里档位键已被删除, 显示
247
+ // pending 会失实 — 2026-10-06 复审 P2-1)。
248
+ const declined = vectorChannelCtl.declined();
249
+ const pendingUpgrade = tierUpgradePending() && !declined;
250
+ const modeLine = `mode=${memoryMode}${pendingUpgrade ? ", auto-upgrade to full pending (next session)" : ""}`;
251
+ if (declined) {
252
+ return `${modeLine}, off (declined on this machine). Set memory.mode (light|full) in settings.json and restart the session to re-enable`;
253
+ }
254
+ const channelState = vectorChannelCtl.rawState();
255
+ if (channelState === "ready")
256
+ return `${modeLine}, ready`;
257
+ if (channelState === "degraded")
258
+ return `${modeLine}, ready (degraded)`;
259
+ if (channelState === "failed")
260
+ return `${modeLine}, failed: ${vectorChannelCtl.failure()?.reason ?? "unknown reason"}`;
261
+ if (channelState === "consent-required")
262
+ return `${modeLine}, waiting for the model download decision (/memory retry to start it)`;
263
+ return `${modeLine}, loading models in the background`;
264
+ };
265
+ const enableTool = registerTool({
266
+ name: "memory_enable",
267
+ label: "Enable memory",
268
+ description: 'Run or decline the one-time memory model download. The host starts it in the background at session start; call it with "retry" after a failure, or with "decline" when the user chooses to keep memory off',
269
+ parameters: enableSchema,
270
+ execute: async (first, second) => {
271
+ const input = memoryToolInput(first, second);
272
+ const action = input.action;
273
+ if (action !== "download" && action !== "decline" && action !== "retry") {
274
+ throw new Error('action must be "download", "decline", or "retry"');
275
+ }
276
+ if (action === "decline")
277
+ return vectorChannelCtl.decline();
278
+ return vectorChannelCtl.download();
279
+ },
280
+ });
281
+ const memoryCommand = registerCommand({
282
+ name: "memory",
283
+ description: "Memory controls: bare shows status; light|full switches the model preset (persisted, effective next session); off persists disable; retry re-runs the model download; forget <memoryId> [confirm] is the user-only physical delete (two-step)",
284
+ argumentHint: "[light|full|off|retry|forget <memoryId> [confirm]]",
285
+ execute: async (args) => {
286
+ const tokens = args.trim().split(/\s+/).filter(Boolean);
287
+ if (tokens[0] === "forget") {
288
+ const memoryId = tokens[1] ?? "";
289
+ const confirmed = tokens[2] === "confirm";
290
+ if (memoryId === "" || tokens.length > 3 || (tokens[2] !== undefined && !confirmed)) {
291
+ return { status: "error", message: "Usage: /memory forget <memoryId> [confirm]" };
292
+ }
293
+ const { domain, domainName } = resolveDomain();
294
+ const unscoped = store.get(memoryId, { owner });
295
+ if (unscoped === undefined) {
296
+ return {
297
+ status: "error",
298
+ message: `No memory found with id ${memoryId}; run memory_list for this suite's memory ids`,
299
+ };
300
+ }
301
+ const isMember = domain.kind === "suite" ? unscoped.atom.suiteId === domain.suiteId : unscoped.atom.suiteId === undefined;
302
+ if (!isMember) {
303
+ return {
304
+ status: "error",
305
+ message: `${memoryId} belongs to another suite; each suite forgets only its own memories`,
306
+ };
307
+ }
308
+ if (!confirmed) {
309
+ return {
310
+ status: "success",
311
+ message: `Forget target: "${unwrapEgressStatement(statementOf(unscoped.atom.payload))}"\n` +
312
+ "This permanently deletes the memory (irreversible, purge-gated). Nothing is deleted yet — re-run to confirm:\n" +
313
+ `/memory forget ${memoryId} confirm`,
314
+ };
315
+ }
316
+ const result = purgeMemoryViaUserCommand(memoryId);
317
+ if (result.status === "completed") {
318
+ await publish({
319
+ type: EVENT_TYPE,
320
+ version: 1,
321
+ correlationId: capabilityManifest.id,
322
+ data: { action: "forgotten", memoryId, domain: domainName, batchId: result.batchId },
323
+ });
324
+ return {
325
+ status: "success",
326
+ message: `Forgot ${memoryId} (${domainName}): the memory is physically deleted`,
327
+ data: { memoryId, domain: domainName, batchId: result.batchId },
328
+ };
329
+ }
330
+ return { status: "error", message: `forget failed: ${result.status}` };
331
+ }
332
+ const sub = args.trim().toLowerCase();
333
+ if (sub === "" || sub === "status") {
334
+ return { status: "success", message: `memory: ${memoryStatusLine()}` };
335
+ }
336
+ if (sub === "light" || sub === "full") {
337
+ // 无"已是该档"早退: 持久化档位与会话内已解析档位是两回事——会话可能
338
+ // 因默认档而运行 light, 用户降档仍需把持久化值落盘 (或覆盖旧档)。
339
+ writeMemorySettingsMode(agentDir, sub);
340
+ // 升/降档清了文件里的拒绝标记, 内存标记同步翻回: 用户最新的显式
341
+ // 意图是启用——本会话恢复对当前预置的响应 (retry 可用), 新档与
342
+ // 新模型下载在下一会话生效。
343
+ vectorChannelCtl.clearDeclined();
344
+ // 用户的显式档位表达取代本实例的自动升档声明: 降回 light 后 pending
345
+ // 尾巴不再显示, 且显式 light 会让自动升档在后续写入中跳过 (复审 P2-1)。
346
+ if (sub === "light")
347
+ clearTierUpgrade();
348
+ return {
349
+ status: "success",
350
+ message: `memory: preset ${sub} persisted (capabilities/builtin.memory.json). It takes effect next session — ` +
351
+ (sub === "full"
352
+ ? "the larger embedding model (bge-m3, hundreds of MB) downloads in the background at the next start, disk headroom ≥2GB, and write-side semantic dedup turns on. "
353
+ : "") +
354
+ "Existing memories carry over: the projection rebuilds onto the new model automatically.",
355
+ };
356
+ }
357
+ // 命令面结果映射: 工具闭包的 completed/failed 面转 CapabilityCommandResult
358
+ // 的 success/error; 行动清单/next 指引并入 message (命令结果无 actions 字段)。
359
+ const toCommandResult = (result) => ({
360
+ status: result.status === "completed" ? "success" : "error",
361
+ message: result.status === "failed"
362
+ ? [result.message, ...(result.actions ?? []), result.next].filter(Boolean).join(" — ")
363
+ : result.message,
364
+ });
365
+ if (sub === "off")
366
+ return toCommandResult(vectorChannelCtl.decline());
367
+ if (sub === "retry")
368
+ return toCommandResult(await vectorChannelCtl.download());
369
+ return {
370
+ status: "error",
371
+ message: "Usage: /memory [light|full|off|retry|forget <memoryId> [confirm]]",
372
+ };
373
+ },
374
+ });
375
+ return { listTool, forgetTool, enableTool, memoryCommand, promoteCommand, schedulerCapability };
376
+ }
377
+ //# sourceMappingURL=command-face.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command-face.js","sourceRoot":"","sources":["../../src/memory/command-face.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AAExD,OAAO,EAAE,8BAA8B,EAAE,MAAM,2BAA2B,CAAC;AAI3E,OAAO,EACN,kBAAkB,EAClB,kBAAkB,GAIlB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAE9B,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC;IAC9B,KAAK,EAAE,IAAI,CAAC,QAAQ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OAAO;gBAAE,OAAO,eAAe,CAAC,MAAM,gBAAgB,CAAC,QAAQ,EAAE,CAAC,CAAC;YAC/E,OAAO;gBACN,MAAM,EAAE,OAAgB;gBACxB,OAAO,EAAE,mEAAmE;aAC5E,CAAC;QAAA,CACF;KACD,CAAC,CAAC;IAEH,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,UAAU,EAAE,aAAa,EAAE,cAAc,EAAE,mBAAmB,EAAE,CAAC;AAAA,CAChG","sourcesContent":["/**\n * 命令面(capability 拆分战役 slice 6):memory_list / memory_forget 工具、\n * /memory 与 /promote 命令、memory_enable 征询执行面与 memory.scheduler 能力\n * 声明。物理删除的授权引用构造在本面(用户命令链专用); decline/download 仍\n * 薄委托 vectorChannelCtl(slice 3b 先例, 经 deps 下的 channel 对象调用);\n * 搬移函数体逐字节保留。\n */\nimport type { CapabilityAPI, DisposableRegistration } from \"@agent-forge/plugin-sdk\";\nimport { Type } from \"typebox\";\nimport { writeMemorySettingsMode } from \"./enabling.ts\";\nimport type { DurableMemoryLedgerV1 } from \"./ledger.ts\";\nimport { promotePreferenceToUserDefault } from \"./preference-promotion.ts\";\nimport type { MemoryPurgeGateV1 } from \"./purge.ts\";\nimport type { MemoryPurgeJournalV1 } from \"./purge-journal.ts\";\nimport type { MemoryStoreV1 } from \"./store.ts\";\nimport {\n\tforgetDomainMemory,\n\tlistDomainMemories,\n\ttype SuiteForgetAuthorizationRefV1,\n\ttype SuiteMemoryDomainV1,\n\ttype SuiteMemoryListEntryV1,\n} from \"./suite-memory.ts\";\nimport type { MemoryVectorChannelV1 } from \"./vector-channel.ts\";\nimport type { MemoryVectorProjectionV1 } from \"./vector-projection.ts\";\nimport { EVENT_TYPE } from \"./write-face.ts\";\n\nconst DEFAULT_LIST_LIMIT = 20;\n\nconst listSchema = Type.Object({\n\tlimit: Type.Optional(\n\t\tType.Integer({ description: \"Maximum number of entries to list (1-100)\", minimum: 1, maximum: 100 }),\n\t),\n});\n\nconst forgetSchema = Type.Object({\n\tmemoryId: Type.String({\n\t\tdescription: \"The memoryId of the memory to forget, as returned by memory_write or memory_list\",\n\t}),\n});\n\nconst enableSchema = Type.Object({\n\taction: Type.Union([Type.Literal(\"download\"), Type.Literal(\"decline\"), Type.Literal(\"retry\")], {\n\t\tdescription:\n\t\t\t'\"download\" / \"retry\" run the one-time model download (retry re-runs after a failure); \"decline\" persists memory off for this machine',\n\t}),\n});\n\n/** Canonical memoryId of the promoted copy of one preference (promotePreferenceToUserDefault suffix). */\nconst userDefaultMemoryId = (memoryId: string): string => `${memoryId}-user-default`;\n\n/**\n * 命令面对 capability 闭包的显式依赖视图 (slice 6): 逐项来自\n * createMemoryCapabilityHarness 的闭包捕获核实。状态机 (vectorChannelCtl)、\n * 写侧投影 (vectorProjection) 与 purge 组件归 capability 装配所有, 本模块经\n * 对象只读消费; capability 模块级纯函数经 deps 注入避免双头定义。\n */\nexport interface MemoryCommandFaceDepsV1 {\n\t/** 工具注册面 (api.registerTool): memory_list/forget/enable 经同一公共通道注册。 */\n\treadonly registerTool: CapabilityAPI[\"registerTool\"];\n\t/** 命令注册面 (api.registerCommand): /memory 与 /promote。 */\n\treadonly registerCommand: CapabilityAPI[\"registerCommand\"];\n\t/** 事件发布面 (api.publish): memory.changed forgotten 事件。 */\n\treadonly publish: CapabilityAPI[\"publish\"];\n\t/** 能力声明面 (api.capabilities): memory.scheduler@1 provide。 */\n\treadonly capabilities: CapabilityAPI[\"capabilities\"];\n\t/** 检索行 owner (capability.BUILTIN_MEMORY_OWNER)。 */\n\treadonly owner: string;\n\t/** 会话 id (harness sessionId): forget 授权引用 confirmationRef 组成。 */\n\treadonly sessionId: string;\n\t/** capability 清单 (capabilityManifest): issuedBy / authorizedBy / 事件 correlationId 来源。 */\n\treadonly manifest: { readonly id: string };\n\t/** agent 根目录 (MemoryCapabilityContext.agentDir): 档位持久化路径域。 */\n\treadonly agentDir: string;\n\t/** 已解析的全局档位 (harness memoryMode, off 已被工厂入口拦截)。 */\n\treadonly memoryMode: \"light\" | \"full\";\n\t/** 时钟 (harness now)。 */\n\treadonly now: () => number;\n\t/** canonical store (per-capability 单例): 列表/成员判定/晋升回查。 */\n\treadonly store: MemoryStoreV1;\n\t/** purge 门 (capability.purgeGate): 物理删除唯一生产入口的授权面。 */\n\treadonly purgeGate: MemoryPurgeGateV1;\n\t/** purge 日志 (capability.purgeJournal)。 */\n\treadonly purgeJournal: MemoryPurgeJournalV1;\n\t/** 写侧投影 (slice 3a 的 vectorProjection): forget 批次的 index 副本分派与晋升埋点。 */\n\treadonly vectorProjection: MemoryVectorProjectionV1;\n\t/** 向量通道 (slice 3b 的 vectorChannelCtl): 状态行与 decline/download 薄委托。 */\n\treadonly vectorChannelCtl: MemoryVectorChannelV1;\n\t/** 域解析 (capability.resolveDomain): 每次调用时惰性解析 (B1 语义)。 */\n\treadonly resolveDomain: () => {\n\t\treadonly domain: SuiteMemoryDomainV1;\n\t\treadonly domainName: string;\n\t\treadonly ledger: DurableMemoryLedgerV1;\n\t};\n\t// ---- capability 模块级纯函数 (留守方, 经 deps 注入避免双头定义) ----\n\treadonly assertNonEmptyString: (value: unknown, label: string) => asserts value is string;\n\treadonly memoryToolInput: (first: unknown, second: unknown) => Record<string, unknown>;\n\treadonly statementOf: (payload: unknown) => string;\n\treadonly unwrapEgressStatement: (statement: string) => string;\n\t// ---- 写入面闭包视图 (slice 5 的 writeFace): 升档声明状态归 write-face 所有 ----\n\t/** 升档声明只读视图 (/memory 状态行 pending 尾巴)。 */\n\treadonly tierUpgradePending: () => boolean;\n\t/** 用户显式档位表达取代本实例升档声明 (/memory light)。 */\n\treadonly clearTierUpgrade: () => void;\n}\n\n/** 命令面工厂产物: 注册项集合 (capability registrations 按既有顺序收集)。 */\nexport interface MemoryCommandFaceV1 {\n\t/** memory_list 工具注册项。 */\n\treadonly listTool: DisposableRegistration;\n\t/** memory_forget 工具注册项 (仅登记请求, 物理删除在 /memory forget)。 */\n\treadonly forgetTool: DisposableRegistration;\n\t/** memory_enable 工具注册项 (征询门执行面)。 */\n\treadonly enableTool: DisposableRegistration;\n\t/** /memory 命令注册项。 */\n\treadonly memoryCommand: DisposableRegistration;\n\t/** /promote 命令注册项。 */\n\treadonly promoteCommand: DisposableRegistration;\n\t/** memory.scheduler@1 plugin capability 声明注册项。 */\n\treadonly schedulerCapability: DisposableRegistration;\n}\n\nexport function createMemoryCommandFace(deps: MemoryCommandFaceDepsV1): MemoryCommandFaceV1 {\n\tconst {\n\t\tregisterTool,\n\t\tregisterCommand,\n\t\tpublish,\n\t\tcapabilities,\n\t\towner,\n\t\tsessionId,\n\t\tagentDir,\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\tmemoryToolInput,\n\t\tstatementOf,\n\t\tunwrapEgressStatement,\n\t\ttierUpgradePending,\n\t\tclearTierUpgrade,\n\t} = deps;\n\tconst { manifest: capabilityManifest } = deps;\n\n\t/** Recency-first payload projection: unwraps the `{ statement }` payload convention. */\n\tfunction entryToToolEntry(entry: SuiteMemoryListEntryV1): Record<string, unknown> {\n\t\treturn {\n\t\t\tmemoryId: entry.memoryId,\n\t\t\tkind: entry.memoryKind,\n\t\t\tstatement: statementOf(entry.payload),\n\t\t\toccurredAt: entry.occurredAt,\n\t\t\t...(entry.preference === undefined\n\t\t\t\t? {}\n\t\t\t\t: {\n\t\t\t\t\t\tpreference: {\n\t\t\t\t\t\t\tsubject: entry.preference.subject,\n\t\t\t\t\t\t\tkey: entry.preference.key,\n\t\t\t\t\t\t\tscopeLevel: entry.preference.scopeLevel,\n\t\t\t\t\t\t\tcrossSuiteVisible: entry.preference.crossSuiteVisible,\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t};\n\t}\n\n\tconst listTool = registerTool({\n\t\tname: \"memory_list\",\n\t\tlabel: \"List memories\",\n\t\tdescription: \"List this suite's durable memories (the explicit management surface for personal data)\",\n\t\tparameters: listSchema,\n\t\texecute: async (first: unknown, second?: unknown) => {\n\t\t\tconst input = memoryToolInput(first, second);\n\t\t\tconst rawLimit: unknown = input.limit;\n\t\t\tconst limit =\n\t\t\t\trawLimit === undefined\n\t\t\t\t\t? DEFAULT_LIST_LIMIT\n\t\t\t\t\t: ((): number => {\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\ttypeof rawLimit !== \"number\" ||\n\t\t\t\t\t\t\t\t!Number.isSafeInteger(rawLimit) ||\n\t\t\t\t\t\t\t\trawLimit < 1 ||\n\t\t\t\t\t\t\t\trawLimit > 100\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tthrow new Error(\"limit must be an integer between 1 and 100\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn rawLimit;\n\t\t\t\t\t\t})();\n\t\t\tconst { domain } = resolveDomain();\n\t\t\tconst page = listDomainMemories({ store }, { owner, domain });\n\t\t\treturn {\n\t\t\t\tdomain: page.domain,\n\t\t\t\tentries: page.entries.slice(0, limit).map(entryToToolEntry),\n\t\t\t\ttotal: page.entries.length,\n\t\t\t\tpreferenceCount: page.preferenceCount,\n\t\t\t\tfactCount: page.factCount,\n\t\t\t\tfilter: page.filter,\n\t\t\t};\n\t\t},\n\t});\n\n\t/**\n\t * 物理删除唯一生产入口 (诚实化设计 §2, 2026-10-05 裁决): 用户命令链\n\t * `/memory forget <id> confirm`。授权引用由命令分发构造 (structured\n\t * confirmationRef `memory-forget-command:<session>:<memoryId>:confirmed`),\n\t * 模型工具面不再签发 user-immediate 授权 (记忆系统设计 :997 — 授权不能由\n\t * 模型生成)。\n\t */\n\tconst purgeMemoryViaUserCommand = (memoryId: string) => {\n\t\tconst { domain, ledger } = resolveDomain();\n\t\tconst authorizationRef: SuiteForgetAuthorizationRefV1 = {\n\t\t\tmode: \"user-immediate\",\n\t\t\tissuedAt: now(),\n\t\t\tissuedBy: `${capabilityManifest.id}:/memory-forget-confirm`,\n\t\t\tconfirmationRef: `memory-forget-command:${sessionId}:${memoryId}:confirmed`,\n\t\t};\n\t\treturn forgetDomainMemory(\n\t\t\t{\n\t\t\t\tstore,\n\t\t\t\tpurgeGate,\n\t\t\t\tpurgeJournal,\n\t\t\t\t// index 副本分派 (混合检索工程化): canonical 走下方原回调, 向量投影由\n\t\t\t\t// suite-memory 的 executePurgeBatch 按副本路由到这里。\n\t\t\t\tpurgeIndexReplica: vectorProjection.purgeMemories,\n\t\t\t\tnow,\n\t\t\t},\n\t\t\t{\n\t\t\t\towner,\n\t\t\t\tdomain,\n\t\t\t\tmemoryId,\n\t\t\t\tauthorizedBy: `${capabilityManifest.id}:memory-forget-command`,\n\t\t\t\tauthorizationRef,\n\t\t\t},\n\t\t\t(memoryIds) => {\n\t\t\t\tconst purged = new Set(memoryIds);\n\t\t\t\t// Physical replica purge: rewrite the durable ledger without the\n\t\t\t\t// purged atoms, then evict them from the in-memory store so the\n\t\t\t\t// running process cannot recall them either (both idempotent for\n\t\t\t\t// purge_eligible retries).\n\t\t\t\tledger.rewrite(ledger.atomsSnapshot().filter((atom) => !purged.has(atom.memoryId)));\n\t\t\t\tfor (const id of memoryIds) store.evict(id);\n\t\t\t},\n\t\t);\n\t};\n\n\tconst forgetTool = registerTool({\n\t\tname: \"memory_forget\",\n\t\tlabel: \"File a forget request\",\n\t\tdescription:\n\t\t\t\"File a request to forget one memory of this suite by memoryId. This tool never deletes anything — physical deletion is user-only: the user confirms via /memory forget <memoryId> confirm\",\n\t\tparameters: forgetSchema,\n\t\texecute: async (first: unknown, second?: unknown) => {\n\t\t\tconst input = memoryToolInput(first, second);\n\t\t\tdeps.assertNonEmptyString(input.memoryId, \"memoryId\");\n\t\t\tconst { domain, domainName } = resolveDomain();\n\t\t\tconst unscoped = store.get(input.memoryId, { owner });\n\t\t\tif (unscoped === undefined) {\n\t\t\t\treturn { status: \"not_found\" as const, memoryId: input.memoryId };\n\t\t\t}\n\t\t\t// 域成员判定与 forgetDomainMemory 同判据 (suiteId 匹配 / legacy 为\n\t\t\t// undefined): 请求面同样拒绝外域 id — 模型连\"请求遗忘\"都不能指向别的域。\n\t\t\tconst isMember =\n\t\t\t\tdomain.kind === \"suite\" ? unscoped.atom.suiteId === domain.suiteId : unscoped.atom.suiteId === undefined;\n\t\t\tif (!isMember) {\n\t\t\t\treturn { status: \"foreign_domain\" as const, memoryId: input.memoryId };\n\t\t\t}\n\t\t\t// 请求的登记价值由返回文本承载 (转告用户确认命令); 无进程内状态 —\n\t\t\t// 重复请求幂等 (同一提示再次返回)。\n\t\t\treturn {\n\t\t\t\tstatus: \"requested\" as const,\n\t\t\t\tmemoryId: input.memoryId,\n\t\t\t\trequest:\n\t\t\t\t\t`Forget request filed for \"${unwrapEgressStatement(statementOf(unscoped.atom.payload))}\" in domain ${domainName}. ` +\n\t\t\t\t\t`Nothing is deleted yet — tell the user to confirm the deletion with: /memory forget ${input.memoryId} confirm`,\n\t\t\t};\n\t\t},\n\t});\n\n\t/**\n\t * /promote (偏好晋升触发, B2; 2026-10-05 诚实化裁决起两步确认): the production\n\t * caller of {@link promotePreferenceToUserDefault}. Promotes one of THIS\n\t * session's preferences to the user-default scope: the promoted canonical atom\n\t * is appended to the session domain's durable ledger and committed to the\n\t * store, so every suite's preference-card read (which applies the suite read\n\t * boundary across all of the owner's ledgers) sees it from now on. The\n\t * original atom is never rewritten. Promotion is an irreversible cross-suite\n\t * authorization face, so the first run only shows the target and asks the\n\t * user to re-run with `confirm`. Errors (unknown id, non-preference, already\n\t * promoted) surface as error results, never as thrown failures — a slash\n\t * command must not crash the host.\n\t */\n\tconst promoteCommand = registerCommand({\n\t\tname: \"promote\",\n\t\tdescription:\n\t\t\t\"Promote a memory preference to the user-default scope (visible in every suite; two-step — re-run with confirm)\",\n\t\targumentHint: \"<memoryId> [confirm]\",\n\t\texecute: async (args: string) => {\n\t\t\tconst tokens = args.trim().split(/\\s+/).filter(Boolean);\n\t\t\tconst memoryId = tokens[0] ?? \"\";\n\t\t\tconst confirmed = tokens[1] === \"confirm\";\n\t\t\tif (memoryId === \"\" || tokens.length > 2 || (tokens[1] !== undefined && !confirmed)) {\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\tmessage: \"Usage: /promote <memoryId> [confirm] — run memory_list for this suite's memory ids\",\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst record = store.get(memoryId, { owner });\n\t\t\tif (!record) {\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\tmessage: `No memory found with id ${memoryId}; run memory_list for this suite's memory ids`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst atom = record.atom;\n\t\t\tif (atom.memoryKind !== \"preference\" || atom.preference === undefined) {\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\tmessage: `${memoryId} is a fact, not a preference; only preferences can be promoted`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (store.get(userDefaultMemoryId(memoryId), { owner }) !== undefined) {\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\tmessage: `Preference ${memoryId} is already promoted to the user-default scope`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!confirmed) {\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"success\" as const,\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t`Promotion target: \"${unwrapEgressStatement(statementOf(atom.payload))}\"\\n` +\n\t\t\t\t\t\t\"This makes the preference visible in EVERY suite (user-default scope, permanent). Nothing is promoted yet — re-run to confirm:\\n\" +\n\t\t\t\t\t\t`/promote ${memoryId} confirm`,\n\t\t\t\t};\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst promoted = promotePreferenceToUserDefault({\n\t\t\t\t\tatom,\n\t\t\t\t\tauthorizedBy: \"user:/promote\",\n\t\t\t\t\tconfirmedAt: new Date(now()).toISOString(),\n\t\t\t\t});\n\t\t\t\tconst { domainName, ledger } = resolveDomain();\n\t\t\t\tledger.append(promoted);\n\t\t\t\tstore.commit(promoted);\n\t\t\t\t// 向量投影埋点: 与 memory_write 同一异步旁路 (失败不阻塞命令返回)。\n\t\t\t\tvectorProjection.upsertAtom(promoted);\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"success\" as const,\n\t\t\t\t\tmessage: `Promoted \"${unwrapEgressStatement(statementOf(promoted.payload))}\" to the user-default scope; it is now visible in every suite`,\n\t\t\t\t\tdata: { memoryId: promoted.memoryId, sourceMemoryId: memoryId, domain: domainName },\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\treturn { status: \"error\" as const, message: error instanceof Error ? error.message : String(error) };\n\t\t\t}\n\t\t},\n\t});\n\n\t// memory.scheduler@1 plugin capability (宪法 §3 显式声明面): a declarative\n\t// marker only — the scheduler enforcement itself (per-instance single\n\t// lease, acquired above) stays carried by the host builtin implementation.\n\t// The declaration anchors \"this suite's memory scheduling is provided by\n\t// this plugin\" so the code Profile assembly check (requiresMemoryScheduler)\n\t// and third-party replacement detection have an explicit surface:\n\t// list()-visible, a same-id double provide fails explicitly (no override\n\t// priority), and after dispose a replacement provider can take the id.\n\tconst schedulerCapability = capabilities.provide({ id: \"memory.scheduler\", version: 1, kind: \"service\" }, () =>\n\t\tObject.freeze({\n\t\t\tid: \"memory.scheduler\",\n\t\t\tversion: 1,\n\t\t\towner: \"agent-forge.builtin.memory\",\n\t\t\tleaseScope: \"per-agent-instance\",\n\t\t}),\n\t);\n\n\t// ---- 征询门执行面 (2026-10-05 用户裁决「首次使用征询、拒绝/失败可跳过」) ----\n\t// memory_enable 是 consent-required / failed 态的唯一下载入口: consentGranted\n\t// 只在这里置位, recall/auto-recall 永不触发下载。decline 同时持久化\n\t// (writeMemoryConsentDeclined), 只抑制默认档——用户显式设置 memory.mode 后\n\t// 下次启用会在首次使用时再次走到征询门。\n\t// ---- 记忆模型下载控制面 (2026-10-05 流程裁决「后台预热、不阻塞提问」) ----\n\t// 生产入口 (交互模式会话绑定后) 经公共工具面调用 memory_enable download\n\t// 触发后台预热; 命令面 /memory off|retry 是用户的直接出口。decline/download\n\t// 核心在 memory/vector-channel.ts (slice 3b), 工具与命令面经\n\t// vectorChannelCtl.decline()/download() 薄委托; decline 持久化只抑制默认档。\n\tconst memoryStatusLine = (): string => {\n\t\t// pending 尾巴只对仍有效的升档声明 (declined 分支里档位键已被删除, 显示\n\t\t// pending 会失实 — 2026-10-06 复审 P2-1)。\n\t\tconst declined = vectorChannelCtl.declined();\n\t\tconst pendingUpgrade = tierUpgradePending() && !declined;\n\t\tconst modeLine = `mode=${memoryMode}${pendingUpgrade ? \", auto-upgrade to full pending (next session)\" : \"\"}`;\n\t\tif (declined) {\n\t\t\treturn `${modeLine}, off (declined on this machine). Set memory.mode (light|full) in settings.json and restart the session to re-enable`;\n\t\t}\n\t\tconst channelState = vectorChannelCtl.rawState();\n\t\tif (channelState === \"ready\") return `${modeLine}, ready`;\n\t\tif (channelState === \"degraded\") return `${modeLine}, ready (degraded)`;\n\t\tif (channelState === \"failed\")\n\t\t\treturn `${modeLine}, failed: ${vectorChannelCtl.failure()?.reason ?? \"unknown reason\"}`;\n\t\tif (channelState === \"consent-required\")\n\t\t\treturn `${modeLine}, waiting for the model download decision (/memory retry to start it)`;\n\t\treturn `${modeLine}, loading models in the background`;\n\t};\n\tconst enableTool = registerTool({\n\t\tname: \"memory_enable\",\n\t\tlabel: \"Enable memory\",\n\t\tdescription:\n\t\t\t'Run or decline the one-time memory model download. The host starts it in the background at session start; call it with \"retry\" after a failure, or with \"decline\" when the user chooses to keep memory off',\n\t\tparameters: enableSchema,\n\t\texecute: async (first: unknown, second?: unknown) => {\n\t\t\tconst input = memoryToolInput(first, second);\n\t\t\tconst action: unknown = input.action;\n\t\t\tif (action !== \"download\" && action !== \"decline\" && action !== \"retry\") {\n\t\t\t\tthrow new Error('action must be \"download\", \"decline\", or \"retry\"');\n\t\t\t}\n\t\t\tif (action === \"decline\") return vectorChannelCtl.decline();\n\t\t\treturn vectorChannelCtl.download();\n\t\t},\n\t});\n\tconst memoryCommand = registerCommand({\n\t\tname: \"memory\",\n\t\tdescription:\n\t\t\t\"Memory controls: bare shows status; light|full switches the model preset (persisted, effective next session); off persists disable; retry re-runs the model download; forget <memoryId> [confirm] is the user-only physical delete (two-step)\",\n\t\targumentHint: \"[light|full|off|retry|forget <memoryId> [confirm]]\",\n\t\texecute: async (args: string) => {\n\t\t\tconst tokens = args.trim().split(/\\s+/).filter(Boolean);\n\t\t\tif (tokens[0] === \"forget\") {\n\t\t\t\tconst memoryId = tokens[1] ?? \"\";\n\t\t\t\tconst confirmed = tokens[2] === \"confirm\";\n\t\t\t\tif (memoryId === \"\" || tokens.length > 3 || (tokens[2] !== undefined && !confirmed)) {\n\t\t\t\t\treturn { status: \"error\" as const, message: \"Usage: /memory forget <memoryId> [confirm]\" };\n\t\t\t\t}\n\t\t\t\tconst { domain, domainName } = resolveDomain();\n\t\t\t\tconst unscoped = store.get(memoryId, { owner });\n\t\t\t\tif (unscoped === undefined) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\t\tmessage: `No memory found with id ${memoryId}; run memory_list for this suite's memory ids`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst isMember =\n\t\t\t\t\tdomain.kind === \"suite\" ? unscoped.atom.suiteId === domain.suiteId : unscoped.atom.suiteId === undefined;\n\t\t\t\tif (!isMember) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\t\tmessage: `${memoryId} belongs to another suite; each suite forgets only its own memories`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (!confirmed) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: \"success\" as const,\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t`Forget target: \"${unwrapEgressStatement(statementOf(unscoped.atom.payload))}\"\\n` +\n\t\t\t\t\t\t\t\"This permanently deletes the memory (irreversible, purge-gated). Nothing is deleted yet — re-run to confirm:\\n\" +\n\t\t\t\t\t\t\t`/memory forget ${memoryId} confirm`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst result = purgeMemoryViaUserCommand(memoryId);\n\t\t\t\tif (result.status === \"completed\") {\n\t\t\t\t\tawait publish({\n\t\t\t\t\t\ttype: EVENT_TYPE,\n\t\t\t\t\t\tversion: 1,\n\t\t\t\t\t\tcorrelationId: capabilityManifest.id,\n\t\t\t\t\t\tdata: { action: \"forgotten\", memoryId, domain: domainName, batchId: result.batchId },\n\t\t\t\t\t});\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: \"success\" as const,\n\t\t\t\t\t\tmessage: `Forgot ${memoryId} (${domainName}): the memory is physically deleted`,\n\t\t\t\t\t\tdata: { memoryId, domain: domainName, batchId: result.batchId },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { status: \"error\" as const, message: `forget failed: ${result.status}` };\n\t\t\t}\n\t\t\tconst sub = args.trim().toLowerCase();\n\t\t\tif (sub === \"\" || sub === \"status\") {\n\t\t\t\treturn { status: \"success\" as const, message: `memory: ${memoryStatusLine()}` };\n\t\t\t}\n\t\t\tif (sub === \"light\" || sub === \"full\") {\n\t\t\t\t// 无\"已是该档\"早退: 持久化档位与会话内已解析档位是两回事——会话可能\n\t\t\t\t// 因默认档而运行 light, 用户降档仍需把持久化值落盘 (或覆盖旧档)。\n\t\t\t\twriteMemorySettingsMode(agentDir, sub);\n\t\t\t\t// 升/降档清了文件里的拒绝标记, 内存标记同步翻回: 用户最新的显式\n\t\t\t\t// 意图是启用——本会话恢复对当前预置的响应 (retry 可用), 新档与\n\t\t\t\t// 新模型下载在下一会话生效。\n\t\t\t\tvectorChannelCtl.clearDeclined();\n\t\t\t\t// 用户的显式档位表达取代本实例的自动升档声明: 降回 light 后 pending\n\t\t\t\t// 尾巴不再显示, 且显式 light 会让自动升档在后续写入中跳过 (复审 P2-1)。\n\t\t\t\tif (sub === \"light\") clearTierUpgrade();\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"success\" as const,\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t`memory: preset ${sub} persisted (capabilities/builtin.memory.json). It takes effect next session — ` +\n\t\t\t\t\t\t(sub === \"full\"\n\t\t\t\t\t\t\t? \"the larger embedding model (bge-m3, hundreds of MB) downloads in the background at the next start, disk headroom ≥2GB, and write-side semantic dedup turns on. \"\n\t\t\t\t\t\t\t: \"\") +\n\t\t\t\t\t\t\"Existing memories carry over: the projection rebuilds onto the new model automatically.\",\n\t\t\t\t};\n\t\t\t}\n\t\t\t// 命令面结果映射: 工具闭包的 completed/failed 面转 CapabilityCommandResult\n\t\t\t// 的 success/error; 行动清单/next 指引并入 message (命令结果无 actions 字段)。\n\t\t\tconst toCommandResult = (\n\t\t\t\tresult: Awaited<ReturnType<typeof vectorChannelCtl.download>>,\n\t\t\t): { status: \"success\" | \"error\"; message: string } => ({\n\t\t\t\tstatus: result.status === \"completed\" ? \"success\" : \"error\",\n\t\t\t\tmessage:\n\t\t\t\t\tresult.status === \"failed\"\n\t\t\t\t\t\t? [result.message, ...(result.actions ?? []), result.next].filter(Boolean).join(\" — \")\n\t\t\t\t\t\t: result.message,\n\t\t\t});\n\t\t\tif (sub === \"off\") return toCommandResult(vectorChannelCtl.decline());\n\t\t\tif (sub === \"retry\") return toCommandResult(await vectorChannelCtl.download());\n\t\t\treturn {\n\t\t\t\tstatus: \"error\" as const,\n\t\t\t\tmessage: \"Usage: /memory [light|full|off|retry|forget <memoryId> [confirm]]\",\n\t\t\t};\n\t\t},\n\t});\n\n\treturn { listTool, forgetTool, enableTool, memoryCommand, promoteCommand, schedulerCapability };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"embedding-provider.d.ts","sourceRoot":"","sources":["../../src/memory/embedding-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAUH,MAAM,WAAW,yBAAyB;IACzC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACz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 1024d) and\n * low tier (Xenova/bge-small-zh-v1.5, 512d) inference is deterministic\n * bit-exact across runs; high-tier drift queries reach re@10 100% after\n * reranking, low tier 83%. Tier presets are caller configuration — this module\n * only exposes a modelId-parameterized interface (宪法: 不绑死单一 provider).\n *\n * Runtime dep @huggingface/transformers is lazy-loaded via `await import` at\n * first embed (惯例参考 packages/agent-forge/src/utils/photon.ts); type\n * positions use type-only imports. The deterministic mock provider keeps tests\n * offline (门禁: deterministic mock AI; 真实模型不进 CI).\n */\n\n/**\n * Batch embedding provider. Implementations must be deterministic for\n * identical input and must not silently degrade: any failure propagates.\n */\nimport { join } from \"node:path\";\nimport { importHostOrBareModule } from \"./host-module-import.ts\";\nimport { purgeZeroByteCacheArtifacts } from \"./model-cache-hygiene.ts\";\n\nexport interface MemoryEmbeddingProviderV1 {\n\treadonly modelId: string;\n\treadonly dimensions: number;\n\t/**\n\t * Batch embed. Vectors are L2-normalized float arrays. Deterministic for\n\t * identical input. Plain text mapping — no instruction prefix is added\n\t * here; query-side instructions for bge-small-zh family are the caller's\n\t * responsibility (低档 bge-small-zh 系查询侧指令由调用方负责添加).\n\t */\n\tembed(texts: readonly string[]): Promise<readonly (readonly number[])[]>;\n}\n\n/**\n * Minimal structural seam around a transformers.js feature-extraction\n * pipeline, so tests can inject a fake without touching the real loader.\n */\nexport interface TransformersEmbeddingBackendV1 {\n\t/** Extract features for a batch of texts; one vector per input, input order. */\n\textract: (texts: string[]) => Promise<{ toList: () => number[][] }>;\n}\n\nexport type TransformersEmbeddingLoadImpl = (\n\tmodelId: string,\n\tcacheDir: string,\n\tremoteHost: string,\n) => Promise<TransformersEmbeddingBackendV1>;\n\nconst DEFAULT_TRANSFORMERS_MODEL_ID = \"Xenova/bge-m3\";\nconst DEFAULT_TRANSFORMERS_DIMENSIONS = 1024;\nconst DEFAULT_TRANSFORMERS_BATCH_SIZE = 16;\nconst DEFAULT_REMOTE_HOST = \"https://huggingface.co\";\n\nfunction fnv1a32(input: string): number {\n\tlet hash = 0x811c9dc5;\n\tfor (let offset = 0; offset < input.length; offset += 1) {\n\t\thash ^= input.charCodeAt(offset);\n\t\thash = Math.imul(hash, 0x01000193);\n\t}\n\treturn hash >>> 0;\n}\n\nfunction embedDeterministicMock(text: string, dimensions: number): number[] {\n\tconst values = new Array<number>(dimensions).fill(0);\n\tconst tokens = text.toLowerCase().split(/[^\\p{L}\\p{N}]+/u);\n\tfor (const token of tokens) {\n\t\tif (token.length === 0) {\n\t\t\tcontinue;\n\t\t}\n\t\t// 多轮混淆累加: 每个 token 经 FNV-1a 后再派生 3 个维度沉点,\n\t\t// 放大不同文本间的向量差异; 全程无随机、无时钟。\n\t\tlet mixed = fnv1a32(token);\n\t\tfor (let round = 0; round < 3; round += 1) {\n\t\t\tmixed = Math.imul(mixed ^ 0x9e3779b9, 0x85ebca6b) >>> 0;\n\t\t\tvalues[mixed % dimensions] += 1;\n\t\t}\n\t}\n\tlet sumSquares = 0;\n\tfor (const value of values) {\n\t\tsumSquares += value * value;\n\t}\n\tif (sumSquares === 0) {\n\t\t// 空文本/全标点: 确定性零向量; L2 范数为 0, 不归一化 (避免除零 NaN)。\n\t\treturn values;\n\t}\n\tconst norm = Math.sqrt(sumSquares);\n\treturn values.map((value) => value / norm);\n}\n\n/**\n * Deterministic mock embedding provider for offline tests: tokenizes by\n * `[^\\p{L}\\p{N}]+`, hashes each token with FNV-1a plus multi-round mixing into\n * dimension indices, then L2-normalizes. Same text → same vector, no random,\n * no clock. POC 已用真实模型验证 bit-exact; mock 只承担确定性测试门禁。\n */\nexport function createDeterministicMockEmbeddingProvider(options?: {\n\treadonly dimensions?: number;\n}): MemoryEmbeddingProviderV1 {\n\tconst dimensions = options?.dimensions ?? 64;\n\treturn {\n\t\tmodelId: \"mock-embedding@1\",\n\t\tdimensions,\n\t\tembed: async (texts) => texts.map((text) => embedDeterministicMock(text, dimensions)),\n\t};\n}\n\nconst createDefaultTransformersLoadImpl = (moduleEntryPath?: string): TransformersEmbeddingLoadImpl => {\n\treturn async (modelId, cacheDir, remoteHost) => {\n\t\tconst transformers = await importHostOrBareModule<typeof import(\"@huggingface/transformers\")>(\n\t\t\tmoduleEntryPath ?? \"@huggingface/transformers\",\n\t\t);\n\t\ttransformers.env.cacheDir = cacheDir;\n\t\ttransformers.env.remoteHost = remoteHost;\n\t\tconst extractor = await transformers.pipeline(\"feature-extraction\", modelId, { dtype: \"q8\" });\n\t\treturn {\n\t\t\textract: async (texts) => {\n\t\t\t\tconst output = await extractor(texts, { pooling: \"cls\", normalize: true });\n\t\t\t\treturn { toList: () => output.tolist() as number[][] };\n\t\t\t},\n\t\t};\n\t};\n};\n\n/**\n * Transformers.js-backed embedding provider (POC 档位: 高档默认\n * Xenova/bge-m3/1024d; 低档由调用方传 modelId \"Xenova/bge-small-zh-v1.5\" +\n * dimensions 512)。\n *\n * 镜像序列: 首次 embed 时按 `remoteHosts` 顺序逐个尝试加载 (调用方通常传\n * [\"https://huggingface.co\", \"https://hf-mirror.com\"]); 某 host 加载抛错则\n * 尝试下一个, 全部失败时抛最后一个错误。host 确定后模型句柄只加载一次\n * (并发 embed 共享同一 in-flight promise); 加载失败不缓存, 下次 embed 重新\n * 走完整序列, 失败原因原样保留, 不静默降级。\n *\n * `loadImpl` 是测试 seam: 注入后绕过真实加载, 签名\n * (modelId, cacheDir, remoteHost) => backend。\n */\nexport function createTransformersEmbeddingProvider(options: {\n\treadonly modelId?: string;\n\treadonly dimensions?: number;\n\treadonly cacheDir: string;\n\treadonly remoteHosts?: readonly string[];\n\treadonly batchSize?: number;\n\treadonly loadImpl?: TransformersEmbeddingLoadImpl;\n\t/** Host-resolved transformers entry path (install-store visibility); undefined = bare import. */\n\treadonly moduleEntryPath?: string;\n}): MemoryEmbeddingProviderV1 {\n\tconst modelId = options.modelId ?? DEFAULT_TRANSFORMERS_MODEL_ID;\n\tconst dimensions = options.dimensions ?? DEFAULT_TRANSFORMERS_DIMENSIONS;\n\tconst batchSize = options.batchSize ?? DEFAULT_TRANSFORMERS_BATCH_SIZE;\n\tconst cacheDir = options.cacheDir;\n\tconst remoteHosts = options.remoteHosts ?? [DEFAULT_REMOTE_HOST];\n\tconst load = options.loadImpl ?? createDefaultTransformersLoadImpl(options.moduleEntryPath);\n\n\tlet backendPromise: Promise<TransformersEmbeddingBackendV1> | null = null;\n\tconst loadBackend = (): Promise<TransformersEmbeddingBackendV1> => {\n\t\tconst existing = backendPromise;\n\t\tif (existing) {\n\t\t\treturn existing;\n\t\t}\n\t\tconst attempt = (async () => {\n\t\t\tlet lastError: unknown;\n\t\t\tfor (const remoteHost of remoteHosts) {\n\t\t\t\ttry {\n\t\t\t\t\treturn await load(modelId, cacheDir, remoteHost);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlastError = error;\n\t\t\t\t\t// 镜像轮换前清 0 字节残骸: 失败下载留下的空文件会被 transformers\n\t\t\t\t\t// 当作缓存命中, 毒化下一个 host 的重试 (model-cache-hygiene)。\n\t\t\t\t\tpurgeZeroByteCacheArtifacts(join(cacheDir, modelId));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (lastError === undefined) throw new Error(`no remote hosts configured for model ${modelId}`);\n\t\t\tthrow lastError;\n\t\t})();\n\t\tbackendPromise = attempt;\n\t\tattempt.catch(() => {\n\t\t\t// 失败不缓存: 下次 embed 重新走镜像序列 (显式失败, 不静默降级)。\n\t\t\tif (backendPromise === attempt) {\n\t\t\t\tbackendPromise = null;\n\t\t\t}\n\t\t});\n\t\treturn attempt;\n\t};\n\n\treturn {\n\t\tmodelId,\n\t\tdimensions,\n\t\tembed: async (texts) => {\n\t\t\tif (texts.length === 0) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\tconst backend = await loadBackend();\n\t\t\tconst vectors: number[][] = [];\n\t\t\tfor (let offset = 0; offset < texts.length; offset += batchSize) {\n\t\t\t\tconst batchTexts = texts.slice(offset, offset + batchSize);\n\t\t\t\tconst rows = (await backend.extract(batchTexts)).toList();\n\t\t\t\tfor (const row of rows) {\n\t\t\t\t\tif (row.length !== dimensions) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`embedding dimension mismatch: model ${modelId} returned ${row.length} dims, provider declares ${dimensions}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tvectors.push(row);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn vectors;\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"embedding-provider.d.ts","sourceRoot":"","sources":["../../src/memory/embedding-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAUH,MAAM,WAAW,yBAAyB;IACzC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B;;;;;OAKG;IACH,KAAK,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,SAAS,CAAC,SAAS,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC;CACzE;AAED;;;GAGG;AACH,MAAM,WAAW,8BAA8B;IAC9C,gFAAgF;IAChF,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,OAAO,CAAC;QAAE,MAAM,EAAE,MAAM,MAAM,EAAE,EAAE,CAAA;KAAE,CAAC,CAAC;CACpE;AAED,MAAM,MAAM,6BAA6B,GAAG,CAC3C,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,KACd,OAAO,CAAC,8BAA8B,CAAC,CAAC;AA2C7C;;;;;GAKG;AACH,wBAAgB,wCAAwC,CAAC,OAAO,CAAC,EAAE;IAClE,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAC7B,GAAG,yBAAyB,CAO5B;AAmBD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,mCAAmC,CAAC,OAAO,EAAE;IAC5D,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACzC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,QAAQ,CAAC,EAAE,6BAA6B,CAAC;IAClD,iGAAiG;IACjG,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;CAClC,GAAG,yBAAyB,CA0E5B","sourcesContent":["/**\n * Memory embedding providers for hybrid retrieval (混合检索 · 向量侧).\n *\n * POC-verified (2026-09, 100k corpus): high tier (Xenova/bge-m3, 1024d) and\n * low tier (Xenova/bge-small-zh-v1.5, 512d) inference is deterministic\n * bit-exact across runs; high-tier drift queries reach re@10 100% after\n * reranking, low tier 83%. Tier presets are caller configuration — this module\n * only exposes a modelId-parameterized interface (宪法: 不绑死单一 provider).\n *\n * Runtime dep @huggingface/transformers is lazy-loaded via `await import` at\n * first embed (惯例参考 packages/agent-forge/src/utils/photon.ts); type\n * positions use type-only imports. The deterministic mock provider keeps tests\n * offline (门禁: deterministic mock AI; 真实模型不进 CI).\n */\n\n/**\n * Batch embedding provider. Implementations must be deterministic for\n * identical input and must not silently degrade: any failure propagates.\n */\nimport { join } from \"node:path\";\nimport { importHostOrBareModule } from \"./host-module-import.ts\";\nimport { annotateUpstreamListingPoison, purgeZeroByteCacheArtifacts } from \"./model-cache-hygiene.ts\";\n\nexport interface MemoryEmbeddingProviderV1 {\n\treadonly modelId: string;\n\treadonly dimensions: number;\n\t/**\n\t * Batch embed. Vectors are L2-normalized float arrays. Deterministic for\n\t * identical input. Plain text mapping — no instruction prefix is added\n\t * here; query-side instructions for bge-small-zh family are the caller's\n\t * responsibility (低档 bge-small-zh 系查询侧指令由调用方负责添加).\n\t */\n\tembed(texts: readonly string[]): Promise<readonly (readonly number[])[]>;\n}\n\n/**\n * Minimal structural seam around a transformers.js feature-extraction\n * pipeline, so tests can inject a fake without touching the real loader.\n */\nexport interface TransformersEmbeddingBackendV1 {\n\t/** Extract features for a batch of texts; one vector per input, input order. */\n\textract: (texts: string[]) => Promise<{ toList: () => number[][] }>;\n}\n\nexport type TransformersEmbeddingLoadImpl = (\n\tmodelId: string,\n\tcacheDir: string,\n\tremoteHost: string,\n) => Promise<TransformersEmbeddingBackendV1>;\n\nconst DEFAULT_TRANSFORMERS_MODEL_ID = \"Xenova/bge-m3\";\nconst DEFAULT_TRANSFORMERS_DIMENSIONS = 1024;\nconst DEFAULT_TRANSFORMERS_BATCH_SIZE = 16;\nconst DEFAULT_REMOTE_HOST = \"https://huggingface.co\";\n\nfunction fnv1a32(input: string): number {\n\tlet hash = 0x811c9dc5;\n\tfor (let offset = 0; offset < input.length; offset += 1) {\n\t\thash ^= input.charCodeAt(offset);\n\t\thash = Math.imul(hash, 0x01000193);\n\t}\n\treturn hash >>> 0;\n}\n\nfunction embedDeterministicMock(text: string, dimensions: number): number[] {\n\tconst values = new Array<number>(dimensions).fill(0);\n\tconst tokens = text.toLowerCase().split(/[^\\p{L}\\p{N}]+/u);\n\tfor (const token of tokens) {\n\t\tif (token.length === 0) {\n\t\t\tcontinue;\n\t\t}\n\t\t// 多轮混淆累加: 每个 token 经 FNV-1a 后再派生 3 个维度沉点,\n\t\t// 放大不同文本间的向量差异; 全程无随机、无时钟。\n\t\tlet mixed = fnv1a32(token);\n\t\tfor (let round = 0; round < 3; round += 1) {\n\t\t\tmixed = Math.imul(mixed ^ 0x9e3779b9, 0x85ebca6b) >>> 0;\n\t\t\tvalues[mixed % dimensions] += 1;\n\t\t}\n\t}\n\tlet sumSquares = 0;\n\tfor (const value of values) {\n\t\tsumSquares += value * value;\n\t}\n\tif (sumSquares === 0) {\n\t\t// 空文本/全标点: 确定性零向量; L2 范数为 0, 不归一化 (避免除零 NaN)。\n\t\treturn values;\n\t}\n\tconst norm = Math.sqrt(sumSquares);\n\treturn values.map((value) => value / norm);\n}\n\n/**\n * Deterministic mock embedding provider for offline tests: tokenizes by\n * `[^\\p{L}\\p{N}]+`, hashes each token with FNV-1a plus multi-round mixing into\n * dimension indices, then L2-normalizes. Same text → same vector, no random,\n * no clock. POC 已用真实模型验证 bit-exact; mock 只承担确定性测试门禁。\n */\nexport function createDeterministicMockEmbeddingProvider(options?: {\n\treadonly dimensions?: number;\n}): MemoryEmbeddingProviderV1 {\n\tconst dimensions = options?.dimensions ?? 64;\n\treturn {\n\t\tmodelId: \"mock-embedding@1\",\n\t\tdimensions,\n\t\tembed: async (texts) => texts.map((text) => embedDeterministicMock(text, dimensions)),\n\t};\n}\n\nconst createDefaultTransformersLoadImpl = (moduleEntryPath?: string): TransformersEmbeddingLoadImpl => {\n\treturn async (modelId, cacheDir, remoteHost) => {\n\t\tconst transformers = await importHostOrBareModule<typeof import(\"@huggingface/transformers\")>(\n\t\t\tmoduleEntryPath ?? \"@huggingface/transformers\",\n\t\t);\n\t\ttransformers.env.cacheDir = cacheDir;\n\t\ttransformers.env.remoteHost = remoteHost;\n\t\tconst extractor = await transformers.pipeline(\"feature-extraction\", modelId, { dtype: \"q8\" });\n\t\treturn {\n\t\t\textract: async (texts) => {\n\t\t\t\tconst output = await extractor(texts, { pooling: \"cls\", normalize: true });\n\t\t\t\treturn { toList: () => output.tolist() as number[][] };\n\t\t\t},\n\t\t};\n\t};\n};\n\n/**\n * Transformers.js-backed embedding provider (POC 档位: 高档默认\n * Xenova/bge-m3/1024d; 低档由调用方传 modelId \"Xenova/bge-small-zh-v1.5\" +\n * dimensions 512)。\n *\n * 镜像序列: 首次 embed 时按 `remoteHosts` 顺序逐个尝试加载 (调用方通常传\n * [\"https://huggingface.co\", \"https://hf-mirror.com\"]); 某 host 加载抛错则\n * 尝试下一个, 全部失败时抛最后一个错误。host 确定后模型句柄只加载一次\n * (并发 embed 共享同一 in-flight promise); 加载失败不缓存, 下次 embed 重新\n * 走完整序列, 失败原因原样保留, 不静默降级。\n *\n * `loadImpl` 是测试 seam: 注入后绕过真实加载, 签名\n * (modelId, cacheDir, remoteHost) => backend。\n */\nexport function createTransformersEmbeddingProvider(options: {\n\treadonly modelId?: string;\n\treadonly dimensions?: number;\n\treadonly cacheDir: string;\n\treadonly remoteHosts?: readonly string[];\n\treadonly batchSize?: number;\n\treadonly loadImpl?: TransformersEmbeddingLoadImpl;\n\t/** Host-resolved transformers entry path (install-store visibility); undefined = bare import. */\n\treadonly moduleEntryPath?: string;\n}): MemoryEmbeddingProviderV1 {\n\tconst modelId = options.modelId ?? DEFAULT_TRANSFORMERS_MODEL_ID;\n\tconst dimensions = options.dimensions ?? DEFAULT_TRANSFORMERS_DIMENSIONS;\n\tconst batchSize = options.batchSize ?? DEFAULT_TRANSFORMERS_BATCH_SIZE;\n\tconst cacheDir = options.cacheDir;\n\tconst remoteHosts = options.remoteHosts ?? [DEFAULT_REMOTE_HOST];\n\tconst load = options.loadImpl ?? createDefaultTransformersLoadImpl(options.moduleEntryPath);\n\n\tlet backendPromise: Promise<TransformersEmbeddingBackendV1> | null = null;\n\tconst loadBackend = (): Promise<TransformersEmbeddingBackendV1> => {\n\t\tconst existing = backendPromise;\n\t\tif (existing) {\n\t\t\treturn existing;\n\t\t}\n\t\tconst attempt = (async () => {\n\t\t\tlet lastError: unknown;\n\t\t\tfor (const remoteHost of remoteHosts) {\n\t\t\t\ttry {\n\t\t\t\t\treturn await load(modelId, cacheDir, remoteHost);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlastError = error;\n\t\t\t\t\t// 镜像轮换前清 0 字节残骸: 失败下载留下的空文件会被 transformers\n\t\t\t\t\t// 当作缓存命中, 毒化下一个 host 的重试 (model-cache-hygiene)。\n\t\t\t\t\tpurgeZeroByteCacheArtifacts(join(cacheDir, modelId));\n\t\t\t\t}\n\t\t\t\t// 同 host 一次短退避重试 (2026-10-06 live E2E): 覆盖 rejection 型瞬断\n\t\t\t\t// (fetch 网络错/5xx)。对\"仓库 API 清单缺文件\"型不生效——该结果被\n\t\t\t\t// transformers 模块级 memoize (见 annotateUpstreamListingPoison),\n\t\t\t\t// 进程内换 host 也拿同一空清单。\n\t\t\t\ttry {\n\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 2_000));\n\t\t\t\t\treturn await load(modelId, cacheDir, remoteHost);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlastError = error;\n\t\t\t\t\tpurgeZeroByteCacheArtifacts(join(cacheDir, modelId));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (lastError === undefined) throw new Error(`no remote hosts configured for model ${modelId}`);\n\t\t\tthrow annotateUpstreamListingPoison(lastError);\n\t\t})();\n\t\tbackendPromise = attempt;\n\t\tattempt.catch(() => {\n\t\t\t// 失败不缓存: 下次 embed 重新走镜像序列 (显式失败, 不静默降级)。\n\t\t\tif (backendPromise === attempt) {\n\t\t\t\tbackendPromise = null;\n\t\t\t}\n\t\t});\n\t\treturn attempt;\n\t};\n\n\treturn {\n\t\tmodelId,\n\t\tdimensions,\n\t\tembed: async (texts) => {\n\t\t\tif (texts.length === 0) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\tconst backend = await loadBackend();\n\t\t\tconst vectors: number[][] = [];\n\t\t\tfor (let offset = 0; offset < texts.length; offset += batchSize) {\n\t\t\t\tconst batchTexts = texts.slice(offset, offset + batchSize);\n\t\t\t\tconst rows = (await backend.extract(batchTexts)).toList();\n\t\t\t\tfor (const row of rows) {\n\t\t\t\t\tif (row.length !== dimensions) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`embedding dimension mismatch: model ${modelId} returned ${row.length} dims, provider declares ${dimensions}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tvectors.push(row);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn vectors;\n\t\t},\n\t};\n}\n"]}
@@ -18,7 +18,7 @@
18
18
  */
19
19
  import { join } from "node:path";
20
20
  import { importHostOrBareModule } from "./host-module-import.js";
21
- import { purgeZeroByteCacheArtifacts } from "./model-cache-hygiene.js";
21
+ import { annotateUpstreamListingPoison, purgeZeroByteCacheArtifacts } from "./model-cache-hygiene.js";
22
22
  const DEFAULT_TRANSFORMERS_MODEL_ID = "Xenova/bge-m3";
23
23
  const DEFAULT_TRANSFORMERS_DIMENSIONS = 1024;
24
24
  const DEFAULT_TRANSFORMERS_BATCH_SIZE = 16;
@@ -124,10 +124,22 @@ export function createTransformersEmbeddingProvider(options) {
124
124
  // 当作缓存命中, 毒化下一个 host 的重试 (model-cache-hygiene)。
125
125
  purgeZeroByteCacheArtifacts(join(cacheDir, modelId));
126
126
  }
127
+ // 同 host 一次短退避重试 (2026-10-06 live E2E): 覆盖 rejection 型瞬断
128
+ // (fetch 网络错/5xx)。对"仓库 API 清单缺文件"型不生效——该结果被
129
+ // transformers 模块级 memoize (见 annotateUpstreamListingPoison),
130
+ // 进程内换 host 也拿同一空清单。
131
+ try {
132
+ await new Promise((resolve) => setTimeout(resolve, 2_000));
133
+ return await load(modelId, cacheDir, remoteHost);
134
+ }
135
+ catch (error) {
136
+ lastError = error;
137
+ purgeZeroByteCacheArtifacts(join(cacheDir, modelId));
138
+ }
127
139
  }
128
140
  if (lastError === undefined)
129
141
  throw new Error(`no remote hosts configured for model ${modelId}`);
130
- throw lastError;
142
+ throw annotateUpstreamListingPoison(lastError);
131
143
  })();
132
144
  backendPromise = attempt;
133
145
  attempt.catch(() => {
@@ -1 +1 @@
1
- {"version":3,"file":"embedding-provider.js","sourceRoot":"","sources":["../../src/memory/embedding-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH;;;GAGG;AACH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AACjE,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AA6BvE,MAAM,6BAA6B,GAAG,eAAe,CAAC;AACtD,MAAM,+BAA+B,GAAG,IAAI,CAAC;AAC7C,MAAM,+BAA+B,G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C;oBACH,CAAC;oBACD,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;gBACnB,CAAC;YACF,CAAC;YACD,OAAO,OAAO,CAAC;QAAA,CACf;KACD,CAAC;AAAA,CACF","sourcesContent":["/**\n * Memory embedding providers for hybrid retrieval (混合检索 · 向量侧).\n *\n * POC-verified (2026-09, 100k corpus): high tier (Xenova/bge-m3, 1024d) and\n * low tier (Xenova/bge-small-zh-v1.5, 512d) inference is deterministic\n * bit-exact across runs; high-tier drift queries reach re@10 100% after\n * reranking, low tier 83%. Tier presets are caller configuration — this module\n * only exposes a modelId-parameterized interface (宪法: 不绑死单一 provider).\n *\n * Runtime dep @huggingface/transformers is lazy-loaded via `await import` at\n * first embed (惯例参考 packages/agent-forge/src/utils/photon.ts); type\n * positions use type-only imports. The deterministic mock provider keeps tests\n * offline (门禁: deterministic mock AI; 真实模型不进 CI).\n */\n\n/**\n * Batch embedding provider. Implementations must be deterministic for\n * identical input and must not silently degrade: any failure propagates.\n */\nimport { join } from \"node:path\";\nimport { importHostOrBareModule } from \"./host-module-import.ts\";\nimport { purgeZeroByteCacheArtifacts } from \"./model-cache-hygiene.ts\";\n\nexport interface MemoryEmbeddingProviderV1 {\n\treadonly modelId: string;\n\treadonly dimensions: number;\n\t/**\n\t * Batch embed. Vectors are L2-normalized float arrays. Deterministic for\n\t * identical input. Plain text mapping — no instruction prefix is added\n\t * here; query-side instructions for bge-small-zh family are the caller's\n\t * responsibility (低档 bge-small-zh 系查询侧指令由调用方负责添加).\n\t */\n\tembed(texts: readonly string[]): Promise<readonly (readonly number[])[]>;\n}\n\n/**\n * Minimal structural seam around a transformers.js feature-extraction\n * pipeline, so tests can inject a fake without touching the real loader.\n */\nexport interface TransformersEmbeddingBackendV1 {\n\t/** Extract features for a batch of texts; one vector per input, input order. */\n\textract: (texts: string[]) => Promise<{ toList: () => number[][] }>;\n}\n\nexport type TransformersEmbeddingLoadImpl = (\n\tmodelId: string,\n\tcacheDir: string,\n\tremoteHost: string,\n) => Promise<TransformersEmbeddingBackendV1>;\n\nconst DEFAULT_TRANSFORMERS_MODEL_ID = \"Xenova/bge-m3\";\nconst DEFAULT_TRANSFORMERS_DIMENSIONS = 1024;\nconst DEFAULT_TRANSFORMERS_BATCH_SIZE = 16;\nconst DEFAULT_REMOTE_HOST = \"https://huggingface.co\";\n\nfunction fnv1a32(input: string): number {\n\tlet hash = 0x811c9dc5;\n\tfor (let offset = 0; offset < input.length; offset += 1) {\n\t\thash ^= input.charCodeAt(offset);\n\t\thash = Math.imul(hash, 0x01000193);\n\t}\n\treturn hash >>> 0;\n}\n\nfunction embedDeterministicMock(text: string, dimensions: number): number[] {\n\tconst values = new Array<number>(dimensions).fill(0);\n\tconst tokens = text.toLowerCase().split(/[^\\p{L}\\p{N}]+/u);\n\tfor (const token of tokens) {\n\t\tif (token.length === 0) {\n\t\t\tcontinue;\n\t\t}\n\t\t// 多轮混淆累加: 每个 token 经 FNV-1a 后再派生 3 个维度沉点,\n\t\t// 放大不同文本间的向量差异; 全程无随机、无时钟。\n\t\tlet mixed = fnv1a32(token);\n\t\tfor (let round = 0; round < 3; round += 1) {\n\t\t\tmixed = Math.imul(mixed ^ 0x9e3779b9, 0x85ebca6b) >>> 0;\n\t\t\tvalues[mixed % dimensions] += 1;\n\t\t}\n\t}\n\tlet sumSquares = 0;\n\tfor (const value of values) {\n\t\tsumSquares += value * value;\n\t}\n\tif (sumSquares === 0) {\n\t\t// 空文本/全标点: 确定性零向量; L2 范数为 0, 不归一化 (避免除零 NaN)。\n\t\treturn values;\n\t}\n\tconst norm = Math.sqrt(sumSquares);\n\treturn values.map((value) => value / norm);\n}\n\n/**\n * Deterministic mock embedding provider for offline tests: tokenizes by\n * `[^\\p{L}\\p{N}]+`, hashes each token with FNV-1a plus multi-round mixing into\n * dimension indices, then L2-normalizes. Same text → same vector, no random,\n * no clock. POC 已用真实模型验证 bit-exact; mock 只承担确定性测试门禁。\n */\nexport function createDeterministicMockEmbeddingProvider(options?: {\n\treadonly dimensions?: number;\n}): MemoryEmbeddingProviderV1 {\n\tconst dimensions = options?.dimensions ?? 64;\n\treturn {\n\t\tmodelId: \"mock-embedding@1\",\n\t\tdimensions,\n\t\tembed: async (texts) => texts.map((text) => embedDeterministicMock(text, dimensions)),\n\t};\n}\n\nconst createDefaultTransformersLoadImpl = (moduleEntryPath?: string): TransformersEmbeddingLoadImpl => {\n\treturn async (modelId, cacheDir, remoteHost) => {\n\t\tconst transformers = await importHostOrBareModule<typeof import(\"@huggingface/transformers\")>(\n\t\t\tmoduleEntryPath ?? \"@huggingface/transformers\",\n\t\t);\n\t\ttransformers.env.cacheDir = cacheDir;\n\t\ttransformers.env.remoteHost = remoteHost;\n\t\tconst extractor = await transformers.pipeline(\"feature-extraction\", modelId, { dtype: \"q8\" });\n\t\treturn {\n\t\t\textract: async (texts) => {\n\t\t\t\tconst output = await extractor(texts, { pooling: \"cls\", normalize: true });\n\t\t\t\treturn { toList: () => output.tolist() as number[][] };\n\t\t\t},\n\t\t};\n\t};\n};\n\n/**\n * Transformers.js-backed embedding provider (POC 档位: 高档默认\n * Xenova/bge-m3/1024d; 低档由调用方传 modelId \"Xenova/bge-small-zh-v1.5\" +\n * dimensions 512)。\n *\n * 镜像序列: 首次 embed 时按 `remoteHosts` 顺序逐个尝试加载 (调用方通常传\n * [\"https://huggingface.co\", \"https://hf-mirror.com\"]); 某 host 加载抛错则\n * 尝试下一个, 全部失败时抛最后一个错误。host 确定后模型句柄只加载一次\n * (并发 embed 共享同一 in-flight promise); 加载失败不缓存, 下次 embed 重新\n * 走完整序列, 失败原因原样保留, 不静默降级。\n *\n * `loadImpl` 是测试 seam: 注入后绕过真实加载, 签名\n * (modelId, cacheDir, remoteHost) => backend。\n */\nexport function createTransformersEmbeddingProvider(options: {\n\treadonly modelId?: string;\n\treadonly dimensions?: number;\n\treadonly cacheDir: string;\n\treadonly remoteHosts?: readonly string[];\n\treadonly batchSize?: number;\n\treadonly loadImpl?: TransformersEmbeddingLoadImpl;\n\t/** Host-resolved transformers entry path (install-store visibility); undefined = bare import. */\n\treadonly moduleEntryPath?: string;\n}): MemoryEmbeddingProviderV1 {\n\tconst modelId = options.modelId ?? DEFAULT_TRANSFORMERS_MODEL_ID;\n\tconst dimensions = options.dimensions ?? DEFAULT_TRANSFORMERS_DIMENSIONS;\n\tconst batchSize = options.batchSize ?? DEFAULT_TRANSFORMERS_BATCH_SIZE;\n\tconst cacheDir = options.cacheDir;\n\tconst remoteHosts = options.remoteHosts ?? [DEFAULT_REMOTE_HOST];\n\tconst load = options.loadImpl ?? createDefaultTransformersLoadImpl(options.moduleEntryPath);\n\n\tlet backendPromise: Promise<TransformersEmbeddingBackendV1> | null = null;\n\tconst loadBackend = (): Promise<TransformersEmbeddingBackendV1> => {\n\t\tconst existing = backendPromise;\n\t\tif (existing) {\n\t\t\treturn existing;\n\t\t}\n\t\tconst attempt = (async () => {\n\t\t\tlet lastError: unknown;\n\t\t\tfor (const remoteHost of remoteHosts) {\n\t\t\t\ttry {\n\t\t\t\t\treturn await load(modelId, cacheDir, remoteHost);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlastError = error;\n\t\t\t\t\t// 镜像轮换前清 0 字节残骸: 失败下载留下的空文件会被 transformers\n\t\t\t\t\t// 当作缓存命中, 毒化下一个 host 的重试 (model-cache-hygiene)。\n\t\t\t\t\tpurgeZeroByteCacheArtifacts(join(cacheDir, modelId));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (lastError === undefined) throw new Error(`no remote hosts configured for model ${modelId}`);\n\t\t\tthrow lastError;\n\t\t})();\n\t\tbackendPromise = attempt;\n\t\tattempt.catch(() => {\n\t\t\t// 失败不缓存: 下次 embed 重新走镜像序列 (显式失败, 不静默降级)。\n\t\t\tif (backendPromise === attempt) {\n\t\t\t\tbackendPromise = null;\n\t\t\t}\n\t\t});\n\t\treturn attempt;\n\t};\n\n\treturn {\n\t\tmodelId,\n\t\tdimensions,\n\t\tembed: async (texts) => {\n\t\t\tif (texts.length === 0) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\tconst backend = await loadBackend();\n\t\t\tconst vectors: number[][] = [];\n\t\t\tfor (let offset = 0; offset < texts.length; offset += batchSize) {\n\t\t\t\tconst batchTexts = texts.slice(offset, offset + batchSize);\n\t\t\t\tconst rows = (await backend.extract(batchTexts)).toList();\n\t\t\t\tfor (const row of rows) {\n\t\t\t\t\tif (row.length !== dimensions) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`embedding dimension mismatch: model ${modelId} returned ${row.length} dims, provider declares ${dimensions}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tvectors.push(row);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn vectors;\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"embedding-provider.js","sourceRoot":"","sources":["../../src/memory/embedding-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH;;;GAGG;AACH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AACjE,OAAO,EAAE,6BAA6B,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AA6BtG,MAAM,6BAA6B,GAAG,eAAe,CAAC;AACtD,MAAM,+BAA+B,GAAG,IAAI,CAAC;AAC7C,MAAM,+BAA+B,GAAG,EAAE,CAAC;AAC3C,MAAM,mBAAmB,GAAG,wBAAwB,CAAC;AAErD,SAAS,OAAO,CAAC,KAAa,EAAU;IACvC,IAAI,IAAI,GAAG,UAAU,CAAC;IACtB,KAAK,IAAI,MAAM,GAAG,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,EAAE,MAAM,IAAI,CAAC,EAAE,CAAC;QACzD,IAAI,IAAI,KAAK,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QACjC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,UAAU,CAA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IAAI,KAAK,CACd,uCAAuC,OAAO,aAAa,GAAG,CAAC,MAAM,4BAA4B,UAAU,EAAE,CAC7G,CAAC;oBACH,CAAC;oBACD,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;gBACnB,CAAC;YACF,CAAC;YACD,OAAO,OAAO,CAAC;QAAA,CACf;KACD,CAAC;AAAA,CACF","sourcesContent":["/**\n * Memory embedding providers for hybrid retrieval (混合检索 · 向量侧).\n *\n * POC-verified (2026-09, 100k corpus): high tier (Xenova/bge-m3, 1024d) and\n * low tier (Xenova/bge-small-zh-v1.5, 512d) inference is deterministic\n * bit-exact across runs; high-tier drift queries reach re@10 100% after\n * reranking, low tier 83%. Tier presets are caller configuration — this module\n * only exposes a modelId-parameterized interface (宪法: 不绑死单一 provider).\n *\n * Runtime dep @huggingface/transformers is lazy-loaded via `await import` at\n * first embed (惯例参考 packages/agent-forge/src/utils/photon.ts); type\n * positions use type-only imports. The deterministic mock provider keeps tests\n * offline (门禁: deterministic mock AI; 真实模型不进 CI).\n */\n\n/**\n * Batch embedding provider. Implementations must be deterministic for\n * identical input and must not silently degrade: any failure propagates.\n */\nimport { join } from \"node:path\";\nimport { importHostOrBareModule } from \"./host-module-import.ts\";\nimport { annotateUpstreamListingPoison, purgeZeroByteCacheArtifacts } from \"./model-cache-hygiene.ts\";\n\nexport interface MemoryEmbeddingProviderV1 {\n\treadonly modelId: string;\n\treadonly dimensions: number;\n\t/**\n\t * Batch embed. Vectors are L2-normalized float arrays. Deterministic for\n\t * identical input. Plain text mapping — no instruction prefix is added\n\t * here; query-side instructions for bge-small-zh family are the caller's\n\t * responsibility (低档 bge-small-zh 系查询侧指令由调用方负责添加).\n\t */\n\tembed(texts: readonly string[]): Promise<readonly (readonly number[])[]>;\n}\n\n/**\n * Minimal structural seam around a transformers.js feature-extraction\n * pipeline, so tests can inject a fake without touching the real loader.\n */\nexport interface TransformersEmbeddingBackendV1 {\n\t/** Extract features for a batch of texts; one vector per input, input order. */\n\textract: (texts: string[]) => Promise<{ toList: () => number[][] }>;\n}\n\nexport type TransformersEmbeddingLoadImpl = (\n\tmodelId: string,\n\tcacheDir: string,\n\tremoteHost: string,\n) => Promise<TransformersEmbeddingBackendV1>;\n\nconst DEFAULT_TRANSFORMERS_MODEL_ID = \"Xenova/bge-m3\";\nconst DEFAULT_TRANSFORMERS_DIMENSIONS = 1024;\nconst DEFAULT_TRANSFORMERS_BATCH_SIZE = 16;\nconst DEFAULT_REMOTE_HOST = \"https://huggingface.co\";\n\nfunction fnv1a32(input: string): number {\n\tlet hash = 0x811c9dc5;\n\tfor (let offset = 0; offset < input.length; offset += 1) {\n\t\thash ^= input.charCodeAt(offset);\n\t\thash = Math.imul(hash, 0x01000193);\n\t}\n\treturn hash >>> 0;\n}\n\nfunction embedDeterministicMock(text: string, dimensions: number): number[] {\n\tconst values = new Array<number>(dimensions).fill(0);\n\tconst tokens = text.toLowerCase().split(/[^\\p{L}\\p{N}]+/u);\n\tfor (const token of tokens) {\n\t\tif (token.length === 0) {\n\t\t\tcontinue;\n\t\t}\n\t\t// 多轮混淆累加: 每个 token 经 FNV-1a 后再派生 3 个维度沉点,\n\t\t// 放大不同文本间的向量差异; 全程无随机、无时钟。\n\t\tlet mixed = fnv1a32(token);\n\t\tfor (let round = 0; round < 3; round += 1) {\n\t\t\tmixed = Math.imul(mixed ^ 0x9e3779b9, 0x85ebca6b) >>> 0;\n\t\t\tvalues[mixed % dimensions] += 1;\n\t\t}\n\t}\n\tlet sumSquares = 0;\n\tfor (const value of values) {\n\t\tsumSquares += value * value;\n\t}\n\tif (sumSquares === 0) {\n\t\t// 空文本/全标点: 确定性零向量; L2 范数为 0, 不归一化 (避免除零 NaN)。\n\t\treturn values;\n\t}\n\tconst norm = Math.sqrt(sumSquares);\n\treturn values.map((value) => value / norm);\n}\n\n/**\n * Deterministic mock embedding provider for offline tests: tokenizes by\n * `[^\\p{L}\\p{N}]+`, hashes each token with FNV-1a plus multi-round mixing into\n * dimension indices, then L2-normalizes. Same text → same vector, no random,\n * no clock. POC 已用真实模型验证 bit-exact; mock 只承担确定性测试门禁。\n */\nexport function createDeterministicMockEmbeddingProvider(options?: {\n\treadonly dimensions?: number;\n}): MemoryEmbeddingProviderV1 {\n\tconst dimensions = options?.dimensions ?? 64;\n\treturn {\n\t\tmodelId: \"mock-embedding@1\",\n\t\tdimensions,\n\t\tembed: async (texts) => texts.map((text) => embedDeterministicMock(text, dimensions)),\n\t};\n}\n\nconst createDefaultTransformersLoadImpl = (moduleEntryPath?: string): TransformersEmbeddingLoadImpl => {\n\treturn async (modelId, cacheDir, remoteHost) => {\n\t\tconst transformers = await importHostOrBareModule<typeof import(\"@huggingface/transformers\")>(\n\t\t\tmoduleEntryPath ?? \"@huggingface/transformers\",\n\t\t);\n\t\ttransformers.env.cacheDir = cacheDir;\n\t\ttransformers.env.remoteHost = remoteHost;\n\t\tconst extractor = await transformers.pipeline(\"feature-extraction\", modelId, { dtype: \"q8\" });\n\t\treturn {\n\t\t\textract: async (texts) => {\n\t\t\t\tconst output = await extractor(texts, { pooling: \"cls\", normalize: true });\n\t\t\t\treturn { toList: () => output.tolist() as number[][] };\n\t\t\t},\n\t\t};\n\t};\n};\n\n/**\n * Transformers.js-backed embedding provider (POC 档位: 高档默认\n * Xenova/bge-m3/1024d; 低档由调用方传 modelId \"Xenova/bge-small-zh-v1.5\" +\n * dimensions 512)。\n *\n * 镜像序列: 首次 embed 时按 `remoteHosts` 顺序逐个尝试加载 (调用方通常传\n * [\"https://huggingface.co\", \"https://hf-mirror.com\"]); 某 host 加载抛错则\n * 尝试下一个, 全部失败时抛最后一个错误。host 确定后模型句柄只加载一次\n * (并发 embed 共享同一 in-flight promise); 加载失败不缓存, 下次 embed 重新\n * 走完整序列, 失败原因原样保留, 不静默降级。\n *\n * `loadImpl` 是测试 seam: 注入后绕过真实加载, 签名\n * (modelId, cacheDir, remoteHost) => backend。\n */\nexport function createTransformersEmbeddingProvider(options: {\n\treadonly modelId?: string;\n\treadonly dimensions?: number;\n\treadonly cacheDir: string;\n\treadonly remoteHosts?: readonly string[];\n\treadonly batchSize?: number;\n\treadonly loadImpl?: TransformersEmbeddingLoadImpl;\n\t/** Host-resolved transformers entry path (install-store visibility); undefined = bare import. */\n\treadonly moduleEntryPath?: string;\n}): MemoryEmbeddingProviderV1 {\n\tconst modelId = options.modelId ?? DEFAULT_TRANSFORMERS_MODEL_ID;\n\tconst dimensions = options.dimensions ?? DEFAULT_TRANSFORMERS_DIMENSIONS;\n\tconst batchSize = options.batchSize ?? DEFAULT_TRANSFORMERS_BATCH_SIZE;\n\tconst cacheDir = options.cacheDir;\n\tconst remoteHosts = options.remoteHosts ?? [DEFAULT_REMOTE_HOST];\n\tconst load = options.loadImpl ?? createDefaultTransformersLoadImpl(options.moduleEntryPath);\n\n\tlet backendPromise: Promise<TransformersEmbeddingBackendV1> | null = null;\n\tconst loadBackend = (): Promise<TransformersEmbeddingBackendV1> => {\n\t\tconst existing = backendPromise;\n\t\tif (existing) {\n\t\t\treturn existing;\n\t\t}\n\t\tconst attempt = (async () => {\n\t\t\tlet lastError: unknown;\n\t\t\tfor (const remoteHost of remoteHosts) {\n\t\t\t\ttry {\n\t\t\t\t\treturn await load(modelId, cacheDir, remoteHost);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlastError = error;\n\t\t\t\t\t// 镜像轮换前清 0 字节残骸: 失败下载留下的空文件会被 transformers\n\t\t\t\t\t// 当作缓存命中, 毒化下一个 host 的重试 (model-cache-hygiene)。\n\t\t\t\t\tpurgeZeroByteCacheArtifacts(join(cacheDir, modelId));\n\t\t\t\t}\n\t\t\t\t// 同 host 一次短退避重试 (2026-10-06 live E2E): 覆盖 rejection 型瞬断\n\t\t\t\t// (fetch 网络错/5xx)。对\"仓库 API 清单缺文件\"型不生效——该结果被\n\t\t\t\t// transformers 模块级 memoize (见 annotateUpstreamListingPoison),\n\t\t\t\t// 进程内换 host 也拿同一空清单。\n\t\t\t\ttry {\n\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 2_000));\n\t\t\t\t\treturn await load(modelId, cacheDir, remoteHost);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlastError = error;\n\t\t\t\t\tpurgeZeroByteCacheArtifacts(join(cacheDir, modelId));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (lastError === undefined) throw new Error(`no remote hosts configured for model ${modelId}`);\n\t\t\tthrow annotateUpstreamListingPoison(lastError);\n\t\t})();\n\t\tbackendPromise = attempt;\n\t\tattempt.catch(() => {\n\t\t\t// 失败不缓存: 下次 embed 重新走镜像序列 (显式失败, 不静默降级)。\n\t\t\tif (backendPromise === attempt) {\n\t\t\t\tbackendPromise = null;\n\t\t\t}\n\t\t});\n\t\treturn attempt;\n\t};\n\n\treturn {\n\t\tmodelId,\n\t\tdimensions,\n\t\tembed: async (texts) => {\n\t\t\tif (texts.length === 0) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\tconst backend = await loadBackend();\n\t\t\tconst vectors: number[][] = [];\n\t\t\tfor (let offset = 0; offset < texts.length; offset += batchSize) {\n\t\t\t\tconst batchTexts = texts.slice(offset, offset + batchSize);\n\t\t\t\tconst rows = (await backend.extract(batchTexts)).toList();\n\t\t\t\tfor (const row of rows) {\n\t\t\t\t\tif (row.length !== dimensions) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`embedding dimension mismatch: model ${modelId} returned ${row.length} dims, provider declares ${dimensions}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tvectors.push(row);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn vectors;\n\t\t},\n\t};\n}\n"]}