@kenz1117/dsh-engram 0.11.5 → 0.12.0
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/CHANGELOG.md +42 -2
- package/README.md +3 -0
- package/i18n/panel.ru.txt +6 -0
- package/i18n/ru.txt +4 -0
- package/lib/client.js +2 -2
- package/lib/client.js.map +1 -1
- package/lib/index.js +1352 -326
- package/package.json +6 -6
- package/registry/schema.json +5 -1
package/lib/index.js
CHANGED
|
@@ -6,12 +6,12 @@ import { homedir } from "node:os";
|
|
|
6
6
|
import z from "@deepseek-ai/schemastery";
|
|
7
7
|
import { execFileSync } from "node:child_process";
|
|
8
8
|
import { fileURLToPath } from "node:url";
|
|
9
|
-
import {
|
|
9
|
+
import { mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
10
10
|
import { createGzip, gunzip } from "node:zlib";
|
|
11
11
|
import { promisify } from "node:util";
|
|
12
12
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
13
13
|
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
14
|
-
|
|
14
|
+
// src/i18n/language.ts
|
|
15
15
|
/**
|
|
16
16
|
* Язык вывода — серверная половина плагина.
|
|
17
17
|
*
|
|
@@ -177,8 +177,7 @@ function pickLanguage(setting, packaged) {
|
|
|
177
177
|
if (packaged !== void 0 && BUILTIN_LANGUAGES.includes(packaged)) return packaged;
|
|
178
178
|
return resolveLanguage("auto");
|
|
179
179
|
}
|
|
180
|
-
|
|
181
|
-
//#region src/i18n/catalog/core.ts
|
|
180
|
+
// src/i18n/catalog/core.ts
|
|
182
181
|
/**
|
|
183
182
|
* Словарь: ядро плагина — профиль сессии, бюджет токенов, предложение экскурсии,
|
|
184
183
|
* обоснование отбора, образцы памяти.
|
|
@@ -230,8 +229,9 @@ const zh$5 = {
|
|
|
230
229
|
"core.warnIngestPreviousFailed": "[dsh-engram] 本轮自动摄取失败(已跳过,不影响对话):",
|
|
231
230
|
"core.warnHistoryBackfillFailed": "[dsh-engram] 历史回填失败:",
|
|
232
231
|
"core.warnDisposeFinalFailed": "[dsh-engram] 会话结束的收尾处理异常(不影响对话):",
|
|
232
|
+
"core.warnInjectionSnapshotFailed": "[dsh-engram] 注入快照落库失败(不影响对话):",
|
|
233
233
|
"core.warnReflectFailed": "[dsh-engram] 会话结束的信念巩固异常({scope},不影响对话):",
|
|
234
|
-
"core.warnReflectBatchDropped": "[dsh-engram] 信念巩固丢弃 {count}
|
|
234
|
+
"core.warnReflectBatchDropped": "[dsh-engram] 信念巩固丢弃 {count} 条候选(输出预算/解析失败;未被巩固、下次巩固继续取材)",
|
|
235
235
|
"core.warnDecayStartupFailed": "[dsh-engram] 启动衰减调度失败(跳过):",
|
|
236
236
|
"core.warnDecayPeriodicFailed": "[dsh-engram] 周期衰减调度失败(跳过):",
|
|
237
237
|
"core.warnConsolidationFailed": "[dsh-engram] 闭馆整理失败(不影响对话):",
|
|
@@ -287,8 +287,9 @@ const en$5 = {
|
|
|
287
287
|
"core.warnIngestPreviousFailed": "[dsh-engram] Automatic ingest of this turn failed (skipped, conversation unaffected):",
|
|
288
288
|
"core.warnHistoryBackfillFailed": "[dsh-engram] History backfill failed:",
|
|
289
289
|
"core.warnDisposeFinalFailed": "[dsh-engram] Session-end finalisation threw (conversation unaffected):",
|
|
290
|
+
"core.warnInjectionSnapshotFailed": "[dsh-engram] Could not persist the injection snapshot (conversation unaffected):",
|
|
290
291
|
"core.warnReflectFailed": "[dsh-engram] Belief consolidation at session end threw ({scope}, conversation unaffected):",
|
|
291
|
-
"core.warnReflectBatchDropped": "[dsh-engram] Belief consolidation dropped {count} candidates (
|
|
292
|
+
"core.warnReflectBatchDropped": "[dsh-engram] Belief consolidation dropped {count} candidates (output budget/parse failure; not consolidated, will be picked up next consolidation)",
|
|
292
293
|
"core.warnDecayStartupFailed": "[dsh-engram] Startup decay scheduling failed (skipped):",
|
|
293
294
|
"core.warnDecayPeriodicFailed": "[dsh-engram] Periodic decay scheduling failed (skipped):",
|
|
294
295
|
"core.warnConsolidationFailed": "[dsh-engram] Closing-time consolidation failed (conversation unaffected):",
|
|
@@ -303,8 +304,7 @@ const en$5 = {
|
|
|
303
304
|
"core.decayTargetProject": "project “{title}”",
|
|
304
305
|
"core.backfillBusy": "A backfill job is already running; pause it or wait for it to finish first"
|
|
305
306
|
};
|
|
306
|
-
|
|
307
|
-
//#region src/i18n/catalog/llm.ts
|
|
307
|
+
// src/i18n/catalog/llm.ts
|
|
308
308
|
/**
|
|
309
309
|
* Словарь: обращения к вспомогательной модели — извлечение, дистилляция,
|
|
310
310
|
* консолидация убеждений, переписывание запроса.
|
|
@@ -379,8 +379,7 @@ const en$4 = {
|
|
|
379
379
|
"llm.finishUnsupported": "dsh-engram: unsupported finish reason \"{kind}\"",
|
|
380
380
|
"llm.emptyOutput": "the auxiliary call returned empty output"
|
|
381
381
|
};
|
|
382
|
-
|
|
383
|
-
//#region src/i18n/catalog/misc.ts
|
|
382
|
+
// src/i18n/catalog/misc.ts
|
|
384
383
|
/**
|
|
385
384
|
* Словарь: HTTP-маршруты панели, экспорт-зеркало, предложения по обновлению,
|
|
386
385
|
* проверка таблички-названия, настройки Jev.
|
|
@@ -438,6 +437,7 @@ const zh$3 = {
|
|
|
438
437
|
"misc.jevProviderUnresolved": "Jev:没有提供商——面板、插件设置和会话路由都没有指定",
|
|
439
438
|
"misc.jevModelNotPicked": "Jev:提供商「{provider}」的 DSH 设置里没有 JEV 模型,请手动指定模型",
|
|
440
439
|
"misc.jevEndpointMustBeHttp": "invalid: jev.endpoint 必须是 http(s) URL",
|
|
440
|
+
"misc.jevEndpointOriginMismatch": "Jev:endpoint 必须与提供商「{provider}」的 baseURL 同源;拒绝把宿主凭据发往其他服务",
|
|
441
441
|
"misc.jevModelMustNotBeEmpty": "invalid: jev.model 不能为空",
|
|
442
442
|
"misc.jevTimeoutMsMustBeInteger": "invalid: jev.timeoutMs 必须是 1000-60000 的整数毫秒",
|
|
443
443
|
"tool.languageGuideDescription": "如何把新语言引入记忆宫殿:返回说明文本(文件 docs/agent-language-guide.ru.md,目前只有俄文草稿)。用户的语言不在 zh/en 之内时使用:先读说明,再与用户一起完成登记语言、词典和切换。",
|
|
@@ -492,6 +492,7 @@ const en$3 = {
|
|
|
492
492
|
"misc.jevProviderUnresolved": "Jev: no provider — neither the panel, nor the plugin settings, nor the session route names one",
|
|
493
493
|
"misc.jevModelNotPicked": "Jev: provider \"{provider}\" has no JEV model in its DSH settings; name the model explicitly",
|
|
494
494
|
"misc.jevEndpointMustBeHttp": "invalid: jev.endpoint must be an http(s) URL",
|
|
495
|
+
"misc.jevEndpointOriginMismatch": "Jev: endpoint must share the origin of provider \"{provider}\" baseURL; refusing to send host credentials to another service",
|
|
495
496
|
"misc.jevModelMustNotBeEmpty": "invalid: jev.model must not be empty",
|
|
496
497
|
"misc.jevTimeoutMsMustBeInteger": "invalid: jev.timeoutMs must be an integer number of milliseconds between 1000 and 60000",
|
|
497
498
|
"misc.warnDictionaryProblems": "[dsh-engram] The translation dictionary skipped {count} problem line(s); those texts stay English: {sample}",
|
|
@@ -499,8 +500,7 @@ const en$3 = {
|
|
|
499
500
|
"tool.languageGuideDescription": "How to bring a new language into the memory palace: returns the instruction text (docs/agent-language-guide.ru.md, currently a Russian draft). Use it when the user's language is not zh/en: read it, then walk the user through registering the language, the dictionaries and the switch.",
|
|
500
501
|
"tool.languageGuideMissing": "[dsh-engram] language guide file is missing: {file} — {error}"
|
|
501
502
|
};
|
|
502
|
-
|
|
503
|
-
//#region src/i18n/catalog/store.ts
|
|
503
|
+
// src/i18n/catalog/store.ts
|
|
504
504
|
/**
|
|
505
505
|
* Словарь: хранилище, резервные копии, безопасность, привязка к проекту, эмбеддер.
|
|
506
506
|
*
|
|
@@ -604,8 +604,7 @@ const en$2 = {
|
|
|
604
604
|
"store.embedderRemoteEmpty": "embedding endpoint returned an empty vector",
|
|
605
605
|
"store.budgetDropped": "({count} more not shown: narrow the query or lower the limit and retry)"
|
|
606
606
|
};
|
|
607
|
-
|
|
608
|
-
//#region src/i18n/catalog/tool.ts
|
|
607
|
+
// src/i18n/catalog/tool.ts
|
|
609
608
|
/**
|
|
610
609
|
* Словарь: 23 инструмента `engram_*` — описания схем, тексты результатов и ошибки.
|
|
611
610
|
*
|
|
@@ -1283,8 +1282,7 @@ const en$1 = {
|
|
|
1283
1282
|
"tool.profileEditNoBlockToRollback": "engram_profile_edit: the {scope} store has no curated profile block, so there is nothing to roll back",
|
|
1284
1283
|
"tool.profileEditRolledBack": "Wrote the content of v{from} as v{to} ({scope}; the version chain only grows, so further rollbacks are possible)."
|
|
1285
1284
|
};
|
|
1286
|
-
|
|
1287
|
-
//#region src/i18n/messages.ts
|
|
1285
|
+
// src/i18n/messages.ts
|
|
1288
1286
|
/**
|
|
1289
1287
|
* Словарь служебных сообщений серверной половины.
|
|
1290
1288
|
*
|
|
@@ -1411,8 +1409,7 @@ function messageIn(language, key, params) {
|
|
|
1411
1409
|
function message(key, params) {
|
|
1412
1410
|
return messageIn(current, key, params);
|
|
1413
1411
|
}
|
|
1414
|
-
|
|
1415
|
-
//#region src/jev/stale.ts
|
|
1412
|
+
// src/jev/stale.ts
|
|
1416
1413
|
/**
|
|
1417
1414
|
* Поля Jev прежнего формата: ключ и адрес когда-то хранились у самого плагина
|
|
1418
1415
|
* (`jev.apiKey`, `jev.baseUrl`). После переезда к провайдеру хоста они больше не
|
|
@@ -1458,8 +1455,7 @@ function noteLegacyJevFields(where, fields) {
|
|
|
1458
1455
|
}));
|
|
1459
1456
|
}
|
|
1460
1457
|
}
|
|
1461
|
-
|
|
1462
|
-
//#region src/config.ts
|
|
1458
|
+
// src/config.ts
|
|
1463
1459
|
/**
|
|
1464
1460
|
* 插件 Config:所有部署可变项集中于此,禁止在实现里内嵌默认值。
|
|
1465
1461
|
* @module @kenz1117/dsh-engram/config
|
|
@@ -1489,6 +1485,7 @@ const CONFIG_KEYS = /* @__PURE__ */ new Set([
|
|
|
1489
1485
|
"reviewScheduling",
|
|
1490
1486
|
"assessReminder",
|
|
1491
1487
|
"palaceChangeWindowSec",
|
|
1488
|
+
"panelAccess",
|
|
1492
1489
|
"historyBackfillDays",
|
|
1493
1490
|
"historyBackfillMaxTurnsPerSession",
|
|
1494
1491
|
"historyBackfillMaxTotalTurns",
|
|
@@ -1545,6 +1542,7 @@ const Config = z.object({
|
|
|
1545
1542
|
queryRewrite: z.boolean(),
|
|
1546
1543
|
autoSlot: z.boolean(),
|
|
1547
1544
|
reviewScheduling: z.boolean(),
|
|
1545
|
+
panelAccess: z.string(),
|
|
1548
1546
|
palaceChangeWindowSec: z.number().step(1).min(5).max(600),
|
|
1549
1547
|
assessReminder: z.boolean(),
|
|
1550
1548
|
historyBackfillDays: z.number().step(1).min(0).max(3650),
|
|
@@ -1592,13 +1590,14 @@ function readLanguageSetting(value) {
|
|
|
1592
1590
|
* 显式 resolve 步骤:默认值只在唯一的此处落地,非法值 loud 失败。
|
|
1593
1591
|
* @param config - cordis.yml 传入的未校验配置。
|
|
1594
1592
|
* @returns 完整解析配置。
|
|
1595
|
-
* @throws 未知键、ingest 档位非法、provider/model 只给其一、decay/预算/排序权重/历史回填规则越界时抛错。
|
|
1593
|
+
* @throws 未知键、ingest/reflect/panelAccess 档位非法、provider/model 只给其一、decay/预算/排序权重/历史回填规则越界时抛错。
|
|
1596
1594
|
*/
|
|
1597
1595
|
function resolveConfig(config = {}) {
|
|
1598
1596
|
for (const key of Object.keys(config)) if (!CONFIG_KEYS.has(key)) throw new Error(`dsh-engram: unknown config key "${key}"`);
|
|
1599
1597
|
if (config.legacyMigration !== void 0 && config.legacyMigration !== "eager" && config.legacyMigration !== "conservative") throw new Error("dsh-engram: legacyMigration must be one of eager|conservative");
|
|
1600
1598
|
if (config.ingest !== void 0 && !INGEST_MODES.has(config.ingest)) throw new Error(`dsh-engram: ingest must be one of off|light|eager, got "${String(config.ingest)}"`);
|
|
1601
1599
|
if (config.reflect !== void 0 && !REFLECT_MODES.has(config.reflect)) throw new Error(`dsh-engram: reflect must be one of off|suggest|auto, got "${String(config.reflect)}"`);
|
|
1600
|
+
if (config.panelAccess !== void 0 && config.panelAccess !== "loopback" && config.panelAccess !== "lan") throw new Error(`dsh-engram: panelAccess must be one of loopback|lan, got "${String(config.panelAccess)}"`);
|
|
1602
1601
|
const languageSetting = readLanguageSetting(config.language);
|
|
1603
1602
|
if (languageSetting !== void 0 && languageSetting !== "auto" && !isLanguageCode(languageSetting)) throw new Error(`dsh-engram: language must be "auto" or a language code (zh, en, ru, fr, …), got "${String(languageSetting)}"`);
|
|
1604
1603
|
if (config.profileTopN !== void 0 && (!Number.isInteger(config.profileTopN) || config.profileTopN < 1 || config.profileTopN > 64)) throw new Error("dsh-engram: profileTopN must be an integer in [1, 64]");
|
|
@@ -1690,6 +1689,7 @@ function resolveConfig(config = {}) {
|
|
|
1690
1689
|
queryRewrite: config.queryRewrite ?? true,
|
|
1691
1690
|
autoSlot: config.autoSlot ?? true,
|
|
1692
1691
|
reviewScheduling: config.reviewScheduling ?? true,
|
|
1692
|
+
panelAccess: config.panelAccess ?? "loopback",
|
|
1693
1693
|
palaceChangeWindowSec: config.palaceChangeWindowSec ?? 30,
|
|
1694
1694
|
historyBackfill: {
|
|
1695
1695
|
days: config.historyBackfillDays ?? 7,
|
|
@@ -1724,8 +1724,7 @@ function resolveConfig(config = {}) {
|
|
|
1724
1724
|
}
|
|
1725
1725
|
};
|
|
1726
1726
|
}
|
|
1727
|
-
|
|
1728
|
-
//#region src/registry/root.ts
|
|
1727
|
+
// src/registry/root.ts
|
|
1729
1728
|
/**
|
|
1730
1729
|
* Корень пакета — общий для всех файлов, которые читаются с диска при работе:
|
|
1731
1730
|
* словарей (`i18n/`) и реестров (`registry/`).
|
|
@@ -1750,8 +1749,7 @@ function packageRoot() {
|
|
|
1750
1749
|
}
|
|
1751
1750
|
return dir;
|
|
1752
1751
|
}
|
|
1753
|
-
|
|
1754
|
-
//#region src/i18n/dictionary.ts
|
|
1752
|
+
// src/i18n/dictionary.ts
|
|
1755
1753
|
/** Раскрытие экранированной последовательности. */
|
|
1756
1754
|
const UNESCAPE = {
|
|
1757
1755
|
"\\": "\\",
|
|
@@ -1895,8 +1893,7 @@ function parseDictionary(text, options) {
|
|
|
1895
1893
|
seen
|
|
1896
1894
|
};
|
|
1897
1895
|
}
|
|
1898
|
-
|
|
1899
|
-
//#region src/i18n/dictionary-file.ts
|
|
1896
|
+
// src/i18n/dictionary-file.ts
|
|
1900
1897
|
/**
|
|
1901
1898
|
* Чтение словарей перевода с диска: сначала поставка, поверх неё — слой пользователя.
|
|
1902
1899
|
*
|
|
@@ -2011,8 +2008,7 @@ function describeDictionaryProblems(problems, limit = 3) {
|
|
|
2011
2008
|
const rest = problems.length - head.length;
|
|
2012
2009
|
return rest > 0 ? `${head.join("; ")}; ещё ${rest}` : head.join("; ");
|
|
2013
2010
|
}
|
|
2014
|
-
|
|
2015
|
-
//#region src/client/locales/en.ts
|
|
2011
|
+
// src/client/locales/en.ts
|
|
2016
2012
|
/** 英文词典。整页采用「Memory Palace」语言:palace / room (kind group) / memory / placard / tour / curator / corridor。
|
|
2017
2013
|
数据层英文枚举(status/kind/op)不在此映射,文案键保持稳定。 */
|
|
2018
2014
|
const en = {
|
|
@@ -2345,6 +2341,12 @@ const en = {
|
|
|
2345
2341
|
beliefEvidence: "{n} evidence",
|
|
2346
2342
|
beliefEvidenceEmpty: "Evidence memories were purged; the belief is kept",
|
|
2347
2343
|
beliefNone: "No consolidated beliefs yet; the butler induces them once memories accumulate",
|
|
2344
|
+
beliefRefute: "Refute",
|
|
2345
|
+
beliefRefuteConfirm: "Click again to refute",
|
|
2346
|
+
beliefRestore: "Restore",
|
|
2347
|
+
beliefRefuteDone: "Belief refuted",
|
|
2348
|
+
beliefRestoreDone: "Belief restored",
|
|
2349
|
+
beliefActionFailed: "Action failed: {msg}",
|
|
2348
2350
|
entityKindAll: "All kinds",
|
|
2349
2351
|
entityKindPerson: "People",
|
|
2350
2352
|
entityKindProject: "Projects",
|
|
@@ -2449,6 +2451,34 @@ const en = {
|
|
|
2449
2451
|
corridorIndexRooms: "{n} rooms",
|
|
2450
2452
|
skipEmptyAnswer: "empty output (empty after retry)",
|
|
2451
2453
|
skipAllCandidatesFailed: "every candidate failed to write (kept for replay)",
|
|
2454
|
+
tabReplay: "Context replay",
|
|
2455
|
+
pageHeaderReplaySubtitle: "Replay exact injected packets, selected memories, and their provenance",
|
|
2456
|
+
replayFilterLabel: "Session",
|
|
2457
|
+
replayFilterPlaceholder: "Filter by sessionId (optional)",
|
|
2458
|
+
replayCount: "{n} injections",
|
|
2459
|
+
replayEmpty: "No injection snapshots yet; enable profile injection to record them",
|
|
2460
|
+
replayFailed: "Failed to load injection replay",
|
|
2461
|
+
replayOpen: "View final packet",
|
|
2462
|
+
replayClose: "Hide final packet",
|
|
2463
|
+
replayPacketTitle: "Final packet actually received by the model",
|
|
2464
|
+
replayMetaTitle: "Snapshot metadata",
|
|
2465
|
+
replayExactNote: "This text is byte-for-byte the packet used for the hash, audit trail, and model request.",
|
|
2466
|
+
replaySession: "Session",
|
|
2467
|
+
replayHash: "SHA-256",
|
|
2468
|
+
replayMemories: "Selected memories",
|
|
2469
|
+
replayCurated: "Curated profile",
|
|
2470
|
+
replayCompactions: "Compactions",
|
|
2471
|
+
replaySize: "Packet size",
|
|
2472
|
+
benchInspect: "Inspect placard",
|
|
2473
|
+
governanceTitle: "Contradiction governance",
|
|
2474
|
+
governanceHint: "Only contradictions with both sides active are shown; reclassifying keeps both; closing archives the selected side",
|
|
2475
|
+
governanceCount: "{n} pairs pending",
|
|
2476
|
+
governanceEmpty: "No contradictions pending",
|
|
2477
|
+
governanceFailed: "Failed to load governance queue",
|
|
2478
|
+
governanceDismiss: "Reclassify as related",
|
|
2479
|
+
governanceForget: "Close this memory",
|
|
2480
|
+
governanceActionFailed: "Action failed",
|
|
2481
|
+
governanceStableId: "Stable ID",
|
|
2452
2482
|
tabSpiral: "Memory Spiral",
|
|
2453
2483
|
spiralAriaLabel: "memory spiral view",
|
|
2454
2484
|
spiralCenterLabel: "Now",
|
|
@@ -2580,8 +2610,7 @@ const en = {
|
|
|
2580
2610
|
dictFillDone: "AI filled {n} cell(s)",
|
|
2581
2611
|
dictFillFailed: "Could not fill with AI: {error}"
|
|
2582
2612
|
};
|
|
2583
|
-
|
|
2584
|
-
//#region src/client/locales/ru.ts
|
|
2613
|
+
// src/client/locales/ru.ts
|
|
2585
2614
|
/** Русский словарь. Метафора английского словаря сохранена: дворец (palace) / комната (kind-группа) /
|
|
2586
2615
|
воспоминание (memory) / табличка (placard) / экскурсия (tour) / куратор (curator) / коридор (corridor).
|
|
2587
2616
|
Английские перечисления слоя данных (status/kind/op) здесь не отображаются: ключи стабильны ради
|
|
@@ -2916,6 +2945,12 @@ const ru = {
|
|
|
2916
2945
|
beliefEvidence: "{n} доказательство|{n} доказательства|{n} доказательств",
|
|
2917
2946
|
beliefEvidenceEmpty: "Воспоминания-доказательства удалены; убеждение сохранено",
|
|
2918
2947
|
beliefNone: "Консолидированных убеждений пока нет; куратор выводит их по мере накопления воспоминаний",
|
|
2948
|
+
beliefRefute: "Опровергнуть",
|
|
2949
|
+
beliefRefuteConfirm: "Нажми ещё раз для опровержения",
|
|
2950
|
+
beliefRestore: "Восстановить",
|
|
2951
|
+
beliefRefuteDone: "Убеждение опровергнуто",
|
|
2952
|
+
beliefRestoreDone: "Убеждение восстановлено",
|
|
2953
|
+
beliefActionFailed: "Не удалось выполнить: {msg}",
|
|
2919
2954
|
entityKindAll: "Все виды",
|
|
2920
2955
|
entityKindPerson: "Люди",
|
|
2921
2956
|
entityKindProject: "Проекты",
|
|
@@ -3020,6 +3055,34 @@ const ru = {
|
|
|
3020
3055
|
corridorIndexRooms: "комнат: {n}",
|
|
3021
3056
|
skipEmptyAnswer: "вывод дистилляции пуст (пуст и после повтора)",
|
|
3022
3057
|
skipAllCandidatesFailed: "все кандидаты не записались (сохранено для повтора)",
|
|
3058
|
+
tabReplay: "Воспроизведение контекста",
|
|
3059
|
+
pageHeaderReplaySubtitle: "Точные пакеты внедрения, выбранные воспоминания и их происхождение",
|
|
3060
|
+
replayFilterLabel: "Сессия",
|
|
3061
|
+
replayFilterPlaceholder: "Фильтр по sessionId (необязательно)",
|
|
3062
|
+
replayCount: "внедрений: {n}",
|
|
3063
|
+
replayEmpty: "Снимков внедрения ещё нет; включите внедрение профиля для записи",
|
|
3064
|
+
replayFailed: "Не удалось загрузить воспроизведение",
|
|
3065
|
+
replayOpen: "Показать итоговый пакет",
|
|
3066
|
+
replayClose: "Скрыть итоговый пакет",
|
|
3067
|
+
replayPacketTitle: "Пакет, фактически полученный моделью",
|
|
3068
|
+
replayMetaTitle: "Метаданные снимка",
|
|
3069
|
+
replayExactNote: "Этот текст дословно совпадает с пакетом для хеша, аудита и запроса модели.",
|
|
3070
|
+
replaySession: "Сессия",
|
|
3071
|
+
replayHash: "Хеш SHA-256",
|
|
3072
|
+
replayMemories: "Выбранные воспоминания",
|
|
3073
|
+
replayCurated: "Курируемый профиль",
|
|
3074
|
+
replayCompactions: "Сжатий",
|
|
3075
|
+
replaySize: "Размер пакета",
|
|
3076
|
+
benchInspect: "Открыть табличку",
|
|
3077
|
+
governanceTitle: "Разбор противоречий",
|
|
3078
|
+
governanceHint: "Показаны только противоречия с двумя активными сторонами; переклассификация сохраняет обе; закрытие архивирует выбранную",
|
|
3079
|
+
governanceCount: "ожидают решения: {n}",
|
|
3080
|
+
governanceEmpty: "Нет противоречий для решения",
|
|
3081
|
+
governanceFailed: "Не удалось загрузить очередь разбора",
|
|
3082
|
+
governanceDismiss: "Переклассифицировать как связанные",
|
|
3083
|
+
governanceForget: "Закрыть это воспоминание",
|
|
3084
|
+
governanceActionFailed: "Не удалось выполнить действие",
|
|
3085
|
+
governanceStableId: "Стабильный ID",
|
|
3023
3086
|
tabSpiral: "Спираль воспоминаний",
|
|
3024
3087
|
spiralAriaLabel: "спираль воспоминаний",
|
|
3025
3088
|
spiralCenterLabel: "сейчас",
|
|
@@ -3151,8 +3214,7 @@ const ru = {
|
|
|
3151
3214
|
dictFillDone: "ИИ заполнил клеток: {n}",
|
|
3152
3215
|
dictFillFailed: "Не удалось заполнить с помощью ИИ: {error}"
|
|
3153
3216
|
};
|
|
3154
|
-
|
|
3155
|
-
//#region src/client/locales/zh.ts
|
|
3217
|
+
// src/client/locales/zh.ts
|
|
3156
3218
|
/** 中文词典(宿主默认语言)。整页采用「记忆宫殿」语言:宫殿 / 房间(kind 分组)/ 记忆 / 铭牌 / 参观 / 管家 / 走廊。
|
|
3157
3219
|
数据层英文枚举(status/kind/op)不在此映射,文案键保持稳定以保证编译约束。 */
|
|
3158
3220
|
const zh = {
|
|
@@ -3485,6 +3547,12 @@ const zh = {
|
|
|
3485
3547
|
beliefEvidence: "证据 {n} 条",
|
|
3486
3548
|
beliefEvidenceEmpty: "证据记忆已被清理,信念保留",
|
|
3487
3549
|
beliefNone: "还没有巩固出信念;管家会在记忆积累后自动归纳",
|
|
3550
|
+
beliefRefute: "作废",
|
|
3551
|
+
beliefRefuteConfirm: "再点一次确认作废",
|
|
3552
|
+
beliefRestore: "恢复",
|
|
3553
|
+
beliefRefuteDone: "已作废该信念",
|
|
3554
|
+
beliefRestoreDone: "已恢复该信念",
|
|
3555
|
+
beliefActionFailed: "执行失败:{msg}",
|
|
3488
3556
|
entityKindAll: "全部类别",
|
|
3489
3557
|
entityKindPerson: "人物",
|
|
3490
3558
|
entityKindProject: "项目",
|
|
@@ -3589,6 +3657,34 @@ const zh = {
|
|
|
3589
3657
|
corridorIndexRooms: "{n} 间房",
|
|
3590
3658
|
skipEmptyAnswer: "提炼输出为空(重试后仍空)",
|
|
3591
3659
|
skipAllCandidatesFailed: "全部候选落库失败(保留待重放)",
|
|
3660
|
+
tabReplay: "上下文回放",
|
|
3661
|
+
pageHeaderReplaySubtitle: "回看每次实际注入的最终包、入选记忆和逐字事实源",
|
|
3662
|
+
replayFilterLabel: "会话",
|
|
3663
|
+
replayFilterPlaceholder: "按 sessionId 过滤(可留空)",
|
|
3664
|
+
replayCount: "{n} 次注入",
|
|
3665
|
+
replayEmpty: "还没有注入快照;开启画像注入后自动记录",
|
|
3666
|
+
replayFailed: "注入回放加载失败",
|
|
3667
|
+
replayOpen: "查看最终包",
|
|
3668
|
+
replayClose: "收起最终包",
|
|
3669
|
+
replayPacketTitle: "模型实际收到的最终包",
|
|
3670
|
+
replayMetaTitle: "快照元数据",
|
|
3671
|
+
replayExactNote: "此处正文与哈希、审计和当时模型收到的内容逐字一致。",
|
|
3672
|
+
replaySession: "会话",
|
|
3673
|
+
replayHash: "SHA-256",
|
|
3674
|
+
replayMemories: "入选记忆",
|
|
3675
|
+
replayCurated: "人工画像",
|
|
3676
|
+
replayCompactions: "压缩次数",
|
|
3677
|
+
replaySize: "包大小",
|
|
3678
|
+
benchInspect: "查看铭牌",
|
|
3679
|
+
governanceTitle: "矛盾治理",
|
|
3680
|
+
governanceHint: "只显示双侧仍驻留的矛盾边;改判保留两条记忆,闭馆会作废所选一侧",
|
|
3681
|
+
governanceCount: "{n} 组待处置",
|
|
3682
|
+
governanceEmpty: "没有待处置矛盾",
|
|
3683
|
+
governanceFailed: "治理队列加载失败",
|
|
3684
|
+
governanceDismiss: "改判为相关",
|
|
3685
|
+
governanceForget: "闭馆此条",
|
|
3686
|
+
governanceActionFailed: "处置失败",
|
|
3687
|
+
governanceStableId: "稳定身份",
|
|
3592
3688
|
tabSpiral: "回忆螺旋",
|
|
3593
3689
|
spiralAriaLabel: "回忆螺旋视图",
|
|
3594
3690
|
spiralCenterLabel: "现在",
|
|
@@ -3720,8 +3816,7 @@ const zh = {
|
|
|
3720
3816
|
dictFillDone: "AI 已填充 {n} 个单元格",
|
|
3721
3817
|
dictFillFailed: "AI 填充失败:{error}"
|
|
3722
3818
|
};
|
|
3723
|
-
|
|
3724
|
-
//#region src/i18n/dictionary-terms.ts
|
|
3819
|
+
// src/i18n/dictionary-terms.ts
|
|
3725
3820
|
/**
|
|
3726
3821
|
* Словарь как список терминов: что показывать в таблице правки и что стоит справа.
|
|
3727
3822
|
*
|
|
@@ -3797,8 +3892,7 @@ function dictionaryBuiltin(set, language, left) {
|
|
|
3797
3892
|
const key = panelByText.get(left);
|
|
3798
3893
|
return key === void 0 ? void 0 : PANEL_PACKS[language]?.[key];
|
|
3799
3894
|
}
|
|
3800
|
-
|
|
3801
|
-
//#region src/i18n/dictionary-edit.ts
|
|
3895
|
+
// src/i18n/dictionary-edit.ts
|
|
3802
3896
|
/**
|
|
3803
3897
|
* Правка словарей: что можно править, где это лежит и как записать.
|
|
3804
3898
|
*
|
|
@@ -4134,8 +4228,7 @@ function splitFillBatch(terms, maxCount = 30, maxChars = FILL_BATCH_CHARS) {
|
|
|
4134
4228
|
if (current.length > 0) chunks.push(current);
|
|
4135
4229
|
return chunks;
|
|
4136
4230
|
}
|
|
4137
|
-
|
|
4138
|
-
//#region src/types.ts
|
|
4231
|
+
// src/types.ts
|
|
4139
4232
|
/** 从任意字符串铸造品牌化 id(存储层入库前调用)。 */
|
|
4140
4233
|
function asMemoryId(raw) {
|
|
4141
4234
|
return raw;
|
|
@@ -4168,8 +4261,7 @@ var EngramError = class extends Error {
|
|
|
4168
4261
|
this.code = code;
|
|
4169
4262
|
}
|
|
4170
4263
|
};
|
|
4171
|
-
|
|
4172
|
-
//#region src/i18n/dictionary-ai.ts
|
|
4264
|
+
// src/i18n/dictionary-ai.ts
|
|
4173
4265
|
/**
|
|
4174
4266
|
* Язык в запросе: модель должна понимать, на какой язык переводить.
|
|
4175
4267
|
* Имя английское — это метаязык инструкции, а не тот, на который переводим.
|
|
@@ -4436,8 +4528,7 @@ function fillBatch(terms) {
|
|
|
4436
4528
|
}));
|
|
4437
4529
|
return list;
|
|
4438
4530
|
}
|
|
4439
|
-
|
|
4440
|
-
//#region src/registry/languages.ts
|
|
4531
|
+
// src/registry/languages.ts
|
|
4441
4532
|
/**
|
|
4442
4533
|
* Реестр языков: какие языки дворца плагин знает и откуда берёт их тексты.
|
|
4443
4534
|
*
|
|
@@ -4547,8 +4638,7 @@ function parseLanguages(text) {
|
|
|
4547
4638
|
issues
|
|
4548
4639
|
};
|
|
4549
4640
|
}
|
|
4550
|
-
|
|
4551
|
-
//#region src/registry/models.ts
|
|
4641
|
+
// src/registry/models.ts
|
|
4552
4642
|
/** Способы сведения токенов, которые понимает разбор. */
|
|
4553
4643
|
const POOLING_MODES = ["mean", "cls"];
|
|
4554
4644
|
/** Виды весов, которые понимает разбор (множество transformers.js). */
|
|
@@ -4863,8 +4953,7 @@ function checkBindingModels(models, bindings) {
|
|
|
4863
4953
|
});
|
|
4864
4954
|
return issues;
|
|
4865
4955
|
}
|
|
4866
|
-
|
|
4867
|
-
//#region src/registry/registry-file.ts
|
|
4956
|
+
// src/registry/registry-file.ts
|
|
4868
4957
|
/**
|
|
4869
4958
|
* Чтение реестров с диска: каталог моделей — только поставка, привязки —
|
|
4870
4959
|
* поставка плюс слой пользователя.
|
|
@@ -5013,8 +5102,7 @@ function describeRegistryProblems(problems, limit = 3) {
|
|
|
5013
5102
|
const rest = problems.length - head.length;
|
|
5014
5103
|
return rest > 0 ? `${head.join("; ")}; ещё ${rest}` : head.join("; ");
|
|
5015
5104
|
}
|
|
5016
|
-
|
|
5017
|
-
//#region src/i18n/palace-language.ts
|
|
5105
|
+
// src/i18n/palace-language.ts
|
|
5018
5106
|
/**
|
|
5019
5107
|
* Язык дворца: чистые правила определения — без обращения к сервисам и файлам.
|
|
5020
5108
|
*
|
|
@@ -5162,8 +5250,7 @@ function decideLanguage(signals, options = {}) {
|
|
|
5162
5250
|
}]
|
|
5163
5251
|
};
|
|
5164
5252
|
}
|
|
5165
|
-
|
|
5166
|
-
//#region src/language-signals.ts
|
|
5253
|
+
// src/language-signals.ts
|
|
5167
5254
|
/**
|
|
5168
5255
|
* Сбор сигналов для языка дворца: то, что можно прочитать у хоста и на машине.
|
|
5169
5256
|
*
|
|
@@ -5213,8 +5300,7 @@ async function collectLanguageSignals(deps = {}) {
|
|
|
5213
5300
|
machine
|
|
5214
5301
|
};
|
|
5215
5302
|
}
|
|
5216
|
-
|
|
5217
|
-
//#region src/settings-bridge.ts
|
|
5303
|
+
// src/settings-bridge.ts
|
|
5218
5304
|
/**
|
|
5219
5305
|
* Мост к хостовому сервису настроек: чтение preference интерфейса и запись языка дворца.
|
|
5220
5306
|
*
|
|
@@ -5325,8 +5411,7 @@ async function writePalaceLanguageWithRetry(input) {
|
|
|
5325
5411
|
}
|
|
5326
5412
|
return reason;
|
|
5327
5413
|
}
|
|
5328
|
-
|
|
5329
|
-
//#region src/i18n/patterns.ts
|
|
5414
|
+
// src/i18n/patterns.ts
|
|
5330
5415
|
/**
|
|
5331
5416
|
* Языкозависимые образцы распознавания ввода.
|
|
5332
5417
|
*
|
|
@@ -5455,8 +5540,7 @@ function chitchatPatterns(language = messageLanguage()) {
|
|
|
5455
5540
|
function noCapturePatterns(language = messageLanguage()) {
|
|
5456
5541
|
return activePatternLanguages(language).map((lang) => NO_CAPTURE_RE[lang]).filter((pattern) => pattern !== void 0);
|
|
5457
5542
|
}
|
|
5458
|
-
|
|
5459
|
-
//#region src/i18n/rooms.ts
|
|
5543
|
+
// src/i18n/rooms.ts
|
|
5460
5544
|
/** Базовый идентификатор → имя. Ключи совпадают с KIND_ROOM_IDS из palace/slots.ts. */
|
|
5461
5545
|
const BASE_LABELS = {
|
|
5462
5546
|
zh: {
|
|
@@ -5521,8 +5605,7 @@ function resolveRoomInput(input) {
|
|
|
5521
5605
|
}
|
|
5522
5606
|
}
|
|
5523
5607
|
}
|
|
5524
|
-
|
|
5525
|
-
//#region src/embedder/local.ts
|
|
5608
|
+
// src/embedder/local.ts
|
|
5526
5609
|
/**
|
|
5527
5610
|
* transformers.js 本地嵌入实现:离线推理,模型首次使用需联网下载到 cacheDir;
|
|
5528
5611
|
* 之后完全离线,数据不出机。
|
|
@@ -5581,8 +5664,7 @@ async function createLocalEmbedder(cacheDir, remoteHost, spec) {
|
|
|
5581
5664
|
throw new EngramError("EMBEDDER_DOWNLOAD_FAILED", message("store.embedderDownloadFailed"), { cause: error });
|
|
5582
5665
|
}
|
|
5583
5666
|
}
|
|
5584
|
-
|
|
5585
|
-
//#region src/embedder/remote.ts
|
|
5667
|
+
// src/embedder/remote.ts
|
|
5586
5668
|
/**
|
|
5587
5669
|
* OpenAI 兼容端点嵌入器:`POST {baseUrl}/embeddings`。
|
|
5588
5670
|
*
|
|
@@ -5702,8 +5784,7 @@ async function createRemoteEmbedder(options) {
|
|
|
5702
5784
|
close: async () => {}
|
|
5703
5785
|
};
|
|
5704
5786
|
}
|
|
5705
|
-
|
|
5706
|
-
//#region src/embedder/select.ts
|
|
5787
|
+
// src/embedder/select.ts
|
|
5707
5788
|
/**
|
|
5708
5789
|
* Свойства модели, которой нет в каталоге.
|
|
5709
5790
|
*
|
|
@@ -5800,8 +5881,7 @@ function createEmbedder(config, registry, languageOverride) {
|
|
|
5800
5881
|
if (spec === void 0) return Promise.reject(new EngramError("EMBEDDER_MODEL_UNRESOLVED", message("store.embedderModelUnresolved")));
|
|
5801
5882
|
return createLocalEmbedder(config.modelCacheDir, config.hfEndpoint, spec);
|
|
5802
5883
|
}
|
|
5803
|
-
|
|
5804
|
-
//#region src/llm/client.ts
|
|
5884
|
+
// src/llm/client.ts
|
|
5805
5885
|
/**
|
|
5806
5886
|
* 辅助 LLM 调用客户端:封装 ctx.llm.stream + BlockAssembler,路由从会话日志解析。
|
|
5807
5887
|
* 遵守 model-visible ⟺ logged:每次辅助调用的完整请求由调用方 append 到会话日志。
|
|
@@ -5900,8 +5980,7 @@ async function streamText(ctx, params) {
|
|
|
5900
5980
|
if (text.trim() === "") throw new EngramError("LLM_EMPTY_OUTPUT", message("llm.emptyOutput"));
|
|
5901
5981
|
return text;
|
|
5902
5982
|
}
|
|
5903
|
-
|
|
5904
|
-
//#region src/security/sanitize.ts
|
|
5983
|
+
// src/security/sanitize.ts
|
|
5905
5984
|
/**
|
|
5906
5985
|
* 提示注入防护协议:记忆召回内容包 <engram_memory_context> 标签并附使用警告,
|
|
5907
5986
|
* 当前用户请求包 <current_user_request>;任何记忆正文入库前剥离这些协议标签,
|
|
@@ -6046,8 +6125,7 @@ function normalizeWhitespace(value) {
|
|
|
6046
6125
|
function escapeRegExp(value) {
|
|
6047
6126
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
6048
6127
|
}
|
|
6049
|
-
|
|
6050
|
-
//#region src/security/redact.ts
|
|
6128
|
+
// src/security/redact.ts
|
|
6051
6129
|
/**
|
|
6052
6130
|
* 摄取脱敏:记忆入库前用正则清洗常见密钥凭据(API key、Bearer、AWS、GitHub
|
|
6053
6131
|
* token、PEM 私钥、password/token 赋值),命中片段替换为 [REDACTED:<kind>],
|
|
@@ -6080,8 +6158,7 @@ function redactSecrets(text) {
|
|
|
6080
6158
|
for (const { pattern, kind } of redactLabelPatterns()) cleaned = cleaned.replace(pattern, (_match, key) => `${key}=${redacted(kind)}`);
|
|
6081
6159
|
return cleaned.replace(/(?<!\d)1[3-9]\d{9}(?!\d)/g, redacted("phone")).replace(/\b[1-9]\d{5}(?:19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx]\b/g, redacted("id-number"));
|
|
6082
6160
|
}
|
|
6083
|
-
|
|
6084
|
-
//#region src/security/recall.ts
|
|
6161
|
+
// src/security/recall.ts
|
|
6085
6162
|
/** 召回类工具名单:输出含既有记忆正文、重新入库只会自我强化的工具。 */
|
|
6086
6163
|
const RECALL_TOOL_NAMES = /* @__PURE__ */ new Set([
|
|
6087
6164
|
"engram_search",
|
|
@@ -6147,8 +6224,7 @@ function omitRecallToolResults(events) {
|
|
|
6147
6224
|
};
|
|
6148
6225
|
});
|
|
6149
6226
|
}
|
|
6150
|
-
|
|
6151
|
-
//#region src/jev/observe.ts
|
|
6227
|
+
// src/jev/observe.ts
|
|
6152
6228
|
/** 缓冲容量:足够回看一次摄取批次,同时封顶内存占用。 */
|
|
6153
6229
|
const CAPACITY = 50;
|
|
6154
6230
|
const buffer = [];
|
|
@@ -6338,8 +6414,7 @@ async function applyMerge(store, decision, content) {
|
|
|
6338
6414
|
if (record === void 0) throw new Error(message("store.mergeTargetMissing", { id: decision.into.id }));
|
|
6339
6415
|
return record;
|
|
6340
6416
|
}
|
|
6341
|
-
|
|
6342
|
-
//#region src/ingest/hook.ts
|
|
6417
|
+
// src/ingest/hook.ts
|
|
6343
6418
|
/** 档位参数(协议内常量,非部署 tunables)。 */
|
|
6344
6419
|
const MODE_LIMITS = {
|
|
6345
6420
|
light: {
|
|
@@ -6941,22 +7016,28 @@ async function markPendingIngest(store, sessionId, turn) {
|
|
|
6941
7016
|
* pre-step 重放补做),绝不影响对话。
|
|
6942
7017
|
* 本函数不 reject:从取轮次到摄取全程在 try 内,异常一律降级为告警 + pending 键
|
|
6943
7018
|
* (dispose 观察器是 fire-and-forget,逃逸的 rejection 会被宿主的 fail-loud 当作致命错误)。
|
|
6944
|
-
* @returns
|
|
7019
|
+
* @returns 摄取结果;无末轮或异常失败(已尝试落 pending)时返回 null,结果型失败原样返回。
|
|
6945
7020
|
*/
|
|
6946
7021
|
async function ingestFinalTurn(deps) {
|
|
6947
7022
|
/** 末轮轮次号;取不到(无 turn/start 或事件源不可用)时不落 pending——键需要轮次。 */
|
|
6948
7023
|
let round;
|
|
7024
|
+
const persistPending = async () => {
|
|
7025
|
+
if (round === void 0) return;
|
|
7026
|
+
try {
|
|
7027
|
+
await markPendingIngest(await (deps.openAuditStore ?? deps.openStore)(), deps.sessionId, round);
|
|
7028
|
+
} catch {}
|
|
7029
|
+
};
|
|
6949
7030
|
try {
|
|
6950
7031
|
round = lastTurnNumber(deps.events);
|
|
6951
7032
|
if (round === void 0) return null;
|
|
6952
|
-
|
|
7033
|
+
const outcome = await ingestPreviousTurn({
|
|
6953
7034
|
...deps,
|
|
6954
7035
|
slice: "last"
|
|
6955
7036
|
});
|
|
7037
|
+
if (outcome.skipped === "empty-answer" || outcome.skipped === "unparseable-output" || outcome.skipped === "all-candidates-failed") await persistPending();
|
|
7038
|
+
return outcome;
|
|
6956
7039
|
} catch (error) {
|
|
6957
|
-
|
|
6958
|
-
await markPendingIngest(await (deps.openAuditStore ?? deps.openStore)(), deps.sessionId, round);
|
|
6959
|
-
} catch {}
|
|
7040
|
+
await persistPending();
|
|
6960
7041
|
console.warn(message("llm.warnFinalIngestFailed"), error);
|
|
6961
7042
|
return null;
|
|
6962
7043
|
}
|
|
@@ -7095,8 +7176,7 @@ async function replayPendingIngests(deps) {
|
|
|
7095
7176
|
kept
|
|
7096
7177
|
};
|
|
7097
7178
|
}
|
|
7098
|
-
|
|
7099
|
-
//#region src/ingest/history.ts
|
|
7179
|
+
// src/ingest/history.ts
|
|
7100
7180
|
const DAY_MS$1 = 864e5;
|
|
7101
7181
|
/** 估算时并发读取的会话数(读取是 IO,适度并发;摄取阶段始终串行)。 */
|
|
7102
7182
|
const ESTIMATE_CONCURRENCY = 4;
|
|
@@ -7414,8 +7494,7 @@ async function runHistoryBackfill(deps, defaults, overrides, onProgress, signal)
|
|
|
7414
7494
|
failures
|
|
7415
7495
|
};
|
|
7416
7496
|
}
|
|
7417
|
-
|
|
7418
|
-
//#region src/vec.ts
|
|
7497
|
+
// src/vec.ts
|
|
7419
7498
|
/**
|
|
7420
7499
|
* 向量相似度共享实现:store 检索与巩固聚类共用一份,替代历史上的两处复制。
|
|
7421
7500
|
* @module @kenz1117/dsh-engram/vec
|
|
@@ -7459,8 +7538,7 @@ function cosine(a, b) {
|
|
|
7459
7538
|
function isDimensionMismatch(error) {
|
|
7460
7539
|
return error instanceof EngramError && error.code === "EMBEDDER_DIMENSION_MISMATCH";
|
|
7461
7540
|
}
|
|
7462
|
-
|
|
7463
|
-
//#region src/consolidation/run.ts
|
|
7541
|
+
// src/consolidation/run.ts
|
|
7464
7542
|
/** 单条整理动作(写入 op_log 的统一标记)。 */
|
|
7465
7543
|
const CONSOLIDATION_OP = "consolidation";
|
|
7466
7544
|
/** 默认参数。 */
|
|
@@ -7598,8 +7676,7 @@ async function runConsolidation(store, embedder, opts = {}) {
|
|
|
7598
7676
|
} catch {}
|
|
7599
7677
|
return report;
|
|
7600
7678
|
}
|
|
7601
|
-
|
|
7602
|
-
//#region src/consolidation/reflect.ts
|
|
7679
|
+
// src/consolidation/reflect.ts
|
|
7603
7680
|
/**
|
|
7604
7681
|
* 信念巩固(Reflect):把尚未成为任何信念证据的原始记忆交辅助 LLM 巩固为一句话信念
|
|
7605
7682
|
* (observation),并对被新证据波及的 stale 信念做新鲜度复核。
|
|
@@ -7910,8 +7987,541 @@ function requireCandidateIds(raw, candidateIds) {
|
|
|
7910
7987
|
}
|
|
7911
7988
|
return ids;
|
|
7912
7989
|
}
|
|
7913
|
-
|
|
7914
|
-
|
|
7990
|
+
// src/jobs/queue.ts
|
|
7991
|
+
/**
|
|
7992
|
+
* 持久作业队列原语:基于 node:sqlite 的独立 DB 文件(WAL + busy_timeout),
|
|
7993
|
+
* 供后续 reflect/consolidation 等宿主调度使用——本模块只提供队列原语,不做调度。
|
|
7994
|
+
*
|
|
7995
|
+
* 与主库(store/sqlite)的差别:队列按「多 worker 竞争」设计,写事务一律
|
|
7996
|
+
* BEGIN IMMEDIATE——先拿写锁再动手,撞车交给 busy_timeout 等待,而不是让
|
|
7997
|
+
* 事务中途从读锁升级写锁时撞 SQLITE_BUSY。表名固定常量、全部参数化查询,
|
|
7998
|
+
* 不存在拼接用户输入的 SQL 面。
|
|
7999
|
+
*
|
|
8000
|
+
* 状态机(无独立 retrying 状态,重试 = 回 queued + 延期 runAfter,attempts 保留):
|
|
8001
|
+
* queued --claim--> running --complete--> done
|
|
8002
|
+
* ^ | --fail(attempts<max)--> queued(runAfter 延期)
|
|
8003
|
+
* | └─── --fail(attempts>=max)--> dead
|
|
8004
|
+
* └-------- claim 到期的 queued;claim 租约过期的 running(被新 owner 抢走)
|
|
8005
|
+
*
|
|
8006
|
+
* done/dead 是终态:不可 claim、不可 complete/fail/checkpoint;只能被 prune 按
|
|
8007
|
+
* 保留窗口清除(历史垃圾回收),或因 payload 损坏(毒丸)被 claim 就地 dead-letter。
|
|
8008
|
+
* @module @kenz1117/dsh-engram/jobs/queue
|
|
8009
|
+
*/
|
|
8010
|
+
/** 表名固定常量:所有语句写死引用它,绝不拼接调用方输入。 */
|
|
8011
|
+
const TABLE = "jobs";
|
|
8012
|
+
/** 队列库自身结构版本(PRAGMA user_version);结构性变更必须 +1。 */
|
|
8013
|
+
const QUEUE_SCHEMA_VERSION = 1;
|
|
8014
|
+
/** maxAttempts 缺省值:允许 3 次尝试(首次 + 2 次重试)。 */
|
|
8015
|
+
const DEFAULT_MAX_ATTEMPTS = 3;
|
|
8016
|
+
/** 校验非空字符串(不静默 trim:只拒绝纯空白,原文原样入库)。 */
|
|
8017
|
+
function requireText(value, field) {
|
|
8018
|
+
if (typeof value !== "string" || value.trim().length === 0) throw new EngramError("JOB_INVALID", `jobs: ${field} 必须是非空字符串`);
|
|
8019
|
+
return value;
|
|
8020
|
+
}
|
|
8021
|
+
/** 校验正整数(maxAttempts/leaseMs/limit)。 */
|
|
8022
|
+
function requirePositiveInt(value, field) {
|
|
8023
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) throw new EngramError("JOB_INVALID", `jobs: ${field} 必须是正整数`);
|
|
8024
|
+
return value;
|
|
8025
|
+
}
|
|
8026
|
+
/** 校验非负整数(runAfter/retryDelayMs)。 */
|
|
8027
|
+
function requireNonNegativeInt(value, field) {
|
|
8028
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) throw new EngramError("JOB_INVALID", `jobs: ${field} 必须是非负整数`);
|
|
8029
|
+
return value;
|
|
8030
|
+
}
|
|
8031
|
+
/** payload 只收可 JSON 序列化的值:undefined/函数/循环引用一律 JOB_INVALID。 */
|
|
8032
|
+
function serializePayload(payload) {
|
|
8033
|
+
let json;
|
|
8034
|
+
try {
|
|
8035
|
+
json = JSON.stringify(payload);
|
|
8036
|
+
} catch (cause) {
|
|
8037
|
+
throw new EngramError("JOB_INVALID", "jobs: payload 必须可 JSON 序列化", { cause });
|
|
8038
|
+
}
|
|
8039
|
+
if (json === void 0) throw new EngramError("JOB_INVALID", "jobs: payload 必须可 JSON 序列化");
|
|
8040
|
+
return json;
|
|
8041
|
+
}
|
|
8042
|
+
/** complete/fail/checkpoint 共用的守卫:作业存在、正在 running、调用方就是当前租约持有者、且租约未过期。 */
|
|
8043
|
+
function requireOwnedRunning(row, input, at) {
|
|
8044
|
+
if (row.status !== "running") throw new EngramError("JOB_NOT_RUNNING", `jobs: 作业 ${row.id} 不在 running(当前 ${row.status})`);
|
|
8045
|
+
if (row.lease_owner !== input.owner) throw new EngramError("JOB_OWNER_MISMATCH", `jobs: 作业 ${row.id} 的租约持有者是 ${row.lease_owner ?? "无"},不是 ${input.owner}`);
|
|
8046
|
+
if (row.lease_expires_at === null || row.lease_expires_at <= at) throw new EngramError("JOB_LEASE_EXPIRED", `jobs: 作业 ${row.id} 的租约已于 ${row.lease_expires_at} 过期(now ${at}),owner ${input.owner} 须重新 claim`);
|
|
8047
|
+
}
|
|
8048
|
+
/**
|
|
8049
|
+
* 打开(必要时创建)一个独立队列库。
|
|
8050
|
+
* @param path - SQLite 文件路径;目录不存在会自动创建(0o700)。
|
|
8051
|
+
* @param options - now 注入时钟;缺省 Date.now。
|
|
8052
|
+
* @returns 就绪的 JobQueue。
|
|
8053
|
+
* @throws EngramError(code=SCHEMA_INCOMPATIBLE) 当队列库结构版本高于当前实现。
|
|
8054
|
+
* @throws EngramError(code=JOB_INVALID) 当 path 非法或时钟不可用。
|
|
8055
|
+
*/
|
|
8056
|
+
async function openJobQueue(path, options = {}) {
|
|
8057
|
+
if (typeof path !== "string" || path.length === 0) throw new EngramError("JOB_INVALID", "jobs: path 必须是非空字符串");
|
|
8058
|
+
const now = options.now ?? (() => Date.now());
|
|
8059
|
+
const probed = now();
|
|
8060
|
+
if (typeof probed !== "number" || !Number.isFinite(probed)) throw new EngramError("JOB_INVALID", "jobs: 注入的 now() 必须返回有限数字");
|
|
8061
|
+
await mkdir(dirname(path), {
|
|
8062
|
+
recursive: true,
|
|
8063
|
+
mode: 448
|
|
8064
|
+
});
|
|
8065
|
+
const { DatabaseSync } = await import("node:sqlite");
|
|
8066
|
+
const db = new DatabaseSync(path);
|
|
8067
|
+
/** 手工事务(IMMEDIATE:队列是多写者场景,先拿写锁让 busy_timeout 吸收竞争)。 */
|
|
8068
|
+
const withTransaction = (fn) => {
|
|
8069
|
+
db.exec("BEGIN IMMEDIATE");
|
|
8070
|
+
try {
|
|
8071
|
+
fn();
|
|
8072
|
+
db.exec("COMMIT");
|
|
8073
|
+
} catch (error) {
|
|
8074
|
+
db.exec("ROLLBACK");
|
|
8075
|
+
throw error;
|
|
8076
|
+
}
|
|
8077
|
+
};
|
|
8078
|
+
let versionRow;
|
|
8079
|
+
try {
|
|
8080
|
+
db.exec("PRAGMA journal_mode = WAL;");
|
|
8081
|
+
db.exec("PRAGMA busy_timeout = 5000;");
|
|
8082
|
+
db.exec("PRAGMA synchronous = NORMAL;");
|
|
8083
|
+
versionRow = db.prepare("PRAGMA user_version").get();
|
|
8084
|
+
const version = versionRow?.user_version ?? 0;
|
|
8085
|
+
if (version > QUEUE_SCHEMA_VERSION) throw new EngramError("SCHEMA_INCOMPATIBLE", `jobs: 队列库结构版本过新(found ${version} > supported ${QUEUE_SCHEMA_VERSION},path ${path})`);
|
|
8086
|
+
if (version < QUEUE_SCHEMA_VERSION) db.exec(`
|
|
8087
|
+
CREATE TABLE IF NOT EXISTS ${TABLE} (
|
|
8088
|
+
id TEXT PRIMARY KEY,
|
|
8089
|
+
kind TEXT NOT NULL,
|
|
8090
|
+
payload TEXT NOT NULL,
|
|
8091
|
+
status TEXT NOT NULL,
|
|
8092
|
+
attempts INTEGER NOT NULL,
|
|
8093
|
+
max_attempts INTEGER NOT NULL,
|
|
8094
|
+
run_after INTEGER NOT NULL,
|
|
8095
|
+
lease_owner TEXT,
|
|
8096
|
+
lease_expires_at INTEGER,
|
|
8097
|
+
checkpoint TEXT,
|
|
8098
|
+
last_error TEXT,
|
|
8099
|
+
created_at INTEGER NOT NULL,
|
|
8100
|
+
updated_at INTEGER NOT NULL);
|
|
8101
|
+
CREATE INDEX IF NOT EXISTS jobs_due ON ${TABLE} (status, run_after);
|
|
8102
|
+
PRAGMA user_version = ${QUEUE_SCHEMA_VERSION};`);
|
|
8103
|
+
} catch (error) {
|
|
8104
|
+
try {
|
|
8105
|
+
db.close();
|
|
8106
|
+
} catch {}
|
|
8107
|
+
throw error;
|
|
8108
|
+
}
|
|
8109
|
+
const sqlGet = db.prepare(`SELECT * FROM ${TABLE} WHERE id = ?`);
|
|
8110
|
+
const sqlInsert = db.prepare(`INSERT INTO ${TABLE}
|
|
8111
|
+
(id, kind, payload, status, attempts, max_attempts, run_after, lease_owner, lease_expires_at, checkpoint, last_error, created_at, updated_at)
|
|
8112
|
+
VALUES (?, ?, ?, 'queued', 0, ?, ?, NULL, NULL, NULL, NULL, ?, ?)`);
|
|
8113
|
+
const sqlDue = db.prepare(`SELECT * FROM ${TABLE}
|
|
8114
|
+
WHERE ((status = 'queued' AND run_after <= ?)
|
|
8115
|
+
OR (status = 'running' AND lease_expires_at IS NOT NULL AND lease_expires_at <= ?))
|
|
8116
|
+
ORDER BY run_after ASC, id ASC
|
|
8117
|
+
LIMIT ?`);
|
|
8118
|
+
const sqlDueKinds = db.prepare(`SELECT * FROM ${TABLE}
|
|
8119
|
+
WHERE ((status = 'queued' AND run_after <= ?)
|
|
8120
|
+
OR (status = 'running' AND lease_expires_at IS NOT NULL AND lease_expires_at <= ?))
|
|
8121
|
+
AND kind IN (SELECT value FROM json_each(?))
|
|
8122
|
+
ORDER BY run_after ASC, id ASC
|
|
8123
|
+
LIMIT ?`);
|
|
8124
|
+
const sqlTake = db.prepare(`UPDATE ${TABLE}
|
|
8125
|
+
SET status = 'running', attempts = attempts + 1, lease_owner = ?, lease_expires_at = ?, updated_at = ?
|
|
8126
|
+
WHERE id = ?`);
|
|
8127
|
+
const sqlComplete = db.prepare(`UPDATE ${TABLE}
|
|
8128
|
+
SET status = 'done', lease_owner = NULL, lease_expires_at = NULL, updated_at = ?
|
|
8129
|
+
WHERE id = ?`);
|
|
8130
|
+
const sqlRetry = db.prepare(`UPDATE ${TABLE}
|
|
8131
|
+
SET status = 'queued', run_after = ?, lease_owner = NULL, lease_expires_at = NULL, last_error = ?, updated_at = ?
|
|
8132
|
+
WHERE id = ?`);
|
|
8133
|
+
const sqlDead = db.prepare(`UPDATE ${TABLE}
|
|
8134
|
+
SET status = 'dead', lease_owner = NULL, lease_expires_at = NULL, last_error = ?, updated_at = ?
|
|
8135
|
+
WHERE id = ?`);
|
|
8136
|
+
const sqlCheckpoint = db.prepare(`UPDATE ${TABLE} SET checkpoint = ?, updated_at = ? WHERE id = ?`);
|
|
8137
|
+
const sqlPrune = db.prepare(`DELETE FROM ${TABLE} WHERE status IN ('done', 'dead') AND updated_at < ?`);
|
|
8138
|
+
/** 行 → 记录:payload 反序列化;坏行(解析失败)明确报 JOB_CORRUPT 而不是静默吞掉。 */
|
|
8139
|
+
const toRecord = (row) => {
|
|
8140
|
+
let payload;
|
|
8141
|
+
try {
|
|
8142
|
+
payload = JSON.parse(row.payload);
|
|
8143
|
+
} catch (cause) {
|
|
8144
|
+
throw new EngramError("JOB_CORRUPT", `jobs: 作业 ${row.id} 的 payload 不是合法 JSON`, { cause });
|
|
8145
|
+
}
|
|
8146
|
+
return {
|
|
8147
|
+
id: row.id,
|
|
8148
|
+
kind: row.kind,
|
|
8149
|
+
payload,
|
|
8150
|
+
status: row.status,
|
|
8151
|
+
attempts: row.attempts,
|
|
8152
|
+
maxAttempts: row.max_attempts,
|
|
8153
|
+
runAfter: row.run_after,
|
|
8154
|
+
leaseOwner: row.lease_owner,
|
|
8155
|
+
leaseExpiresAt: row.lease_expires_at,
|
|
8156
|
+
checkpoint: row.checkpoint,
|
|
8157
|
+
lastError: row.last_error,
|
|
8158
|
+
createdAt: row.created_at,
|
|
8159
|
+
updatedAt: row.updated_at
|
|
8160
|
+
};
|
|
8161
|
+
};
|
|
8162
|
+
return {
|
|
8163
|
+
enqueue(input) {
|
|
8164
|
+
const id = requireText(input.id, "id");
|
|
8165
|
+
const kind = requireText(input.kind, "kind");
|
|
8166
|
+
const payloadJson = serializePayload(input.payload);
|
|
8167
|
+
const maxAttempts = input.maxAttempts === void 0 ? DEFAULT_MAX_ATTEMPTS : requirePositiveInt(input.maxAttempts, "maxAttempts");
|
|
8168
|
+
const at = now();
|
|
8169
|
+
const runAfter = input.runAfter === void 0 ? at : requireNonNegativeInt(input.runAfter, "runAfter");
|
|
8170
|
+
const existing = sqlGet.get(id);
|
|
8171
|
+
if (existing !== void 0) return {
|
|
8172
|
+
job: toRecord(existing),
|
|
8173
|
+
deduped: true
|
|
8174
|
+
};
|
|
8175
|
+
let deduped = false;
|
|
8176
|
+
withTransaction(() => {
|
|
8177
|
+
if (sqlGet.get(id) !== void 0) {
|
|
8178
|
+
deduped = true;
|
|
8179
|
+
return;
|
|
8180
|
+
}
|
|
8181
|
+
sqlInsert.run(id, kind, payloadJson, maxAttempts, runAfter, at, at);
|
|
8182
|
+
});
|
|
8183
|
+
return {
|
|
8184
|
+
job: toRecord(sqlGet.get(id)),
|
|
8185
|
+
deduped
|
|
8186
|
+
};
|
|
8187
|
+
},
|
|
8188
|
+
claim(input) {
|
|
8189
|
+
const owner = requireText(input.owner, "owner");
|
|
8190
|
+
const leaseMs = requirePositiveInt(input.leaseMs, "leaseMs");
|
|
8191
|
+
const limit = input.limit === void 0 ? 1 : requirePositiveInt(input.limit, "limit");
|
|
8192
|
+
const kinds = input.kinds === void 0 ? void 0 : input.kinds.map((kind) => requireText(kind, "kinds"));
|
|
8193
|
+
const at = now();
|
|
8194
|
+
const expiresAt = at + leaseMs;
|
|
8195
|
+
const taken = [];
|
|
8196
|
+
withTransaction(() => {
|
|
8197
|
+
const candidates = kinds === void 0 ? sqlDue.all(at, at, limit) : sqlDueKinds.all(at, at, JSON.stringify(kinds), limit);
|
|
8198
|
+
for (const row of candidates) {
|
|
8199
|
+
sqlTake.run(owner, expiresAt, at, row.id);
|
|
8200
|
+
try {
|
|
8201
|
+
taken.push(toRecord(sqlGet.get(row.id)));
|
|
8202
|
+
} catch (error) {
|
|
8203
|
+
if (!(error instanceof EngramError && error.code === "JOB_CORRUPT")) throw error;
|
|
8204
|
+
const cause = error.cause;
|
|
8205
|
+
const causeText = cause instanceof Error ? cause.message : cause === void 0 ? "" : String(cause);
|
|
8206
|
+
sqlDead.run(causeText === "" ? error.message : `${error.message}(${causeText})`, at, row.id);
|
|
8207
|
+
}
|
|
8208
|
+
}
|
|
8209
|
+
});
|
|
8210
|
+
return taken;
|
|
8211
|
+
},
|
|
8212
|
+
complete(input) {
|
|
8213
|
+
const id = requireText(input.id, "id");
|
|
8214
|
+
requireText(input.owner, "owner");
|
|
8215
|
+
const at = now();
|
|
8216
|
+
withTransaction(() => {
|
|
8217
|
+
const row = sqlGet.get(id);
|
|
8218
|
+
if (row === void 0) throw new EngramError("JOB_NOT_FOUND", `jobs: 作业 ${id} 不存在`);
|
|
8219
|
+
requireOwnedRunning(row, input, at);
|
|
8220
|
+
sqlComplete.run(at, id);
|
|
8221
|
+
});
|
|
8222
|
+
return toRecord(sqlGet.get(id));
|
|
8223
|
+
},
|
|
8224
|
+
fail(input) {
|
|
8225
|
+
const id = requireText(input.id, "id");
|
|
8226
|
+
requireText(input.owner, "owner");
|
|
8227
|
+
const error = requireText(input.error, "error");
|
|
8228
|
+
const retryDelayMs = input.retryDelayMs === void 0 ? 0 : requireNonNegativeInt(input.retryDelayMs, "retryDelayMs");
|
|
8229
|
+
const at = now();
|
|
8230
|
+
withTransaction(() => {
|
|
8231
|
+
const row = sqlGet.get(id);
|
|
8232
|
+
if (row === void 0) throw new EngramError("JOB_NOT_FOUND", `jobs: 作业 ${id} 不存在`);
|
|
8233
|
+
requireOwnedRunning(row, input, at);
|
|
8234
|
+
if (row.attempts >= row.max_attempts) sqlDead.run(error, at, id);
|
|
8235
|
+
else sqlRetry.run(at + retryDelayMs, error, at, id);
|
|
8236
|
+
});
|
|
8237
|
+
return toRecord(sqlGet.get(id));
|
|
8238
|
+
},
|
|
8239
|
+
checkpoint(input) {
|
|
8240
|
+
const id = requireText(input.id, "id");
|
|
8241
|
+
requireText(input.owner, "owner");
|
|
8242
|
+
const mark = requireText(input.checkpoint, "checkpoint");
|
|
8243
|
+
const at = now();
|
|
8244
|
+
withTransaction(() => {
|
|
8245
|
+
const row = sqlGet.get(id);
|
|
8246
|
+
if (row === void 0) throw new EngramError("JOB_NOT_FOUND", `jobs: 作业 ${id} 不存在`);
|
|
8247
|
+
requireOwnedRunning(row, input, at);
|
|
8248
|
+
sqlCheckpoint.run(mark, at, id);
|
|
8249
|
+
});
|
|
8250
|
+
return toRecord(sqlGet.get(id));
|
|
8251
|
+
},
|
|
8252
|
+
get(id) {
|
|
8253
|
+
const row = sqlGet.get(requireText(id, "id"));
|
|
8254
|
+
return row === void 0 ? void 0 : toRecord(row);
|
|
8255
|
+
},
|
|
8256
|
+
prune(olderThanMs) {
|
|
8257
|
+
const thresholdMs = requireNonNegativeInt(olderThanMs, "olderThanMs");
|
|
8258
|
+
const cutoff = now() - thresholdMs;
|
|
8259
|
+
const result = sqlPrune.run(cutoff);
|
|
8260
|
+
return Number(result.changes);
|
|
8261
|
+
},
|
|
8262
|
+
close() {
|
|
8263
|
+
db.close();
|
|
8264
|
+
}
|
|
8265
|
+
};
|
|
8266
|
+
}
|
|
8267
|
+
// src/jobs/reflect-worker.ts
|
|
8268
|
+
/**
|
|
8269
|
+
* reflect 持久调度器:确定性入队、串行认领、限时执行、失败重试与停止恢复。
|
|
8270
|
+
* queue 的生命周期由宿主管理;本 worker 只拥有定时器与自己的执行取消信号。
|
|
8271
|
+
* @module @kenz1117/dsh-engram/jobs/reflect-worker
|
|
8272
|
+
*/
|
|
8273
|
+
function positive(value, fallback, field) {
|
|
8274
|
+
const result = value ?? fallback;
|
|
8275
|
+
if (!Number.isInteger(result) || result <= 0) throw new Error(`reflect worker: ${field} 必须是正整数`);
|
|
8276
|
+
return result;
|
|
8277
|
+
}
|
|
8278
|
+
function nonNegative(value, fallback, field) {
|
|
8279
|
+
const result = value ?? fallback;
|
|
8280
|
+
if (!Number.isInteger(result) || result < 0) throw new Error(`reflect worker: ${field} 必须是非负整数`);
|
|
8281
|
+
return result;
|
|
8282
|
+
}
|
|
8283
|
+
function text(value) {
|
|
8284
|
+
return typeof value === "string" && value.trim() !== "";
|
|
8285
|
+
}
|
|
8286
|
+
function parsePayload(value) {
|
|
8287
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error("reflect job payload 必须是对象");
|
|
8288
|
+
const raw = value;
|
|
8289
|
+
const route = raw.route;
|
|
8290
|
+
if (!text(raw.sessionId) || raw.scope !== "user" && raw.scope !== "project") throw new Error("reflect job payload 缺 sessionId 或 scope 非法");
|
|
8291
|
+
if (raw.cwd !== void 0 && !text(raw.cwd)) throw new Error("reflect job payload.cwd 必须是非空字符串");
|
|
8292
|
+
if (raw.eventSeq !== void 0 && (typeof raw.eventSeq !== "number" || !Number.isInteger(raw.eventSeq) || raw.eventSeq < 0)) throw new Error("reflect job payload.eventSeq 必须是非负整数");
|
|
8293
|
+
if (route === void 0 || !text(route.provider) || !text(route.model)) throw new Error("reflect job payload.route 缺 provider/model");
|
|
8294
|
+
return {
|
|
8295
|
+
sessionId: raw.sessionId,
|
|
8296
|
+
scope: raw.scope,
|
|
8297
|
+
...raw.cwd === void 0 ? {} : { cwd: raw.cwd },
|
|
8298
|
+
...raw.eventSeq === void 0 ? {} : { eventSeq: raw.eventSeq },
|
|
8299
|
+
route: {
|
|
8300
|
+
provider: route.provider,
|
|
8301
|
+
model: route.model
|
|
8302
|
+
}
|
|
8303
|
+
};
|
|
8304
|
+
}
|
|
8305
|
+
function errorText(error) {
|
|
8306
|
+
return error instanceof Error ? error.message : String(error);
|
|
8307
|
+
}
|
|
8308
|
+
var DurableReflectWorker = class {
|
|
8309
|
+
queue;
|
|
8310
|
+
execute;
|
|
8311
|
+
onError;
|
|
8312
|
+
owner;
|
|
8313
|
+
intervalMs;
|
|
8314
|
+
leaseMs;
|
|
8315
|
+
retryDelayMs;
|
|
8316
|
+
timeoutMs;
|
|
8317
|
+
externalSignal;
|
|
8318
|
+
abort = new AbortController();
|
|
8319
|
+
currentAbort;
|
|
8320
|
+
timer;
|
|
8321
|
+
activePump;
|
|
8322
|
+
stopped = false;
|
|
8323
|
+
constructor(options) {
|
|
8324
|
+
this.queue = options.queue;
|
|
8325
|
+
this.execute = options.execute;
|
|
8326
|
+
this.onError = options.onError;
|
|
8327
|
+
this.owner = options.owner ?? `reflect-${randomUUID()}`;
|
|
8328
|
+
this.intervalMs = positive(options.intervalMs, 1e3, "intervalMs");
|
|
8329
|
+
this.leaseMs = positive(options.leaseMs, 18e4, "leaseMs");
|
|
8330
|
+
this.retryDelayMs = nonNegative(options.retryDelayMs, 3e4, "retryDelayMs");
|
|
8331
|
+
this.timeoutMs = positive(options.timeoutMs, 12e4, "timeoutMs");
|
|
8332
|
+
this.externalSignal = options.signal;
|
|
8333
|
+
}
|
|
8334
|
+
enqueue(payload) {
|
|
8335
|
+
const checked = parsePayload(payload);
|
|
8336
|
+
return this.queue.enqueue({
|
|
8337
|
+
id: checked.eventSeq === void 0 ? `reflect:${checked.sessionId}:${checked.scope}` : `reflect:${checked.sessionId}:${checked.scope}:${checked.eventSeq}`,
|
|
8338
|
+
kind: "reflect",
|
|
8339
|
+
payload: checked,
|
|
8340
|
+
maxAttempts: 3
|
|
8341
|
+
});
|
|
8342
|
+
}
|
|
8343
|
+
start() {
|
|
8344
|
+
if (this.stopped) throw new Error("reflect worker: stop 后不可重新 start");
|
|
8345
|
+
if (this.timer !== void 0) return;
|
|
8346
|
+
this.pump();
|
|
8347
|
+
this.timer = setInterval(() => {
|
|
8348
|
+
this.pump();
|
|
8349
|
+
}, this.intervalMs);
|
|
8350
|
+
this.timer.unref();
|
|
8351
|
+
}
|
|
8352
|
+
/** 重入共享同一个 pump;executor 在任意时刻至多一个在跑。 */
|
|
8353
|
+
pump() {
|
|
8354
|
+
if (this.activePump !== void 0) return this.activePump;
|
|
8355
|
+
const active = this.drain();
|
|
8356
|
+
this.activePump = active;
|
|
8357
|
+
const clear = () => {
|
|
8358
|
+
if (this.activePump === active) this.activePump = void 0;
|
|
8359
|
+
};
|
|
8360
|
+
active.then(clear, clear);
|
|
8361
|
+
return active;
|
|
8362
|
+
}
|
|
8363
|
+
get cancelled() {
|
|
8364
|
+
return this.stopped || this.abort.signal.aborted || this.externalSignal?.aborted === true;
|
|
8365
|
+
}
|
|
8366
|
+
report(error, job) {
|
|
8367
|
+
if (this.onError === void 0) return;
|
|
8368
|
+
try {
|
|
8369
|
+
this.onError(error instanceof Error ? error : new Error(String(error)), job);
|
|
8370
|
+
} catch {}
|
|
8371
|
+
}
|
|
8372
|
+
async drain() {
|
|
8373
|
+
try {
|
|
8374
|
+
while (!this.cancelled) {
|
|
8375
|
+
const [job] = this.queue.claim({
|
|
8376
|
+
owner: this.owner,
|
|
8377
|
+
kinds: ["reflect"],
|
|
8378
|
+
leaseMs: this.leaseMs
|
|
8379
|
+
});
|
|
8380
|
+
if (job === void 0) break;
|
|
8381
|
+
const controller = new AbortController();
|
|
8382
|
+
this.currentAbort = controller;
|
|
8383
|
+
const signals = [
|
|
8384
|
+
controller.signal,
|
|
8385
|
+
this.abort.signal,
|
|
8386
|
+
AbortSignal.timeout(this.timeoutMs)
|
|
8387
|
+
];
|
|
8388
|
+
if (this.externalSignal !== void 0) signals.push(this.externalSignal);
|
|
8389
|
+
try {
|
|
8390
|
+
const payload = parsePayload(job.payload);
|
|
8391
|
+
await this.execute(payload, AbortSignal.any(signals));
|
|
8392
|
+
this.queue.complete({
|
|
8393
|
+
id: job.id,
|
|
8394
|
+
owner: this.owner
|
|
8395
|
+
});
|
|
8396
|
+
} catch (error) {
|
|
8397
|
+
let reported = error;
|
|
8398
|
+
try {
|
|
8399
|
+
this.queue.fail({
|
|
8400
|
+
id: job.id,
|
|
8401
|
+
owner: this.owner,
|
|
8402
|
+
error: errorText(error),
|
|
8403
|
+
retryDelayMs: this.retryDelayMs
|
|
8404
|
+
});
|
|
8405
|
+
} catch (queueError) {
|
|
8406
|
+
reported = queueError;
|
|
8407
|
+
}
|
|
8408
|
+
this.report(reported, job);
|
|
8409
|
+
} finally {
|
|
8410
|
+
this.currentAbort = void 0;
|
|
8411
|
+
}
|
|
8412
|
+
}
|
|
8413
|
+
} catch (error) {
|
|
8414
|
+
this.report(error);
|
|
8415
|
+
}
|
|
8416
|
+
}
|
|
8417
|
+
/** 停止认领新作业,取消在途执行并等待 queue 状态收束;queue 保持打开。 */
|
|
8418
|
+
async stop() {
|
|
8419
|
+
if (this.stopped) {
|
|
8420
|
+
await this.activePump;
|
|
8421
|
+
return;
|
|
8422
|
+
}
|
|
8423
|
+
this.stopped = true;
|
|
8424
|
+
if (this.timer !== void 0) clearInterval(this.timer);
|
|
8425
|
+
this.timer = void 0;
|
|
8426
|
+
this.abort.abort();
|
|
8427
|
+
this.currentAbort?.abort();
|
|
8428
|
+
await this.activePump;
|
|
8429
|
+
}
|
|
8430
|
+
};
|
|
8431
|
+
// src/jobs/host-reflect.ts
|
|
8432
|
+
/**
|
|
8433
|
+
* DSH 宿主侧的 reflect 作业工厂:打开持久队列,执行真实巩固,并统一停止/关闭。
|
|
8434
|
+
* @module @kenz1117/dsh-engram/jobs/host-reflect
|
|
8435
|
+
*/
|
|
8436
|
+
/** 终态作业保留窗口:与主库 op_log 同款 366 天,过窗 done/dead 由 prune 清除。 */
|
|
8437
|
+
const PRUNE_RETENTION_MS = 316224e5;
|
|
8438
|
+
/** prune 班车间隔:24 小时一班,启动时先跑一次。 */
|
|
8439
|
+
const PRUNE_INTERVAL_MS = 864e5;
|
|
8440
|
+
/** 启动真实 reflect worker;stop 先取消在途执行,再关闭独立 jobs.db。 */
|
|
8441
|
+
async function startAutoReflectWorker(options) {
|
|
8442
|
+
const queue = await openJobQueue(join(options.dbDir, "jobs.db"));
|
|
8443
|
+
try {
|
|
8444
|
+
queue.prune(PRUNE_RETENTION_MS);
|
|
8445
|
+
} catch (error) {
|
|
8446
|
+
console.warn(message("core.warnReflectFailed", { scope: "prune" }), error);
|
|
8447
|
+
}
|
|
8448
|
+
const pruneTimer = setInterval(() => {
|
|
8449
|
+
try {
|
|
8450
|
+
queue.prune(PRUNE_RETENTION_MS);
|
|
8451
|
+
} catch {}
|
|
8452
|
+
}, PRUNE_INTERVAL_MS);
|
|
8453
|
+
pruneTimer.unref();
|
|
8454
|
+
const worker = new DurableReflectWorker({
|
|
8455
|
+
queue,
|
|
8456
|
+
execute: async (payload, signal) => {
|
|
8457
|
+
const scope = payload.scope;
|
|
8458
|
+
if (scope === "project" && (payload.cwd === void 0 || !existsSync(join(options.dbDir, options.dbNameForCwd(payload.cwd))))) return;
|
|
8459
|
+
const store = scope === "user" ? await options.openStore("user") : await options.openProjectStore(payload.cwd);
|
|
8460
|
+
const outcome = await reflectObservations({
|
|
8461
|
+
store,
|
|
8462
|
+
embedder: await options.embedder(),
|
|
8463
|
+
scope,
|
|
8464
|
+
call: (params) => options.call(payload.sessionId, params),
|
|
8465
|
+
logRequest: (data) => {
|
|
8466
|
+
store.audit("reflect-request", "AUX", JSON.stringify(data)).catch(() => {});
|
|
8467
|
+
},
|
|
8468
|
+
route: payload.route,
|
|
8469
|
+
signal
|
|
8470
|
+
});
|
|
8471
|
+
if (outcome.formed + outcome.refined + outcome.confirmed + outcome.refuted > 0) console.log(message("core.logReflectDone", {
|
|
8472
|
+
scope,
|
|
8473
|
+
formed: outcome.formed,
|
|
8474
|
+
refined: outcome.refined,
|
|
8475
|
+
confirmed: outcome.confirmed,
|
|
8476
|
+
refuted: outcome.refuted
|
|
8477
|
+
}));
|
|
8478
|
+
if (outcome.dropped > 0) console.warn(message("core.warnReflectBatchDropped", { count: outcome.dropped }));
|
|
8479
|
+
},
|
|
8480
|
+
onError: (error, job) => {
|
|
8481
|
+
const scope = (job?.payload)?.scope;
|
|
8482
|
+
console.warn(message("core.warnReflectFailed", { scope: typeof scope === "string" ? scope : "unknown" }), error);
|
|
8483
|
+
}
|
|
8484
|
+
});
|
|
8485
|
+
worker.start();
|
|
8486
|
+
return {
|
|
8487
|
+
enqueue: (payload) => {
|
|
8488
|
+
worker.enqueue(payload);
|
|
8489
|
+
},
|
|
8490
|
+
pump: () => worker.pump(),
|
|
8491
|
+
stop: async () => {
|
|
8492
|
+
clearInterval(pruneTimer);
|
|
8493
|
+
try {
|
|
8494
|
+
await worker.stop();
|
|
8495
|
+
} finally {
|
|
8496
|
+
queue.close();
|
|
8497
|
+
}
|
|
8498
|
+
}
|
|
8499
|
+
};
|
|
8500
|
+
}
|
|
8501
|
+
// src/application/memory-commands.ts
|
|
8502
|
+
/**
|
|
8503
|
+
* 更新一条记忆。不存在返回 undefined,让工具与 HTTP 各自保留既有错误协议。
|
|
8504
|
+
* 内容变化必须产生新向量;embedder 不可用时显式清空旧向量,禁止语义索引停在旧正文。
|
|
8505
|
+
*/
|
|
8506
|
+
async function updateMemory(deps, input) {
|
|
8507
|
+
const content = redactSecrets(sanitizeProtocolText(input.content));
|
|
8508
|
+
if (content.trim() === "") throw new EngramError("EMPTY_CONTENT", message("tool.updateContentEmptyAfterSanitize"));
|
|
8509
|
+
const old = await deps.store.get(input.id) ?? await deps.store.getMemory(input.id);
|
|
8510
|
+
if (old === void 0) return void 0;
|
|
8511
|
+
let embedding = null;
|
|
8512
|
+
const embedder = await deps.embedder;
|
|
8513
|
+
if (embedder !== void 0) embedding = (await embedder.embed([content.trim()]))[0] ?? null;
|
|
8514
|
+
return deps.store.update({
|
|
8515
|
+
id: old.id,
|
|
8516
|
+
scope: input.scope,
|
|
8517
|
+
kind: input.kind ?? old.kind,
|
|
8518
|
+
content,
|
|
8519
|
+
embedding,
|
|
8520
|
+
...input.importance === void 0 ? {} : { importance: Math.min(1, Math.max(0, input.importance)) },
|
|
8521
|
+
...input.imagery === void 0 ? {} : { imagery: input.imagery }
|
|
8522
|
+
});
|
|
8523
|
+
}
|
|
8524
|
+
// src/store/import.ts
|
|
7915
8525
|
const SCOPES = [
|
|
7916
8526
|
"user",
|
|
7917
8527
|
"project",
|
|
@@ -7968,6 +8578,7 @@ const parseRecord = (raw, index) => {
|
|
|
7968
8578
|
if (imagery !== void 0 && imagery !== null && !(isObj(imagery) && isStr(imagery.caption) && Array.isArray(imagery.sensoryTags) && isNum(imagery.emotionalValence) && typeof imagery.provisional === "boolean")) return `records[${index}].imagery 非法`;
|
|
7969
8579
|
return {
|
|
7970
8580
|
id: asMemoryId(id),
|
|
8581
|
+
memoryId: asMemoryId(isStr(raw.memoryId) && raw.memoryId !== "" ? raw.memoryId : id),
|
|
7971
8582
|
scope: raw.scope,
|
|
7972
8583
|
kind: raw.kind,
|
|
7973
8584
|
content,
|
|
@@ -8130,6 +8741,7 @@ function parseMarkdownExport(raw, scope) {
|
|
|
8130
8741
|
if (!Number.isFinite(importance)) continue;
|
|
8131
8742
|
records.push({
|
|
8132
8743
|
id: asMemoryId(id),
|
|
8744
|
+
memoryId: asMemoryId(id),
|
|
8133
8745
|
scope,
|
|
8134
8746
|
kind,
|
|
8135
8747
|
content,
|
|
@@ -8174,8 +8786,7 @@ async function embedImportedRecords(store, embedder, importedIds) {
|
|
|
8174
8786
|
}
|
|
8175
8787
|
return embedded;
|
|
8176
8788
|
}
|
|
8177
|
-
|
|
8178
|
-
//#region src/body-limits.ts
|
|
8789
|
+
// src/body-limits.ts
|
|
8179
8790
|
/**
|
|
8180
8791
|
* 回环 API 的 body 字节上限(服务端与面板共用一份数字)。
|
|
8181
8792
|
*
|
|
@@ -8201,8 +8812,7 @@ function formatBytes(bytes) {
|
|
|
8201
8812
|
if (bytes >= 1024) return `${String(Math.round(bytes / 1024))} KB`;
|
|
8202
8813
|
return `${String(bytes)} B`;
|
|
8203
8814
|
}
|
|
8204
|
-
|
|
8205
|
-
//#region src/http-body.ts
|
|
8815
|
+
// src/http-body.ts
|
|
8206
8816
|
/**
|
|
8207
8817
|
* 读取并解析 JSON body。
|
|
8208
8818
|
*
|
|
@@ -8274,8 +8884,7 @@ async function readJsonBody(req, limit = BODY_LIMIT_BYTES) {
|
|
|
8274
8884
|
body: parsed
|
|
8275
8885
|
};
|
|
8276
8886
|
}
|
|
8277
|
-
|
|
8278
|
-
//#region src/jev/client.ts
|
|
8887
|
+
// src/jev/client.ts
|
|
8279
8888
|
/**
|
|
8280
8889
|
* HTTP-клиент модели Jev (System One): задаёт пачке «Noul»-вопросов (да/нет) по
|
|
8281
8890
|
* одному тексту состояния и получает вероятности. Формат запроса — JSON вида
|
|
@@ -8464,8 +9073,7 @@ async function testJevConnection(connection) {
|
|
|
8464
9073
|
};
|
|
8465
9074
|
}
|
|
8466
9075
|
}
|
|
8467
|
-
|
|
8468
|
-
//#region src/jev/host.ts
|
|
9076
|
+
// src/jev/host.ts
|
|
8469
9077
|
/**
|
|
8470
9078
|
* Мост к хосту DSH: провайдеры, их модели и ключи живут в одном месте — у хоста.
|
|
8471
9079
|
*
|
|
@@ -8539,6 +9147,19 @@ function joinUrl(base, relative) {
|
|
|
8539
9147
|
function systemOneEndpoint(baseUrl) {
|
|
8540
9148
|
return joinUrl(baseUrl, "systemone");
|
|
8541
9149
|
}
|
|
9150
|
+
/**
|
|
9151
|
+
* 宿主凭据只能发往 provider 配置中已信任的 origin。面板可以覆盖同源路径,
|
|
9152
|
+
* 但不能把存储在 DSH 凭据库里的 Bearer key 指向另一个服务。
|
|
9153
|
+
*/
|
|
9154
|
+
function isTrustedJevEndpoint(baseUrl, endpoint) {
|
|
9155
|
+
try {
|
|
9156
|
+
const trusted = new URL(baseUrl);
|
|
9157
|
+
const candidate = new URL(endpoint);
|
|
9158
|
+
return (candidate.protocol === "http:" || candidate.protocol === "https:") && candidate.username === "" && candidate.password === "" && candidate.origin === trusted.origin;
|
|
9159
|
+
} catch {
|
|
9160
|
+
return false;
|
|
9161
|
+
}
|
|
9162
|
+
}
|
|
8542
9163
|
/** Дескриптор конфигурации хоста по namespace (например `llm-pi-ai`). */
|
|
8543
9164
|
async function readSettingsValue(ctx, ns) {
|
|
8544
9165
|
const settings = ctx.get("settings");
|
|
@@ -8724,7 +9345,9 @@ async function resolveJevConnection(ctx, providerId, model, timeoutMs, endpointO
|
|
|
8724
9345
|
if (typeof rekvisites === "string") return rekvisites;
|
|
8725
9346
|
const chosenModel = model.trim() !== "" ? model.trim() : pickJevModel(rekvisites.modelIds);
|
|
8726
9347
|
if (chosenModel === void 0) return message("misc.jevModelNotPicked", { provider: providerId });
|
|
8727
|
-
const
|
|
9348
|
+
const chosen = endpointOverride !== void 0 && endpointOverride.trim() !== "" ? endpointOverride.trim() : void 0;
|
|
9349
|
+
if (chosen !== void 0 && (rekvisites.baseUrl === void 0 || !isTrustedJevEndpoint(rekvisites.baseUrl, chosen))) return message("misc.jevEndpointOriginMismatch", { provider: providerId });
|
|
9350
|
+
const endpoint = chosen ?? (rekvisites.baseUrl === void 0 ? void 0 : systemOneEndpoint(rekvisites.baseUrl));
|
|
8728
9351
|
if (endpoint === void 0) return message("misc.jevProviderHasNoBaseUrl", { provider: providerId });
|
|
8729
9352
|
if (rekvisites.apiKey === "") return message("misc.jevProviderKeyMissing", {
|
|
8730
9353
|
provider: providerId,
|
|
@@ -8747,8 +9370,7 @@ async function resolveJevConnection(ctx, providerId, model, timeoutMs, endpointO
|
|
|
8747
9370
|
function pickJevModel(modelIds) {
|
|
8748
9371
|
return modelIds.find((id) => /jev/i.test(id));
|
|
8749
9372
|
}
|
|
8750
|
-
|
|
8751
|
-
//#region src/jev/runtime.ts
|
|
9373
|
+
// src/jev/runtime.ts
|
|
8752
9374
|
/**
|
|
8753
9375
|
* Настройки Jev, задаваемые из панели: сохраняются в `<dbDir>/jev-config.json` (0600)
|
|
8754
9376
|
* и пофайлово перекрывают подконфигурацию `jev` из cordis.yml.
|
|
@@ -8924,8 +9546,7 @@ function resolveJevField(ctx, base, dbDir, routeProvider) {
|
|
|
8924
9546
|
});
|
|
8925
9547
|
} };
|
|
8926
9548
|
}
|
|
8927
|
-
|
|
8928
|
-
//#region src/mirror/markdown.ts
|
|
9549
|
+
// src/mirror/markdown.ts
|
|
8929
9550
|
/**
|
|
8930
9551
|
* Markdown 镜像:把 SQLite 记忆库导出为可被 Obsidian / VS Code / git 直接漫游的
|
|
8931
9552
|
* 文件树:按房间(kind)分目录,每条记忆一个 .md + frontmatter,附房间清单 _meta.json 与全宫殿入口 _index.md。
|
|
@@ -9126,8 +9747,7 @@ function buildShareManifest(data, now = Date.now()) {
|
|
|
9126
9747
|
loans
|
|
9127
9748
|
};
|
|
9128
9749
|
}
|
|
9129
|
-
|
|
9130
|
-
//#region src/backup/tar-stream.ts
|
|
9750
|
+
// src/backup/tar-stream.ts
|
|
9131
9751
|
/**
|
|
9132
9752
|
* 极简 tar 流的写入与解包:UStar 格式(POSIX.1-1988),足够本插件「打包几个 .db + _meta.json」场景。
|
|
9133
9753
|
* 文件名长度 ≤ 99 字节、文件 ≤ 8 GiB 已覆盖本插件的备份规模;超过则抛错。
|
|
@@ -9209,8 +9829,7 @@ async function extractTar(buffer, destDir) {
|
|
|
9209
9829
|
} else offset += (BLOCK_SIZE - size % BLOCK_SIZE) % BLOCK_SIZE;
|
|
9210
9830
|
}
|
|
9211
9831
|
}
|
|
9212
|
-
|
|
9213
|
-
//#region src/backup/tar.ts
|
|
9832
|
+
// src/backup/tar.ts
|
|
9214
9833
|
/**
|
|
9215
9834
|
* 宫殿备份与恢复:把当前 user/project 两库的 .db + 元信息打包成单一 .tar.gz 文件;
|
|
9216
9835
|
* 恢复时校验 tar 内的 _meta.json schema 版本并覆盖原库(恢复前自动备份现状为 .before-restore-<ts>)。
|
|
@@ -9432,8 +10051,7 @@ async function untarGz(archivePath, destDir) {
|
|
|
9432
10051
|
const compressed = await readFileBuffer(archivePath);
|
|
9433
10052
|
await extractTar(await gunzipAsync(compressed), destDir);
|
|
9434
10053
|
}
|
|
9435
|
-
|
|
9436
|
-
//#region src/telemetry/aggregate.ts
|
|
10054
|
+
// src/telemetry/aggregate.ts
|
|
9437
10055
|
/** 聚合窗口(默认 7 天,可由路由 query 覆盖)。 */
|
|
9438
10056
|
const DEFAULT_WINDOW_DAYS = 7;
|
|
9439
10057
|
/** 从单库 op_log 统计各 op 的计数(窗口内)——SQL GROUP BY,不物化明细行(审计 N1)。 */
|
|
@@ -9535,8 +10153,7 @@ async function aggregateTelemetry(openStore, windowDays = DEFAULT_WINDOW_DAYS, s
|
|
|
9535
10153
|
}))
|
|
9536
10154
|
};
|
|
9537
10155
|
}
|
|
9538
|
-
|
|
9539
|
-
//#region src/tour-proposal.ts
|
|
10156
|
+
// src/tour-proposal.ts
|
|
9540
10157
|
/**
|
|
9541
10158
|
* 入殿导航:会话首轮时主动提议一条入门巡游路线。
|
|
9542
10159
|
* 设计:取当前会话最近一轮 user/project 的高频 kind + importance × confidence 排序,
|
|
@@ -9573,8 +10190,7 @@ function buildTourProposal(scope, records, focusKind) {
|
|
|
9573
10190
|
empty
|
|
9574
10191
|
};
|
|
9575
10192
|
}
|
|
9576
|
-
|
|
9577
|
-
//#region src/refurb.ts
|
|
10193
|
+
// src/refurb.ts
|
|
9578
10194
|
/** 缺省参数。 */
|
|
9579
10195
|
const DEFAULT_REFURB_OPTIONS = {
|
|
9580
10196
|
minActive: 8,
|
|
@@ -9676,55 +10292,121 @@ function gatherRefurbSuggestions(records, language, options = DEFAULT_REFURB_OPT
|
|
|
9676
10292
|
}
|
|
9677
10293
|
return suggestions;
|
|
9678
10294
|
}
|
|
9679
|
-
|
|
9680
|
-
//#region src/routes.ts
|
|
10295
|
+
// src/routes.ts
|
|
9681
10296
|
/**
|
|
9682
10297
|
* /engram 管理页与 /api/engram/* 数据接口的回环路由。
|
|
9683
|
-
* 安全面:peer socket + Host
|
|
9684
|
-
* Content-Type(billing guardLoopback
|
|
9685
|
-
* client 模块表,管理页为 host 直出的自包含单文件页。
|
|
10298
|
+
* 安全面:peer socket + Host 头校验(默认仅本机回环;panelAccess='lan' 放宽到私网,
|
|
10299
|
+
* 防线结构不变);写操作额外校验 Origin 与 Content-Type(billing guardLoopback
|
|
10300
|
+
* 同款三重防线)。下游插件不进宿主 client 模块表,管理页为 host 直出的自包含单文件页。
|
|
9686
10301
|
* @module @kenz1117/dsh-engram/routes
|
|
9687
10302
|
*/
|
|
9688
|
-
/**
|
|
9689
|
-
function
|
|
10303
|
+
/** 回环地址:IPv4 127/8、IPv6 ::1、IPv4-mapped IPv6。 */
|
|
10304
|
+
function isLoopbackAddress(address) {
|
|
10305
|
+
return address === "::1" || address.startsWith("127.") || address.startsWith("::ffff:127.");
|
|
10306
|
+
}
|
|
10307
|
+
/** RFC1918 私网 IPv4 字面量(10/8、172.16/12、192.168/16;每段 ≤255 才算字面量)。 */
|
|
10308
|
+
function isPrivateIPv4(address) {
|
|
10309
|
+
const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(address);
|
|
10310
|
+
if (match === null) return false;
|
|
10311
|
+
const [first, second] = [Number(match[1]), Number(match[2])];
|
|
10312
|
+
if ([
|
|
10313
|
+
first,
|
|
10314
|
+
second,
|
|
10315
|
+
Number(match[3]),
|
|
10316
|
+
Number(match[4])
|
|
10317
|
+
].some((octet) => octet > 255)) return false;
|
|
10318
|
+
return first === 10 || first === 172 && second >= 16 && second <= 31 || first === 192 && second === 168;
|
|
10319
|
+
}
|
|
10320
|
+
/** IPv6 ULA fc00::/7(fc/fd 开头)与链路本地 fe80::/10(fe80-febf)。 */
|
|
10321
|
+
function isPrivateIPv6(address) {
|
|
10322
|
+
const lower = address.toLowerCase();
|
|
10323
|
+
return lower.startsWith("fc") || lower.startsWith("fd") || lower.startsWith("fe8") || lower.startsWith("fe9") || lower.startsWith("fea") || lower.startsWith("feb");
|
|
10324
|
+
}
|
|
10325
|
+
/** lan 模式的 peer 面:回环 + 私网(含 IPv4-mapped IPv6 去映射后判定)。 */
|
|
10326
|
+
function isAllowedPeer(req, lan) {
|
|
9690
10327
|
const address = req.socket.remoteAddress;
|
|
9691
10328
|
if (address === void 0) return false;
|
|
9692
|
-
|
|
10329
|
+
if (isLoopbackAddress(address)) return true;
|
|
10330
|
+
if (!lan) return false;
|
|
10331
|
+
const unMapped = address.startsWith("::ffff:") ? address.slice(7) : address;
|
|
10332
|
+
return isPrivateIPv4(unMapped) || isPrivateIPv6(unMapped);
|
|
10333
|
+
}
|
|
10334
|
+
/** Host 头去端口:IPv6 字面量按方括号取;其余在「末冒号后是纯数字端口」时才切。 */
|
|
10335
|
+
function hostNameOf(header) {
|
|
10336
|
+
if (header.startsWith("[")) {
|
|
10337
|
+
const end = header.indexOf("]");
|
|
10338
|
+
return end === -1 ? header.slice(1) : header.slice(1, end);
|
|
10339
|
+
}
|
|
10340
|
+
const colon = header.lastIndexOf(":");
|
|
10341
|
+
if (colon === -1) return header;
|
|
10342
|
+
const port = header.slice(colon + 1);
|
|
10343
|
+
return /^\d+$/.test(port) ? header.slice(0, colon) : header;
|
|
10344
|
+
}
|
|
10345
|
+
/** 回环 Host 名:localhost、::1、127/8 字面量。 */
|
|
10346
|
+
function isLoopbackHostName(name) {
|
|
10347
|
+
return name === "localhost" || name === "::1" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(name);
|
|
10348
|
+
}
|
|
10349
|
+
/** IPv4 字面量(点分四段、每段 ≤255);与 peer 判定解耦——Host 只看字面性,不看私网段。 */
|
|
10350
|
+
function isIPv4Literal(name) {
|
|
10351
|
+
const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(name);
|
|
10352
|
+
if (match === null) return false;
|
|
10353
|
+
return [
|
|
10354
|
+
Number(match[1]),
|
|
10355
|
+
Number(match[2]),
|
|
10356
|
+
Number(match[3]),
|
|
10357
|
+
Number(match[4])
|
|
10358
|
+
].every((octet) => octet <= 255);
|
|
10359
|
+
}
|
|
10360
|
+
/**
|
|
10361
|
+
* lan 模式的 Host 放宽面:字面 IPv4/IPv6、localhost、单标签主机名、`*.local`。
|
|
10362
|
+
* 多标签域名仍拒绝——防 DNS rebinding(`127.0.0.1.attacker.com` 解析回环的老把戏)。
|
|
10363
|
+
*/
|
|
10364
|
+
function isLanHostName(name) {
|
|
10365
|
+
if (isLoopbackHostName(name)) return true;
|
|
10366
|
+
if (isIPv4Literal(name)) return true;
|
|
10367
|
+
if (name.includes(":")) return true;
|
|
10368
|
+
if (!name.includes(".")) return true;
|
|
10369
|
+
return name.toLowerCase().endsWith(".local");
|
|
9693
10370
|
}
|
|
9694
|
-
/** Host
|
|
9695
|
-
function
|
|
10371
|
+
/** Host 头校验:缺省放行(同旧版);loopback 模式要回环名,lan 模式再放行私网名字面量。 */
|
|
10372
|
+
function isAllowedHost(req, lan) {
|
|
9696
10373
|
const host = req.headers.host;
|
|
9697
10374
|
if (host === void 0 || host === "") return true;
|
|
9698
|
-
const name = host
|
|
9699
|
-
return
|
|
10375
|
+
const name = hostNameOf(host);
|
|
10376
|
+
return lan ? isLanHostName(name) : isLoopbackHostName(name);
|
|
9700
10377
|
}
|
|
9701
|
-
/** 写操作的 Origin
|
|
9702
|
-
function
|
|
10378
|
+
/** 写操作的 Origin 校验(防跨站表单/fetch)。缺失视为放行,由 Content-Type 兜底。 */
|
|
10379
|
+
function isAllowedOrigin(origin, lan) {
|
|
9703
10380
|
if (origin === void 0 || origin === "") return true;
|
|
9704
10381
|
try {
|
|
9705
10382
|
const host = new URL(origin).hostname;
|
|
9706
|
-
return
|
|
10383
|
+
return lan ? isLanHostName(host) : isLoopbackHostName(host);
|
|
9707
10384
|
} catch {
|
|
9708
10385
|
return false;
|
|
9709
10386
|
}
|
|
9710
10387
|
}
|
|
10388
|
+
/** 访问面拒绝时的说法:loopback 模式与 lan 模式各说各的边界,方便排障。 */
|
|
10389
|
+
function forbiddenReason(lan) {
|
|
10390
|
+
return lan ? "forbidden: loopback or private LAN only" : "forbidden: loopback only";
|
|
10391
|
+
}
|
|
9711
10392
|
/**
|
|
9712
|
-
*
|
|
10393
|
+
* 访问面守卫:GET/POST + peer + Host 同时校验。
|
|
10394
|
+
* @param lan - 是否已开启局域网访问(config.panelAccess = 'lan')。
|
|
9713
10395
|
* @returns 是否放行;false = 已拒绝并结束响应。
|
|
9714
10396
|
*/
|
|
9715
|
-
function guardLoopback(req, res) {
|
|
9716
|
-
if (!(req.method === "GET" || req.method === "POST") || !
|
|
10397
|
+
function guardLoopback(req, res, lan = false) {
|
|
10398
|
+
if (!(req.method === "GET" || req.method === "POST") || !isAllowedPeer(req, lan) || !isAllowedHost(req, lan)) {
|
|
9717
10399
|
res.writeHead(403, { "content-type": "application/json; charset=utf-8" });
|
|
9718
|
-
res.end(JSON.stringify({ error:
|
|
10400
|
+
res.end(JSON.stringify({ error: forbiddenReason(lan) }));
|
|
9719
10401
|
return false;
|
|
9720
10402
|
}
|
|
9721
10403
|
return true;
|
|
9722
10404
|
}
|
|
9723
|
-
/** 写操作守卫:Origin
|
|
9724
|
-
function guardWrite(req, res) {
|
|
9725
|
-
if (!
|
|
10405
|
+
/** 写操作守卫:Origin 访问面 + Content-Type JSON(导出仅供守卫单元测试,#49)。 */
|
|
10406
|
+
function guardWrite(req, res, lan) {
|
|
10407
|
+
if (!isAllowedOrigin(req.headers.origin, lan)) {
|
|
9726
10408
|
res.writeHead(403, { "content-type": "application/json; charset=utf-8" });
|
|
9727
|
-
res.end(JSON.stringify({ error:
|
|
10409
|
+
res.end(JSON.stringify({ error: forbiddenReason(lan) }));
|
|
9728
10410
|
return false;
|
|
9729
10411
|
}
|
|
9730
10412
|
if (!(req.headers["content-type"] ?? "").toLowerCase().includes("application/json")) {
|
|
@@ -9849,7 +10531,7 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
9849
10531
|
kind: "prefix",
|
|
9850
10532
|
path: "/api/engram",
|
|
9851
10533
|
handler: async (req, res) => {
|
|
9852
|
-
if (!guardLoopback(req, res)) return;
|
|
10534
|
+
if (!guardLoopback(req, res, deps.panelAccess === "lan")) return;
|
|
9853
10535
|
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
9854
10536
|
const route = url.pathname.slice(12);
|
|
9855
10537
|
const selectorRef = { value: url.searchParams.get("project") ?? void 0 };
|
|
@@ -9890,6 +10572,31 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
9890
10572
|
}))) });
|
|
9891
10573
|
return;
|
|
9892
10574
|
}
|
|
10575
|
+
if (req.method === "GET" && route === "injections") {
|
|
10576
|
+
const scope = scopeOf$1(url.searchParams.get("scope"), "user");
|
|
10577
|
+
const sessionId = url.searchParams.get("sessionId") ?? void 0;
|
|
10578
|
+
const limit = Math.min(200, Math.max(1, Number(url.searchParams.get("limit") ?? 50) || 50));
|
|
10579
|
+
json(res, 200, { items: await (await storeFor(scope)).listInjections({
|
|
10580
|
+
...sessionId === void 0 ? {} : { sessionId },
|
|
10581
|
+
limit
|
|
10582
|
+
}) });
|
|
10583
|
+
return;
|
|
10584
|
+
}
|
|
10585
|
+
if (req.method === "GET" && route === "injection") {
|
|
10586
|
+
const scope = scopeOf$1(url.searchParams.get("scope"), "user");
|
|
10587
|
+
const id = url.searchParams.get("id");
|
|
10588
|
+
if (id === null || id === "") {
|
|
10589
|
+
json(res, 400, { error: "id required" });
|
|
10590
|
+
return;
|
|
10591
|
+
}
|
|
10592
|
+
const snapshot = await (await storeFor(scope)).getInjection(id);
|
|
10593
|
+
if (snapshot === void 0) {
|
|
10594
|
+
json(res, 404, { error: "injection not found" });
|
|
10595
|
+
return;
|
|
10596
|
+
}
|
|
10597
|
+
json(res, 200, snapshot);
|
|
10598
|
+
return;
|
|
10599
|
+
}
|
|
9893
10600
|
if (req.method === "GET" && route === "list") {
|
|
9894
10601
|
const scope = scopeOf$1(url.searchParams.get("scope"), "user");
|
|
9895
10602
|
const status = url.searchParams.get("status");
|
|
@@ -9937,6 +10644,8 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
9937
10644
|
degraded,
|
|
9938
10645
|
hits: hits.map((hit) => ({
|
|
9939
10646
|
id: hit.record.id,
|
|
10647
|
+
memoryId: hit.record.memoryId,
|
|
10648
|
+
revisionId: hit.record.id,
|
|
9940
10649
|
score: hit.score,
|
|
9941
10650
|
via: hit.via,
|
|
9942
10651
|
...hit.viaEdge === void 0 ? {} : { viaEdge: hit.viaEdge },
|
|
@@ -9949,6 +10658,46 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
9949
10658
|
});
|
|
9950
10659
|
return;
|
|
9951
10660
|
}
|
|
10661
|
+
if (req.method === "GET" && route === "governance") {
|
|
10662
|
+
const scope = scopeOf$1(url.searchParams.get("scope"), "user");
|
|
10663
|
+
const limit = Math.min(100, Math.max(1, Number(url.searchParams.get("limit") ?? 50) || 50));
|
|
10664
|
+
const all = await (await storeFor(scope)).listContradictions(200);
|
|
10665
|
+
json(res, 200, {
|
|
10666
|
+
scope,
|
|
10667
|
+
items: all.slice(0, limit),
|
|
10668
|
+
total: all.length
|
|
10669
|
+
});
|
|
10670
|
+
return;
|
|
10671
|
+
}
|
|
10672
|
+
if (req.method === "POST" && route === "governance") {
|
|
10673
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10674
|
+
const body = await readBody(req, res, deps.language);
|
|
10675
|
+
if (body === null) return;
|
|
10676
|
+
const scope = scopeOf$1(typeof body.scope === "string" ? body.scope : null, "user");
|
|
10677
|
+
const action = body.action;
|
|
10678
|
+
if (action !== "dismiss" && action !== "forget-loser") {
|
|
10679
|
+
json(res, 400, { error: "action must be dismiss or forget-loser" });
|
|
10680
|
+
return;
|
|
10681
|
+
}
|
|
10682
|
+
if (typeof body.firstId !== "string" || typeof body.secondId !== "string" || body.firstId === "" || body.secondId === "") {
|
|
10683
|
+
json(res, 400, { error: "firstId and secondId required" });
|
|
10684
|
+
return;
|
|
10685
|
+
}
|
|
10686
|
+
if (action === "forget-loser" && (typeof body.loserId !== "string" || body.loserId === "")) {
|
|
10687
|
+
json(res, 400, { error: "loserId required" });
|
|
10688
|
+
return;
|
|
10689
|
+
}
|
|
10690
|
+
json(res, 200, {
|
|
10691
|
+
ok: true,
|
|
10692
|
+
result: await (await storeFor(scope)).resolveContradiction({
|
|
10693
|
+
firstId: body.firstId,
|
|
10694
|
+
secondId: body.secondId,
|
|
10695
|
+
action,
|
|
10696
|
+
...typeof body.loserId === "string" ? { loserId: body.loserId } : {}
|
|
10697
|
+
})
|
|
10698
|
+
});
|
|
10699
|
+
return;
|
|
10700
|
+
}
|
|
9952
10701
|
if (req.method === "GET" && route === "observations") {
|
|
9953
10702
|
const scope = scopeOf$1(url.searchParams.get("scope"), "user");
|
|
9954
10703
|
const status = url.searchParams.get("status");
|
|
@@ -9977,6 +10726,32 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
9977
10726
|
});
|
|
9978
10727
|
return;
|
|
9979
10728
|
}
|
|
10729
|
+
if (req.method === "POST" && route === "observation-status") {
|
|
10730
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10731
|
+
const body = await readBody(req, res, deps.language);
|
|
10732
|
+
if (body === null) return;
|
|
10733
|
+
adoptBodySelector(body);
|
|
10734
|
+
if (typeof body.id !== "string" || body.id === "") {
|
|
10735
|
+
json(res, 400, { error: "id required" });
|
|
10736
|
+
return;
|
|
10737
|
+
}
|
|
10738
|
+
const status = body.status;
|
|
10739
|
+
if (status !== "active" && status !== "refuted" && status !== "stale") {
|
|
10740
|
+
json(res, 400, { error: "status must be one of active|refuted|stale" });
|
|
10741
|
+
return;
|
|
10742
|
+
}
|
|
10743
|
+
const store = await storeFor(scopeOf$1(typeof body.scope === "string" ? body.scope : null, "user"));
|
|
10744
|
+
const observation = status === "active" ? await store.confirmObservation(asObservationId(body.id)) : status === "refuted" ? await store.refuteObservation(asObservationId(body.id)) : await store.markObservationStale(asObservationId(body.id));
|
|
10745
|
+
if (observation === void 0) {
|
|
10746
|
+
json(res, 404, { error: "observation not found" });
|
|
10747
|
+
return;
|
|
10748
|
+
}
|
|
10749
|
+
json(res, 200, {
|
|
10750
|
+
ok: true,
|
|
10751
|
+
observation
|
|
10752
|
+
});
|
|
10753
|
+
return;
|
|
10754
|
+
}
|
|
9980
10755
|
if (req.method === "GET" && route === "entities") {
|
|
9981
10756
|
const scope = scopeOf$1(url.searchParams.get("scope"), "user");
|
|
9982
10757
|
const kind = url.searchParams.get("kind");
|
|
@@ -10119,7 +10894,7 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10119
10894
|
if (req.method === "GET" && route === "log-info" || req.method === "POST" && route === "log-clear") {
|
|
10120
10895
|
const clear = req.method === "POST";
|
|
10121
10896
|
if (clear) {
|
|
10122
|
-
if (!guardWrite(req, res)) return;
|
|
10897
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10123
10898
|
const body = await readBody(req, res, deps.language);
|
|
10124
10899
|
if (body === null) return;
|
|
10125
10900
|
adoptBodySelector(body);
|
|
@@ -10205,7 +10980,7 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10205
10980
|
return;
|
|
10206
10981
|
}
|
|
10207
10982
|
if (req.method === "POST" && route === "review-answer") {
|
|
10208
|
-
if (!guardWrite(req, res)) return;
|
|
10983
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10209
10984
|
const body = await readBody(req, res, deps.language);
|
|
10210
10985
|
if (body === null) return;
|
|
10211
10986
|
if (typeof body.id !== "string" || body.id === "") {
|
|
@@ -10272,7 +11047,7 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10272
11047
|
return;
|
|
10273
11048
|
}
|
|
10274
11049
|
if (req.method === "POST" && route === "import") {
|
|
10275
|
-
if (!guardWrite(req, res)) return;
|
|
11050
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10276
11051
|
const bodyResult = await readJsonBody(req, IMPORT_BODY_LIMIT_BYTES);
|
|
10277
11052
|
if (!bodyResult.ok) {
|
|
10278
11053
|
if (bodyResult.reason === "too-large") {
|
|
@@ -10529,7 +11304,7 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10529
11304
|
return;
|
|
10530
11305
|
}
|
|
10531
11306
|
if (req.method === "POST" && route === "dictionary") {
|
|
10532
|
-
if (!guardWrite(req, res)) return;
|
|
11307
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10533
11308
|
const body = await readBody(req, res, deps.language);
|
|
10534
11309
|
if (body === null) return;
|
|
10535
11310
|
const set = body.set;
|
|
@@ -10544,7 +11319,7 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10544
11319
|
return;
|
|
10545
11320
|
}
|
|
10546
11321
|
if (req.method === "POST" && route === "dictionary-create") {
|
|
10547
|
-
if (!guardWrite(req, res)) return;
|
|
11322
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10548
11323
|
const body = await readBody(req, res, deps.language);
|
|
10549
11324
|
if (body === null) return;
|
|
10550
11325
|
const language = languageOf(body.language);
|
|
@@ -10562,7 +11337,7 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10562
11337
|
return;
|
|
10563
11338
|
}
|
|
10564
11339
|
if (req.method === "POST" && route === "dictionary-fill") {
|
|
10565
|
-
if (!guardWrite(req, res)) return;
|
|
11340
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10566
11341
|
const body = await readBody(req, res, deps.language);
|
|
10567
11342
|
if (body === null) return;
|
|
10568
11343
|
const set = body.set;
|
|
@@ -10578,17 +11353,17 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10578
11353
|
return;
|
|
10579
11354
|
}
|
|
10580
11355
|
if (req.method === "POST" && route === "base-label") {
|
|
10581
|
-
if (!guardWrite(req, res)) return;
|
|
11356
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10582
11357
|
json(res, 200, await deps.writeBaseLabels());
|
|
10583
11358
|
return;
|
|
10584
11359
|
}
|
|
10585
11360
|
if (req.method === "POST" && route === "base-convert") {
|
|
10586
|
-
if (!guardWrite(req, res)) return;
|
|
11361
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10587
11362
|
json(res, 200, await deps.convertBases());
|
|
10588
11363
|
return;
|
|
10589
11364
|
}
|
|
10590
11365
|
if (req.method === "POST" && route === "palace-change/open") {
|
|
10591
|
-
if (!guardWrite(req, res)) return;
|
|
11366
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10592
11367
|
const language = await deps.palaceCurrentLanguage();
|
|
10593
11368
|
const window = deps.palaceGuard.open(language, Date.now());
|
|
10594
11369
|
json(res, 200, {
|
|
@@ -10601,7 +11376,7 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10601
11376
|
return;
|
|
10602
11377
|
}
|
|
10603
11378
|
if (req.method === "POST" && route === "palace-change") {
|
|
10604
|
-
if (!guardWrite(req, res)) return;
|
|
11379
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10605
11380
|
const body = await readBody(req, res, deps.language);
|
|
10606
11381
|
if (body === null) return;
|
|
10607
11382
|
const verdict = deps.palaceGuard.check(typeof body.language === "string" ? body.language : "", Date.now(), deps.palaceChangeWindowSec);
|
|
@@ -10632,7 +11407,7 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10632
11407
|
return;
|
|
10633
11408
|
}
|
|
10634
11409
|
if (req.method === "POST" && route === "palace-language") {
|
|
10635
|
-
if (!guardWrite(req, res)) return;
|
|
11410
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10636
11411
|
const body = await readBody(req, res, deps.language);
|
|
10637
11412
|
if (body === null) return;
|
|
10638
11413
|
const wanted = body.language;
|
|
@@ -10683,7 +11458,7 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10683
11458
|
return;
|
|
10684
11459
|
}
|
|
10685
11460
|
if (req.method === "POST" && route === "history-backfill/start") {
|
|
10686
|
-
if (!guardWrite(req, res)) return;
|
|
11461
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10687
11462
|
const body = await readBody(req, res, deps.language);
|
|
10688
11463
|
if (body === null) return;
|
|
10689
11464
|
const started = deps.history.start(historyRulesOf(body));
|
|
@@ -10701,7 +11476,7 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10701
11476
|
return;
|
|
10702
11477
|
}
|
|
10703
11478
|
if (req.method === "POST" && route === "history-backfill/cancel") {
|
|
10704
|
-
if (!guardWrite(req, res)) return;
|
|
11479
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10705
11480
|
deps.history.cancel();
|
|
10706
11481
|
json(res, 200, {
|
|
10707
11482
|
ok: true,
|
|
@@ -10718,7 +11493,7 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10718
11493
|
return;
|
|
10719
11494
|
}
|
|
10720
11495
|
if (req.method === "POST" && route === "jev-config") {
|
|
10721
|
-
if (!guardWrite(req, res)) return;
|
|
11496
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10722
11497
|
const body = await readBody(req, res, deps.language);
|
|
10723
11498
|
if (body === null) return;
|
|
10724
11499
|
const parsed = parseJevPatch(loadJevOverride(deps.jev.dbDir), body);
|
|
@@ -10738,7 +11513,7 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10738
11513
|
return;
|
|
10739
11514
|
}
|
|
10740
11515
|
if (req.method === "POST" && route === "jev-test") {
|
|
10741
|
-
if (!guardWrite(req, res)) return;
|
|
11516
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10742
11517
|
const body = await readBody(req, res, deps.language);
|
|
10743
11518
|
if (body === null) return;
|
|
10744
11519
|
const base = effectiveJevConfig(deps.jev.base, loadJevOverride(deps.jev.dbDir));
|
|
@@ -10773,7 +11548,7 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10773
11548
|
return;
|
|
10774
11549
|
}
|
|
10775
11550
|
if (req.method === "POST" && route === "jev-models") {
|
|
10776
|
-
if (!guardWrite(req, res)) return;
|
|
11551
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10777
11552
|
const body = await readBody(req, res, deps.language);
|
|
10778
11553
|
if (body === null) return;
|
|
10779
11554
|
const provider = typeof body.provider === "string" ? body.provider.trim() : "";
|
|
@@ -10793,7 +11568,7 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10793
11568
|
return;
|
|
10794
11569
|
}
|
|
10795
11570
|
if (req.method === "POST" && route === "consolidate") {
|
|
10796
|
-
if (!guardWrite(req, res)) return;
|
|
11571
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10797
11572
|
const body = await readBody(req, res, deps.language);
|
|
10798
11573
|
if (body === null) return;
|
|
10799
11574
|
adoptBodySelector(body);
|
|
@@ -10807,7 +11582,7 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10807
11582
|
return;
|
|
10808
11583
|
}
|
|
10809
11584
|
if (req.method === "POST" && route === "backup") {
|
|
10810
|
-
if (!guardWrite(req, res)) return;
|
|
11585
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10811
11586
|
const result = await createBackup(deps.dbDir, deps.pluginVersion);
|
|
10812
11587
|
json(res, 200, {
|
|
10813
11588
|
archivePath: result.archivePath,
|
|
@@ -10818,7 +11593,7 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10818
11593
|
return;
|
|
10819
11594
|
}
|
|
10820
11595
|
if (req.method === "POST" && route === "restore-backup") {
|
|
10821
|
-
if (!guardWrite(req, res)) return;
|
|
11596
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10822
11597
|
const body = await readBody(req, res, deps.language);
|
|
10823
11598
|
if (body === null) return;
|
|
10824
11599
|
if (typeof body.archivePath !== "string" || body.archivePath === "") {
|
|
@@ -10845,7 +11620,7 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10845
11620
|
return;
|
|
10846
11621
|
}
|
|
10847
11622
|
if (req.method === "POST" && (route === "update" || route === "forget" || route === "restore")) {
|
|
10848
|
-
if (!guardWrite(req, res)) return;
|
|
11623
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10849
11624
|
const body = await readBody(req, res, deps.language);
|
|
10850
11625
|
if (body === null) return;
|
|
10851
11626
|
if (typeof body.id !== "string" || body.id === "") {
|
|
@@ -10860,25 +11635,36 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10860
11635
|
json(res, 400, { error: "content required" });
|
|
10861
11636
|
return;
|
|
10862
11637
|
}
|
|
10863
|
-
|
|
10864
|
-
|
|
10865
|
-
|
|
11638
|
+
try {
|
|
11639
|
+
const record = await updateMemory({
|
|
11640
|
+
store,
|
|
11641
|
+
embedder: deps.embedder
|
|
11642
|
+
}, {
|
|
11643
|
+
id: body.id,
|
|
11644
|
+
scope,
|
|
11645
|
+
content: body.content,
|
|
11646
|
+
...typeof body.kind === "string" && [
|
|
11647
|
+
"fact",
|
|
11648
|
+
"preference",
|
|
11649
|
+
"decision",
|
|
11650
|
+
"episode",
|
|
11651
|
+
"skill"
|
|
11652
|
+
].includes(body.kind) ? { kind: body.kind } : {},
|
|
11653
|
+
...typeof body.importance === "number" && Number.isFinite(body.importance) ? { importance: body.importance } : {}
|
|
11654
|
+
});
|
|
11655
|
+
if (record === void 0) {
|
|
11656
|
+
json(res, 404, { error: messageIn(deps.language, "misc.recordNotFound", { id: body.id }) });
|
|
11657
|
+
return;
|
|
11658
|
+
}
|
|
11659
|
+
json(res, 200, { record });
|
|
10866
11660
|
return;
|
|
11661
|
+
} catch (error) {
|
|
11662
|
+
if (error instanceof EngramError && error.code === "EMPTY_CONTENT") {
|
|
11663
|
+
json(res, 400, { error: error.message });
|
|
11664
|
+
return;
|
|
11665
|
+
}
|
|
11666
|
+
throw error;
|
|
10867
11667
|
}
|
|
10868
|
-
json(res, 200, { record: await store.update({
|
|
10869
|
-
id: body.id,
|
|
10870
|
-
scope,
|
|
10871
|
-
kind: typeof body.kind === "string" && [
|
|
10872
|
-
"fact",
|
|
10873
|
-
"preference",
|
|
10874
|
-
"decision",
|
|
10875
|
-
"episode",
|
|
10876
|
-
"skill"
|
|
10877
|
-
].includes(body.kind) ? body.kind : old.kind,
|
|
10878
|
-
content: body.content,
|
|
10879
|
-
...typeof body.importance === "number" && Number.isFinite(body.importance) ? { importance: Math.min(1, Math.max(0, body.importance)) } : {}
|
|
10880
|
-
}) });
|
|
10881
|
-
return;
|
|
10882
11668
|
}
|
|
10883
11669
|
json(res, 200, { record: route === "forget" ? await store.forget(body.id) : await store.restore(body.id) });
|
|
10884
11670
|
return;
|
|
@@ -10894,8 +11680,7 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10894
11680
|
}
|
|
10895
11681
|
}), "dsh-engram: api routes");
|
|
10896
11682
|
}
|
|
10897
|
-
|
|
10898
|
-
//#region src/registry/base-state.ts
|
|
11683
|
+
// src/registry/base-state.ts
|
|
10899
11684
|
/**
|
|
10900
11685
|
* Состояние базы дворца: на чём она стоит и что с ней будет делать кнопка.
|
|
10901
11686
|
*
|
|
@@ -11080,8 +11865,7 @@ function labelToStamp(input) {
|
|
|
11080
11865
|
if (facts.rows === 0) return target.label;
|
|
11081
11866
|
return judgeBase(input).action === "write-label" ? target.label : void 0;
|
|
11082
11867
|
}
|
|
11083
|
-
|
|
11084
|
-
//#region src/registry/base-census.ts
|
|
11868
|
+
// src/registry/base-census.ts
|
|
11085
11869
|
/**
|
|
11086
11870
|
* Факты о базе дворца: что в ней лежит — только чтение.
|
|
11087
11871
|
*
|
|
@@ -11386,8 +12170,7 @@ async function runVectorConvert(input) {
|
|
|
11386
12170
|
failed
|
|
11387
12171
|
};
|
|
11388
12172
|
}
|
|
11389
|
-
|
|
11390
|
-
//#region src/registry/palace-guard.ts
|
|
12173
|
+
// src/registry/palace-guard.ts
|
|
11391
12174
|
/**
|
|
11392
12175
|
* Предохранитель смены языка дворца: состояние на сервере, а не в панели.
|
|
11393
12176
|
*
|
|
@@ -11513,8 +12296,7 @@ var PalaceGuard = class {
|
|
|
11513
12296
|
return Math.max(left, 0);
|
|
11514
12297
|
}
|
|
11515
12298
|
};
|
|
11516
|
-
|
|
11517
|
-
//#region src/registry/vector-schema.ts
|
|
12299
|
+
// src/registry/vector-schema.ts
|
|
11518
12300
|
/**
|
|
11519
12301
|
* Объявление схемы данных: какие таблицы несут векторы и по какому условию.
|
|
11520
12302
|
*
|
|
@@ -11676,8 +12458,7 @@ function loadVectorSchema(sources) {
|
|
|
11676
12458
|
problems
|
|
11677
12459
|
};
|
|
11678
12460
|
}
|
|
11679
|
-
|
|
11680
|
-
//#region src/project/identity.ts
|
|
12461
|
+
// src/project/identity.ts
|
|
11681
12462
|
/**
|
|
11682
12463
|
* 项目标识:git origin URL 归一化 → sha256 短哈希分库名;无 git 或无 origin 时
|
|
11683
12464
|
* 回退完整 cwd 哈希。纯文件读(.git/config、worktree 的 gitdir/commondir
|
|
@@ -11874,8 +12655,7 @@ function migrationWarning(dbDir, identity, outcome) {
|
|
|
11874
12655
|
}
|
|
11875
12656
|
}
|
|
11876
12657
|
}
|
|
11877
|
-
|
|
11878
|
-
//#region src/project/registry.ts
|
|
12658
|
+
// src/project/registry.ts
|
|
11879
12659
|
/**
|
|
11880
12660
|
* 项目宫殿清单:把 dsh 的工作区(`ctx.workspaceRegistry` 的注册表)与会话 cwd
|
|
11881
12661
|
* 映射成记忆分库,供管理面板「切换/显示当前工作区」使用。
|
|
@@ -11987,8 +12767,7 @@ function assignSlot(kind, occupancy) {
|
|
|
11987
12767
|
};
|
|
11988
12768
|
}
|
|
11989
12769
|
}
|
|
11990
|
-
|
|
11991
|
-
//#region src/review/sm2.ts
|
|
12770
|
+
// src/review/sm2.ts
|
|
11992
12771
|
/** ease 系数下限(SM-2 标准值):低于此值记忆会陷入过密复习。 */
|
|
11993
12772
|
const MIN_EASE = 1.3;
|
|
11994
12773
|
const DAY_MS = 864e5;
|
|
@@ -12019,8 +12798,7 @@ function nextSchedule(grade, state, now) {
|
|
|
12019
12798
|
reps
|
|
12020
12799
|
};
|
|
12021
12800
|
}
|
|
12022
|
-
|
|
12023
|
-
//#region src/i18n/dates.ts
|
|
12801
|
+
// src/i18n/dates.ts
|
|
12024
12802
|
/** Относительные даты и дни недели по языкам. Числовые формы — общие, см. ниже. */
|
|
12025
12803
|
const DATE_WORDS = {
|
|
12026
12804
|
zh: [
|
|
@@ -12113,8 +12891,7 @@ function placardImprovementHint(score) {
|
|
|
12113
12891
|
if (score >= .5) return null;
|
|
12114
12892
|
return message("misc.placardImprovementHint");
|
|
12115
12893
|
}
|
|
12116
|
-
|
|
12117
|
-
//#region src/store/sqlite.ts
|
|
12894
|
+
// src/store/sqlite.ts
|
|
12118
12895
|
/**
|
|
12119
12896
|
* EngramStore 的 node:sqlite 实现:节点表 + 边表 + FTS5(unicode61 + 中文 2-gram 预切词)
|
|
12120
12897
|
* + 操作日志,单调 SCHEMA_VERSION,打开时校验、不兼容拒绝加载(不写兼容 shim)。
|
|
@@ -12124,7 +12901,7 @@ function placardImprovementHint(score) {
|
|
|
12124
12901
|
*/
|
|
12125
12902
|
/** 当前 schema 版本;结构性变更必须 +1。可空列与伴随表走增量迁移(见 openEngramStore 的迁移段)。
|
|
12126
12903
|
* v12→v13 是纯数据迁移(历史房名归一化),但同样借版本号作为「只跑一次」的开关。 */
|
|
12127
|
-
const SCHEMA_VERSION =
|
|
12904
|
+
const SCHEMA_VERSION = 15;
|
|
12128
12905
|
/** 增量迁移表:key 为起始版本,value 为升到下一版本的 SQL(可多语句)。
|
|
12129
12906
|
* v2 → v3:nodes 补可空列 outcome(使用效果回报)。
|
|
12130
12907
|
* v3 → v4:新增 nodes_revisions 修订表(update 归档旧条目时的内容快照)。
|
|
@@ -12152,7 +12929,10 @@ const SCHEMA_VERSION = 13;
|
|
|
12152
12929
|
* v12 → v13:历史房名归一化——0.8.12 及更早把**显示名**写进 slot_room(「事实厅」),
|
|
12153
12930
|
* 语言中立 id 启用后同一逻辑房会裂成两间(容量 9 变 18、tour_routes 按 room 断开)。
|
|
12154
12931
|
* 升级时一次性改写为 id,含扩建房(「事实厅-2」→「fact-2」);已经是 id 的库零行改动,
|
|
12155
|
-
* SQL 自身幂等。手动脚本 scripts/migrate-room-ids.mjs 保留为兜底。
|
|
12932
|
+
* SQL 自身幂等。手动脚本 scripts/migrate-room-ids.mjs 保留为兜底。
|
|
12933
|
+
* v13 → v14:injection_snapshots 持久化实际注入的最终包;列表只取 head,正文按 id 读取。
|
|
12934
|
+
* v14 → v15:稳定逻辑身份 memory_id——nodes.id 保留为 revision id;存量行 memory_id=id,
|
|
12935
|
+
* update 继承旧 memory_id,修订表补 memory_id 使同一逻辑身份的完整修订链可查。 */
|
|
12156
12936
|
const MIGRATIONS = {
|
|
12157
12937
|
"2": "ALTER TABLE nodes ADD COLUMN outcome TEXT",
|
|
12158
12938
|
"3": `CREATE TABLE IF NOT EXISTS nodes_revisions (
|
|
@@ -12203,7 +12983,19 @@ const MIGRATIONS = {
|
|
|
12203
12983
|
UPDATE nodes SET slot_room = replace(slot_room, '偏好阁', 'preference') WHERE slot_room LIKE '偏好阁%';
|
|
12204
12984
|
UPDATE nodes SET slot_room = replace(slot_room, '决策堂', 'decision') WHERE slot_room LIKE '决策堂%';
|
|
12205
12985
|
UPDATE nodes SET slot_room = replace(slot_room, '往事廊', 'episode') WHERE slot_room LIKE '往事廊%';
|
|
12206
|
-
UPDATE nodes SET slot_room = replace(slot_room, '技法坊', 'skill') WHERE slot_room LIKE '技法坊%'
|
|
12986
|
+
UPDATE nodes SET slot_room = replace(slot_room, '技法坊', 'skill') WHERE slot_room LIKE '技法坊%';`,
|
|
12987
|
+
"14": `ALTER TABLE nodes ADD COLUMN memory_id TEXT;
|
|
12988
|
+
UPDATE nodes SET memory_id = id WHERE memory_id IS NULL;
|
|
12989
|
+
ALTER TABLE nodes_revisions ADD COLUMN memory_id TEXT;
|
|
12990
|
+
UPDATE nodes_revisions SET memory_id = (
|
|
12991
|
+
SELECT nodes.memory_id FROM nodes WHERE nodes.id = nodes_revisions.node_id
|
|
12992
|
+
) WHERE memory_id IS NULL;
|
|
12993
|
+
CREATE INDEX IF NOT EXISTS nodes_memory_created ON nodes (memory_id, created_at);`,
|
|
12994
|
+
"13": `CREATE TABLE IF NOT EXISTS injection_snapshots (
|
|
12995
|
+
id TEXT PRIMARY KEY, session_id TEXT NOT NULL, packet_hash TEXT NOT NULL,
|
|
12996
|
+
packet TEXT NOT NULL, memory_ids_json TEXT NOT NULL, has_curated INTEGER NOT NULL,
|
|
12997
|
+
compaction_count INTEGER NOT NULL, created_at INTEGER NOT NULL);
|
|
12998
|
+
CREATE INDEX IF NOT EXISTS injection_session_created ON injection_snapshots (session_id, created_at);`
|
|
12207
12999
|
};
|
|
12208
13000
|
/** RRF 融合常数:score = Σ 1/(K + rank)。 */
|
|
12209
13001
|
const RRF_K = 60;
|
|
@@ -12215,12 +13007,29 @@ const CONTRADICTION_COSINE = .88;
|
|
|
12215
13007
|
const RANK_POOL = 64;
|
|
12216
13008
|
/** 一跳扩展引入的邻居上限。 */
|
|
12217
13009
|
const EXPANSION_LIMIT = 32;
|
|
12218
|
-
/**
|
|
13010
|
+
/** 置信度增量:真实反馈专用——效果回报 success 与写入期 MERGE 并入强化(检索曝光不算反馈)。 */
|
|
12219
13011
|
const CONFIDENCE_BUMP = .05;
|
|
12220
13012
|
/** 效果回报降权:failure 回报的置信度扣减(success 复用 CONFIDENCE_BUMP)。 */
|
|
12221
13013
|
const OUTCOME_PENALTY = .1;
|
|
12222
13014
|
/** 审计视图返回的操作日志条数上限。 */
|
|
12223
13015
|
const REVIEW_LOG_LIMIT = 20;
|
|
13016
|
+
function rowToInjectionHead(row) {
|
|
13017
|
+
let memoryIds = [];
|
|
13018
|
+
try {
|
|
13019
|
+
const parsed = JSON.parse(row.memory_ids_json);
|
|
13020
|
+
if (Array.isArray(parsed)) memoryIds = parsed.filter((id) => typeof id === "string").map(asMemoryId);
|
|
13021
|
+
} catch {}
|
|
13022
|
+
return {
|
|
13023
|
+
id: row.id,
|
|
13024
|
+
sessionId: row.session_id,
|
|
13025
|
+
packetHash: row.packet_hash,
|
|
13026
|
+
memoryIds,
|
|
13027
|
+
hasCurated: row.has_curated === 1,
|
|
13028
|
+
compactionCount: row.compaction_count,
|
|
13029
|
+
packetBytes: row.packet_bytes,
|
|
13030
|
+
createdAt: row.created_at
|
|
13031
|
+
};
|
|
13032
|
+
}
|
|
12224
13033
|
/** 把意象铭牌序列化为 JSON(缺省序列化为 null,落库)。 */
|
|
12225
13034
|
function imageryToJson(imagery) {
|
|
12226
13035
|
if (imagery === void 0) return null;
|
|
@@ -12251,6 +13060,7 @@ function rowToRecord(row) {
|
|
|
12251
13060
|
const hasReviewState = row.next_review_at !== null || row.ease_factor !== null || row.interval_days !== null;
|
|
12252
13061
|
return {
|
|
12253
13062
|
id: asMemoryId(row.id),
|
|
13063
|
+
memoryId: asMemoryId(row.memory_id ?? row.id),
|
|
12254
13064
|
scope: row.scope,
|
|
12255
13065
|
kind: row.kind,
|
|
12256
13066
|
content: row.content,
|
|
@@ -12434,7 +13244,7 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12434
13244
|
db.exec(`
|
|
12435
13245
|
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
12436
13246
|
CREATE TABLE IF NOT EXISTS nodes (
|
|
12437
|
-
id TEXT PRIMARY KEY, scope TEXT NOT NULL, kind TEXT NOT NULL, content TEXT NOT NULL,
|
|
13247
|
+
id TEXT PRIMARY KEY, memory_id TEXT, scope TEXT NOT NULL, kind TEXT NOT NULL, content TEXT NOT NULL,
|
|
12438
13248
|
importance REAL NOT NULL, confidence REAL NOT NULL, status TEXT NOT NULL,
|
|
12439
13249
|
created_at INTEGER NOT NULL, last_accessed_at INTEGER NOT NULL, access_count INTEGER NOT NULL,
|
|
12440
13250
|
source_session_id TEXT, source_round INTEGER, source_seq INTEGER, embedding BLOB, outcome TEXT,
|
|
@@ -12449,7 +13259,7 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12449
13259
|
seq INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL, op TEXT NOT NULL,
|
|
12450
13260
|
target_id TEXT NOT NULL, detail TEXT);
|
|
12451
13261
|
CREATE TABLE IF NOT EXISTS nodes_revisions (
|
|
12452
|
-
node_id TEXT NOT NULL, content TEXT NOT NULL, kind TEXT NOT NULL,
|
|
13262
|
+
node_id TEXT NOT NULL, memory_id TEXT, content TEXT NOT NULL, kind TEXT NOT NULL,
|
|
12453
13263
|
importance REAL NOT NULL, superseded_at INTEGER NOT NULL);
|
|
12454
13264
|
CREATE TABLE IF NOT EXISTS tour_routes (
|
|
12455
13265
|
position INTEGER PRIMARY KEY, node_id TEXT NOT NULL);
|
|
@@ -12476,6 +13286,10 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12476
13286
|
id TEXT PRIMARY KEY, scope TEXT NOT NULL, belief TEXT NOT NULL, status TEXT NOT NULL,
|
|
12477
13287
|
sources_json TEXT NOT NULL, proof_count INTEGER NOT NULL, embedding BLOB,
|
|
12478
13288
|
created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, last_validated_at INTEGER NOT NULL);
|
|
13289
|
+
CREATE TABLE IF NOT EXISTS injection_snapshots (
|
|
13290
|
+
id TEXT PRIMARY KEY, session_id TEXT NOT NULL, packet_hash TEXT NOT NULL,
|
|
13291
|
+
packet TEXT NOT NULL, memory_ids_json TEXT NOT NULL, has_curated INTEGER NOT NULL,
|
|
13292
|
+
compaction_count INTEGER NOT NULL, created_at INTEGER NOT NULL);
|
|
12479
13293
|
CREATE VIRTUAL TABLE IF NOT EXISTS nodes_fts USING fts5(node_id UNINDEXED, content, tokenize='unicode61');
|
|
12480
13294
|
CREATE INDEX IF NOT EXISTS nodes_scope_status ON nodes (scope, status);
|
|
12481
13295
|
CREATE INDEX IF NOT EXISTS nodes_kind_created ON nodes (kind, created_at);
|
|
@@ -12484,11 +13298,13 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12484
13298
|
CREATE INDEX IF NOT EXISTS node_entities_entity ON node_entities (entity_id);
|
|
12485
13299
|
CREATE INDEX IF NOT EXISTS facts_entity ON facts (entity_id);
|
|
12486
13300
|
CREATE INDEX IF NOT EXISTS observations_status ON observations (status, proof_count, updated_at);
|
|
13301
|
+
CREATE INDEX IF NOT EXISTS injection_session_created ON injection_snapshots (session_id, created_at);
|
|
12487
13302
|
`);
|
|
12488
13303
|
const versionRow = db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get();
|
|
12489
13304
|
if (versionRow === void 0) {
|
|
12490
13305
|
db.exec(`CREATE INDEX IF NOT EXISTS nodes_slot ON nodes (slot_room, slot_index);
|
|
12491
|
-
CREATE INDEX IF NOT EXISTS nodes_review_due ON nodes (next_review_at)
|
|
13306
|
+
CREATE INDEX IF NOT EXISTS nodes_review_due ON nodes (next_review_at);
|
|
13307
|
+
CREATE INDEX IF NOT EXISTS nodes_memory_created ON nodes (memory_id, created_at);`);
|
|
12492
13308
|
db.prepare("INSERT INTO meta (key, value) VALUES ('schema_version', ?)").run(String(SCHEMA_VERSION));
|
|
12493
13309
|
} else {
|
|
12494
13310
|
let version = Number(versionRow.value);
|
|
@@ -12497,13 +13313,18 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12497
13313
|
supported: SCHEMA_VERSION,
|
|
12498
13314
|
path
|
|
12499
13315
|
}));
|
|
12500
|
-
if (version < SCHEMA_VERSION)
|
|
12501
|
-
|
|
12502
|
-
|
|
12503
|
-
|
|
12504
|
-
|
|
12505
|
-
|
|
12506
|
-
})
|
|
13316
|
+
if (version < SCHEMA_VERSION) {
|
|
13317
|
+
const snapshotPath = `${path}.pre-migration`;
|
|
13318
|
+
try {
|
|
13319
|
+
await rm(snapshotPath, { force: true });
|
|
13320
|
+
const quoted = snapshotPath.replaceAll("'", "''");
|
|
13321
|
+
db.exec(`VACUUM INTO '${quoted}'`);
|
|
13322
|
+
} catch (error) {
|
|
13323
|
+
console.warn(message("store.preMigrationSnapshotFailed", {
|
|
13324
|
+
path,
|
|
13325
|
+
msg: error instanceof Error ? error.message : String(error)
|
|
13326
|
+
}));
|
|
13327
|
+
}
|
|
12507
13328
|
}
|
|
12508
13329
|
while (version < SCHEMA_VERSION) {
|
|
12509
13330
|
const migration = MIGRATIONS[String(version)];
|
|
@@ -12558,18 +13379,22 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12558
13379
|
storedDim = length;
|
|
12559
13380
|
};
|
|
12560
13381
|
const sqlGet = db.prepare("SELECT * FROM nodes WHERE id = ?");
|
|
13382
|
+
const sqlGetMemory = db.prepare(`SELECT * FROM nodes WHERE memory_id = ?
|
|
13383
|
+
ORDER BY CASE status WHEN 'active' THEN 0 ELSE 1 END, created_at DESC, id DESC LIMIT 1`);
|
|
12561
13384
|
const sqlInsert = db.prepare(`INSERT INTO nodes
|
|
12562
|
-
(id, scope, kind, content, importance, confidence, status, created_at, last_accessed_at, access_count,
|
|
13385
|
+
(id, memory_id, scope, kind, content, importance, confidence, status, created_at, last_accessed_at, access_count,
|
|
12563
13386
|
source_session_id, source_round, source_seq, embedding, imagery_json,
|
|
12564
13387
|
slot_room, slot_index, imagery_score, next_review_at, ease_factor, interval_days)
|
|
12565
|
-
VALUES (?, ?, ?, ?, ?, ?, 'active', ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
13388
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
12566
13389
|
const sqlFtsInsert = db.prepare("INSERT INTO nodes_fts (node_id, content) VALUES (?, ?)");
|
|
12567
13390
|
const sqlSetStatus = db.prepare("UPDATE nodes SET status = ?, last_accessed_at = ? WHERE id = ?");
|
|
13391
|
+
const sqlActiveMemorySiblings = db.prepare(`SELECT id FROM nodes
|
|
13392
|
+
WHERE memory_id = ? AND id != ? AND status = 'active'`);
|
|
12568
13393
|
const sqlSetOutcome = db.prepare(`UPDATE nodes
|
|
12569
13394
|
SET outcome = ?,
|
|
12570
13395
|
confidence = CASE WHEN ? = 'success' THEN min(1.0, confidence + ${CONFIDENCE_BUMP}) ELSE max(0.0, confidence - ${OUTCOME_PENALTY}) END
|
|
12571
13396
|
WHERE id = ?`);
|
|
12572
|
-
const
|
|
13397
|
+
const sqlReinforce = db.prepare(`UPDATE nodes SET access_count = access_count + 1, last_accessed_at = ?,
|
|
12573
13398
|
confidence = MIN(1, confidence + ${CONFIDENCE_BUMP}) WHERE id = ?`);
|
|
12574
13399
|
const sqlLog = db.prepare("INSERT INTO op_log (at, op, target_id, detail) VALUES (?, ?, ?, ?)");
|
|
12575
13400
|
const sqlHasAudit = db.prepare("SELECT 1 AS x FROM op_log WHERE op = ? AND detail = ? LIMIT 1");
|
|
@@ -12593,13 +13418,24 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12593
13418
|
)`);
|
|
12594
13419
|
const sqlRecentOps = db.prepare("SELECT at, op, target_id, detail FROM op_log ORDER BY seq DESC LIMIT ?");
|
|
12595
13420
|
const sqlCountOps = db.prepare("SELECT op, COUNT(*) AS n FROM op_log WHERE at >= ? GROUP BY op");
|
|
12596
|
-
const sqlRevisionInsert = db.prepare("INSERT INTO nodes_revisions (node_id, content, kind, importance, superseded_at) VALUES (?, ?, ?, ?, ?)");
|
|
12597
|
-
const sqlRevisionsById = db.prepare("SELECT content, kind, importance, superseded_at FROM nodes_revisions WHERE
|
|
13421
|
+
const sqlRevisionInsert = db.prepare("INSERT INTO nodes_revisions (node_id, memory_id, content, kind, importance, superseded_at) VALUES (?, ?, ?, ?, ?, ?)");
|
|
13422
|
+
const sqlRevisionsById = db.prepare("SELECT content, kind, importance, superseded_at FROM nodes_revisions WHERE memory_id = ? ORDER BY superseded_at DESC, rowid DESC");
|
|
12598
13423
|
const sqlTopActive = db.prepare("SELECT * FROM nodes WHERE scope = ? AND status = 'active' ORDER BY importance DESC, confidence DESC LIMIT ?");
|
|
12599
13424
|
const sqlEdgeUpsert = db.prepare("INSERT OR IGNORE INTO edges (from_id, to_id, type, created_at) VALUES (?, ?, ?, ?)");
|
|
12600
13425
|
const sqlNeighbors = db.prepare(`SELECT * FROM edges WHERE from_id IN (SELECT value FROM json_each(?))
|
|
12601
13426
|
AND type IN ('supports','refines','related') LIMIT ?`);
|
|
12602
13427
|
const sqlEdgesTouching = db.prepare("SELECT from_id, to_id, type FROM edges WHERE from_id = ? OR to_id = ?");
|
|
13428
|
+
const sqlContradictions = db.prepare(`SELECT e.from_id, e.to_id, e.created_at
|
|
13429
|
+
FROM edges e
|
|
13430
|
+
JOIN nodes first ON first.id = e.from_id AND first.status = 'active'
|
|
13431
|
+
JOIN nodes second ON second.id = e.to_id AND second.status = 'active'
|
|
13432
|
+
WHERE e.type = 'contradicts'
|
|
13433
|
+
ORDER BY e.created_at DESC LIMIT ?`);
|
|
13434
|
+
const sqlContradictionPair = db.prepare(`SELECT from_id, to_id, created_at FROM edges
|
|
13435
|
+
WHERE type = 'contradicts'
|
|
13436
|
+
AND ((from_id = ? AND to_id = ?) OR (from_id = ? AND to_id = ?))
|
|
13437
|
+
LIMIT 1`);
|
|
13438
|
+
const sqlEdgeDelete = db.prepare("DELETE FROM edges WHERE from_id = ? AND to_id = ? AND type = ?");
|
|
12603
13439
|
const sqlCountBy = db.prepare("SELECT status, COUNT(*) AS n FROM nodes GROUP BY status");
|
|
12604
13440
|
const sqlCountKind = db.prepare("SELECT kind, COUNT(*) AS n FROM nodes GROUP BY kind");
|
|
12605
13441
|
const sqlCountEdges = db.prepare("SELECT COUNT(*) AS n FROM edges");
|
|
@@ -12608,10 +13444,10 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12608
13444
|
const sqlAllNodes = db.prepare("SELECT * FROM nodes ORDER BY created_at");
|
|
12609
13445
|
const sqlAllEdges = db.prepare("SELECT * FROM edges");
|
|
12610
13446
|
const sqlImportInsert = db.prepare(`INSERT INTO nodes
|
|
12611
|
-
(id, scope, kind, content, importance, confidence, status, created_at, last_accessed_at, access_count,
|
|
13447
|
+
(id, memory_id, scope, kind, content, importance, confidence, status, created_at, last_accessed_at, access_count,
|
|
12612
13448
|
source_session_id, source_round, source_seq, embedding, outcome, imagery_json,
|
|
12613
13449
|
slot_room, slot_index, imagery_score, next_review_at, ease_factor, interval_days, review_reps)
|
|
12614
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
13450
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
12615
13451
|
const sqlImportContentMatch = db.prepare("SELECT id FROM nodes WHERE content = ? LIMIT 1");
|
|
12616
13452
|
const sqlImportAttachEmbedding = db.prepare("UPDATE nodes SET embedding = ? WHERE id = ?");
|
|
12617
13453
|
const vectorStatements = /* @__PURE__ */ new Map();
|
|
@@ -12629,6 +13465,8 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12629
13465
|
};
|
|
12630
13466
|
const sqlImportEntityAliases = db.prepare("UPDATE entities SET aliases_json = ?, updated_at = ? WHERE id = ?");
|
|
12631
13467
|
const sqlDecay = db.prepare(`UPDATE nodes SET status = 'archived'
|
|
13468
|
+
WHERE status = 'active' AND importance < ? AND last_accessed_at < ? AND next_review_at IS NULL`);
|
|
13469
|
+
const sqlDecayVictims = db.prepare(`SELECT id FROM nodes
|
|
12632
13470
|
WHERE status = 'active' AND importance < ? AND last_accessed_at < ? AND next_review_at IS NULL`);
|
|
12633
13471
|
const sqlScheduleReview = db.prepare(`UPDATE nodes
|
|
12634
13472
|
SET next_review_at = ?, ease_factor = ?, interval_days = ?, review_reps = ?, last_accessed_at = ?
|
|
@@ -12667,6 +13505,16 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12667
13505
|
ON CONFLICT (session_id) DO UPDATE SET summary = excluded.summary, updated_at = excluded.updated_at`);
|
|
12668
13506
|
const sqlSessionSummaryGet = db.prepare("SELECT session_id, summary FROM session_summaries WHERE session_id = ?");
|
|
12669
13507
|
const sqlSessionSummaryMany = db.prepare("SELECT session_id, summary FROM session_summaries WHERE session_id IN (SELECT value FROM json_each(?))");
|
|
13508
|
+
const sqlInjectionInsert = db.prepare(`INSERT INTO injection_snapshots
|
|
13509
|
+
(id, session_id, packet_hash, packet, memory_ids_json, has_curated, compaction_count, created_at)
|
|
13510
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
13511
|
+
const sqlInjectionHead = `SELECT id, session_id, packet_hash, memory_ids_json, has_curated,
|
|
13512
|
+
compaction_count, LENGTH(CAST(packet AS BLOB)) AS packet_bytes, created_at FROM injection_snapshots`;
|
|
13513
|
+
const sqlInjectionList = db.prepare(`${sqlInjectionHead} ORDER BY created_at DESC, id DESC LIMIT ?`);
|
|
13514
|
+
const sqlInjectionListSession = db.prepare(`${sqlInjectionHead} WHERE session_id = ? ORDER BY created_at DESC, id DESC LIMIT ?`);
|
|
13515
|
+
const sqlInjectionGet = db.prepare(`SELECT id, session_id, packet_hash, packet, memory_ids_json, has_curated,
|
|
13516
|
+
compaction_count, LENGTH(CAST(packet AS BLOB)) AS packet_bytes, created_at FROM injection_snapshots WHERE id = ?`);
|
|
13517
|
+
const sqlInjectionPrune = db.prepare("DELETE FROM injection_snapshots WHERE created_at < ?");
|
|
12670
13518
|
const sqlEntityAll = db.prepare("SELECT * FROM entities");
|
|
12671
13519
|
const sqlEntityGet = db.prepare("SELECT * FROM entities WHERE id = ?");
|
|
12672
13520
|
const sqlEntityInsert = db.prepare("INSERT INTO entities (id, name, kind, aliases_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)");
|
|
@@ -12696,8 +13544,52 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12696
13544
|
const sqlObservationSetStatus = db.prepare("UPDATE observations SET status = ?, updated_at = ?, last_validated_at = ? WHERE id = ?");
|
|
12697
13545
|
const sqlObservationMarkStale = db.prepare("UPDATE observations SET status = 'stale' WHERE id = ?");
|
|
12698
13546
|
const sqlObservationRefute = db.prepare("UPDATE observations SET status = 'refuted', updated_at = ? WHERE id = ?");
|
|
13547
|
+
const sqlObservationEvidenceHit = db.prepare(`SELECT id, sources_json FROM observations
|
|
13548
|
+
WHERE status IN ('active','stale') AND instr(sources_json, ?) > 0`);
|
|
13549
|
+
const sqlObservationDetachStale = db.prepare("UPDATE observations SET status = 'stale', sources_json = ?, proof_count = ? WHERE id = ?");
|
|
12699
13550
|
const sqlObservationActiveVectors = db.prepare(`SELECT * FROM observations WHERE status != 'refuted' AND embedding IS NOT NULL AND LENGTH(embedding) % ${Float32Array.BYTES_PER_ELEMENT} = 0`);
|
|
12700
13551
|
const sqlPurgeObservations = db.prepare("DELETE FROM observations");
|
|
13552
|
+
/**
|
|
13553
|
+
* 归档传播(#48 Fix A):源记忆死亡(forget/闭馆/supersede/蒸馏/衰减归档)时,把以它为
|
|
13554
|
+
* 证据的 active/stale 信念扣源——instr 带引号子串只是预筛,落库前对 JSON.parse 结果做
|
|
13555
|
+
* 精确成员过滤再去重。证据耗尽置 refuted(与 refuteObservation 同款:刷 updated_at,
|
|
13556
|
+
* last_validated_at 保留为上次成立时间);尚有余证置 stale 并重写 sources_json/proof_count
|
|
13557
|
+
* (不刷 updated_at,复核队列顺序语义不变)。refuted 是终态审计标记,不参与传播;
|
|
13558
|
+
* restore 也不调用本 helper:节点复活时信念保持既有状态,由下次复核确认回来。
|
|
13559
|
+
* 返回 { staled, refuted } 计数,调用方可忽略。
|
|
13560
|
+
*/
|
|
13561
|
+
const detachArchivedEvidence = (nodeIds) => {
|
|
13562
|
+
const dead = [...new Set(nodeIds.map(String))].filter((nodeId) => nodeId !== "");
|
|
13563
|
+
let staled = 0;
|
|
13564
|
+
let refuted = 0;
|
|
13565
|
+
const processed = /* @__PURE__ */ new Set();
|
|
13566
|
+
for (const deadId of dead) {
|
|
13567
|
+
const hits = sqlObservationEvidenceHit.all(`"${deadId}"`);
|
|
13568
|
+
for (const hit of hits) {
|
|
13569
|
+
if (processed.has(hit.id)) continue;
|
|
13570
|
+
processed.add(hit.id);
|
|
13571
|
+
let sources;
|
|
13572
|
+
try {
|
|
13573
|
+
const parsed = JSON.parse(hit.sources_json);
|
|
13574
|
+
sources = Array.isArray(parsed) ? parsed.filter((item) => typeof item === "string") : [];
|
|
13575
|
+
} catch {
|
|
13576
|
+
sources = [];
|
|
13577
|
+
}
|
|
13578
|
+
const remaining = [...new Set(sources.filter((source) => !dead.includes(source)))];
|
|
13579
|
+
if (remaining.length === 0) {
|
|
13580
|
+
sqlObservationRefute.run(Date.now(), hit.id);
|
|
13581
|
+
refuted += 1;
|
|
13582
|
+
} else {
|
|
13583
|
+
sqlObservationDetachStale.run(JSON.stringify(remaining), remaining.length, hit.id);
|
|
13584
|
+
staled += 1;
|
|
13585
|
+
}
|
|
13586
|
+
}
|
|
13587
|
+
}
|
|
13588
|
+
return {
|
|
13589
|
+
staled,
|
|
13590
|
+
refuted
|
|
13591
|
+
};
|
|
13592
|
+
};
|
|
12701
13593
|
/** FTS 道:按 scope 集合检索(占位符动态生成,scope 集合由调用方去重);rooms 非空时只查指定房间。 */
|
|
12702
13594
|
const ftsSearch = (match, scopes, rooms) => {
|
|
12703
13595
|
const placeholders = scopes.map(() => "?").join(",");
|
|
@@ -12840,7 +13732,7 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12840
13732
|
const initialReview = input.initialReviewAt ?? null;
|
|
12841
13733
|
const safeImportance = clampUnit(importance, .5);
|
|
12842
13734
|
const safeConfidence = clampUnit(confidence, .5);
|
|
12843
|
-
sqlInsert.run(id, input.scope, input.kind, content, safeImportance, safeConfidence, at, at, sourceSessionId, input.sourceRound ?? null, input.sourceSeq ?? null, stored, imageryToJson(imagery), input.slot?.room ?? null, input.slot?.index ?? null, input.imageryScore ?? null, initialReview, initialReview === null ? null : 2.5, initialReview === null ? null : 0);
|
|
13735
|
+
sqlInsert.run(id, input.memoryId ?? id, input.scope, input.kind, content, safeImportance, safeConfidence, at, at, sourceSessionId, input.sourceRound ?? null, input.sourceSeq ?? null, stored, imageryToJson(imagery), input.slot?.room ?? null, input.slot?.index ?? null, input.imageryScore ?? null, initialReview, initialReview === null ? null : 2.5, initialReview === null ? null : 0);
|
|
12844
13736
|
sqlFtsInsert.run(id, tokenizeForFts(content));
|
|
12845
13737
|
sqlLog.run(at, op, id, JSON.stringify({
|
|
12846
13738
|
kind: input.kind,
|
|
@@ -12955,6 +13847,11 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12955
13847
|
const row = getRow(id);
|
|
12956
13848
|
return row === void 0 ? void 0 : rowToRecord(row);
|
|
12957
13849
|
},
|
|
13850
|
+
/** 稳定逻辑身份 → 当前修订(active 优先,其次最新版)。 */
|
|
13851
|
+
async getMemory(id) {
|
|
13852
|
+
const row = sqlGetMemory.get(id);
|
|
13853
|
+
return row === void 0 ? void 0 : rowToRecord(row);
|
|
13854
|
+
},
|
|
12958
13855
|
async getMany(ids) {
|
|
12959
13856
|
if (ids.length === 0) return [];
|
|
12960
13857
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -13086,8 +13983,14 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13086
13983
|
name: r.name
|
|
13087
13984
|
})) }
|
|
13088
13985
|
});
|
|
13089
|
-
sqlTouch.run(Date.now(), id);
|
|
13090
13986
|
}
|
|
13987
|
+
sqlLog.run(Date.now(), "search-exposure", "AUX", JSON.stringify({
|
|
13988
|
+
ids: hits.map((hit) => String(hit.record.id)),
|
|
13989
|
+
scopes: query.scopes,
|
|
13990
|
+
limit,
|
|
13991
|
+
degraded,
|
|
13992
|
+
q: createHash("sha256").update(query.text).digest("hex").slice(0, 12)
|
|
13993
|
+
}));
|
|
13091
13994
|
return {
|
|
13092
13995
|
hits,
|
|
13093
13996
|
degraded
|
|
@@ -13183,6 +14086,31 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13183
14086
|
async getSessionSummary(sessionId) {
|
|
13184
14087
|
return sqlSessionSummaryGet.get(sessionId)?.summary;
|
|
13185
14088
|
},
|
|
14089
|
+
async recordInjection(input) {
|
|
14090
|
+
const id = randomUUID();
|
|
14091
|
+
const at = Date.now();
|
|
14092
|
+
sqlInjectionInsert.run(id, input.sessionId, input.packetHash, input.packet, JSON.stringify(input.memoryIds), input.hasCurated ? 1 : 0, input.compactionCount, at);
|
|
14093
|
+
const row = sqlInjectionGet.get(id);
|
|
14094
|
+
return {
|
|
14095
|
+
...rowToInjectionHead(row),
|
|
14096
|
+
packet: row.packet
|
|
14097
|
+
};
|
|
14098
|
+
},
|
|
14099
|
+
async listInjections(filter) {
|
|
14100
|
+
const limit = Math.max(1, Math.min(200, Math.floor(filter.limit ?? 50)));
|
|
14101
|
+
return (filter.sessionId === void 0 ? sqlInjectionList.all(limit) : sqlInjectionListSession.all(filter.sessionId, limit)).map(rowToInjectionHead);
|
|
14102
|
+
},
|
|
14103
|
+
async getInjection(id) {
|
|
14104
|
+
const row = sqlInjectionGet.get(id);
|
|
14105
|
+
return row === void 0 ? void 0 : {
|
|
14106
|
+
...rowToInjectionHead(row),
|
|
14107
|
+
packet: row.packet
|
|
14108
|
+
};
|
|
14109
|
+
},
|
|
14110
|
+
async pruneInjections(olderThanMs) {
|
|
14111
|
+
const result = sqlInjectionPrune.run(olderThanMs);
|
|
14112
|
+
return Number(result.changes);
|
|
14113
|
+
},
|
|
13186
14114
|
async update(input) {
|
|
13187
14115
|
const old = getRow(input.id);
|
|
13188
14116
|
if (old === void 0) throw new EngramError("NOT_FOUND", message("store.entryNotFound", { id: input.id }));
|
|
@@ -13191,20 +14119,22 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13191
14119
|
const id = asMemoryId(randomUUID());
|
|
13192
14120
|
const at = Date.now();
|
|
13193
14121
|
withTransaction(() => {
|
|
13194
|
-
sqlRevisionInsert.run(input.id, old.content, old.kind, old.importance, at);
|
|
14122
|
+
sqlRevisionInsert.run(input.id, old.memory_id, old.content, old.kind, old.importance, at);
|
|
13195
14123
|
sqlSetStatus.run("archived", at, input.id);
|
|
13196
14124
|
sqlLog.run(at, "superseded", input.id, JSON.stringify({ supersededBy: id }));
|
|
14125
|
+
detachArchivedEvidence([input.id]);
|
|
13197
14126
|
const imagery = input.imagery ?? jsonToImagery(old.imagery_json);
|
|
13198
14127
|
const updateInput = {
|
|
13199
14128
|
scope: input.scope,
|
|
13200
14129
|
kind: input.kind,
|
|
13201
|
-
content
|
|
14130
|
+
content,
|
|
14131
|
+
memoryId: asMemoryId(old.memory_id ?? input.id)
|
|
13202
14132
|
};
|
|
13203
14133
|
const automationFields = applyWriteAutomation(updateInput, id, at, imagery);
|
|
13204
14134
|
insertRecord(id, {
|
|
13205
14135
|
...updateInput,
|
|
13206
14136
|
...automationFields
|
|
13207
|
-
}, content, input.importance ?? old.importance, old.confidence, at, old.source_session_id, input.embedding
|
|
14137
|
+
}, content, input.importance ?? old.importance, old.confidence, at, old.source_session_id, input.embedding === void 0 ? old.embedding : input.embedding, imagery, "update");
|
|
13208
14138
|
sqlEdgeUpsert.run(id, input.id, "supersedes", at);
|
|
13209
14139
|
});
|
|
13210
14140
|
return rowToRecord(sqlGet.get(id));
|
|
@@ -13213,6 +14143,7 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13213
14143
|
if (getRow(id) === void 0) throw new EngramError("NOT_FOUND", message("store.entryNotFound", { id }));
|
|
13214
14144
|
sqlSetStatus.run("forgotten", Date.now(), id);
|
|
13215
14145
|
sqlLog.run(Date.now(), "forget", id, null);
|
|
14146
|
+
detachArchivedEvidence([id]);
|
|
13216
14147
|
return rowToRecord(sqlGet.get(id));
|
|
13217
14148
|
},
|
|
13218
14149
|
async forgetWithTombstone(id, tombstone) {
|
|
@@ -13225,6 +14156,7 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13225
14156
|
};
|
|
13226
14157
|
sqlSetStatus.run("forgotten", at, id);
|
|
13227
14158
|
sqlLog.run(at, "forget", id, JSON.stringify({ tombstone: cleaned }));
|
|
14159
|
+
detachArchivedEvidence([id]);
|
|
13228
14160
|
return rowToRecord(sqlGet.get(id));
|
|
13229
14161
|
},
|
|
13230
14162
|
async listForgottenWithTombs(limit) {
|
|
@@ -13397,9 +14329,19 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13397
14329
|
};
|
|
13398
14330
|
},
|
|
13399
14331
|
async restore(id) {
|
|
13400
|
-
|
|
13401
|
-
|
|
13402
|
-
|
|
14332
|
+
const row = getRow(id);
|
|
14333
|
+
if (row === void 0) throw new EngramError("NOT_FOUND", message("store.entryNotFound", { id }));
|
|
14334
|
+
const at = Date.now();
|
|
14335
|
+
withTransaction(() => {
|
|
14336
|
+
const memoryId = row.memory_id ?? row.id;
|
|
14337
|
+
const siblings = sqlActiveMemorySiblings.all(memoryId, id);
|
|
14338
|
+
for (const sibling of siblings) {
|
|
14339
|
+
sqlSetStatus.run("archived", at, asMemoryId(sibling.id));
|
|
14340
|
+
sqlEdgeUpsert.run(id, sibling.id, "supersedes", at);
|
|
14341
|
+
}
|
|
14342
|
+
sqlSetStatus.run("active", at, id);
|
|
14343
|
+
sqlLog.run(at, "restore", id, JSON.stringify({ archivedRevisions: siblings.map((s) => s.id) }));
|
|
14344
|
+
});
|
|
13403
14345
|
return rowToRecord(sqlGet.get(id));
|
|
13404
14346
|
},
|
|
13405
14347
|
async topActive(scope, n) {
|
|
@@ -13433,7 +14375,7 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13433
14375
|
const row = getRow(id);
|
|
13434
14376
|
if (row === void 0) return void 0;
|
|
13435
14377
|
const operations = sqlOpLogById.all(id, REVIEW_LOG_LIMIT);
|
|
13436
|
-
const revisions = sqlRevisionsById.all(id);
|
|
14378
|
+
const revisions = sqlRevisionsById.all(row.memory_id ?? row.id);
|
|
13437
14379
|
return {
|
|
13438
14380
|
record: rowToRecord(row),
|
|
13439
14381
|
...edgeGroups(id),
|
|
@@ -13575,7 +14517,7 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13575
14517
|
for (const c of eligible) {
|
|
13576
14518
|
const r = c.record;
|
|
13577
14519
|
const review = r.review;
|
|
13578
|
-
sqlImportInsert.run(r.id, r.scope, r.kind, c.content, clampUnit(r.importance, .5), clampUnit(r.confidence, .5), r.status, r.createdAt, r.lastAccessedAt, r.accessCount, r.sourceSessionId ?? null, r.sourceRound ?? null, r.sourceSeq ?? null, null, r.outcome ?? null, imageryToJson(r.imagery), r.slot?.room ?? null, r.slot?.index ?? null, r.imageryScore ?? null, review?.nextReviewAt ?? null, review?.easeFactor ?? null, review?.intervalDays ?? null, review?.reps ?? null);
|
|
14520
|
+
sqlImportInsert.run(r.id, r.memoryId ?? r.id, r.scope, r.kind, c.content, clampUnit(r.importance, .5), clampUnit(r.confidence, .5), r.status, r.createdAt, r.lastAccessedAt, r.accessCount, r.sourceSessionId ?? null, r.sourceRound ?? null, r.sourceSeq ?? null, null, r.outcome ?? null, imageryToJson(r.imagery), r.slot?.room ?? null, r.slot?.index ?? null, r.imageryScore ?? null, review?.nextReviewAt ?? null, review?.easeFactor ?? null, review?.intervalDays ?? null, review?.reps ?? null);
|
|
13579
14521
|
sqlFtsInsert.run(r.id, tokenizeForFts(c.content));
|
|
13580
14522
|
}
|
|
13581
14523
|
for (const edge of data.edges ?? []) {
|
|
@@ -13652,9 +14594,13 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13652
14594
|
},
|
|
13653
14595
|
async decay(options) {
|
|
13654
14596
|
const cutoff = Date.now() - options.olderThanDays * 864e5;
|
|
14597
|
+
const victims = sqlDecayVictims.all(options.importanceBelow, cutoff).map((row) => row.id);
|
|
13655
14598
|
const result = sqlDecay.run(options.importanceBelow, cutoff);
|
|
13656
14599
|
const changed = Number(result.changes);
|
|
13657
|
-
if (changed > 0)
|
|
14600
|
+
if (changed > 0) {
|
|
14601
|
+
sqlLog.run(Date.now(), "decay", "BATCH", JSON.stringify({ archived: changed }));
|
|
14602
|
+
detachArchivedEvidence(victims);
|
|
14603
|
+
}
|
|
13658
14604
|
return changed;
|
|
13659
14605
|
},
|
|
13660
14606
|
async findContradictions(embedding, limit = 3) {
|
|
@@ -13681,6 +14627,48 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13681
14627
|
hits.sort((a, b) => b.sim - a.sim);
|
|
13682
14628
|
return hits.slice(0, limit).map((hit) => getRow(matrix.ids[hit.index])).filter((row) => row !== void 0).map((row) => rowToRecord(row));
|
|
13683
14629
|
},
|
|
14630
|
+
async listContradictions(limit) {
|
|
14631
|
+
const boundedLimit = Math.max(1, Math.min(200, Math.floor(limit)));
|
|
14632
|
+
const rows = sqlContradictions.all(boundedLimit);
|
|
14633
|
+
const result = [];
|
|
14634
|
+
for (const row of rows) {
|
|
14635
|
+
const first = getRow(row.from_id);
|
|
14636
|
+
const second = getRow(row.to_id);
|
|
14637
|
+
if (first === void 0 || second === void 0) continue;
|
|
14638
|
+
result.push({
|
|
14639
|
+
first: rowToRecord(first),
|
|
14640
|
+
second: rowToRecord(second),
|
|
14641
|
+
createdAt: row.created_at
|
|
14642
|
+
});
|
|
14643
|
+
}
|
|
14644
|
+
return result;
|
|
14645
|
+
},
|
|
14646
|
+
async resolveContradiction(input) {
|
|
14647
|
+
const forward = sqlContradictionPair.get(input.firstId, input.secondId, input.secondId, input.firstId);
|
|
14648
|
+
if (forward === void 0) throw new EngramError("NOT_FOUND", message("store.entryNotFound", { id: input.firstId }));
|
|
14649
|
+
const at = Date.now();
|
|
14650
|
+
if (input.action === "dismiss") {
|
|
14651
|
+
withTransaction(() => {
|
|
14652
|
+
sqlEdgeDelete.run(forward.from_id, forward.to_id, "contradicts");
|
|
14653
|
+
sqlEdgeUpsert.run(forward.from_id, forward.to_id, "related", at);
|
|
14654
|
+
sqlLog.run(at, "governance", "AUX", JSON.stringify({
|
|
14655
|
+
action: "dismiss",
|
|
14656
|
+
from: forward.from_id,
|
|
14657
|
+
to: forward.to_id
|
|
14658
|
+
}));
|
|
14659
|
+
});
|
|
14660
|
+
return { dismissed: true };
|
|
14661
|
+
}
|
|
14662
|
+
const loser = input.loserId === void 0 ? void 0 : getRow(input.loserId);
|
|
14663
|
+
if (loser === void 0 || loser.id !== forward.from_id && loser.id !== forward.to_id) throw new EngramError("NOT_FOUND", message("store.entryNotFound", { id: input.loserId ?? input.firstId }));
|
|
14664
|
+
sqlSetStatus.run("forgotten", at, loser.id);
|
|
14665
|
+
sqlLog.run(at, "forget", loser.id, null);
|
|
14666
|
+
detachArchivedEvidence([loser.id]);
|
|
14667
|
+
return {
|
|
14668
|
+
dismissed: false,
|
|
14669
|
+
forgotten: rowToRecord(sqlGet.get(loser.id))
|
|
14670
|
+
};
|
|
14671
|
+
},
|
|
13684
14672
|
async linkEdge(from, to, type) {
|
|
13685
14673
|
sqlEdgeUpsert.run(from, to, type, Date.now());
|
|
13686
14674
|
},
|
|
@@ -13724,7 +14712,7 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13724
14712
|
},
|
|
13725
14713
|
async reinforce(id, note) {
|
|
13726
14714
|
if (sqlGet.get(id) === void 0) return void 0;
|
|
13727
|
-
|
|
14715
|
+
sqlReinforce.run(Date.now(), id);
|
|
13728
14716
|
sqlLog.run(Date.now(), "write-merge", id, note);
|
|
13729
14717
|
return rowToRecord(sqlGet.get(id));
|
|
13730
14718
|
},
|
|
@@ -13743,6 +14731,7 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13743
14731
|
sqlSetStatus.run("archived", at, oldId);
|
|
13744
14732
|
sqlEdgeUpsert.run(id, oldId, "supersedes", at);
|
|
13745
14733
|
}
|
|
14734
|
+
detachArchivedEvidence(oldIds);
|
|
13746
14735
|
});
|
|
13747
14736
|
return rowToRecord(sqlGet.get(id));
|
|
13748
14737
|
},
|
|
@@ -14021,8 +15010,7 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
14021
15010
|
}
|
|
14022
15011
|
};
|
|
14023
15012
|
}
|
|
14024
|
-
|
|
14025
|
-
//#region src/flywheel/distill.ts
|
|
15013
|
+
// src/flywheel/distill.ts
|
|
14026
15014
|
/**
|
|
14027
15015
|
* 知识飞轮的蒸馏步骤:把同主题的记忆簇由辅助 LLM 合并提炼为更高层的
|
|
14028
15016
|
* skill/fact,被合并条目归档并逐条建立 supersedes 链,新条目继承簇内
|
|
@@ -14197,8 +15185,7 @@ function mergeQueryResults(retrievals, limit, rrfConstant, minPerQuery) {
|
|
|
14197
15185
|
const reserved = new Set(retrievals.flatMap((retrieval) => retrieval.hits.slice(0, perQueryKeep).map((hit) => hit.record.id)));
|
|
14198
15186
|
return [...ranked.filter((entry) => reserved.has(entry.hit.record.id)), ...ranked.filter((entry) => !reserved.has(entry.hit.record.id))].slice(0, Math.max(0, limit)).map((entry) => entry.hit);
|
|
14199
15187
|
}
|
|
14200
|
-
|
|
14201
|
-
//#region src/retrieve/budget.ts
|
|
15188
|
+
// src/retrieve/budget.ts
|
|
14202
15189
|
/**
|
|
14203
15190
|
* 召回输出的字符预算:单条与总量双重截断,控制记忆正文占用的模型上下文
|
|
14204
15191
|
* (协议内定值,对齐同类记忆插件的单轮召回配额,非部署可变项)。
|
|
@@ -14408,8 +15395,7 @@ function assessEvidence(batch, request) {
|
|
|
14408
15395
|
forced: claimed !== sufficient || strategy !== requestedStrategy || nextStrategy !== strategy
|
|
14409
15396
|
};
|
|
14410
15397
|
}
|
|
14411
|
-
|
|
14412
|
-
//#region src/tools/create.ts
|
|
15398
|
+
// src/tools/create.ts
|
|
14413
15399
|
/**
|
|
14414
15400
|
* 23 个 engram_ 工具的定义与执行器。工具 schema 保持窄参数;
|
|
14415
15401
|
* scope 决定读写哪个分库;嵌入缺失时检索结果显式标记降级。
|
|
@@ -15920,27 +16906,25 @@ function createEngramTools(baseDeps) {
|
|
|
15920
16906
|
},
|
|
15921
16907
|
async execute(args) {
|
|
15922
16908
|
const input = args;
|
|
15923
|
-
const content = redactSecrets(sanitizeProtocolText(input.content));
|
|
15924
|
-
if (content.trim() === "") throw new Error(message("tool.updateContentEmptyAfterSanitize"));
|
|
15925
16909
|
const scope = scopeOf(input.scope, "project");
|
|
15926
16910
|
const store = await deps.openStore(scope);
|
|
15927
|
-
const
|
|
15928
|
-
|
|
16911
|
+
const imagery = placardOf(input.placard);
|
|
16912
|
+
const record = await updateMemory({
|
|
16913
|
+
store,
|
|
16914
|
+
embedder: deps.embedder
|
|
16915
|
+
}, {
|
|
16916
|
+
id: input.id,
|
|
16917
|
+
scope,
|
|
16918
|
+
content: input.content,
|
|
16919
|
+
...input.kind === void 0 ? {} : { kind: input.kind },
|
|
16920
|
+
...imagery === void 0 ? {} : { imagery }
|
|
16921
|
+
});
|
|
16922
|
+
if (record === void 0) throw new Error(message("tool.updateNotFound", {
|
|
15929
16923
|
id: input.id,
|
|
15930
16924
|
scope
|
|
15931
16925
|
}));
|
|
15932
|
-
const embedder = await deps.embedder;
|
|
15933
|
-
const embeddings = embedder === void 0 ? void 0 : await embedder.embed([content.trim()]);
|
|
15934
|
-
const imagery = placardOf(input.placard);
|
|
15935
16926
|
return {
|
|
15936
|
-
id:
|
|
15937
|
-
id: input.id,
|
|
15938
|
-
scope,
|
|
15939
|
-
kind: input.kind ?? old.kind,
|
|
15940
|
-
content,
|
|
15941
|
-
...embeddings === void 0 ? {} : { embedding: embeddings[0] },
|
|
15942
|
-
...imagery === void 0 ? {} : { imagery }
|
|
15943
|
-
})).id,
|
|
16927
|
+
id: record.id,
|
|
15944
16928
|
superseded: input.id
|
|
15945
16929
|
};
|
|
15946
16930
|
}
|
|
@@ -17270,8 +18254,7 @@ function renderTourNarrative(stops, query) {
|
|
|
17270
18254
|
});
|
|
17271
18255
|
return lines.join("\n");
|
|
17272
18256
|
}
|
|
17273
|
-
|
|
17274
|
-
//#region src/selection-rationale.ts
|
|
18257
|
+
// src/selection-rationale.ts
|
|
17275
18258
|
/**
|
|
17276
18259
|
* 注入归因:把画像中每条记忆按启发式打标签(recent / bright / corridor-hit / strong-evidence),
|
|
17277
18260
|
* 输出成 XML 注解块附加在画像文本前,让 agent 知道「为什么这条进了宫」。
|
|
@@ -17289,7 +18272,7 @@ function buildSelectionRationale(records) {
|
|
|
17289
18272
|
];
|
|
17290
18273
|
for (const record of records) {
|
|
17291
18274
|
const reasons = classifyRecord(record, now);
|
|
17292
|
-
lines.push(`- #${record.
|
|
18275
|
+
lines.push(`- #${record.memoryId.slice(0, 8)} [${record.kind}/${record.scope}] ${reasonsLabel(reasons)}:${record.content.slice(0, 40)}${record.content.length > 40 ? "…" : ""}`);
|
|
17293
18276
|
}
|
|
17294
18277
|
lines.push("", message("core.rationaleFooter"), "</engram_selection_rationale>");
|
|
17295
18278
|
return lines.join("\n");
|
|
@@ -17319,8 +18302,7 @@ function reasonsLabel(reasons) {
|
|
|
17319
18302
|
};
|
|
17320
18303
|
return reasons.map((r) => LABELS[r]).join(" / ");
|
|
17321
18304
|
}
|
|
17322
|
-
|
|
17323
|
-
//#region src/token.ts
|
|
18305
|
+
// src/token.ts
|
|
17324
18306
|
/**
|
|
17325
18307
|
* token 估算:CJK 感知的上下文预算口径。
|
|
17326
18308
|
*
|
|
@@ -17351,11 +18333,9 @@ function estimateTokens(text) {
|
|
|
17351
18333
|
else narrow += 1;
|
|
17352
18334
|
return Math.ceil(wide * WIDE_TOKENS_PER_CHAR + narrow / 4);
|
|
17353
18335
|
}
|
|
17354
|
-
|
|
17355
|
-
|
|
17356
|
-
|
|
17357
|
-
//#endregion
|
|
17358
|
-
//#region src/index.ts
|
|
18336
|
+
// package.json
|
|
18337
|
+
var version = "0.12.0";
|
|
18338
|
+
// src/index.ts
|
|
17359
18339
|
/**
|
|
17360
18340
|
* dsh-engram:DeepSeek Harness 跨会话长期记忆插件(host 半)。
|
|
17361
18341
|
* 注册 23 个 engram_ 工具、会话开始注入画像(curated block 优先于派生画像)、
|
|
@@ -17515,6 +18495,18 @@ async function compressProfileOverflow(ctx, agent, routeOverride, overflow, sign
|
|
|
17515
18495
|
return;
|
|
17516
18496
|
}
|
|
17517
18497
|
}
|
|
18498
|
+
function preStepSession(state, sessionId) {
|
|
18499
|
+
const existing = state.sessions.get(sessionId);
|
|
18500
|
+
if (existing !== void 0) return existing;
|
|
18501
|
+
const created = {
|
|
18502
|
+
lastProfileHash: null,
|
|
18503
|
+
lastProfileCompactions: null,
|
|
18504
|
+
lastAssessReminder: null,
|
|
18505
|
+
route: void 0
|
|
18506
|
+
};
|
|
18507
|
+
state.sessions.set(sessionId, created);
|
|
18508
|
+
return created;
|
|
18509
|
+
}
|
|
17518
18510
|
/**
|
|
17519
18511
|
* agent/pre-step waterfall:每轮第一步注入画像(内容与上次相同则跳过重复注入);
|
|
17520
18512
|
* 同时 fire-and-forget 触发上一轮的自动摄取(不阻塞请求);进程内首次第一步
|
|
@@ -17524,11 +18516,16 @@ async function compressProfileOverflow(ctx, agent, routeOverride, overflow, sign
|
|
|
17524
18516
|
async function preStep(ctx, openStore, openStoreForProjectCwd, resolved, embedder, state, logRequest, onDialogueLanguage, { agent, step, turn, signal }, next) {
|
|
17525
18517
|
const decision = await next();
|
|
17526
18518
|
if (decision.kind === "reject") return decision;
|
|
18519
|
+
const sessionId = String(agent.session.id);
|
|
18520
|
+
const sessionState = preStepSession(state, sessionId);
|
|
17527
18521
|
const observed = dominantLanguage(userTexts(agent.session.snapshotEvents()));
|
|
17528
18522
|
if (observed !== void 0) onDialogueLanguage(observed.language);
|
|
17529
18523
|
if (step === 1) {
|
|
17530
18524
|
const currentRoute = resolved.routeOverride ?? routeFromEvents(agent.session.snapshotEvents());
|
|
17531
|
-
if (currentRoute !== void 0)
|
|
18525
|
+
if (currentRoute !== void 0) {
|
|
18526
|
+
sessionState.route = currentRoute;
|
|
18527
|
+
state.route = currentRoute;
|
|
18528
|
+
}
|
|
17532
18529
|
}
|
|
17533
18530
|
const mode = resolved.ingest;
|
|
17534
18531
|
const routing = ingestWriteRouting(sessionCwd(agent.session), openStoreForProjectCwd, openStore);
|
|
@@ -17542,7 +18539,7 @@ async function preStep(ctx, openStore, openStoreForProjectCwd, resolved, embedde
|
|
|
17542
18539
|
embedder,
|
|
17543
18540
|
mode,
|
|
17544
18541
|
routeOverride: resolved.routeOverride,
|
|
17545
|
-
...resolveJevField(ctx, resolved.jev, resolved.dbDir, () =>
|
|
18542
|
+
...resolveJevField(ctx, resolved.jev, resolved.dbDir, () => sessionState.route?.provider),
|
|
17546
18543
|
call: (params) => streamText(ctx, {
|
|
17547
18544
|
...params,
|
|
17548
18545
|
sessionId: agent.session.id
|
|
@@ -17563,7 +18560,7 @@ async function preStep(ctx, openStore, openStoreForProjectCwd, resolved, embedde
|
|
|
17563
18560
|
embedder,
|
|
17564
18561
|
mode,
|
|
17565
18562
|
routeOverride: resolved.routeOverride,
|
|
17566
|
-
...resolveJevField(ctx, resolved.jev, resolved.dbDir, () =>
|
|
18563
|
+
...resolveJevField(ctx, resolved.jev, resolved.dbDir, () => sessionState.route?.provider),
|
|
17567
18564
|
call: (params) => streamText(ctx, {
|
|
17568
18565
|
...params,
|
|
17569
18566
|
sessionId: agent.session.id
|
|
@@ -17575,11 +18572,11 @@ async function preStep(ctx, openStore, openStoreForProjectCwd, resolved, embedde
|
|
|
17575
18572
|
});
|
|
17576
18573
|
}
|
|
17577
18574
|
if (step !== 1 && resolved.assessReminder) {
|
|
17578
|
-
const sessionId = String(agent.session.id);
|
|
17579
18575
|
const pending = evidenceBatches.pendingBatches(sessionId).length;
|
|
17580
18576
|
const reminder = buildAssessReminder(pending, evidenceBatches.insufficientStreak(sessionId));
|
|
17581
|
-
if (reminder
|
|
17582
|
-
|
|
18577
|
+
if (reminder === void 0) sessionState.lastAssessReminder = null;
|
|
18578
|
+
if (reminder !== void 0 && reminder !== sessionState.lastAssessReminder) {
|
|
18579
|
+
sessionState.lastAssessReminder = reminder;
|
|
17583
18580
|
return {
|
|
17584
18581
|
...decision,
|
|
17585
18582
|
messages: [...decision.messages, createUserMessage({
|
|
@@ -17599,9 +18596,10 @@ async function preStep(ctx, openStore, openStoreForProjectCwd, resolved, embedde
|
|
|
17599
18596
|
};
|
|
17600
18597
|
}
|
|
17601
18598
|
}
|
|
18599
|
+
if (!resolved.injectProfile) return decision;
|
|
17602
18600
|
const compactionCount = agent.session.snapshotEvents().filter((event) => event.type === "compaction/end").length;
|
|
17603
|
-
const compacted =
|
|
17604
|
-
if (
|
|
18601
|
+
const compacted = sessionState.lastProfileCompactions !== null && compactionCount > sessionState.lastProfileCompactions;
|
|
18602
|
+
if (sessionState.lastProfileCompactions === null) sessionState.lastProfileCompactions = compactionCount;
|
|
17605
18603
|
if (step !== 1 && !compacted) return decision;
|
|
17606
18604
|
const store = await openStore("user");
|
|
17607
18605
|
const curated = await store.getProfileBlock("user");
|
|
@@ -17646,13 +18644,24 @@ async function preStep(ctx, openStore, openStoreForProjectCwd, resolved, embedde
|
|
|
17646
18644
|
});
|
|
17647
18645
|
const textWithRationale = wrapWithRationale(text, top) + dueLine;
|
|
17648
18646
|
const hash = createHash("sha256").update(`${parts.curated ?? ""}\n${textWithRationale}`).digest("hex");
|
|
17649
|
-
if (!compacted &&
|
|
17650
|
-
|
|
17651
|
-
|
|
17652
|
-
|
|
17653
|
-
const requestText = currentUserRequestText(decision.messages);
|
|
17654
|
-
const memoryPacket = renderMemoryPacket(text, "turn_start", requestText);
|
|
18647
|
+
if (!compacted && hash === sessionState.lastProfileHash) return decision;
|
|
18648
|
+
sessionState.lastProfileHash = hash;
|
|
18649
|
+
sessionState.lastProfileCompactions = compactionCount;
|
|
18650
|
+
const memoryPacket = renderMemoryPacket(textWithRationale, "turn_start", currentUserRequestText(decision.messages));
|
|
17655
18651
|
const packet = parts.curated === void 0 ? memoryPacket : `${renderProfilePacket(parts.curated)}\n\n${memoryPacket}`;
|
|
18652
|
+
const packetHash = createHash("sha256").update(packet).digest("hex");
|
|
18653
|
+
try {
|
|
18654
|
+
await store.recordInjection({
|
|
18655
|
+
sessionId,
|
|
18656
|
+
packetHash,
|
|
18657
|
+
packet,
|
|
18658
|
+
memoryIds: top.map((record) => record.memoryId),
|
|
18659
|
+
hasCurated: parts.curated !== void 0,
|
|
18660
|
+
compactionCount
|
|
18661
|
+
});
|
|
18662
|
+
} catch (error) {
|
|
18663
|
+
console.warn(message("core.warnInjectionSnapshotFailed"), error);
|
|
18664
|
+
}
|
|
17656
18665
|
return {
|
|
17657
18666
|
...decision,
|
|
17658
18667
|
messages: [...decision.messages, createUserMessage({
|
|
@@ -18066,7 +19075,11 @@ async function apply(ctx, config = {}) {
|
|
|
18066
19075
|
}));
|
|
18067
19076
|
stores.clear();
|
|
18068
19077
|
};
|
|
18069
|
-
|
|
19078
|
+
let stopReflectJobs;
|
|
19079
|
+
ctx.effect(() => async () => {
|
|
19080
|
+
await stopReflectJobs?.();
|
|
19081
|
+
await closeStores();
|
|
19082
|
+
}, "dsh-engram: close stores");
|
|
18070
19083
|
/** cwd → 分库文件名(历史回填会对每个历史 cwd 解析一次,避免重复读 git 元数据)。 */
|
|
18071
19084
|
const cwdDbNames = /* @__PURE__ */ new Map();
|
|
18072
19085
|
/**
|
|
@@ -18121,10 +19134,7 @@ async function apply(ctx, config = {}) {
|
|
|
18121
19134
|
};
|
|
18122
19135
|
const preStepState = {
|
|
18123
19136
|
pendingReplayed: false,
|
|
18124
|
-
|
|
18125
|
-
lastProfileHash: null,
|
|
18126
|
-
lastProfileCompactions: null,
|
|
18127
|
-
lastAssessReminder: null,
|
|
19137
|
+
sessions: /* @__PURE__ */ new Map(),
|
|
18128
19138
|
route: void 0
|
|
18129
19139
|
};
|
|
18130
19140
|
/** 会话持久化服务(可选;缺席时历史回填不可用)。 */
|
|
@@ -18761,6 +19771,7 @@ async function apply(ctx, config = {}) {
|
|
|
18761
19771
|
dbDir: resolved.dbDir,
|
|
18762
19772
|
pluginVersion: VERSION,
|
|
18763
19773
|
language: resolved.language,
|
|
19774
|
+
panelAccess: resolved.panelAccess,
|
|
18764
19775
|
registry: () => registryView,
|
|
18765
19776
|
dictionaryLanguages: languagesWithDictionary,
|
|
18766
19777
|
baseStates,
|
|
@@ -18806,9 +19817,11 @@ async function apply(ctx, config = {}) {
|
|
|
18806
19817
|
}
|
|
18807
19818
|
});
|
|
18808
19819
|
});
|
|
18809
|
-
if (resolved.injectProfile || resolved.ingest !== "off") ctx.on("agent/pre-step", (payload, next) => preStep(ctx, openStore, openStoreForProjectCwd, resolved, embedder, preStepState, logIngestRequest, observeDialogueLanguage, payload, next), { prepend: true });
|
|
19820
|
+
if (resolved.injectProfile || resolved.ingest !== "off" || resolved.assessReminder) ctx.on("agent/pre-step", (payload, next) => preStep(ctx, openStore, openStoreForProjectCwd, resolved, embedder, preStepState, logIngestRequest, observeDialogueLanguage, payload, next), { prepend: true });
|
|
18810
19821
|
ctx.on("session/disposed", (session) => {
|
|
18811
|
-
|
|
19822
|
+
const sessionId = String(session.id);
|
|
19823
|
+
evidenceBatches.clear(sessionId);
|
|
19824
|
+
preStepState.sessions.delete(sessionId);
|
|
18812
19825
|
});
|
|
18813
19826
|
if (resolved.ingest !== "off") ctx.on("session/disposed", (session) => {
|
|
18814
19827
|
const mode = resolved.ingest;
|
|
@@ -18854,58 +19867,71 @@ async function apply(ctx, config = {}) {
|
|
|
18854
19867
|
console.warn(message("core.warnDisposeFinalFailed"), error);
|
|
18855
19868
|
});
|
|
18856
19869
|
});
|
|
18857
|
-
if (resolved.reflect
|
|
18858
|
-
const
|
|
19870
|
+
if (resolved.reflect === "suggest") ctx.on("session/disposed", (session) => {
|
|
19871
|
+
const sessionId = String(session.id);
|
|
19872
|
+
const cwd = sessionCwd(session);
|
|
19873
|
+
const targets = [{
|
|
19874
|
+
scope: "user",
|
|
19875
|
+
open: () => openStore("user")
|
|
19876
|
+
}];
|
|
19877
|
+
if (cwd !== void 0 && existsSync(join(resolved.dbDir, dbNameForCwd(cwd)))) targets.push({
|
|
19878
|
+
scope: "project",
|
|
19879
|
+
open: () => openStoreForProjectCwd(cwd)
|
|
19880
|
+
});
|
|
19881
|
+
(async () => {
|
|
19882
|
+
for (const target of targets) try {
|
|
19883
|
+
const store = await target.open();
|
|
19884
|
+
const detail = JSON.stringify({
|
|
19885
|
+
scope: target.scope,
|
|
19886
|
+
sessionId
|
|
19887
|
+
});
|
|
19888
|
+
if (!await store.hasAudit("reflect-pending", detail)) await store.audit("reflect-pending", "AUX", detail);
|
|
19889
|
+
} catch (error) {
|
|
19890
|
+
console.warn(message("core.warnReflectFailed", { scope: target.scope }), error);
|
|
19891
|
+
}
|
|
19892
|
+
})();
|
|
19893
|
+
});
|
|
19894
|
+
if (resolved.reflect === "auto") {
|
|
19895
|
+
const reflectJobs = await startAutoReflectWorker({
|
|
19896
|
+
dbDir: resolved.dbDir,
|
|
19897
|
+
dbNameForCwd,
|
|
19898
|
+
openStore,
|
|
19899
|
+
openProjectStore: openStoreForProjectCwd,
|
|
19900
|
+
embedder: () => embedderAttempt(),
|
|
19901
|
+
call: (sessionId, params) => streamText(ctx, {
|
|
19902
|
+
...params,
|
|
19903
|
+
sessionId
|
|
19904
|
+
})
|
|
19905
|
+
});
|
|
19906
|
+
stopReflectJobs = reflectJobs.stop;
|
|
18859
19907
|
ctx.on("session/disposed", (session) => {
|
|
18860
19908
|
const events = session.snapshotEvents();
|
|
18861
|
-
const sessionId = String(session.id);
|
|
18862
|
-
const cwd = sessionCwd(session);
|
|
18863
19909
|
const route = resolved.routeOverride ?? routeFromEvents(events);
|
|
18864
|
-
|
|
18865
|
-
|
|
18866
|
-
|
|
18867
|
-
|
|
18868
|
-
|
|
18869
|
-
|
|
18870
|
-
|
|
19910
|
+
if (route === void 0) return;
|
|
19911
|
+
const eventSeq = events.reduce((max, event) => typeof event.seq === "number" && Number.isInteger(event.seq) && event.seq > max ? event.seq : max, 0);
|
|
19912
|
+
const sessionId = String(session.id);
|
|
19913
|
+
try {
|
|
19914
|
+
reflectJobs.enqueue({
|
|
19915
|
+
sessionId,
|
|
19916
|
+
scope: "user",
|
|
19917
|
+
route,
|
|
19918
|
+
eventSeq
|
|
19919
|
+
});
|
|
19920
|
+
const cwd = sessionCwd(session);
|
|
19921
|
+
if (cwd !== void 0 && existsSync(join(resolved.dbDir, dbNameForCwd(cwd)))) reflectJobs.enqueue({
|
|
19922
|
+
sessionId,
|
|
19923
|
+
scope: "project",
|
|
19924
|
+
cwd,
|
|
19925
|
+
route,
|
|
19926
|
+
eventSeq
|
|
19927
|
+
});
|
|
19928
|
+
} catch (error) {
|
|
19929
|
+
console.warn(message("core.warnReflectFailed", { scope: "enqueue" }), error);
|
|
19930
|
+
return;
|
|
19931
|
+
}
|
|
19932
|
+
reflectJobs.pump().catch((error) => {
|
|
19933
|
+
console.warn(message("core.warnReflectFailed", { scope: "scheduler" }), error);
|
|
18871
19934
|
});
|
|
18872
|
-
(async () => {
|
|
18873
|
-
for (const target of targets) try {
|
|
18874
|
-
const store = await target.open();
|
|
18875
|
-
if (resolved.reflect === "suggest") {
|
|
18876
|
-
const detail = JSON.stringify({
|
|
18877
|
-
scope: target.scope,
|
|
18878
|
-
sessionId
|
|
18879
|
-
});
|
|
18880
|
-
if (!await store.hasAudit("reflect-pending", detail)) await store.audit("reflect-pending", "AUX", detail);
|
|
18881
|
-
continue;
|
|
18882
|
-
}
|
|
18883
|
-
if (route === void 0) continue;
|
|
18884
|
-
const outcome = await reflectObservations({
|
|
18885
|
-
store,
|
|
18886
|
-
embedder: await embedderAttempt(),
|
|
18887
|
-
scope: target.scope,
|
|
18888
|
-
call: (params) => streamText(ctx, {
|
|
18889
|
-
...params,
|
|
18890
|
-
sessionId: session.id
|
|
18891
|
-
}),
|
|
18892
|
-
logRequest: (data) => {
|
|
18893
|
-
store.audit("reflect-request", "AUX", JSON.stringify(data)).catch(() => {});
|
|
18894
|
-
},
|
|
18895
|
-
route,
|
|
18896
|
-
signal: AbortSignal.timeout(REFLECT_TIMEOUT_MS)
|
|
18897
|
-
});
|
|
18898
|
-
if (outcome.formed + outcome.refined + outcome.confirmed + outcome.refuted > 0) console.log(message("core.logReflectDone", {
|
|
18899
|
-
scope: target.scope,
|
|
18900
|
-
formed: outcome.formed,
|
|
18901
|
-
refined: outcome.refined,
|
|
18902
|
-
confirmed: outcome.confirmed,
|
|
18903
|
-
refuted: outcome.refuted
|
|
18904
|
-
}));
|
|
18905
|
-
} catch (error) {
|
|
18906
|
-
console.warn(message("core.warnReflectFailed", { scope: target.scope }), error);
|
|
18907
|
-
}
|
|
18908
|
-
})();
|
|
18909
19935
|
});
|
|
18910
19936
|
}
|
|
18911
19937
|
const OP_LOG_RETENTION_DAYS = 366;
|
|
@@ -18934,6 +19960,7 @@ async function apply(ctx, config = {}) {
|
|
|
18934
19960
|
}));
|
|
18935
19961
|
try {
|
|
18936
19962
|
await store.pruneOps(pruneBefore, LOG_KEEP_OPS);
|
|
19963
|
+
await store.pruneInjections(pruneBefore);
|
|
18937
19964
|
} catch (error) {
|
|
18938
19965
|
console.warn(message("core.warnDecayPeriodicFailed"), error);
|
|
18939
19966
|
}
|
|
@@ -18978,5 +20005,4 @@ async function apply(ctx, config = {}) {
|
|
|
18978
20005
|
};
|
|
18979
20006
|
}, "dsh-engram: consolidation timer");
|
|
18980
20007
|
}
|
|
18981
|
-
//#endregion
|
|
18982
20008
|
export { CURATED_HEADER, Config, DEFAULT_ITEM_BUDGET, VERSION, apply, inject, name, renderProfile, renderProfileDetailed, renderProfileParts };
|