@kenz1117/dsh-engram 0.11.6 → 0.13.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 +54 -1
- package/README.md +9 -12
- package/i18n/ru.txt +2 -0
- package/lib/client.js +3 -3
- package/lib/client.js.map +1 -1
- package/lib/index.js +1322 -171
- package/package.json +1 -1
- package/registry/schema.json +5 -1
- package/scripts/check-messages.mjs +13 -2
package/lib/index.js
CHANGED
|
@@ -6,7 +6,7 @@ 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";
|
|
@@ -229,6 +229,7 @@ const zh$5 = {
|
|
|
229
229
|
"core.warnIngestPreviousFailed": "[dsh-engram] 本轮自动摄取失败(已跳过,不影响对话):",
|
|
230
230
|
"core.warnHistoryBackfillFailed": "[dsh-engram] 历史回填失败:",
|
|
231
231
|
"core.warnDisposeFinalFailed": "[dsh-engram] 会话结束的收尾处理异常(不影响对话):",
|
|
232
|
+
"core.warnInjectionSnapshotFailed": "[dsh-engram] 注入快照落库失败(不影响对话):",
|
|
232
233
|
"core.warnReflectFailed": "[dsh-engram] 会话结束的信念巩固异常({scope},不影响对话):",
|
|
233
234
|
"core.warnReflectBatchDropped": "[dsh-engram] 信念巩固丢弃 {count} 条候选(输出预算/解析失败;未被巩固、下次巩固继续取材)",
|
|
234
235
|
"core.warnDecayStartupFailed": "[dsh-engram] 启动衰减调度失败(跳过):",
|
|
@@ -286,6 +287,7 @@ const en$5 = {
|
|
|
286
287
|
"core.warnIngestPreviousFailed": "[dsh-engram] Automatic ingest of this turn failed (skipped, conversation unaffected):",
|
|
287
288
|
"core.warnHistoryBackfillFailed": "[dsh-engram] History backfill failed:",
|
|
288
289
|
"core.warnDisposeFinalFailed": "[dsh-engram] Session-end finalisation threw (conversation unaffected):",
|
|
290
|
+
"core.warnInjectionSnapshotFailed": "[dsh-engram] Could not persist the injection snapshot (conversation unaffected):",
|
|
289
291
|
"core.warnReflectFailed": "[dsh-engram] Belief consolidation at session end threw ({scope}, conversation unaffected):",
|
|
290
292
|
"core.warnReflectBatchDropped": "[dsh-engram] Belief consolidation dropped {count} candidates (output budget/parse failure; not consolidated, will be picked up next consolidation)",
|
|
291
293
|
"core.warnDecayStartupFailed": "[dsh-engram] Startup decay scheduling failed (skipped):",
|
|
@@ -435,6 +437,7 @@ const zh$3 = {
|
|
|
435
437
|
"misc.jevProviderUnresolved": "Jev:没有提供商——面板、插件设置和会话路由都没有指定",
|
|
436
438
|
"misc.jevModelNotPicked": "Jev:提供商「{provider}」的 DSH 设置里没有 JEV 模型,请手动指定模型",
|
|
437
439
|
"misc.jevEndpointMustBeHttp": "invalid: jev.endpoint 必须是 http(s) URL",
|
|
440
|
+
"misc.jevEndpointOriginMismatch": "Jev:endpoint 必须与提供商「{provider}」的 baseURL 同源;拒绝把宿主凭据发往其他服务",
|
|
438
441
|
"misc.jevModelMustNotBeEmpty": "invalid: jev.model 不能为空",
|
|
439
442
|
"misc.jevTimeoutMsMustBeInteger": "invalid: jev.timeoutMs 必须是 1000-60000 的整数毫秒",
|
|
440
443
|
"tool.languageGuideDescription": "如何把新语言引入记忆宫殿:返回说明文本(文件 docs/agent-language-guide.ru.md,目前只有俄文草稿)。用户的语言不在 zh/en 之内时使用:先读说明,再与用户一起完成登记语言、词典和切换。",
|
|
@@ -489,6 +492,7 @@ const en$3 = {
|
|
|
489
492
|
"misc.jevProviderUnresolved": "Jev: no provider — neither the panel, nor the plugin settings, nor the session route names one",
|
|
490
493
|
"misc.jevModelNotPicked": "Jev: provider \"{provider}\" has no JEV model in its DSH settings; name the model explicitly",
|
|
491
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",
|
|
492
496
|
"misc.jevModelMustNotBeEmpty": "invalid: jev.model must not be empty",
|
|
493
497
|
"misc.jevTimeoutMsMustBeInteger": "invalid: jev.timeoutMs must be an integer number of milliseconds between 1000 and 60000",
|
|
494
498
|
"misc.warnDictionaryProblems": "[dsh-engram] The translation dictionary skipped {count} problem line(s); those texts stay English: {sample}",
|
|
@@ -2094,8 +2098,6 @@ const en = {
|
|
|
2094
2098
|
relContradicts: "Contradicts",
|
|
2095
2099
|
relRelated: "Adjacent",
|
|
2096
2100
|
tabToday: "Today",
|
|
2097
|
-
tabLibrary: "Palace",
|
|
2098
|
-
tabCorridor: "Corridor",
|
|
2099
2101
|
tabLog: "Log",
|
|
2100
2102
|
roomsTitle: "Room directory",
|
|
2101
2103
|
roomsHint: "A new room opens once 9 slots fill",
|
|
@@ -2312,7 +2314,6 @@ const en = {
|
|
|
2312
2314
|
adBillingDesc: "Real usage · history ledger · peak/valley pricing · subscription quota",
|
|
2313
2315
|
adRainbowName: "RainbowSpeak",
|
|
2314
2316
|
adRainbowDesc: "A flowing rainbow border + Xiao-Hong the window pet",
|
|
2315
|
-
tabEpisodes: "Episodes",
|
|
2316
2317
|
episodeSince: "From date",
|
|
2317
2318
|
episodeUntil: "To date",
|
|
2318
2319
|
episodeSessionId: "Session id (optional)",
|
|
@@ -2327,8 +2328,6 @@ const en = {
|
|
|
2327
2328
|
episodeAroundMissing: "This memory is no longer in the store (archived or deleted), so there is no anchor for the nearby view.",
|
|
2328
2329
|
episodeAroundEmpty: "No other episodes within the proximity window",
|
|
2329
2330
|
episodeClose: "Collapse",
|
|
2330
|
-
tabEntities: "Entities",
|
|
2331
|
-
tabBeliefs: "Beliefs",
|
|
2332
2331
|
beliefStatusAll: "All",
|
|
2333
2332
|
beliefStatusActive: "Held",
|
|
2334
2333
|
beliefStatusStale: "Stale",
|
|
@@ -2414,7 +2413,6 @@ const en = {
|
|
|
2414
2413
|
heroDeltaAnswered: "{n} answered",
|
|
2415
2414
|
heroDeltaUnanswered: "not answered today",
|
|
2416
2415
|
healthLabel: "Palace health",
|
|
2417
|
-
tabOps: "Ops",
|
|
2418
2416
|
backfillLabelCandidates: "Candidate sessions",
|
|
2419
2417
|
backfillLabelPending: "Pending turns",
|
|
2420
2418
|
backfillLabelSkipped: "Already captured",
|
|
@@ -2428,7 +2426,6 @@ const en = {
|
|
|
2428
2426
|
pageHeaderBeliefsSubtitle: "Consolidated beliefs with evidence chain, click \"n evidence\" for read-only recall",
|
|
2429
2427
|
pageHeaderLogSubtitle: "Merged operation log across both DBs, filterable by category",
|
|
2430
2428
|
pageHeaderBackfillSubtitle: "Distil historical sessions into the palace, estimate first then run, resumable",
|
|
2431
|
-
pageHeaderOpsSubtitle: "Backfill, languages and models, arbitration: day-to-day upkeep of the palace",
|
|
2432
2429
|
pageHeaderJevSubtitle: "Jev system-one adjudication, config overrides and recent decisions log",
|
|
2433
2430
|
heatmapTitle: "Last 26 weeks activity",
|
|
2434
2431
|
heatmapTotal: "writes",
|
|
@@ -2447,7 +2444,88 @@ const en = {
|
|
|
2447
2444
|
corridorIndexRooms: "{n} rooms",
|
|
2448
2445
|
skipEmptyAnswer: "empty output (empty after retry)",
|
|
2449
2446
|
skipAllCandidatesFailed: "every candidate failed to write (kept for replay)",
|
|
2450
|
-
|
|
2447
|
+
pageHeaderReplaySubtitle: "Replay exact injected packets, selected memories, and their provenance",
|
|
2448
|
+
replayFilterLabel: "Session",
|
|
2449
|
+
replayFilterPlaceholder: "Filter by sessionId (optional)",
|
|
2450
|
+
replayCount: "{n} injections",
|
|
2451
|
+
replayEmpty: "No injection snapshots yet; enable profile injection to record them",
|
|
2452
|
+
replayFailed: "Failed to load injection replay",
|
|
2453
|
+
replayOpen: "View final packet",
|
|
2454
|
+
replayClose: "Hide final packet",
|
|
2455
|
+
replayPacketTitle: "Final packet actually received by the model",
|
|
2456
|
+
replayMetaTitle: "Snapshot metadata",
|
|
2457
|
+
replayExactNote: "This text is byte-for-byte the packet used for the hash, audit trail, and model request.",
|
|
2458
|
+
replaySession: "Session",
|
|
2459
|
+
replayHash: "SHA-256",
|
|
2460
|
+
replayMemories: "Selected memories",
|
|
2461
|
+
replayCurated: "Curated profile",
|
|
2462
|
+
replayCompactions: "Compactions",
|
|
2463
|
+
replaySize: "Packet size",
|
|
2464
|
+
navWorkfaces: "Workfaces",
|
|
2465
|
+
identityStable: "Stable ID",
|
|
2466
|
+
identityRevision: "Current revision",
|
|
2467
|
+
identityRevisionNote: "Full revision chain of the same logical memory (newest first)",
|
|
2468
|
+
pageHeaderRecallSubtitle: "Live recall bench: hit channel, score and stable-identity provenance",
|
|
2469
|
+
pageHeaderGovernanceSubtitle: "Contradiction and belief desk: full context before any action",
|
|
2470
|
+
workfaceToday: "Today",
|
|
2471
|
+
workfaceRecall: "Recall",
|
|
2472
|
+
workfaceMemory: "Memory",
|
|
2473
|
+
workfaceGovernance: "Governance",
|
|
2474
|
+
workfaceReplay: "Replay",
|
|
2475
|
+
workfaceSystem: "System",
|
|
2476
|
+
pageHeaderSystemSubtitle: "Runtime, storage, models and dictionaries, history backfill, Jev and the journal.",
|
|
2477
|
+
memoryRecords: "Records",
|
|
2478
|
+
memoryTimeline: "Timeline",
|
|
2479
|
+
memoryEntities: "Entities",
|
|
2480
|
+
memoryAtlas: "Atlas",
|
|
2481
|
+
governanceConflicts: "Conflicts",
|
|
2482
|
+
governanceBeliefs: "Beliefs",
|
|
2483
|
+
systemRuntime: "Runtime",
|
|
2484
|
+
systemStorage: "Storage",
|
|
2485
|
+
systemModels: "Models & language",
|
|
2486
|
+
pageHeaderRuntimeSubtitle: "Plugin and panel versions, the durable job queue, embedding model status.",
|
|
2487
|
+
pageHeaderStorageSubtitle: "Size of each memory store and what the journal costs.",
|
|
2488
|
+
pageHeaderModelsSubtitle: "Memory language, embedding models, panel dictionaries and history backfill.",
|
|
2489
|
+
systemVersionPlugin: "Plugin version",
|
|
2490
|
+
systemVersionClient: "Panel version",
|
|
2491
|
+
systemVersionOk: "Plugin and panel versions match.",
|
|
2492
|
+
systemVersionDiff: "Plugin and panel versions differ — restart the plugin process, then reopen the panel.",
|
|
2493
|
+
systemJobsTitle: "Durable job queue",
|
|
2494
|
+
systemJobsUnavailable: "Job queue unavailable (this backend does not run durable jobs).",
|
|
2495
|
+
systemJobsQueued: "Queued",
|
|
2496
|
+
systemJobsRunning: "Running",
|
|
2497
|
+
systemJobsDone: "Done",
|
|
2498
|
+
systemJobsDead: "Dead-lettered",
|
|
2499
|
+
systemJobAttempts: "{n} attempts",
|
|
2500
|
+
systemJobError: "Last error",
|
|
2501
|
+
systemJobEmpty: "The queue is empty: nothing pending and nothing failed.",
|
|
2502
|
+
systemStorageTotal: "Total",
|
|
2503
|
+
systemStorageActive: "Active",
|
|
2504
|
+
systemStorageArchived: "Archived",
|
|
2505
|
+
systemStorageForgotten: "Forgotten",
|
|
2506
|
+
systemStorageOpLog: "Journal rows",
|
|
2507
|
+
systemStorageLogSize: "Journal size",
|
|
2508
|
+
systemStorageLogPath: "Journal path",
|
|
2509
|
+
systemStorageFailed: "Could not read storage information.",
|
|
2510
|
+
systemModelStatus: "Embedding model",
|
|
2511
|
+
systemModelNone: "No embedding model registered yet.",
|
|
2512
|
+
benchInspect: "Inspect placard",
|
|
2513
|
+
kpiExposures: "Search exposures",
|
|
2514
|
+
attentionEmpty: "Nothing needs attention",
|
|
2515
|
+
attentionFailed: "Failed to load attention facts",
|
|
2516
|
+
attentionGovernance: "{n} contradictions pending",
|
|
2517
|
+
attentionJobsDead: "{n} jobs dead-lettered",
|
|
2518
|
+
attentionJobsQueued: "{n} jobs queued",
|
|
2519
|
+
attentionJobsUnavailable: "Job queue not running",
|
|
2520
|
+
governanceTitle: "Contradiction governance",
|
|
2521
|
+
governanceHint: "Only contradictions with both sides active are shown; reclassifying keeps both; closing archives the selected side",
|
|
2522
|
+
governanceCount: "{n} pairs pending",
|
|
2523
|
+
governanceEmpty: "No contradictions pending",
|
|
2524
|
+
governanceFailed: "Failed to load governance queue",
|
|
2525
|
+
governanceDismiss: "Reclassify as related",
|
|
2526
|
+
governanceForget: "Close this memory",
|
|
2527
|
+
governanceActionFailed: "Action failed",
|
|
2528
|
+
governanceStableId: "Stable ID",
|
|
2451
2529
|
spiralAriaLabel: "memory spiral view",
|
|
2452
2530
|
spiralCenterLabel: "Now",
|
|
2453
2531
|
spiralSideTitle: "Time scale",
|
|
@@ -2670,8 +2748,6 @@ const ru = {
|
|
|
2670
2748
|
relContradicts: "Противоречит",
|
|
2671
2749
|
relRelated: "Смежное",
|
|
2672
2750
|
tabToday: "Сегодня",
|
|
2673
|
-
tabLibrary: "Дворец",
|
|
2674
|
-
tabCorridor: "Коридор",
|
|
2675
2751
|
tabLog: "Журнал",
|
|
2676
2752
|
roomsTitle: "Каталог комнат",
|
|
2677
2753
|
roomsHint: "Новая комната открывается, когда заполняются 9 мест",
|
|
@@ -2888,7 +2964,6 @@ const ru = {
|
|
|
2888
2964
|
adBillingDesc: "Реальное использование · история · тарифы пик/долина · квоты подписки",
|
|
2889
2965
|
adRainbowName: "RainbowSpeak",
|
|
2890
2966
|
adRainbowDesc: "Переливающаяся радужная рамка + питомец «Сяохун»",
|
|
2891
|
-
tabEpisodes: "Эпизоды",
|
|
2892
2967
|
episodeSince: "С даты",
|
|
2893
2968
|
episodeUntil: "По дату",
|
|
2894
2969
|
episodeSessionId: "ID сессии (необязательно)",
|
|
@@ -2903,8 +2978,6 @@ const ru = {
|
|
|
2903
2978
|
episodeAroundMissing: "Этого воспоминания больше нет в базе (архивировано или удалено) — точку опоры для соседей взять неоткуда.",
|
|
2904
2979
|
episodeAroundEmpty: "В окне близости других эпизодов нет",
|
|
2905
2980
|
episodeClose: "Свернуть",
|
|
2906
|
-
tabEntities: "Сущности",
|
|
2907
|
-
tabBeliefs: "Убеждения",
|
|
2908
2981
|
beliefStatusAll: "Все",
|
|
2909
2982
|
beliefStatusActive: "Держится",
|
|
2910
2983
|
beliefStatusStale: "Устарело",
|
|
@@ -2990,7 +3063,6 @@ const ru = {
|
|
|
2990
3063
|
heroDeltaAnswered: "{n} с ответом",
|
|
2991
3064
|
heroDeltaUnanswered: "сегодня без ответа",
|
|
2992
3065
|
healthLabel: "Здоровье дворца",
|
|
2993
|
-
tabOps: "Обслуживание",
|
|
2994
3066
|
backfillLabelCandidates: "Сессии-кандидаты",
|
|
2995
3067
|
backfillLabelPending: "Ходов в очереди",
|
|
2996
3068
|
backfillLabelSkipped: "Уже извлечено",
|
|
@@ -3004,7 +3076,6 @@ const ru = {
|
|
|
3004
3076
|
pageHeaderBeliefsSubtitle: "Закреплённые убеждения с цепочкой доказательств; щелчок по числу доказательств открывает чтение",
|
|
3005
3077
|
pageHeaderLogSubtitle: "Полный журнал операций обеих баз с фильтром по категориям",
|
|
3006
3078
|
pageHeaderBackfillSubtitle: "История сессий — по ходам во дворец: сначала оценка, потом запуск, с паузой и продолжением",
|
|
3007
|
-
pageHeaderOpsSubtitle: "Догрузка, языки и модели, арбитраж: ежедневное обслуживание дворца",
|
|
3008
3079
|
pageHeaderJevSubtitle: "Арбитраж системы один Jev: переопределения настроек и журнал недавних решений",
|
|
3009
3080
|
heatmapTitle: "Активность за последние 26 недель",
|
|
3010
3081
|
heatmapTotal: "записей",
|
|
@@ -3023,7 +3094,88 @@ const ru = {
|
|
|
3023
3094
|
corridorIndexRooms: "комнат: {n}",
|
|
3024
3095
|
skipEmptyAnswer: "вывод дистилляции пуст (пуст и после повтора)",
|
|
3025
3096
|
skipAllCandidatesFailed: "все кандидаты не записались (сохранено для повтора)",
|
|
3026
|
-
|
|
3097
|
+
pageHeaderReplaySubtitle: "Точные пакеты внедрения, выбранные воспоминания и их происхождение",
|
|
3098
|
+
replayFilterLabel: "Сессия",
|
|
3099
|
+
replayFilterPlaceholder: "Фильтр по sessionId (необязательно)",
|
|
3100
|
+
replayCount: "внедрений: {n}",
|
|
3101
|
+
replayEmpty: "Снимков внедрения ещё нет; включите внедрение профиля для записи",
|
|
3102
|
+
replayFailed: "Не удалось загрузить воспроизведение",
|
|
3103
|
+
replayOpen: "Показать итоговый пакет",
|
|
3104
|
+
replayClose: "Скрыть итоговый пакет",
|
|
3105
|
+
replayPacketTitle: "Пакет, фактически полученный моделью",
|
|
3106
|
+
replayMetaTitle: "Метаданные снимка",
|
|
3107
|
+
replayExactNote: "Этот текст дословно совпадает с пакетом для хеша, аудита и запроса модели.",
|
|
3108
|
+
replaySession: "Сессия",
|
|
3109
|
+
replayHash: "Хеш SHA-256",
|
|
3110
|
+
replayMemories: "Выбранные воспоминания",
|
|
3111
|
+
replayCurated: "Курируемый профиль",
|
|
3112
|
+
replayCompactions: "Сжатий",
|
|
3113
|
+
replaySize: "Размер пакета",
|
|
3114
|
+
navWorkfaces: "Рабочие зоны",
|
|
3115
|
+
identityStable: "Стабильный ID",
|
|
3116
|
+
identityRevision: "Текущая ревизия",
|
|
3117
|
+
identityRevisionNote: "Полная цепочка ревизий того же воспоминания (новые сверху)",
|
|
3118
|
+
pageHeaderRecallSubtitle: "Живой стенд припоминания: канал попадания, оценка и происхождение по стабильному ID",
|
|
3119
|
+
pageHeaderGovernanceSubtitle: "Разбор противоречий и убеждений: сначала картина, потом действие",
|
|
3120
|
+
workfaceToday: "Обзор",
|
|
3121
|
+
workfaceRecall: "Припоминание",
|
|
3122
|
+
workfaceMemory: "Память",
|
|
3123
|
+
workfaceGovernance: "Разбор",
|
|
3124
|
+
workfaceReplay: "Воспроизведение",
|
|
3125
|
+
workfaceSystem: "Система",
|
|
3126
|
+
pageHeaderSystemSubtitle: "Время выполнения, хранилище, модели и словари, догрузка истории, Jev и журнал.",
|
|
3127
|
+
memoryRecords: "Записи",
|
|
3128
|
+
memoryTimeline: "Хронология",
|
|
3129
|
+
memoryEntities: "Сущности",
|
|
3130
|
+
memoryAtlas: "Карта",
|
|
3131
|
+
governanceConflicts: "Противоречия",
|
|
3132
|
+
governanceBeliefs: "Убеждения",
|
|
3133
|
+
systemRuntime: "Время выполнения",
|
|
3134
|
+
systemStorage: "Хранилище",
|
|
3135
|
+
systemModels: "Модели и язык",
|
|
3136
|
+
pageHeaderRuntimeSubtitle: "Версии плагина и панели, очередь устойчивых заданий, состояние модели эмбеддинга.",
|
|
3137
|
+
pageHeaderStorageSubtitle: "Размер каждой базы памяти и цена журнала.",
|
|
3138
|
+
pageHeaderModelsSubtitle: "Язык памяти, модели эмбеддинга, словари панели и догрузка истории.",
|
|
3139
|
+
systemVersionPlugin: "Версия плагина",
|
|
3140
|
+
systemVersionClient: "Версия панели",
|
|
3141
|
+
systemVersionOk: "Версии плагина и панели совпадают.",
|
|
3142
|
+
systemVersionDiff: "Версии плагина и панели разошлись — перезапустите процесс плагина и откройте панель заново.",
|
|
3143
|
+
systemJobsTitle: "Очередь устойчивых заданий",
|
|
3144
|
+
systemJobsUnavailable: "Очередь заданий недоступна (этот бэкенд не запускает durable jobs).",
|
|
3145
|
+
systemJobsQueued: "В очереди",
|
|
3146
|
+
systemJobsRunning: "Выполняется",
|
|
3147
|
+
systemJobsDone: "Готово",
|
|
3148
|
+
systemJobsDead: "В мёртвых",
|
|
3149
|
+
systemJobAttempts: "Попыток: {n}",
|
|
3150
|
+
systemJobError: "Последняя ошибка",
|
|
3151
|
+
systemJobEmpty: "Очередь пуста: ни ждущих, ни упавших заданий.",
|
|
3152
|
+
systemStorageTotal: "Всего",
|
|
3153
|
+
systemStorageActive: "Активные",
|
|
3154
|
+
systemStorageArchived: "В архиве",
|
|
3155
|
+
systemStorageForgotten: "Забытые",
|
|
3156
|
+
systemStorageOpLog: "Строк журнала",
|
|
3157
|
+
systemStorageLogSize: "Размер журнала",
|
|
3158
|
+
systemStorageLogPath: "Путь журнала",
|
|
3159
|
+
systemStorageFailed: "Не удалось прочитать сведения о хранилище.",
|
|
3160
|
+
systemModelStatus: "Модель эмбеддинга",
|
|
3161
|
+
systemModelNone: "Модель эмбеддинга ещё не заведена.",
|
|
3162
|
+
benchInspect: "Открыть табличку",
|
|
3163
|
+
kpiExposures: "Экспозиции поиска",
|
|
3164
|
+
attentionEmpty: "Нет пунктов, требующих внимания",
|
|
3165
|
+
attentionFailed: "Не удалось загрузить факты внимания",
|
|
3166
|
+
attentionGovernance: "противоречий: {n}",
|
|
3167
|
+
attentionJobsDead: "задач в dead-letter: {n}",
|
|
3168
|
+
attentionJobsQueued: "задач в очереди: {n}",
|
|
3169
|
+
attentionJobsUnavailable: "Очередь задач не запущена",
|
|
3170
|
+
governanceTitle: "Разбор противоречий",
|
|
3171
|
+
governanceHint: "Показаны только противоречия с двумя активными сторонами; переклассификация сохраняет обе; закрытие архивирует выбранную",
|
|
3172
|
+
governanceCount: "ожидают решения: {n}",
|
|
3173
|
+
governanceEmpty: "Нет противоречий для решения",
|
|
3174
|
+
governanceFailed: "Не удалось загрузить очередь разбора",
|
|
3175
|
+
governanceDismiss: "Переклассифицировать как связанные",
|
|
3176
|
+
governanceForget: "Закрыть это воспоминание",
|
|
3177
|
+
governanceActionFailed: "Не удалось выполнить действие",
|
|
3178
|
+
governanceStableId: "Стабильный ID",
|
|
3027
3179
|
spiralAriaLabel: "спираль воспоминаний",
|
|
3028
3180
|
spiralCenterLabel: "сейчас",
|
|
3029
3181
|
spiralSideTitle: "Шкала времени",
|
|
@@ -3244,8 +3396,6 @@ const zh = {
|
|
|
3244
3396
|
relContradicts: "互斥",
|
|
3245
3397
|
relRelated: "相邻",
|
|
3246
3398
|
tabToday: "今日",
|
|
3247
|
-
tabLibrary: "陈展",
|
|
3248
|
-
tabCorridor: "走廊",
|
|
3249
3399
|
tabLog: "日志",
|
|
3250
3400
|
roomsTitle: "房间目录",
|
|
3251
3401
|
roomsHint: "每间满 9 个桩位后开新间",
|
|
@@ -3462,7 +3612,6 @@ const zh = {
|
|
|
3462
3612
|
adBillingDesc: "真实用量 · 历史账本 · 峰谷计价 · 订阅额度",
|
|
3463
3613
|
adRainbowName: "RainbowSpeak · 虹语",
|
|
3464
3614
|
adRainbowDesc: "会流动的彩虹边框 + 窗口桌宠「小虹」",
|
|
3465
|
-
tabEpisodes: "往事",
|
|
3466
3615
|
episodeSince: "开始日期",
|
|
3467
3616
|
episodeUntil: "结束日期",
|
|
3468
3617
|
episodeSessionId: "会话 id(可选)",
|
|
@@ -3477,8 +3626,6 @@ const zh = {
|
|
|
3477
3626
|
episodeAroundMissing: "这条记忆已经不在库里了(可能被归档或删除),邻近扩展拿不到它。",
|
|
3478
3627
|
episodeAroundEmpty: "邻近窗口内没有其他情景",
|
|
3479
3628
|
episodeClose: "收起",
|
|
3480
|
-
tabEntities: "实体",
|
|
3481
|
-
tabBeliefs: "信念",
|
|
3482
3629
|
beliefStatusAll: "全部",
|
|
3483
3630
|
beliefStatusActive: "成立",
|
|
3484
3631
|
beliefStatusStale: "待复核",
|
|
@@ -3564,7 +3711,6 @@ const zh = {
|
|
|
3564
3711
|
heroDeltaAnswered: "{n} 已作答",
|
|
3565
3712
|
heroDeltaUnanswered: "今日未作答",
|
|
3566
3713
|
healthLabel: "宫殿健康",
|
|
3567
|
-
tabOps: "运维",
|
|
3568
3714
|
backfillLabelCandidates: "候选会话",
|
|
3569
3715
|
backfillLabelPending: "待处理轮数",
|
|
3570
3716
|
backfillLabelSkipped: "已摄取跳过",
|
|
@@ -3578,7 +3724,6 @@ const zh = {
|
|
|
3578
3724
|
pageHeaderBeliefsSubtitle: "巩固信念与证据链,点证据 n 条展开只读回查",
|
|
3579
3725
|
pageHeaderLogSubtitle: "两库合并的完整操作日志,按类别筛选",
|
|
3580
3726
|
pageHeaderBackfillSubtitle: "把历史会话逐轮提炼进宫殿,先估算再执行,可暂停续做",
|
|
3581
|
-
pageHeaderOpsSubtitle: "回填、语言与模型、裁决:宫殿的日常维护",
|
|
3582
3727
|
pageHeaderJevSubtitle: "Jev 系统一裁决,配置覆盖与近期裁决观测",
|
|
3583
3728
|
heatmapTitle: "近半年活动热力",
|
|
3584
3729
|
heatmapTotal: "次写入",
|
|
@@ -3597,7 +3742,88 @@ const zh = {
|
|
|
3597
3742
|
corridorIndexRooms: "{n} 间房",
|
|
3598
3743
|
skipEmptyAnswer: "提炼输出为空(重试后仍空)",
|
|
3599
3744
|
skipAllCandidatesFailed: "全部候选落库失败(保留待重放)",
|
|
3600
|
-
|
|
3745
|
+
pageHeaderReplaySubtitle: "回看每次实际注入的最终包、入选记忆和逐字事实源",
|
|
3746
|
+
replayFilterLabel: "会话",
|
|
3747
|
+
replayFilterPlaceholder: "按 sessionId 过滤(可留空)",
|
|
3748
|
+
replayCount: "{n} 次注入",
|
|
3749
|
+
replayEmpty: "还没有注入快照;开启画像注入后自动记录",
|
|
3750
|
+
replayFailed: "注入回放加载失败",
|
|
3751
|
+
replayOpen: "查看最终包",
|
|
3752
|
+
replayClose: "收起最终包",
|
|
3753
|
+
replayPacketTitle: "模型实际收到的最终包",
|
|
3754
|
+
replayMetaTitle: "快照元数据",
|
|
3755
|
+
replayExactNote: "此处正文与哈希、审计和当时模型收到的内容逐字一致。",
|
|
3756
|
+
replaySession: "会话",
|
|
3757
|
+
replayHash: "SHA-256",
|
|
3758
|
+
replayMemories: "入选记忆",
|
|
3759
|
+
replayCurated: "人工画像",
|
|
3760
|
+
replayCompactions: "压缩次数",
|
|
3761
|
+
replaySize: "包大小",
|
|
3762
|
+
navWorkfaces: "工作面",
|
|
3763
|
+
identityStable: "稳定身份",
|
|
3764
|
+
identityRevision: "当前修订",
|
|
3765
|
+
identityRevisionNote: "同一逻辑记忆的完整修订链(最新在前)",
|
|
3766
|
+
pageHeaderRecallSubtitle: "真实检索实验台:命中道、得分与稳定身份 provenance",
|
|
3767
|
+
pageHeaderGovernanceSubtitle: "矛盾与信念的处置台:先看全貌再落动作",
|
|
3768
|
+
workfaceToday: "总览",
|
|
3769
|
+
workfaceRecall: "召回",
|
|
3770
|
+
workfaceMemory: "记忆",
|
|
3771
|
+
workfaceGovernance: "治理",
|
|
3772
|
+
workfaceReplay: "回放",
|
|
3773
|
+
workfaceSystem: "系统",
|
|
3774
|
+
pageHeaderSystemSubtitle: "运行时、存储、模型与词典、历史回填、Jev 与日志。",
|
|
3775
|
+
memoryRecords: "记录",
|
|
3776
|
+
memoryTimeline: "时间线",
|
|
3777
|
+
memoryEntities: "实体",
|
|
3778
|
+
memoryAtlas: "图谱",
|
|
3779
|
+
governanceConflicts: "矛盾",
|
|
3780
|
+
governanceBeliefs: "信念",
|
|
3781
|
+
systemRuntime: "运行时",
|
|
3782
|
+
systemStorage: "存储",
|
|
3783
|
+
systemModels: "模型与词典",
|
|
3784
|
+
pageHeaderRuntimeSubtitle: "插件与面板版本、持久作业队列、嵌入模型状态。",
|
|
3785
|
+
pageHeaderStorageSubtitle: "三个分库的规模与日志占用。",
|
|
3786
|
+
pageHeaderModelsSubtitle: "记忆语言、嵌入模型、面板词典与历史回填。",
|
|
3787
|
+
systemVersionPlugin: "插件版本",
|
|
3788
|
+
systemVersionClient: "面板版本",
|
|
3789
|
+
systemVersionOk: "插件与面板版本一致。",
|
|
3790
|
+
systemVersionDiff: "插件与面板版本不一致——重启插件进程后再打开面板。",
|
|
3791
|
+
systemJobsTitle: "持久作业队列",
|
|
3792
|
+
systemJobsUnavailable: "作业队列不可用(该后端未启用 durable jobs)。",
|
|
3793
|
+
systemJobsQueued: "排队中",
|
|
3794
|
+
systemJobsRunning: "执行中",
|
|
3795
|
+
systemJobsDone: "已完成",
|
|
3796
|
+
systemJobsDead: "已死信",
|
|
3797
|
+
systemJobAttempts: "尝试 {n} 次",
|
|
3798
|
+
systemJobError: "最后错误",
|
|
3799
|
+
systemJobEmpty: "队列为空:没有待处理、也没有失败的作业。",
|
|
3800
|
+
systemStorageTotal: "总条数",
|
|
3801
|
+
systemStorageActive: "活跃",
|
|
3802
|
+
systemStorageArchived: "归档",
|
|
3803
|
+
systemStorageForgotten: "已遗忘",
|
|
3804
|
+
systemStorageOpLog: "日志行数",
|
|
3805
|
+
systemStorageLogSize: "日志占用",
|
|
3806
|
+
systemStorageLogPath: "日志路径",
|
|
3807
|
+
systemStorageFailed: "存储信息读取失败。",
|
|
3808
|
+
systemModelStatus: "嵌入模型",
|
|
3809
|
+
systemModelNone: "尚未登记嵌入模型。",
|
|
3810
|
+
benchInspect: "查看铭牌",
|
|
3811
|
+
kpiExposures: "检索曝光",
|
|
3812
|
+
attentionEmpty: "当前没有待处理事项",
|
|
3813
|
+
attentionFailed: "待办事实源加载失败",
|
|
3814
|
+
attentionGovernance: "{n} 组矛盾待处置",
|
|
3815
|
+
attentionJobsDead: "{n} 个作业已 dead-letter",
|
|
3816
|
+
attentionJobsQueued: "{n} 个作业排队中",
|
|
3817
|
+
attentionJobsUnavailable: "作业队列未运行",
|
|
3818
|
+
governanceTitle: "矛盾治理",
|
|
3819
|
+
governanceHint: "只显示双侧仍驻留的矛盾边;改判保留两条记忆,闭馆会作废所选一侧",
|
|
3820
|
+
governanceCount: "{n} 组待处置",
|
|
3821
|
+
governanceEmpty: "没有待处置矛盾",
|
|
3822
|
+
governanceFailed: "治理队列加载失败",
|
|
3823
|
+
governanceDismiss: "改判为相关",
|
|
3824
|
+
governanceForget: "闭馆此条",
|
|
3825
|
+
governanceActionFailed: "处置失败",
|
|
3826
|
+
governanceStableId: "稳定身份",
|
|
3601
3827
|
spiralAriaLabel: "回忆螺旋视图",
|
|
3602
3828
|
spiralCenterLabel: "现在",
|
|
3603
3829
|
spiralSideTitle: "时间尺度",
|
|
@@ -6928,22 +7154,28 @@ async function markPendingIngest(store, sessionId, turn) {
|
|
|
6928
7154
|
* pre-step 重放补做),绝不影响对话。
|
|
6929
7155
|
* 本函数不 reject:从取轮次到摄取全程在 try 内,异常一律降级为告警 + pending 键
|
|
6930
7156
|
* (dispose 观察器是 fire-and-forget,逃逸的 rejection 会被宿主的 fail-loud 当作致命错误)。
|
|
6931
|
-
* @returns
|
|
7157
|
+
* @returns 摄取结果;无末轮或异常失败(已尝试落 pending)时返回 null,结果型失败原样返回。
|
|
6932
7158
|
*/
|
|
6933
7159
|
async function ingestFinalTurn(deps) {
|
|
6934
7160
|
/** 末轮轮次号;取不到(无 turn/start 或事件源不可用)时不落 pending——键需要轮次。 */
|
|
6935
7161
|
let round;
|
|
7162
|
+
const persistPending = async () => {
|
|
7163
|
+
if (round === void 0) return;
|
|
7164
|
+
try {
|
|
7165
|
+
await markPendingIngest(await (deps.openAuditStore ?? deps.openStore)(), deps.sessionId, round);
|
|
7166
|
+
} catch {}
|
|
7167
|
+
};
|
|
6936
7168
|
try {
|
|
6937
7169
|
round = lastTurnNumber(deps.events);
|
|
6938
7170
|
if (round === void 0) return null;
|
|
6939
|
-
|
|
7171
|
+
const outcome = await ingestPreviousTurn({
|
|
6940
7172
|
...deps,
|
|
6941
7173
|
slice: "last"
|
|
6942
7174
|
});
|
|
7175
|
+
if (outcome.skipped === "empty-answer" || outcome.skipped === "unparseable-output" || outcome.skipped === "all-candidates-failed") await persistPending();
|
|
7176
|
+
return outcome;
|
|
6943
7177
|
} catch (error) {
|
|
6944
|
-
|
|
6945
|
-
await markPendingIngest(await (deps.openAuditStore ?? deps.openStore)(), deps.sessionId, round);
|
|
6946
|
-
} catch {}
|
|
7178
|
+
await persistPending();
|
|
6947
7179
|
console.warn(message("llm.warnFinalIngestFailed"), error);
|
|
6948
7180
|
return null;
|
|
6949
7181
|
}
|
|
@@ -7893,6 +8125,591 @@ function requireCandidateIds(raw, candidateIds) {
|
|
|
7893
8125
|
}
|
|
7894
8126
|
return ids;
|
|
7895
8127
|
}
|
|
8128
|
+
// src/jobs/queue.ts
|
|
8129
|
+
/**
|
|
8130
|
+
* 持久作业队列原语:基于 node:sqlite 的独立 DB 文件(WAL + busy_timeout),
|
|
8131
|
+
* 供后续 reflect/consolidation 等宿主调度使用——本模块只提供队列原语,不做调度。
|
|
8132
|
+
*
|
|
8133
|
+
* 与主库(store/sqlite)的差别:队列按「多 worker 竞争」设计,写事务一律
|
|
8134
|
+
* BEGIN IMMEDIATE——先拿写锁再动手,撞车交给 busy_timeout 等待,而不是让
|
|
8135
|
+
* 事务中途从读锁升级写锁时撞 SQLITE_BUSY。表名固定常量、全部参数化查询,
|
|
8136
|
+
* 不存在拼接用户输入的 SQL 面。
|
|
8137
|
+
*
|
|
8138
|
+
* 状态机(无独立 retrying 状态,重试 = 回 queued + 延期 runAfter,attempts 保留):
|
|
8139
|
+
* queued --claim--> running --complete--> done
|
|
8140
|
+
* ^ | --fail(attempts<max)--> queued(runAfter 延期)
|
|
8141
|
+
* | └─── --fail(attempts>=max)--> dead
|
|
8142
|
+
* └-------- claim 到期的 queued;claim 租约过期的 running(被新 owner 抢走)
|
|
8143
|
+
*
|
|
8144
|
+
* done/dead 是终态:不可 claim、不可 complete/fail/checkpoint;只能被 prune 按
|
|
8145
|
+
* 保留窗口清除(历史垃圾回收),或因 payload 损坏(毒丸)被 claim 就地 dead-letter。
|
|
8146
|
+
* @module @kenz1117/dsh-engram/jobs/queue
|
|
8147
|
+
*/
|
|
8148
|
+
/** 表名固定常量:所有语句写死引用它,绝不拼接调用方输入。 */
|
|
8149
|
+
const TABLE = "jobs";
|
|
8150
|
+
/** 队列库自身结构版本(PRAGMA user_version);结构性变更必须 +1。 */
|
|
8151
|
+
const QUEUE_SCHEMA_VERSION = 1;
|
|
8152
|
+
/** maxAttempts 缺省值:允许 3 次尝试(首次 + 2 次重试)。 */
|
|
8153
|
+
const DEFAULT_MAX_ATTEMPTS = 3;
|
|
8154
|
+
/** 校验非空字符串(不静默 trim:只拒绝纯空白,原文原样入库)。 */
|
|
8155
|
+
function requireText(value, field) {
|
|
8156
|
+
if (typeof value !== "string" || value.trim().length === 0) throw new EngramError("JOB_INVALID", `jobs: ${field} 必须是非空字符串`);
|
|
8157
|
+
return value;
|
|
8158
|
+
}
|
|
8159
|
+
/** 校验正整数(maxAttempts/leaseMs/limit)。 */
|
|
8160
|
+
function requirePositiveInt(value, field) {
|
|
8161
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) throw new EngramError("JOB_INVALID", `jobs: ${field} 必须是正整数`);
|
|
8162
|
+
return value;
|
|
8163
|
+
}
|
|
8164
|
+
/** 校验非负整数(runAfter/retryDelayMs)。 */
|
|
8165
|
+
function requireNonNegativeInt(value, field) {
|
|
8166
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) throw new EngramError("JOB_INVALID", `jobs: ${field} 必须是非负整数`);
|
|
8167
|
+
return value;
|
|
8168
|
+
}
|
|
8169
|
+
/** payload 只收可 JSON 序列化的值:undefined/函数/循环引用一律 JOB_INVALID。 */
|
|
8170
|
+
function serializePayload(payload) {
|
|
8171
|
+
let json;
|
|
8172
|
+
try {
|
|
8173
|
+
json = JSON.stringify(payload);
|
|
8174
|
+
} catch (cause) {
|
|
8175
|
+
throw new EngramError("JOB_INVALID", "jobs: payload 必须可 JSON 序列化", { cause });
|
|
8176
|
+
}
|
|
8177
|
+
if (json === void 0) throw new EngramError("JOB_INVALID", "jobs: payload 必须可 JSON 序列化");
|
|
8178
|
+
return json;
|
|
8179
|
+
}
|
|
8180
|
+
/** complete/fail/checkpoint 共用的守卫:作业存在、正在 running、调用方就是当前租约持有者、且租约未过期。 */
|
|
8181
|
+
function requireOwnedRunning(row, input, at) {
|
|
8182
|
+
if (row.status !== "running") throw new EngramError("JOB_NOT_RUNNING", `jobs: 作业 ${row.id} 不在 running(当前 ${row.status})`);
|
|
8183
|
+
if (row.lease_owner !== input.owner) throw new EngramError("JOB_OWNER_MISMATCH", `jobs: 作业 ${row.id} 的租约持有者是 ${row.lease_owner ?? "无"},不是 ${input.owner}`);
|
|
8184
|
+
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`);
|
|
8185
|
+
}
|
|
8186
|
+
/**
|
|
8187
|
+
* 打开(必要时创建)一个独立队列库。
|
|
8188
|
+
* @param path - SQLite 文件路径;目录不存在会自动创建(0o700)。
|
|
8189
|
+
* @param options - now 注入时钟;缺省 Date.now。
|
|
8190
|
+
* @returns 就绪的 JobQueue。
|
|
8191
|
+
* @throws EngramError(code=SCHEMA_INCOMPATIBLE) 当队列库结构版本高于当前实现。
|
|
8192
|
+
* @throws EngramError(code=JOB_INVALID) 当 path 非法或时钟不可用。
|
|
8193
|
+
*/
|
|
8194
|
+
async function openJobQueue(path, options = {}) {
|
|
8195
|
+
if (typeof path !== "string" || path.length === 0) throw new EngramError("JOB_INVALID", "jobs: path 必须是非空字符串");
|
|
8196
|
+
const now = options.now ?? (() => Date.now());
|
|
8197
|
+
const probed = now();
|
|
8198
|
+
if (typeof probed !== "number" || !Number.isFinite(probed)) throw new EngramError("JOB_INVALID", "jobs: 注入的 now() 必须返回有限数字");
|
|
8199
|
+
await mkdir(dirname(path), {
|
|
8200
|
+
recursive: true,
|
|
8201
|
+
mode: 448
|
|
8202
|
+
});
|
|
8203
|
+
const { DatabaseSync } = await import("node:sqlite");
|
|
8204
|
+
const db = new DatabaseSync(path);
|
|
8205
|
+
/** 手工事务(IMMEDIATE:队列是多写者场景,先拿写锁让 busy_timeout 吸收竞争)。 */
|
|
8206
|
+
const withTransaction = (fn) => {
|
|
8207
|
+
db.exec("BEGIN IMMEDIATE");
|
|
8208
|
+
try {
|
|
8209
|
+
fn();
|
|
8210
|
+
db.exec("COMMIT");
|
|
8211
|
+
} catch (error) {
|
|
8212
|
+
db.exec("ROLLBACK");
|
|
8213
|
+
throw error;
|
|
8214
|
+
}
|
|
8215
|
+
};
|
|
8216
|
+
let versionRow;
|
|
8217
|
+
try {
|
|
8218
|
+
db.exec("PRAGMA journal_mode = WAL;");
|
|
8219
|
+
db.exec("PRAGMA busy_timeout = 5000;");
|
|
8220
|
+
db.exec("PRAGMA synchronous = NORMAL;");
|
|
8221
|
+
versionRow = db.prepare("PRAGMA user_version").get();
|
|
8222
|
+
const version = versionRow?.user_version ?? 0;
|
|
8223
|
+
if (version > QUEUE_SCHEMA_VERSION) throw new EngramError("SCHEMA_INCOMPATIBLE", `jobs: 队列库结构版本过新(found ${version} > supported ${QUEUE_SCHEMA_VERSION},path ${path})`);
|
|
8224
|
+
if (version < QUEUE_SCHEMA_VERSION) db.exec(`
|
|
8225
|
+
CREATE TABLE IF NOT EXISTS ${TABLE} (
|
|
8226
|
+
id TEXT PRIMARY KEY,
|
|
8227
|
+
kind TEXT NOT NULL,
|
|
8228
|
+
payload TEXT NOT NULL,
|
|
8229
|
+
status TEXT NOT NULL,
|
|
8230
|
+
attempts INTEGER NOT NULL,
|
|
8231
|
+
max_attempts INTEGER NOT NULL,
|
|
8232
|
+
run_after INTEGER NOT NULL,
|
|
8233
|
+
lease_owner TEXT,
|
|
8234
|
+
lease_expires_at INTEGER,
|
|
8235
|
+
checkpoint TEXT,
|
|
8236
|
+
last_error TEXT,
|
|
8237
|
+
created_at INTEGER NOT NULL,
|
|
8238
|
+
updated_at INTEGER NOT NULL);
|
|
8239
|
+
CREATE INDEX IF NOT EXISTS jobs_due ON ${TABLE} (status, run_after);
|
|
8240
|
+
PRAGMA user_version = ${QUEUE_SCHEMA_VERSION};`);
|
|
8241
|
+
} catch (error) {
|
|
8242
|
+
try {
|
|
8243
|
+
db.close();
|
|
8244
|
+
} catch {}
|
|
8245
|
+
throw error;
|
|
8246
|
+
}
|
|
8247
|
+
const sqlGet = db.prepare(`SELECT * FROM ${TABLE} WHERE id = ?`);
|
|
8248
|
+
const sqlInsert = db.prepare(`INSERT INTO ${TABLE}
|
|
8249
|
+
(id, kind, payload, status, attempts, max_attempts, run_after, lease_owner, lease_expires_at, checkpoint, last_error, created_at, updated_at)
|
|
8250
|
+
VALUES (?, ?, ?, 'queued', 0, ?, ?, NULL, NULL, NULL, NULL, ?, ?)`);
|
|
8251
|
+
const sqlDue = db.prepare(`SELECT * FROM ${TABLE}
|
|
8252
|
+
WHERE ((status = 'queued' AND run_after <= ?)
|
|
8253
|
+
OR (status = 'running' AND lease_expires_at IS NOT NULL AND lease_expires_at <= ?))
|
|
8254
|
+
ORDER BY run_after ASC, id ASC
|
|
8255
|
+
LIMIT ?`);
|
|
8256
|
+
const sqlDueKinds = db.prepare(`SELECT * FROM ${TABLE}
|
|
8257
|
+
WHERE ((status = 'queued' AND run_after <= ?)
|
|
8258
|
+
OR (status = 'running' AND lease_expires_at IS NOT NULL AND lease_expires_at <= ?))
|
|
8259
|
+
AND kind IN (SELECT value FROM json_each(?))
|
|
8260
|
+
ORDER BY run_after ASC, id ASC
|
|
8261
|
+
LIMIT ?`);
|
|
8262
|
+
const sqlTake = db.prepare(`UPDATE ${TABLE}
|
|
8263
|
+
SET status = 'running', attempts = attempts + 1, lease_owner = ?, lease_expires_at = ?, updated_at = ?
|
|
8264
|
+
WHERE id = ?`);
|
|
8265
|
+
const sqlComplete = db.prepare(`UPDATE ${TABLE}
|
|
8266
|
+
SET status = 'done', lease_owner = NULL, lease_expires_at = NULL, updated_at = ?
|
|
8267
|
+
WHERE id = ?`);
|
|
8268
|
+
const sqlRetry = db.prepare(`UPDATE ${TABLE}
|
|
8269
|
+
SET status = 'queued', run_after = ?, lease_owner = NULL, lease_expires_at = NULL, last_error = ?, updated_at = ?
|
|
8270
|
+
WHERE id = ?`);
|
|
8271
|
+
const sqlDead = db.prepare(`UPDATE ${TABLE}
|
|
8272
|
+
SET status = 'dead', lease_owner = NULL, lease_expires_at = NULL, last_error = ?, updated_at = ?
|
|
8273
|
+
WHERE id = ?`);
|
|
8274
|
+
const sqlCheckpoint = db.prepare(`UPDATE ${TABLE} SET checkpoint = ?, updated_at = ? WHERE id = ?`);
|
|
8275
|
+
const sqlList = db.prepare(`SELECT * FROM ${TABLE} ORDER BY updated_at DESC, rowid DESC LIMIT ?`);
|
|
8276
|
+
const sqlSummary = db.prepare(`SELECT status, COUNT(*) AS n FROM ${TABLE} GROUP BY status`);
|
|
8277
|
+
const sqlPrune = db.prepare(`DELETE FROM ${TABLE} WHERE status IN ('done', 'dead') AND updated_at < ?`);
|
|
8278
|
+
/** 行 → 记录:payload 反序列化;坏行(解析失败)明确报 JOB_CORRUPT 而不是静默吞掉。 */
|
|
8279
|
+
const toRecord = (row) => {
|
|
8280
|
+
let payload;
|
|
8281
|
+
try {
|
|
8282
|
+
payload = JSON.parse(row.payload);
|
|
8283
|
+
} catch (cause) {
|
|
8284
|
+
throw new EngramError("JOB_CORRUPT", `jobs: 作业 ${row.id} 的 payload 不是合法 JSON`, { cause });
|
|
8285
|
+
}
|
|
8286
|
+
return {
|
|
8287
|
+
id: row.id,
|
|
8288
|
+
kind: row.kind,
|
|
8289
|
+
payload,
|
|
8290
|
+
status: row.status,
|
|
8291
|
+
attempts: row.attempts,
|
|
8292
|
+
maxAttempts: row.max_attempts,
|
|
8293
|
+
runAfter: row.run_after,
|
|
8294
|
+
leaseOwner: row.lease_owner,
|
|
8295
|
+
leaseExpiresAt: row.lease_expires_at,
|
|
8296
|
+
checkpoint: row.checkpoint,
|
|
8297
|
+
lastError: row.last_error,
|
|
8298
|
+
createdAt: row.created_at,
|
|
8299
|
+
updatedAt: row.updated_at
|
|
8300
|
+
};
|
|
8301
|
+
};
|
|
8302
|
+
return {
|
|
8303
|
+
enqueue(input) {
|
|
8304
|
+
const id = requireText(input.id, "id");
|
|
8305
|
+
const kind = requireText(input.kind, "kind");
|
|
8306
|
+
const payloadJson = serializePayload(input.payload);
|
|
8307
|
+
const maxAttempts = input.maxAttempts === void 0 ? DEFAULT_MAX_ATTEMPTS : requirePositiveInt(input.maxAttempts, "maxAttempts");
|
|
8308
|
+
const at = now();
|
|
8309
|
+
const runAfter = input.runAfter === void 0 ? at : requireNonNegativeInt(input.runAfter, "runAfter");
|
|
8310
|
+
const existing = sqlGet.get(id);
|
|
8311
|
+
if (existing !== void 0) return {
|
|
8312
|
+
job: toRecord(existing),
|
|
8313
|
+
deduped: true
|
|
8314
|
+
};
|
|
8315
|
+
let deduped = false;
|
|
8316
|
+
withTransaction(() => {
|
|
8317
|
+
if (sqlGet.get(id) !== void 0) {
|
|
8318
|
+
deduped = true;
|
|
8319
|
+
return;
|
|
8320
|
+
}
|
|
8321
|
+
sqlInsert.run(id, kind, payloadJson, maxAttempts, runAfter, at, at);
|
|
8322
|
+
});
|
|
8323
|
+
return {
|
|
8324
|
+
job: toRecord(sqlGet.get(id)),
|
|
8325
|
+
deduped
|
|
8326
|
+
};
|
|
8327
|
+
},
|
|
8328
|
+
claim(input) {
|
|
8329
|
+
const owner = requireText(input.owner, "owner");
|
|
8330
|
+
const leaseMs = requirePositiveInt(input.leaseMs, "leaseMs");
|
|
8331
|
+
const limit = input.limit === void 0 ? 1 : requirePositiveInt(input.limit, "limit");
|
|
8332
|
+
const kinds = input.kinds === void 0 ? void 0 : input.kinds.map((kind) => requireText(kind, "kinds"));
|
|
8333
|
+
const at = now();
|
|
8334
|
+
const expiresAt = at + leaseMs;
|
|
8335
|
+
const taken = [];
|
|
8336
|
+
withTransaction(() => {
|
|
8337
|
+
const candidates = kinds === void 0 ? sqlDue.all(at, at, limit) : sqlDueKinds.all(at, at, JSON.stringify(kinds), limit);
|
|
8338
|
+
for (const row of candidates) {
|
|
8339
|
+
sqlTake.run(owner, expiresAt, at, row.id);
|
|
8340
|
+
try {
|
|
8341
|
+
taken.push(toRecord(sqlGet.get(row.id)));
|
|
8342
|
+
} catch (error) {
|
|
8343
|
+
if (!(error instanceof EngramError && error.code === "JOB_CORRUPT")) throw error;
|
|
8344
|
+
const cause = error.cause;
|
|
8345
|
+
const causeText = cause instanceof Error ? cause.message : cause === void 0 ? "" : String(cause);
|
|
8346
|
+
sqlDead.run(causeText === "" ? error.message : `${error.message}(${causeText})`, at, row.id);
|
|
8347
|
+
}
|
|
8348
|
+
}
|
|
8349
|
+
});
|
|
8350
|
+
return taken;
|
|
8351
|
+
},
|
|
8352
|
+
complete(input) {
|
|
8353
|
+
const id = requireText(input.id, "id");
|
|
8354
|
+
requireText(input.owner, "owner");
|
|
8355
|
+
const at = now();
|
|
8356
|
+
withTransaction(() => {
|
|
8357
|
+
const row = sqlGet.get(id);
|
|
8358
|
+
if (row === void 0) throw new EngramError("JOB_NOT_FOUND", `jobs: 作业 ${id} 不存在`);
|
|
8359
|
+
requireOwnedRunning(row, input, at);
|
|
8360
|
+
sqlComplete.run(at, id);
|
|
8361
|
+
});
|
|
8362
|
+
return toRecord(sqlGet.get(id));
|
|
8363
|
+
},
|
|
8364
|
+
fail(input) {
|
|
8365
|
+
const id = requireText(input.id, "id");
|
|
8366
|
+
requireText(input.owner, "owner");
|
|
8367
|
+
const error = requireText(input.error, "error");
|
|
8368
|
+
const retryDelayMs = input.retryDelayMs === void 0 ? 0 : requireNonNegativeInt(input.retryDelayMs, "retryDelayMs");
|
|
8369
|
+
const at = now();
|
|
8370
|
+
withTransaction(() => {
|
|
8371
|
+
const row = sqlGet.get(id);
|
|
8372
|
+
if (row === void 0) throw new EngramError("JOB_NOT_FOUND", `jobs: 作业 ${id} 不存在`);
|
|
8373
|
+
requireOwnedRunning(row, input, at);
|
|
8374
|
+
if (row.attempts >= row.max_attempts) sqlDead.run(error, at, id);
|
|
8375
|
+
else sqlRetry.run(at + retryDelayMs, error, at, id);
|
|
8376
|
+
});
|
|
8377
|
+
return toRecord(sqlGet.get(id));
|
|
8378
|
+
},
|
|
8379
|
+
checkpoint(input) {
|
|
8380
|
+
const id = requireText(input.id, "id");
|
|
8381
|
+
requireText(input.owner, "owner");
|
|
8382
|
+
const mark = requireText(input.checkpoint, "checkpoint");
|
|
8383
|
+
const at = now();
|
|
8384
|
+
withTransaction(() => {
|
|
8385
|
+
const row = sqlGet.get(id);
|
|
8386
|
+
if (row === void 0) throw new EngramError("JOB_NOT_FOUND", `jobs: 作业 ${id} 不存在`);
|
|
8387
|
+
requireOwnedRunning(row, input, at);
|
|
8388
|
+
sqlCheckpoint.run(mark, at, id);
|
|
8389
|
+
});
|
|
8390
|
+
return toRecord(sqlGet.get(id));
|
|
8391
|
+
},
|
|
8392
|
+
get(id) {
|
|
8393
|
+
const row = sqlGet.get(requireText(id, "id"));
|
|
8394
|
+
return row === void 0 ? void 0 : toRecord(row);
|
|
8395
|
+
},
|
|
8396
|
+
list(filter) {
|
|
8397
|
+
const limit = filter?.limit === void 0 ? 100 : requirePositiveInt(filter.limit, "limit");
|
|
8398
|
+
const statuses = filter?.statuses === void 0 ? void 0 : filter.statuses.map((status) => {
|
|
8399
|
+
if (status !== "queued" && status !== "running" && status !== "done" && status !== "dead") throw new EngramError("JOB_INVALID", `jobs: status 必须是 queued/running/done/dead,收到 ${String(status)}`);
|
|
8400
|
+
return status;
|
|
8401
|
+
});
|
|
8402
|
+
const wanted = statuses === void 0 ? void 0 : new Set(statuses);
|
|
8403
|
+
const rows = sqlList.all(Math.max(1, Math.min(500, limit)));
|
|
8404
|
+
const mapped = [];
|
|
8405
|
+
for (const row of rows) {
|
|
8406
|
+
if (wanted !== void 0 && !wanted.has(row.status)) continue;
|
|
8407
|
+
mapped.push({
|
|
8408
|
+
id: row.id,
|
|
8409
|
+
kind: row.kind,
|
|
8410
|
+
status: row.status,
|
|
8411
|
+
attempts: row.attempts,
|
|
8412
|
+
maxAttempts: row.max_attempts,
|
|
8413
|
+
runAfter: row.run_after,
|
|
8414
|
+
leaseOwner: row.lease_owner,
|
|
8415
|
+
leaseExpiresAt: row.lease_expires_at,
|
|
8416
|
+
checkpoint: row.checkpoint,
|
|
8417
|
+
lastError: row.last_error,
|
|
8418
|
+
createdAt: row.created_at,
|
|
8419
|
+
updatedAt: row.updated_at
|
|
8420
|
+
});
|
|
8421
|
+
}
|
|
8422
|
+
return mapped;
|
|
8423
|
+
},
|
|
8424
|
+
summary() {
|
|
8425
|
+
const summary = {
|
|
8426
|
+
total: 0,
|
|
8427
|
+
queued: 0,
|
|
8428
|
+
running: 0,
|
|
8429
|
+
done: 0,
|
|
8430
|
+
dead: 0
|
|
8431
|
+
};
|
|
8432
|
+
for (const row of sqlSummary.all()) {
|
|
8433
|
+
const count = Number(row.n);
|
|
8434
|
+
if (!Number.isFinite(count)) continue;
|
|
8435
|
+
summary.total += count;
|
|
8436
|
+
if (row.status === "queued") summary.queued = count;
|
|
8437
|
+
else if (row.status === "running") summary.running = count;
|
|
8438
|
+
else if (row.status === "done") summary.done = count;
|
|
8439
|
+
else if (row.status === "dead") summary.dead = count;
|
|
8440
|
+
}
|
|
8441
|
+
return summary;
|
|
8442
|
+
},
|
|
8443
|
+
prune(olderThanMs) {
|
|
8444
|
+
const thresholdMs = requireNonNegativeInt(olderThanMs, "olderThanMs");
|
|
8445
|
+
const cutoff = now() - thresholdMs;
|
|
8446
|
+
const result = sqlPrune.run(cutoff);
|
|
8447
|
+
return Number(result.changes);
|
|
8448
|
+
},
|
|
8449
|
+
close() {
|
|
8450
|
+
db.close();
|
|
8451
|
+
}
|
|
8452
|
+
};
|
|
8453
|
+
}
|
|
8454
|
+
// src/jobs/reflect-worker.ts
|
|
8455
|
+
/**
|
|
8456
|
+
* reflect 持久调度器:确定性入队、串行认领、限时执行、失败重试与停止恢复。
|
|
8457
|
+
* queue 的生命周期由宿主管理;本 worker 只拥有定时器与自己的执行取消信号。
|
|
8458
|
+
* @module @kenz1117/dsh-engram/jobs/reflect-worker
|
|
8459
|
+
*/
|
|
8460
|
+
function positive(value, fallback, field) {
|
|
8461
|
+
const result = value ?? fallback;
|
|
8462
|
+
if (!Number.isInteger(result) || result <= 0) throw new Error(`reflect worker: ${field} 必须是正整数`);
|
|
8463
|
+
return result;
|
|
8464
|
+
}
|
|
8465
|
+
function nonNegative(value, fallback, field) {
|
|
8466
|
+
const result = value ?? fallback;
|
|
8467
|
+
if (!Number.isInteger(result) || result < 0) throw new Error(`reflect worker: ${field} 必须是非负整数`);
|
|
8468
|
+
return result;
|
|
8469
|
+
}
|
|
8470
|
+
function text(value) {
|
|
8471
|
+
return typeof value === "string" && value.trim() !== "";
|
|
8472
|
+
}
|
|
8473
|
+
function parsePayload(value) {
|
|
8474
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error("reflect job payload 必须是对象");
|
|
8475
|
+
const raw = value;
|
|
8476
|
+
const route = raw.route;
|
|
8477
|
+
if (!text(raw.sessionId) || raw.scope !== "user" && raw.scope !== "project") throw new Error("reflect job payload 缺 sessionId 或 scope 非法");
|
|
8478
|
+
if (raw.cwd !== void 0 && !text(raw.cwd)) throw new Error("reflect job payload.cwd 必须是非空字符串");
|
|
8479
|
+
if (raw.eventSeq !== void 0 && (typeof raw.eventSeq !== "number" || !Number.isInteger(raw.eventSeq) || raw.eventSeq < 0)) throw new Error("reflect job payload.eventSeq 必须是非负整数");
|
|
8480
|
+
if (route === void 0 || !text(route.provider) || !text(route.model)) throw new Error("reflect job payload.route 缺 provider/model");
|
|
8481
|
+
return {
|
|
8482
|
+
sessionId: raw.sessionId,
|
|
8483
|
+
scope: raw.scope,
|
|
8484
|
+
...raw.cwd === void 0 ? {} : { cwd: raw.cwd },
|
|
8485
|
+
...raw.eventSeq === void 0 ? {} : { eventSeq: raw.eventSeq },
|
|
8486
|
+
route: {
|
|
8487
|
+
provider: route.provider,
|
|
8488
|
+
model: route.model
|
|
8489
|
+
}
|
|
8490
|
+
};
|
|
8491
|
+
}
|
|
8492
|
+
function errorText(error) {
|
|
8493
|
+
return error instanceof Error ? error.message : String(error);
|
|
8494
|
+
}
|
|
8495
|
+
var DurableReflectWorker = class {
|
|
8496
|
+
queue;
|
|
8497
|
+
execute;
|
|
8498
|
+
onError;
|
|
8499
|
+
owner;
|
|
8500
|
+
intervalMs;
|
|
8501
|
+
leaseMs;
|
|
8502
|
+
retryDelayMs;
|
|
8503
|
+
timeoutMs;
|
|
8504
|
+
externalSignal;
|
|
8505
|
+
abort = new AbortController();
|
|
8506
|
+
currentAbort;
|
|
8507
|
+
timer;
|
|
8508
|
+
activePump;
|
|
8509
|
+
stopped = false;
|
|
8510
|
+
constructor(options) {
|
|
8511
|
+
this.queue = options.queue;
|
|
8512
|
+
this.execute = options.execute;
|
|
8513
|
+
this.onError = options.onError;
|
|
8514
|
+
this.owner = options.owner ?? `reflect-${randomUUID()}`;
|
|
8515
|
+
this.intervalMs = positive(options.intervalMs, 1e3, "intervalMs");
|
|
8516
|
+
this.leaseMs = positive(options.leaseMs, 18e4, "leaseMs");
|
|
8517
|
+
this.retryDelayMs = nonNegative(options.retryDelayMs, 3e4, "retryDelayMs");
|
|
8518
|
+
this.timeoutMs = positive(options.timeoutMs, 12e4, "timeoutMs");
|
|
8519
|
+
this.externalSignal = options.signal;
|
|
8520
|
+
}
|
|
8521
|
+
enqueue(payload) {
|
|
8522
|
+
const checked = parsePayload(payload);
|
|
8523
|
+
return this.queue.enqueue({
|
|
8524
|
+
id: checked.eventSeq === void 0 ? `reflect:${checked.sessionId}:${checked.scope}` : `reflect:${checked.sessionId}:${checked.scope}:${checked.eventSeq}`,
|
|
8525
|
+
kind: "reflect",
|
|
8526
|
+
payload: checked,
|
|
8527
|
+
maxAttempts: 3
|
|
8528
|
+
});
|
|
8529
|
+
}
|
|
8530
|
+
start() {
|
|
8531
|
+
if (this.stopped) throw new Error("reflect worker: stop 后不可重新 start");
|
|
8532
|
+
if (this.timer !== void 0) return;
|
|
8533
|
+
this.pump();
|
|
8534
|
+
this.timer = setInterval(() => {
|
|
8535
|
+
this.pump();
|
|
8536
|
+
}, this.intervalMs);
|
|
8537
|
+
this.timer.unref();
|
|
8538
|
+
}
|
|
8539
|
+
/** 重入共享同一个 pump;executor 在任意时刻至多一个在跑。 */
|
|
8540
|
+
pump() {
|
|
8541
|
+
if (this.activePump !== void 0) return this.activePump;
|
|
8542
|
+
const active = this.drain();
|
|
8543
|
+
this.activePump = active;
|
|
8544
|
+
const clear = () => {
|
|
8545
|
+
if (this.activePump === active) this.activePump = void 0;
|
|
8546
|
+
};
|
|
8547
|
+
active.then(clear, clear);
|
|
8548
|
+
return active;
|
|
8549
|
+
}
|
|
8550
|
+
get cancelled() {
|
|
8551
|
+
return this.stopped || this.abort.signal.aborted || this.externalSignal?.aborted === true;
|
|
8552
|
+
}
|
|
8553
|
+
report(error, job) {
|
|
8554
|
+
if (this.onError === void 0) return;
|
|
8555
|
+
try {
|
|
8556
|
+
this.onError(error instanceof Error ? error : new Error(String(error)), job);
|
|
8557
|
+
} catch {}
|
|
8558
|
+
}
|
|
8559
|
+
async drain() {
|
|
8560
|
+
try {
|
|
8561
|
+
while (!this.cancelled) {
|
|
8562
|
+
const [job] = this.queue.claim({
|
|
8563
|
+
owner: this.owner,
|
|
8564
|
+
kinds: ["reflect"],
|
|
8565
|
+
leaseMs: this.leaseMs
|
|
8566
|
+
});
|
|
8567
|
+
if (job === void 0) break;
|
|
8568
|
+
const controller = new AbortController();
|
|
8569
|
+
this.currentAbort = controller;
|
|
8570
|
+
const signals = [
|
|
8571
|
+
controller.signal,
|
|
8572
|
+
this.abort.signal,
|
|
8573
|
+
AbortSignal.timeout(this.timeoutMs)
|
|
8574
|
+
];
|
|
8575
|
+
if (this.externalSignal !== void 0) signals.push(this.externalSignal);
|
|
8576
|
+
try {
|
|
8577
|
+
const payload = parsePayload(job.payload);
|
|
8578
|
+
await this.execute(payload, AbortSignal.any(signals));
|
|
8579
|
+
this.queue.complete({
|
|
8580
|
+
id: job.id,
|
|
8581
|
+
owner: this.owner
|
|
8582
|
+
});
|
|
8583
|
+
} catch (error) {
|
|
8584
|
+
let reported = error;
|
|
8585
|
+
try {
|
|
8586
|
+
this.queue.fail({
|
|
8587
|
+
id: job.id,
|
|
8588
|
+
owner: this.owner,
|
|
8589
|
+
error: errorText(error),
|
|
8590
|
+
retryDelayMs: this.retryDelayMs
|
|
8591
|
+
});
|
|
8592
|
+
} catch (queueError) {
|
|
8593
|
+
reported = queueError;
|
|
8594
|
+
}
|
|
8595
|
+
this.report(reported, job);
|
|
8596
|
+
} finally {
|
|
8597
|
+
this.currentAbort = void 0;
|
|
8598
|
+
}
|
|
8599
|
+
}
|
|
8600
|
+
} catch (error) {
|
|
8601
|
+
this.report(error);
|
|
8602
|
+
}
|
|
8603
|
+
}
|
|
8604
|
+
/** 停止认领新作业,取消在途执行并等待 queue 状态收束;queue 保持打开。 */
|
|
8605
|
+
async stop() {
|
|
8606
|
+
if (this.stopped) {
|
|
8607
|
+
await this.activePump;
|
|
8608
|
+
return;
|
|
8609
|
+
}
|
|
8610
|
+
this.stopped = true;
|
|
8611
|
+
if (this.timer !== void 0) clearInterval(this.timer);
|
|
8612
|
+
this.timer = void 0;
|
|
8613
|
+
this.abort.abort();
|
|
8614
|
+
this.currentAbort?.abort();
|
|
8615
|
+
await this.activePump;
|
|
8616
|
+
}
|
|
8617
|
+
};
|
|
8618
|
+
// src/jobs/host-reflect.ts
|
|
8619
|
+
/**
|
|
8620
|
+
* DSH 宿主侧的 reflect 作业工厂:打开持久队列,执行真实巩固,并统一停止/关闭。
|
|
8621
|
+
* @module @kenz1117/dsh-engram/jobs/host-reflect
|
|
8622
|
+
*/
|
|
8623
|
+
/** 终态作业保留窗口:与主库 op_log 同款 366 天,过窗 done/dead 由 prune 清除。 */
|
|
8624
|
+
const PRUNE_RETENTION_MS = 316224e5;
|
|
8625
|
+
/** prune 班车间隔:24 小时一班,启动时先跑一次。 */
|
|
8626
|
+
const PRUNE_INTERVAL_MS = 864e5;
|
|
8627
|
+
/** 启动真实 reflect worker;stop 先取消在途执行,再关闭独立 jobs.db。 */
|
|
8628
|
+
async function startAutoReflectWorker(options) {
|
|
8629
|
+
const queue = await openJobQueue(join(options.dbDir, "jobs.db"));
|
|
8630
|
+
try {
|
|
8631
|
+
queue.prune(PRUNE_RETENTION_MS);
|
|
8632
|
+
} catch (error) {
|
|
8633
|
+
console.warn(message("core.warnReflectFailed", { scope: "prune" }), error);
|
|
8634
|
+
}
|
|
8635
|
+
const pruneTimer = setInterval(() => {
|
|
8636
|
+
try {
|
|
8637
|
+
queue.prune(PRUNE_RETENTION_MS);
|
|
8638
|
+
} catch {}
|
|
8639
|
+
}, PRUNE_INTERVAL_MS);
|
|
8640
|
+
pruneTimer.unref();
|
|
8641
|
+
const worker = new DurableReflectWorker({
|
|
8642
|
+
queue,
|
|
8643
|
+
execute: async (payload, signal) => {
|
|
8644
|
+
const scope = payload.scope;
|
|
8645
|
+
if (scope === "project" && (payload.cwd === void 0 || !existsSync(join(options.dbDir, options.dbNameForCwd(payload.cwd))))) return;
|
|
8646
|
+
const store = scope === "user" ? await options.openStore("user") : await options.openProjectStore(payload.cwd);
|
|
8647
|
+
const outcome = await reflectObservations({
|
|
8648
|
+
store,
|
|
8649
|
+
embedder: await options.embedder(),
|
|
8650
|
+
scope,
|
|
8651
|
+
call: (params) => options.call(payload.sessionId, params),
|
|
8652
|
+
logRequest: (data) => {
|
|
8653
|
+
store.audit("reflect-request", "AUX", JSON.stringify(data)).catch(() => {});
|
|
8654
|
+
},
|
|
8655
|
+
route: payload.route,
|
|
8656
|
+
signal
|
|
8657
|
+
});
|
|
8658
|
+
if (outcome.formed + outcome.refined + outcome.confirmed + outcome.refuted > 0) console.log(message("core.logReflectDone", {
|
|
8659
|
+
scope,
|
|
8660
|
+
formed: outcome.formed,
|
|
8661
|
+
refined: outcome.refined,
|
|
8662
|
+
confirmed: outcome.confirmed,
|
|
8663
|
+
refuted: outcome.refuted
|
|
8664
|
+
}));
|
|
8665
|
+
if (outcome.dropped > 0) console.warn(message("core.warnReflectBatchDropped", { count: outcome.dropped }));
|
|
8666
|
+
},
|
|
8667
|
+
onError: (error, job) => {
|
|
8668
|
+
const scope = (job?.payload)?.scope;
|
|
8669
|
+
console.warn(message("core.warnReflectFailed", { scope: typeof scope === "string" ? scope : "unknown" }), error);
|
|
8670
|
+
}
|
|
8671
|
+
});
|
|
8672
|
+
worker.start();
|
|
8673
|
+
return {
|
|
8674
|
+
enqueue: (payload) => {
|
|
8675
|
+
worker.enqueue(payload);
|
|
8676
|
+
},
|
|
8677
|
+
pump: () => worker.pump(),
|
|
8678
|
+
stop: async () => {
|
|
8679
|
+
clearInterval(pruneTimer);
|
|
8680
|
+
try {
|
|
8681
|
+
await worker.stop();
|
|
8682
|
+
} finally {
|
|
8683
|
+
queue.close();
|
|
8684
|
+
}
|
|
8685
|
+
},
|
|
8686
|
+
summary: () => queue.summary(),
|
|
8687
|
+
list: (filter) => queue.list(filter)
|
|
8688
|
+
};
|
|
8689
|
+
}
|
|
8690
|
+
// src/application/memory-commands.ts
|
|
8691
|
+
/**
|
|
8692
|
+
* 更新一条记忆。不存在返回 undefined,让工具与 HTTP 各自保留既有错误协议。
|
|
8693
|
+
* 内容变化必须产生新向量;embedder 不可用时显式清空旧向量,禁止语义索引停在旧正文。
|
|
8694
|
+
*/
|
|
8695
|
+
async function updateMemory(deps, input) {
|
|
8696
|
+
const content = redactSecrets(sanitizeProtocolText(input.content));
|
|
8697
|
+
if (content.trim() === "") throw new EngramError("EMPTY_CONTENT", message("tool.updateContentEmptyAfterSanitize"));
|
|
8698
|
+
const old = await deps.store.get(input.id) ?? await deps.store.getMemory(input.id);
|
|
8699
|
+
if (old === void 0) return void 0;
|
|
8700
|
+
let embedding = null;
|
|
8701
|
+
const embedder = await deps.embedder;
|
|
8702
|
+
if (embedder !== void 0) embedding = (await embedder.embed([content.trim()]))[0] ?? null;
|
|
8703
|
+
return deps.store.update({
|
|
8704
|
+
id: old.id,
|
|
8705
|
+
scope: input.scope,
|
|
8706
|
+
kind: input.kind ?? old.kind,
|
|
8707
|
+
content,
|
|
8708
|
+
embedding,
|
|
8709
|
+
...input.importance === void 0 ? {} : { importance: Math.min(1, Math.max(0, input.importance)) },
|
|
8710
|
+
...input.imagery === void 0 ? {} : { imagery: input.imagery }
|
|
8711
|
+
});
|
|
8712
|
+
}
|
|
7896
8713
|
// src/store/import.ts
|
|
7897
8714
|
const SCOPES = [
|
|
7898
8715
|
"user",
|
|
@@ -7950,6 +8767,7 @@ const parseRecord = (raw, index) => {
|
|
|
7950
8767
|
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 非法`;
|
|
7951
8768
|
return {
|
|
7952
8769
|
id: asMemoryId(id),
|
|
8770
|
+
memoryId: asMemoryId(isStr(raw.memoryId) && raw.memoryId !== "" ? raw.memoryId : id),
|
|
7953
8771
|
scope: raw.scope,
|
|
7954
8772
|
kind: raw.kind,
|
|
7955
8773
|
content,
|
|
@@ -8112,6 +8930,7 @@ function parseMarkdownExport(raw, scope) {
|
|
|
8112
8930
|
if (!Number.isFinite(importance)) continue;
|
|
8113
8931
|
records.push({
|
|
8114
8932
|
id: asMemoryId(id),
|
|
8933
|
+
memoryId: asMemoryId(id),
|
|
8115
8934
|
scope,
|
|
8116
8935
|
kind,
|
|
8117
8936
|
content,
|
|
@@ -8517,6 +9336,19 @@ function joinUrl(base, relative) {
|
|
|
8517
9336
|
function systemOneEndpoint(baseUrl) {
|
|
8518
9337
|
return joinUrl(baseUrl, "systemone");
|
|
8519
9338
|
}
|
|
9339
|
+
/**
|
|
9340
|
+
* 宿主凭据只能发往 provider 配置中已信任的 origin。面板可以覆盖同源路径,
|
|
9341
|
+
* 但不能把存储在 DSH 凭据库里的 Bearer key 指向另一个服务。
|
|
9342
|
+
*/
|
|
9343
|
+
function isTrustedJevEndpoint(baseUrl, endpoint) {
|
|
9344
|
+
try {
|
|
9345
|
+
const trusted = new URL(baseUrl);
|
|
9346
|
+
const candidate = new URL(endpoint);
|
|
9347
|
+
return (candidate.protocol === "http:" || candidate.protocol === "https:") && candidate.username === "" && candidate.password === "" && candidate.origin === trusted.origin;
|
|
9348
|
+
} catch {
|
|
9349
|
+
return false;
|
|
9350
|
+
}
|
|
9351
|
+
}
|
|
8520
9352
|
/** Дескриптор конфигурации хоста по namespace (например `llm-pi-ai`). */
|
|
8521
9353
|
async function readSettingsValue(ctx, ns) {
|
|
8522
9354
|
const settings = ctx.get("settings");
|
|
@@ -8702,7 +9534,9 @@ async function resolveJevConnection(ctx, providerId, model, timeoutMs, endpointO
|
|
|
8702
9534
|
if (typeof rekvisites === "string") return rekvisites;
|
|
8703
9535
|
const chosenModel = model.trim() !== "" ? model.trim() : pickJevModel(rekvisites.modelIds);
|
|
8704
9536
|
if (chosenModel === void 0) return message("misc.jevModelNotPicked", { provider: providerId });
|
|
8705
|
-
const
|
|
9537
|
+
const chosen = endpointOverride !== void 0 && endpointOverride.trim() !== "" ? endpointOverride.trim() : void 0;
|
|
9538
|
+
if (chosen !== void 0 && (rekvisites.baseUrl === void 0 || !isTrustedJevEndpoint(rekvisites.baseUrl, chosen))) return message("misc.jevEndpointOriginMismatch", { provider: providerId });
|
|
9539
|
+
const endpoint = chosen ?? (rekvisites.baseUrl === void 0 ? void 0 : systemOneEndpoint(rekvisites.baseUrl));
|
|
8706
9540
|
if (endpoint === void 0) return message("misc.jevProviderHasNoBaseUrl", { provider: providerId });
|
|
8707
9541
|
if (rekvisites.apiKey === "") return message("misc.jevProviderKeyMissing", {
|
|
8708
9542
|
provider: providerId,
|
|
@@ -9462,6 +10296,7 @@ async function aggregateTelemetry(openStore, windowDays = DEFAULT_WINDOW_DAYS, s
|
|
|
9462
10296
|
distillRequests: 0,
|
|
9463
10297
|
compressRequests: 0,
|
|
9464
10298
|
searchRewrites: 0,
|
|
10299
|
+
searchExposures: 0,
|
|
9465
10300
|
consumptions: 0,
|
|
9466
10301
|
consolidations: 0,
|
|
9467
10302
|
reviewAnswers: 0
|
|
@@ -9485,6 +10320,7 @@ async function aggregateTelemetry(openStore, windowDays = DEFAULT_WINDOW_DAYS, s
|
|
|
9485
10320
|
countsAgg.distillRequests += counts["distill-request"] ?? 0;
|
|
9486
10321
|
countsAgg.compressRequests += counts["compress-request"] ?? 0;
|
|
9487
10322
|
countsAgg.searchRewrites += counts["search-rewrite-request"] ?? 0;
|
|
10323
|
+
countsAgg.searchExposures += counts["search-exposure"] ?? 0;
|
|
9488
10324
|
countsAgg.consumptions += counts["outcome-report"] ?? 0;
|
|
9489
10325
|
countsAgg.consolidations += counts.consolidation ?? 0;
|
|
9490
10326
|
countsAgg.reviewAnswers += counts["review-answer"] ?? 0;
|
|
@@ -9916,6 +10752,26 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
9916
10752
|
});
|
|
9917
10753
|
return;
|
|
9918
10754
|
}
|
|
10755
|
+
if (req.method === "GET" && route === "jobs") {
|
|
10756
|
+
const statusParam = url.searchParams.get("status");
|
|
10757
|
+
const statuses = statusParam === null || statusParam === "" || statusParam === "all" ? void 0 : statusParam.split(",").map((raw) => raw.trim()).filter((raw) => raw === "queued" || raw === "running" || raw === "done" || raw === "dead");
|
|
10758
|
+
const limit = Math.min(200, Math.max(1, Number(url.searchParams.get("limit") ?? 50) || 50));
|
|
10759
|
+
json(res, 200, {
|
|
10760
|
+
available: deps.jobs !== void 0,
|
|
10761
|
+
summary: deps.jobs?.summary() ?? {
|
|
10762
|
+
total: 0,
|
|
10763
|
+
queued: 0,
|
|
10764
|
+
running: 0,
|
|
10765
|
+
done: 0,
|
|
10766
|
+
dead: 0
|
|
10767
|
+
},
|
|
10768
|
+
items: deps.jobs?.list({
|
|
10769
|
+
...statuses === void 0 ? {} : { statuses },
|
|
10770
|
+
limit
|
|
10771
|
+
}) ?? []
|
|
10772
|
+
});
|
|
10773
|
+
return;
|
|
10774
|
+
}
|
|
9919
10775
|
if (req.method === "GET" && route === "stats") {
|
|
9920
10776
|
json(res, 200, { parts: await Promise.all([
|
|
9921
10777
|
"user",
|
|
@@ -9927,6 +10783,31 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
9927
10783
|
}))) });
|
|
9928
10784
|
return;
|
|
9929
10785
|
}
|
|
10786
|
+
if (req.method === "GET" && route === "injections") {
|
|
10787
|
+
const scope = scopeOf$1(url.searchParams.get("scope"), "user");
|
|
10788
|
+
const sessionId = url.searchParams.get("sessionId") ?? void 0;
|
|
10789
|
+
const limit = Math.min(200, Math.max(1, Number(url.searchParams.get("limit") ?? 50) || 50));
|
|
10790
|
+
json(res, 200, { items: await (await storeFor(scope)).listInjections({
|
|
10791
|
+
...sessionId === void 0 ? {} : { sessionId },
|
|
10792
|
+
limit
|
|
10793
|
+
}) });
|
|
10794
|
+
return;
|
|
10795
|
+
}
|
|
10796
|
+
if (req.method === "GET" && route === "injection") {
|
|
10797
|
+
const scope = scopeOf$1(url.searchParams.get("scope"), "user");
|
|
10798
|
+
const id = url.searchParams.get("id");
|
|
10799
|
+
if (id === null || id === "") {
|
|
10800
|
+
json(res, 400, { error: "id required" });
|
|
10801
|
+
return;
|
|
10802
|
+
}
|
|
10803
|
+
const snapshot = await (await storeFor(scope)).getInjection(id);
|
|
10804
|
+
if (snapshot === void 0) {
|
|
10805
|
+
json(res, 404, { error: "injection not found" });
|
|
10806
|
+
return;
|
|
10807
|
+
}
|
|
10808
|
+
json(res, 200, snapshot);
|
|
10809
|
+
return;
|
|
10810
|
+
}
|
|
9930
10811
|
if (req.method === "GET" && route === "list") {
|
|
9931
10812
|
const scope = scopeOf$1(url.searchParams.get("scope"), "user");
|
|
9932
10813
|
const status = url.searchParams.get("status");
|
|
@@ -9974,6 +10855,8 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
9974
10855
|
degraded,
|
|
9975
10856
|
hits: hits.map((hit) => ({
|
|
9976
10857
|
id: hit.record.id,
|
|
10858
|
+
memoryId: hit.record.memoryId,
|
|
10859
|
+
revisionId: hit.record.id,
|
|
9977
10860
|
score: hit.score,
|
|
9978
10861
|
via: hit.via,
|
|
9979
10862
|
...hit.viaEdge === void 0 ? {} : { viaEdge: hit.viaEdge },
|
|
@@ -9986,6 +10869,46 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
9986
10869
|
});
|
|
9987
10870
|
return;
|
|
9988
10871
|
}
|
|
10872
|
+
if (req.method === "GET" && route === "governance") {
|
|
10873
|
+
const scope = scopeOf$1(url.searchParams.get("scope"), "user");
|
|
10874
|
+
const limit = Math.min(100, Math.max(1, Number(url.searchParams.get("limit") ?? 50) || 50));
|
|
10875
|
+
const all = await (await storeFor(scope)).listContradictions(200);
|
|
10876
|
+
json(res, 200, {
|
|
10877
|
+
scope,
|
|
10878
|
+
items: all.slice(0, limit),
|
|
10879
|
+
total: all.length
|
|
10880
|
+
});
|
|
10881
|
+
return;
|
|
10882
|
+
}
|
|
10883
|
+
if (req.method === "POST" && route === "governance") {
|
|
10884
|
+
if (!guardWrite(req, res, deps.panelAccess === "lan")) return;
|
|
10885
|
+
const body = await readBody(req, res, deps.language);
|
|
10886
|
+
if (body === null) return;
|
|
10887
|
+
const scope = scopeOf$1(typeof body.scope === "string" ? body.scope : null, "user");
|
|
10888
|
+
const action = body.action;
|
|
10889
|
+
if (action !== "dismiss" && action !== "forget-loser") {
|
|
10890
|
+
json(res, 400, { error: "action must be dismiss or forget-loser" });
|
|
10891
|
+
return;
|
|
10892
|
+
}
|
|
10893
|
+
if (typeof body.firstId !== "string" || typeof body.secondId !== "string" || body.firstId === "" || body.secondId === "") {
|
|
10894
|
+
json(res, 400, { error: "firstId and secondId required" });
|
|
10895
|
+
return;
|
|
10896
|
+
}
|
|
10897
|
+
if (action === "forget-loser" && (typeof body.loserId !== "string" || body.loserId === "")) {
|
|
10898
|
+
json(res, 400, { error: "loserId required" });
|
|
10899
|
+
return;
|
|
10900
|
+
}
|
|
10901
|
+
json(res, 200, {
|
|
10902
|
+
ok: true,
|
|
10903
|
+
result: await (await storeFor(scope)).resolveContradiction({
|
|
10904
|
+
firstId: body.firstId,
|
|
10905
|
+
secondId: body.secondId,
|
|
10906
|
+
action,
|
|
10907
|
+
...typeof body.loserId === "string" ? { loserId: body.loserId } : {}
|
|
10908
|
+
})
|
|
10909
|
+
});
|
|
10910
|
+
return;
|
|
10911
|
+
}
|
|
9989
10912
|
if (req.method === "GET" && route === "observations") {
|
|
9990
10913
|
const scope = scopeOf$1(url.searchParams.get("scope"), "user");
|
|
9991
10914
|
const status = url.searchParams.get("status");
|
|
@@ -10299,10 +11222,14 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10299
11222
|
json(res, 400, { error: "id required" });
|
|
10300
11223
|
return;
|
|
10301
11224
|
}
|
|
10302
|
-
const
|
|
10303
|
-
|
|
10304
|
-
|
|
10305
|
-
|
|
11225
|
+
const store = await storeFor(scope);
|
|
11226
|
+
let view = await store.review(id);
|
|
11227
|
+
if (view !== void 0 && String(view.record.memoryId) === id) {
|
|
11228
|
+
const current = await store.getMemory(id);
|
|
11229
|
+
if (current !== void 0 && String(current.id) !== id) view = await store.review(current.id);
|
|
11230
|
+
} else if (view === void 0) {
|
|
11231
|
+
const current = await store.getMemory(id);
|
|
11232
|
+
if (current !== void 0) view = await store.review(current.id);
|
|
10306
11233
|
}
|
|
10307
11234
|
json(res, 200, view);
|
|
10308
11235
|
return;
|
|
@@ -10923,25 +11850,36 @@ function registerEngramRoutes(ctx, deps) {
|
|
|
10923
11850
|
json(res, 400, { error: "content required" });
|
|
10924
11851
|
return;
|
|
10925
11852
|
}
|
|
10926
|
-
|
|
10927
|
-
|
|
10928
|
-
|
|
11853
|
+
try {
|
|
11854
|
+
const record = await updateMemory({
|
|
11855
|
+
store,
|
|
11856
|
+
embedder: deps.embedder
|
|
11857
|
+
}, {
|
|
11858
|
+
id: body.id,
|
|
11859
|
+
scope,
|
|
11860
|
+
content: body.content,
|
|
11861
|
+
...typeof body.kind === "string" && [
|
|
11862
|
+
"fact",
|
|
11863
|
+
"preference",
|
|
11864
|
+
"decision",
|
|
11865
|
+
"episode",
|
|
11866
|
+
"skill"
|
|
11867
|
+
].includes(body.kind) ? { kind: body.kind } : {},
|
|
11868
|
+
...typeof body.importance === "number" && Number.isFinite(body.importance) ? { importance: body.importance } : {}
|
|
11869
|
+
});
|
|
11870
|
+
if (record === void 0) {
|
|
11871
|
+
json(res, 404, { error: messageIn(deps.language, "misc.recordNotFound", { id: body.id }) });
|
|
11872
|
+
return;
|
|
11873
|
+
}
|
|
11874
|
+
json(res, 200, { record });
|
|
10929
11875
|
return;
|
|
11876
|
+
} catch (error) {
|
|
11877
|
+
if (error instanceof EngramError && error.code === "EMPTY_CONTENT") {
|
|
11878
|
+
json(res, 400, { error: error.message });
|
|
11879
|
+
return;
|
|
11880
|
+
}
|
|
11881
|
+
throw error;
|
|
10930
11882
|
}
|
|
10931
|
-
json(res, 200, { record: await store.update({
|
|
10932
|
-
id: body.id,
|
|
10933
|
-
scope,
|
|
10934
|
-
kind: typeof body.kind === "string" && [
|
|
10935
|
-
"fact",
|
|
10936
|
-
"preference",
|
|
10937
|
-
"decision",
|
|
10938
|
-
"episode",
|
|
10939
|
-
"skill"
|
|
10940
|
-
].includes(body.kind) ? body.kind : old.kind,
|
|
10941
|
-
content: body.content,
|
|
10942
|
-
...typeof body.importance === "number" && Number.isFinite(body.importance) ? { importance: Math.min(1, Math.max(0, body.importance)) } : {}
|
|
10943
|
-
}) });
|
|
10944
|
-
return;
|
|
10945
11883
|
}
|
|
10946
11884
|
json(res, 200, { record: route === "forget" ? await store.forget(body.id) : await store.restore(body.id) });
|
|
10947
11885
|
return;
|
|
@@ -12178,7 +13116,7 @@ function placardImprovementHint(score) {
|
|
|
12178
13116
|
*/
|
|
12179
13117
|
/** 当前 schema 版本;结构性变更必须 +1。可空列与伴随表走增量迁移(见 openEngramStore 的迁移段)。
|
|
12180
13118
|
* v12→v13 是纯数据迁移(历史房名归一化),但同样借版本号作为「只跑一次」的开关。 */
|
|
12181
|
-
const SCHEMA_VERSION =
|
|
13119
|
+
const SCHEMA_VERSION = 15;
|
|
12182
13120
|
/** 增量迁移表:key 为起始版本,value 为升到下一版本的 SQL(可多语句)。
|
|
12183
13121
|
* v2 → v3:nodes 补可空列 outcome(使用效果回报)。
|
|
12184
13122
|
* v3 → v4:新增 nodes_revisions 修订表(update 归档旧条目时的内容快照)。
|
|
@@ -12206,7 +13144,10 @@ const SCHEMA_VERSION = 13;
|
|
|
12206
13144
|
* v12 → v13:历史房名归一化——0.8.12 及更早把**显示名**写进 slot_room(「事实厅」),
|
|
12207
13145
|
* 语言中立 id 启用后同一逻辑房会裂成两间(容量 9 变 18、tour_routes 按 room 断开)。
|
|
12208
13146
|
* 升级时一次性改写为 id,含扩建房(「事实厅-2」→「fact-2」);已经是 id 的库零行改动,
|
|
12209
|
-
* SQL 自身幂等。手动脚本 scripts/migrate-room-ids.mjs 保留为兜底。
|
|
13147
|
+
* SQL 自身幂等。手动脚本 scripts/migrate-room-ids.mjs 保留为兜底。
|
|
13148
|
+
* v13 → v14:injection_snapshots 持久化实际注入的最终包;列表只取 head,正文按 id 读取。
|
|
13149
|
+
* v14 → v15:稳定逻辑身份 memory_id——nodes.id 保留为 revision id;存量行 memory_id=id,
|
|
13150
|
+
* update 继承旧 memory_id,修订表补 memory_id 使同一逻辑身份的完整修订链可查。 */
|
|
12210
13151
|
const MIGRATIONS = {
|
|
12211
13152
|
"2": "ALTER TABLE nodes ADD COLUMN outcome TEXT",
|
|
12212
13153
|
"3": `CREATE TABLE IF NOT EXISTS nodes_revisions (
|
|
@@ -12257,7 +13198,19 @@ const MIGRATIONS = {
|
|
|
12257
13198
|
UPDATE nodes SET slot_room = replace(slot_room, '偏好阁', 'preference') WHERE slot_room LIKE '偏好阁%';
|
|
12258
13199
|
UPDATE nodes SET slot_room = replace(slot_room, '决策堂', 'decision') WHERE slot_room LIKE '决策堂%';
|
|
12259
13200
|
UPDATE nodes SET slot_room = replace(slot_room, '往事廊', 'episode') WHERE slot_room LIKE '往事廊%';
|
|
12260
|
-
UPDATE nodes SET slot_room = replace(slot_room, '技法坊', 'skill') WHERE slot_room LIKE '技法坊%'
|
|
13201
|
+
UPDATE nodes SET slot_room = replace(slot_room, '技法坊', 'skill') WHERE slot_room LIKE '技法坊%';`,
|
|
13202
|
+
"14": `ALTER TABLE nodes ADD COLUMN memory_id TEXT;
|
|
13203
|
+
UPDATE nodes SET memory_id = id WHERE memory_id IS NULL;
|
|
13204
|
+
ALTER TABLE nodes_revisions ADD COLUMN memory_id TEXT;
|
|
13205
|
+
UPDATE nodes_revisions SET memory_id = (
|
|
13206
|
+
SELECT nodes.memory_id FROM nodes WHERE nodes.id = nodes_revisions.node_id
|
|
13207
|
+
) WHERE memory_id IS NULL;
|
|
13208
|
+
CREATE INDEX IF NOT EXISTS nodes_memory_created ON nodes (memory_id, created_at);`,
|
|
13209
|
+
"13": `CREATE TABLE IF NOT EXISTS injection_snapshots (
|
|
13210
|
+
id TEXT PRIMARY KEY, session_id TEXT NOT NULL, packet_hash TEXT NOT NULL,
|
|
13211
|
+
packet TEXT NOT NULL, memory_ids_json TEXT NOT NULL, has_curated INTEGER NOT NULL,
|
|
13212
|
+
compaction_count INTEGER NOT NULL, created_at INTEGER NOT NULL);
|
|
13213
|
+
CREATE INDEX IF NOT EXISTS injection_session_created ON injection_snapshots (session_id, created_at);`
|
|
12261
13214
|
};
|
|
12262
13215
|
/** RRF 融合常数:score = Σ 1/(K + rank)。 */
|
|
12263
13216
|
const RRF_K = 60;
|
|
@@ -12269,12 +13222,29 @@ const CONTRADICTION_COSINE = .88;
|
|
|
12269
13222
|
const RANK_POOL = 64;
|
|
12270
13223
|
/** 一跳扩展引入的邻居上限。 */
|
|
12271
13224
|
const EXPANSION_LIMIT = 32;
|
|
12272
|
-
/**
|
|
13225
|
+
/** 置信度增量:真实反馈专用——效果回报 success 与写入期 MERGE 并入强化(检索曝光不算反馈)。 */
|
|
12273
13226
|
const CONFIDENCE_BUMP = .05;
|
|
12274
13227
|
/** 效果回报降权:failure 回报的置信度扣减(success 复用 CONFIDENCE_BUMP)。 */
|
|
12275
13228
|
const OUTCOME_PENALTY = .1;
|
|
12276
13229
|
/** 审计视图返回的操作日志条数上限。 */
|
|
12277
13230
|
const REVIEW_LOG_LIMIT = 20;
|
|
13231
|
+
function rowToInjectionHead(row) {
|
|
13232
|
+
let memoryIds = [];
|
|
13233
|
+
try {
|
|
13234
|
+
const parsed = JSON.parse(row.memory_ids_json);
|
|
13235
|
+
if (Array.isArray(parsed)) memoryIds = parsed.filter((id) => typeof id === "string").map(asMemoryId);
|
|
13236
|
+
} catch {}
|
|
13237
|
+
return {
|
|
13238
|
+
id: row.id,
|
|
13239
|
+
sessionId: row.session_id,
|
|
13240
|
+
packetHash: row.packet_hash,
|
|
13241
|
+
memoryIds,
|
|
13242
|
+
hasCurated: row.has_curated === 1,
|
|
13243
|
+
compactionCount: row.compaction_count,
|
|
13244
|
+
packetBytes: row.packet_bytes,
|
|
13245
|
+
createdAt: row.created_at
|
|
13246
|
+
};
|
|
13247
|
+
}
|
|
12278
13248
|
/** 把意象铭牌序列化为 JSON(缺省序列化为 null,落库)。 */
|
|
12279
13249
|
function imageryToJson(imagery) {
|
|
12280
13250
|
if (imagery === void 0) return null;
|
|
@@ -12305,6 +13275,7 @@ function rowToRecord(row) {
|
|
|
12305
13275
|
const hasReviewState = row.next_review_at !== null || row.ease_factor !== null || row.interval_days !== null;
|
|
12306
13276
|
return {
|
|
12307
13277
|
id: asMemoryId(row.id),
|
|
13278
|
+
memoryId: asMemoryId(row.memory_id ?? row.id),
|
|
12308
13279
|
scope: row.scope,
|
|
12309
13280
|
kind: row.kind,
|
|
12310
13281
|
content: row.content,
|
|
@@ -12488,7 +13459,7 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12488
13459
|
db.exec(`
|
|
12489
13460
|
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
12490
13461
|
CREATE TABLE IF NOT EXISTS nodes (
|
|
12491
|
-
id TEXT PRIMARY KEY, scope TEXT NOT NULL, kind TEXT NOT NULL, content TEXT NOT NULL,
|
|
13462
|
+
id TEXT PRIMARY KEY, memory_id TEXT, scope TEXT NOT NULL, kind TEXT NOT NULL, content TEXT NOT NULL,
|
|
12492
13463
|
importance REAL NOT NULL, confidence REAL NOT NULL, status TEXT NOT NULL,
|
|
12493
13464
|
created_at INTEGER NOT NULL, last_accessed_at INTEGER NOT NULL, access_count INTEGER NOT NULL,
|
|
12494
13465
|
source_session_id TEXT, source_round INTEGER, source_seq INTEGER, embedding BLOB, outcome TEXT,
|
|
@@ -12503,7 +13474,7 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12503
13474
|
seq INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL, op TEXT NOT NULL,
|
|
12504
13475
|
target_id TEXT NOT NULL, detail TEXT);
|
|
12505
13476
|
CREATE TABLE IF NOT EXISTS nodes_revisions (
|
|
12506
|
-
node_id TEXT NOT NULL, content TEXT NOT NULL, kind TEXT NOT NULL,
|
|
13477
|
+
node_id TEXT NOT NULL, memory_id TEXT, content TEXT NOT NULL, kind TEXT NOT NULL,
|
|
12507
13478
|
importance REAL NOT NULL, superseded_at INTEGER NOT NULL);
|
|
12508
13479
|
CREATE TABLE IF NOT EXISTS tour_routes (
|
|
12509
13480
|
position INTEGER PRIMARY KEY, node_id TEXT NOT NULL);
|
|
@@ -12530,6 +13501,10 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12530
13501
|
id TEXT PRIMARY KEY, scope TEXT NOT NULL, belief TEXT NOT NULL, status TEXT NOT NULL,
|
|
12531
13502
|
sources_json TEXT NOT NULL, proof_count INTEGER NOT NULL, embedding BLOB,
|
|
12532
13503
|
created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, last_validated_at INTEGER NOT NULL);
|
|
13504
|
+
CREATE TABLE IF NOT EXISTS injection_snapshots (
|
|
13505
|
+
id TEXT PRIMARY KEY, session_id TEXT NOT NULL, packet_hash TEXT NOT NULL,
|
|
13506
|
+
packet TEXT NOT NULL, memory_ids_json TEXT NOT NULL, has_curated INTEGER NOT NULL,
|
|
13507
|
+
compaction_count INTEGER NOT NULL, created_at INTEGER NOT NULL);
|
|
12533
13508
|
CREATE VIRTUAL TABLE IF NOT EXISTS nodes_fts USING fts5(node_id UNINDEXED, content, tokenize='unicode61');
|
|
12534
13509
|
CREATE INDEX IF NOT EXISTS nodes_scope_status ON nodes (scope, status);
|
|
12535
13510
|
CREATE INDEX IF NOT EXISTS nodes_kind_created ON nodes (kind, created_at);
|
|
@@ -12538,11 +13513,13 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12538
13513
|
CREATE INDEX IF NOT EXISTS node_entities_entity ON node_entities (entity_id);
|
|
12539
13514
|
CREATE INDEX IF NOT EXISTS facts_entity ON facts (entity_id);
|
|
12540
13515
|
CREATE INDEX IF NOT EXISTS observations_status ON observations (status, proof_count, updated_at);
|
|
13516
|
+
CREATE INDEX IF NOT EXISTS injection_session_created ON injection_snapshots (session_id, created_at);
|
|
12541
13517
|
`);
|
|
12542
13518
|
const versionRow = db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get();
|
|
12543
13519
|
if (versionRow === void 0) {
|
|
12544
13520
|
db.exec(`CREATE INDEX IF NOT EXISTS nodes_slot ON nodes (slot_room, slot_index);
|
|
12545
|
-
CREATE INDEX IF NOT EXISTS nodes_review_due ON nodes (next_review_at)
|
|
13521
|
+
CREATE INDEX IF NOT EXISTS nodes_review_due ON nodes (next_review_at);
|
|
13522
|
+
CREATE INDEX IF NOT EXISTS nodes_memory_created ON nodes (memory_id, created_at);`);
|
|
12546
13523
|
db.prepare("INSERT INTO meta (key, value) VALUES ('schema_version', ?)").run(String(SCHEMA_VERSION));
|
|
12547
13524
|
} else {
|
|
12548
13525
|
let version = Number(versionRow.value);
|
|
@@ -12551,13 +13528,18 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12551
13528
|
supported: SCHEMA_VERSION,
|
|
12552
13529
|
path
|
|
12553
13530
|
}));
|
|
12554
|
-
if (version < SCHEMA_VERSION)
|
|
12555
|
-
|
|
12556
|
-
|
|
12557
|
-
|
|
12558
|
-
|
|
12559
|
-
|
|
12560
|
-
})
|
|
13531
|
+
if (version < SCHEMA_VERSION) {
|
|
13532
|
+
const snapshotPath = `${path}.pre-migration`;
|
|
13533
|
+
try {
|
|
13534
|
+
await rm(snapshotPath, { force: true });
|
|
13535
|
+
const quoted = snapshotPath.replaceAll("'", "''");
|
|
13536
|
+
db.exec(`VACUUM INTO '${quoted}'`);
|
|
13537
|
+
} catch (error) {
|
|
13538
|
+
console.warn(message("store.preMigrationSnapshotFailed", {
|
|
13539
|
+
path,
|
|
13540
|
+
msg: error instanceof Error ? error.message : String(error)
|
|
13541
|
+
}));
|
|
13542
|
+
}
|
|
12561
13543
|
}
|
|
12562
13544
|
while (version < SCHEMA_VERSION) {
|
|
12563
13545
|
const migration = MIGRATIONS[String(version)];
|
|
@@ -12612,18 +13594,22 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12612
13594
|
storedDim = length;
|
|
12613
13595
|
};
|
|
12614
13596
|
const sqlGet = db.prepare("SELECT * FROM nodes WHERE id = ?");
|
|
13597
|
+
const sqlGetMemory = db.prepare(`SELECT * FROM nodes WHERE memory_id = ?
|
|
13598
|
+
ORDER BY CASE status WHEN 'active' THEN 0 ELSE 1 END, created_at DESC, id DESC LIMIT 1`);
|
|
12615
13599
|
const sqlInsert = db.prepare(`INSERT INTO nodes
|
|
12616
|
-
(id, scope, kind, content, importance, confidence, status, created_at, last_accessed_at, access_count,
|
|
13600
|
+
(id, memory_id, scope, kind, content, importance, confidence, status, created_at, last_accessed_at, access_count,
|
|
12617
13601
|
source_session_id, source_round, source_seq, embedding, imagery_json,
|
|
12618
13602
|
slot_room, slot_index, imagery_score, next_review_at, ease_factor, interval_days)
|
|
12619
|
-
VALUES (?, ?, ?, ?, ?, ?, 'active', ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
13603
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
12620
13604
|
const sqlFtsInsert = db.prepare("INSERT INTO nodes_fts (node_id, content) VALUES (?, ?)");
|
|
12621
13605
|
const sqlSetStatus = db.prepare("UPDATE nodes SET status = ?, last_accessed_at = ? WHERE id = ?");
|
|
13606
|
+
const sqlActiveMemorySiblings = db.prepare(`SELECT id FROM nodes
|
|
13607
|
+
WHERE memory_id = ? AND id != ? AND status = 'active'`);
|
|
12622
13608
|
const sqlSetOutcome = db.prepare(`UPDATE nodes
|
|
12623
13609
|
SET outcome = ?,
|
|
12624
13610
|
confidence = CASE WHEN ? = 'success' THEN min(1.0, confidence + ${CONFIDENCE_BUMP}) ELSE max(0.0, confidence - ${OUTCOME_PENALTY}) END
|
|
12625
13611
|
WHERE id = ?`);
|
|
12626
|
-
const
|
|
13612
|
+
const sqlReinforce = db.prepare(`UPDATE nodes SET access_count = access_count + 1, last_accessed_at = ?,
|
|
12627
13613
|
confidence = MIN(1, confidence + ${CONFIDENCE_BUMP}) WHERE id = ?`);
|
|
12628
13614
|
const sqlLog = db.prepare("INSERT INTO op_log (at, op, target_id, detail) VALUES (?, ?, ?, ?)");
|
|
12629
13615
|
const sqlHasAudit = db.prepare("SELECT 1 AS x FROM op_log WHERE op = ? AND detail = ? LIMIT 1");
|
|
@@ -12647,13 +13633,24 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12647
13633
|
)`);
|
|
12648
13634
|
const sqlRecentOps = db.prepare("SELECT at, op, target_id, detail FROM op_log ORDER BY seq DESC LIMIT ?");
|
|
12649
13635
|
const sqlCountOps = db.prepare("SELECT op, COUNT(*) AS n FROM op_log WHERE at >= ? GROUP BY op");
|
|
12650
|
-
const sqlRevisionInsert = db.prepare("INSERT INTO nodes_revisions (node_id, content, kind, importance, superseded_at) VALUES (?, ?, ?, ?, ?)");
|
|
12651
|
-
const sqlRevisionsById = db.prepare("SELECT content, kind, importance, superseded_at FROM nodes_revisions WHERE
|
|
13636
|
+
const sqlRevisionInsert = db.prepare("INSERT INTO nodes_revisions (node_id, memory_id, content, kind, importance, superseded_at) VALUES (?, ?, ?, ?, ?, ?)");
|
|
13637
|
+
const sqlRevisionsById = db.prepare("SELECT content, kind, importance, superseded_at FROM nodes_revisions WHERE memory_id = ? ORDER BY superseded_at DESC, rowid DESC");
|
|
12652
13638
|
const sqlTopActive = db.prepare("SELECT * FROM nodes WHERE scope = ? AND status = 'active' ORDER BY importance DESC, confidence DESC LIMIT ?");
|
|
12653
13639
|
const sqlEdgeUpsert = db.prepare("INSERT OR IGNORE INTO edges (from_id, to_id, type, created_at) VALUES (?, ?, ?, ?)");
|
|
12654
13640
|
const sqlNeighbors = db.prepare(`SELECT * FROM edges WHERE from_id IN (SELECT value FROM json_each(?))
|
|
12655
13641
|
AND type IN ('supports','refines','related') LIMIT ?`);
|
|
12656
13642
|
const sqlEdgesTouching = db.prepare("SELECT from_id, to_id, type FROM edges WHERE from_id = ? OR to_id = ?");
|
|
13643
|
+
const sqlContradictions = db.prepare(`SELECT e.from_id, e.to_id, e.created_at
|
|
13644
|
+
FROM edges e
|
|
13645
|
+
JOIN nodes first ON first.id = e.from_id AND first.status = 'active'
|
|
13646
|
+
JOIN nodes second ON second.id = e.to_id AND second.status = 'active'
|
|
13647
|
+
WHERE e.type = 'contradicts'
|
|
13648
|
+
ORDER BY e.created_at DESC LIMIT ?`);
|
|
13649
|
+
const sqlContradictionPair = db.prepare(`SELECT from_id, to_id, created_at FROM edges
|
|
13650
|
+
WHERE type = 'contradicts'
|
|
13651
|
+
AND ((from_id = ? AND to_id = ?) OR (from_id = ? AND to_id = ?))
|
|
13652
|
+
LIMIT 1`);
|
|
13653
|
+
const sqlEdgeDelete = db.prepare("DELETE FROM edges WHERE from_id = ? AND to_id = ? AND type = ?");
|
|
12657
13654
|
const sqlCountBy = db.prepare("SELECT status, COUNT(*) AS n FROM nodes GROUP BY status");
|
|
12658
13655
|
const sqlCountKind = db.prepare("SELECT kind, COUNT(*) AS n FROM nodes GROUP BY kind");
|
|
12659
13656
|
const sqlCountEdges = db.prepare("SELECT COUNT(*) AS n FROM edges");
|
|
@@ -12662,10 +13659,10 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12662
13659
|
const sqlAllNodes = db.prepare("SELECT * FROM nodes ORDER BY created_at");
|
|
12663
13660
|
const sqlAllEdges = db.prepare("SELECT * FROM edges");
|
|
12664
13661
|
const sqlImportInsert = db.prepare(`INSERT INTO nodes
|
|
12665
|
-
(id, scope, kind, content, importance, confidence, status, created_at, last_accessed_at, access_count,
|
|
13662
|
+
(id, memory_id, scope, kind, content, importance, confidence, status, created_at, last_accessed_at, access_count,
|
|
12666
13663
|
source_session_id, source_round, source_seq, embedding, outcome, imagery_json,
|
|
12667
13664
|
slot_room, slot_index, imagery_score, next_review_at, ease_factor, interval_days, review_reps)
|
|
12668
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
13665
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
12669
13666
|
const sqlImportContentMatch = db.prepare("SELECT id FROM nodes WHERE content = ? LIMIT 1");
|
|
12670
13667
|
const sqlImportAttachEmbedding = db.prepare("UPDATE nodes SET embedding = ? WHERE id = ?");
|
|
12671
13668
|
const vectorStatements = /* @__PURE__ */ new Map();
|
|
@@ -12723,6 +13720,16 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12723
13720
|
ON CONFLICT (session_id) DO UPDATE SET summary = excluded.summary, updated_at = excluded.updated_at`);
|
|
12724
13721
|
const sqlSessionSummaryGet = db.prepare("SELECT session_id, summary FROM session_summaries WHERE session_id = ?");
|
|
12725
13722
|
const sqlSessionSummaryMany = db.prepare("SELECT session_id, summary FROM session_summaries WHERE session_id IN (SELECT value FROM json_each(?))");
|
|
13723
|
+
const sqlInjectionInsert = db.prepare(`INSERT INTO injection_snapshots
|
|
13724
|
+
(id, session_id, packet_hash, packet, memory_ids_json, has_curated, compaction_count, created_at)
|
|
13725
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
13726
|
+
const sqlInjectionHead = `SELECT id, session_id, packet_hash, memory_ids_json, has_curated,
|
|
13727
|
+
compaction_count, LENGTH(CAST(packet AS BLOB)) AS packet_bytes, created_at FROM injection_snapshots`;
|
|
13728
|
+
const sqlInjectionList = db.prepare(`${sqlInjectionHead} ORDER BY created_at DESC, id DESC LIMIT ?`);
|
|
13729
|
+
const sqlInjectionListSession = db.prepare(`${sqlInjectionHead} WHERE session_id = ? ORDER BY created_at DESC, id DESC LIMIT ?`);
|
|
13730
|
+
const sqlInjectionGet = db.prepare(`SELECT id, session_id, packet_hash, packet, memory_ids_json, has_curated,
|
|
13731
|
+
compaction_count, LENGTH(CAST(packet AS BLOB)) AS packet_bytes, created_at FROM injection_snapshots WHERE id = ?`);
|
|
13732
|
+
const sqlInjectionPrune = db.prepare("DELETE FROM injection_snapshots WHERE created_at < ?");
|
|
12726
13733
|
const sqlEntityAll = db.prepare("SELECT * FROM entities");
|
|
12727
13734
|
const sqlEntityGet = db.prepare("SELECT * FROM entities WHERE id = ?");
|
|
12728
13735
|
const sqlEntityInsert = db.prepare("INSERT INTO entities (id, name, kind, aliases_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)");
|
|
@@ -12940,7 +13947,7 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
12940
13947
|
const initialReview = input.initialReviewAt ?? null;
|
|
12941
13948
|
const safeImportance = clampUnit(importance, .5);
|
|
12942
13949
|
const safeConfidence = clampUnit(confidence, .5);
|
|
12943
|
-
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);
|
|
13950
|
+
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);
|
|
12944
13951
|
sqlFtsInsert.run(id, tokenizeForFts(content));
|
|
12945
13952
|
sqlLog.run(at, op, id, JSON.stringify({
|
|
12946
13953
|
kind: input.kind,
|
|
@@ -13055,6 +14062,11 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13055
14062
|
const row = getRow(id);
|
|
13056
14063
|
return row === void 0 ? void 0 : rowToRecord(row);
|
|
13057
14064
|
},
|
|
14065
|
+
/** 稳定逻辑身份 → 当前修订(active 优先,其次最新版)。 */
|
|
14066
|
+
async getMemory(id) {
|
|
14067
|
+
const row = sqlGetMemory.get(id);
|
|
14068
|
+
return row === void 0 ? void 0 : rowToRecord(row);
|
|
14069
|
+
},
|
|
13058
14070
|
async getMany(ids) {
|
|
13059
14071
|
if (ids.length === 0) return [];
|
|
13060
14072
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -13186,8 +14198,14 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13186
14198
|
name: r.name
|
|
13187
14199
|
})) }
|
|
13188
14200
|
});
|
|
13189
|
-
sqlTouch.run(Date.now(), id);
|
|
13190
14201
|
}
|
|
14202
|
+
sqlLog.run(Date.now(), "search-exposure", "AUX", JSON.stringify({
|
|
14203
|
+
ids: hits.map((hit) => String(hit.record.id)),
|
|
14204
|
+
scopes: query.scopes,
|
|
14205
|
+
limit,
|
|
14206
|
+
degraded,
|
|
14207
|
+
q: createHash("sha256").update(query.text).digest("hex").slice(0, 12)
|
|
14208
|
+
}));
|
|
13191
14209
|
return {
|
|
13192
14210
|
hits,
|
|
13193
14211
|
degraded
|
|
@@ -13283,6 +14301,31 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13283
14301
|
async getSessionSummary(sessionId) {
|
|
13284
14302
|
return sqlSessionSummaryGet.get(sessionId)?.summary;
|
|
13285
14303
|
},
|
|
14304
|
+
async recordInjection(input) {
|
|
14305
|
+
const id = randomUUID();
|
|
14306
|
+
const at = Date.now();
|
|
14307
|
+
sqlInjectionInsert.run(id, input.sessionId, input.packetHash, input.packet, JSON.stringify(input.memoryIds), input.hasCurated ? 1 : 0, input.compactionCount, at);
|
|
14308
|
+
const row = sqlInjectionGet.get(id);
|
|
14309
|
+
return {
|
|
14310
|
+
...rowToInjectionHead(row),
|
|
14311
|
+
packet: row.packet
|
|
14312
|
+
};
|
|
14313
|
+
},
|
|
14314
|
+
async listInjections(filter) {
|
|
14315
|
+
const limit = Math.max(1, Math.min(200, Math.floor(filter.limit ?? 50)));
|
|
14316
|
+
return (filter.sessionId === void 0 ? sqlInjectionList.all(limit) : sqlInjectionListSession.all(filter.sessionId, limit)).map(rowToInjectionHead);
|
|
14317
|
+
},
|
|
14318
|
+
async getInjection(id) {
|
|
14319
|
+
const row = sqlInjectionGet.get(id);
|
|
14320
|
+
return row === void 0 ? void 0 : {
|
|
14321
|
+
...rowToInjectionHead(row),
|
|
14322
|
+
packet: row.packet
|
|
14323
|
+
};
|
|
14324
|
+
},
|
|
14325
|
+
async pruneInjections(olderThanMs) {
|
|
14326
|
+
const result = sqlInjectionPrune.run(olderThanMs);
|
|
14327
|
+
return Number(result.changes);
|
|
14328
|
+
},
|
|
13286
14329
|
async update(input) {
|
|
13287
14330
|
const old = getRow(input.id);
|
|
13288
14331
|
if (old === void 0) throw new EngramError("NOT_FOUND", message("store.entryNotFound", { id: input.id }));
|
|
@@ -13291,7 +14334,7 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13291
14334
|
const id = asMemoryId(randomUUID());
|
|
13292
14335
|
const at = Date.now();
|
|
13293
14336
|
withTransaction(() => {
|
|
13294
|
-
sqlRevisionInsert.run(input.id, old.content, old.kind, old.importance, at);
|
|
14337
|
+
sqlRevisionInsert.run(input.id, old.memory_id, old.content, old.kind, old.importance, at);
|
|
13295
14338
|
sqlSetStatus.run("archived", at, input.id);
|
|
13296
14339
|
sqlLog.run(at, "superseded", input.id, JSON.stringify({ supersededBy: id }));
|
|
13297
14340
|
detachArchivedEvidence([input.id]);
|
|
@@ -13299,13 +14342,14 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13299
14342
|
const updateInput = {
|
|
13300
14343
|
scope: input.scope,
|
|
13301
14344
|
kind: input.kind,
|
|
13302
|
-
content
|
|
14345
|
+
content,
|
|
14346
|
+
memoryId: asMemoryId(old.memory_id ?? input.id)
|
|
13303
14347
|
};
|
|
13304
14348
|
const automationFields = applyWriteAutomation(updateInput, id, at, imagery);
|
|
13305
14349
|
insertRecord(id, {
|
|
13306
14350
|
...updateInput,
|
|
13307
14351
|
...automationFields
|
|
13308
|
-
}, content, input.importance ?? old.importance, old.confidence, at, old.source_session_id, input.embedding
|
|
14352
|
+
}, content, input.importance ?? old.importance, old.confidence, at, old.source_session_id, input.embedding === void 0 ? old.embedding : input.embedding, imagery, "update");
|
|
13309
14353
|
sqlEdgeUpsert.run(id, input.id, "supersedes", at);
|
|
13310
14354
|
});
|
|
13311
14355
|
return rowToRecord(sqlGet.get(id));
|
|
@@ -13500,9 +14544,19 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13500
14544
|
};
|
|
13501
14545
|
},
|
|
13502
14546
|
async restore(id) {
|
|
13503
|
-
|
|
13504
|
-
|
|
13505
|
-
|
|
14547
|
+
const row = getRow(id);
|
|
14548
|
+
if (row === void 0) throw new EngramError("NOT_FOUND", message("store.entryNotFound", { id }));
|
|
14549
|
+
const at = Date.now();
|
|
14550
|
+
withTransaction(() => {
|
|
14551
|
+
const memoryId = row.memory_id ?? row.id;
|
|
14552
|
+
const siblings = sqlActiveMemorySiblings.all(memoryId, id);
|
|
14553
|
+
for (const sibling of siblings) {
|
|
14554
|
+
sqlSetStatus.run("archived", at, asMemoryId(sibling.id));
|
|
14555
|
+
sqlEdgeUpsert.run(id, sibling.id, "supersedes", at);
|
|
14556
|
+
}
|
|
14557
|
+
sqlSetStatus.run("active", at, id);
|
|
14558
|
+
sqlLog.run(at, "restore", id, JSON.stringify({ archivedRevisions: siblings.map((s) => s.id) }));
|
|
14559
|
+
});
|
|
13506
14560
|
return rowToRecord(sqlGet.get(id));
|
|
13507
14561
|
},
|
|
13508
14562
|
async topActive(scope, n) {
|
|
@@ -13536,7 +14590,7 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13536
14590
|
const row = getRow(id);
|
|
13537
14591
|
if (row === void 0) return void 0;
|
|
13538
14592
|
const operations = sqlOpLogById.all(id, REVIEW_LOG_LIMIT);
|
|
13539
|
-
const revisions = sqlRevisionsById.all(id);
|
|
14593
|
+
const revisions = sqlRevisionsById.all(row.memory_id ?? row.id);
|
|
13540
14594
|
return {
|
|
13541
14595
|
record: rowToRecord(row),
|
|
13542
14596
|
...edgeGroups(id),
|
|
@@ -13678,7 +14732,7 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13678
14732
|
for (const c of eligible) {
|
|
13679
14733
|
const r = c.record;
|
|
13680
14734
|
const review = r.review;
|
|
13681
|
-
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);
|
|
14735
|
+
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);
|
|
13682
14736
|
sqlFtsInsert.run(r.id, tokenizeForFts(c.content));
|
|
13683
14737
|
}
|
|
13684
14738
|
for (const edge of data.edges ?? []) {
|
|
@@ -13788,6 +14842,48 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13788
14842
|
hits.sort((a, b) => b.sim - a.sim);
|
|
13789
14843
|
return hits.slice(0, limit).map((hit) => getRow(matrix.ids[hit.index])).filter((row) => row !== void 0).map((row) => rowToRecord(row));
|
|
13790
14844
|
},
|
|
14845
|
+
async listContradictions(limit) {
|
|
14846
|
+
const boundedLimit = Math.max(1, Math.min(200, Math.floor(limit)));
|
|
14847
|
+
const rows = sqlContradictions.all(boundedLimit);
|
|
14848
|
+
const result = [];
|
|
14849
|
+
for (const row of rows) {
|
|
14850
|
+
const first = getRow(row.from_id);
|
|
14851
|
+
const second = getRow(row.to_id);
|
|
14852
|
+
if (first === void 0 || second === void 0) continue;
|
|
14853
|
+
result.push({
|
|
14854
|
+
first: rowToRecord(first),
|
|
14855
|
+
second: rowToRecord(second),
|
|
14856
|
+
createdAt: row.created_at
|
|
14857
|
+
});
|
|
14858
|
+
}
|
|
14859
|
+
return result;
|
|
14860
|
+
},
|
|
14861
|
+
async resolveContradiction(input) {
|
|
14862
|
+
const forward = sqlContradictionPair.get(input.firstId, input.secondId, input.secondId, input.firstId);
|
|
14863
|
+
if (forward === void 0) throw new EngramError("NOT_FOUND", message("store.entryNotFound", { id: input.firstId }));
|
|
14864
|
+
const at = Date.now();
|
|
14865
|
+
if (input.action === "dismiss") {
|
|
14866
|
+
withTransaction(() => {
|
|
14867
|
+
sqlEdgeDelete.run(forward.from_id, forward.to_id, "contradicts");
|
|
14868
|
+
sqlEdgeUpsert.run(forward.from_id, forward.to_id, "related", at);
|
|
14869
|
+
sqlLog.run(at, "governance", "AUX", JSON.stringify({
|
|
14870
|
+
action: "dismiss",
|
|
14871
|
+
from: forward.from_id,
|
|
14872
|
+
to: forward.to_id
|
|
14873
|
+
}));
|
|
14874
|
+
});
|
|
14875
|
+
return { dismissed: true };
|
|
14876
|
+
}
|
|
14877
|
+
const loser = input.loserId === void 0 ? void 0 : getRow(input.loserId);
|
|
14878
|
+
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 }));
|
|
14879
|
+
sqlSetStatus.run("forgotten", at, loser.id);
|
|
14880
|
+
sqlLog.run(at, "forget", loser.id, null);
|
|
14881
|
+
detachArchivedEvidence([loser.id]);
|
|
14882
|
+
return {
|
|
14883
|
+
dismissed: false,
|
|
14884
|
+
forgotten: rowToRecord(sqlGet.get(loser.id))
|
|
14885
|
+
};
|
|
14886
|
+
},
|
|
13791
14887
|
async linkEdge(from, to, type) {
|
|
13792
14888
|
sqlEdgeUpsert.run(from, to, type, Date.now());
|
|
13793
14889
|
},
|
|
@@ -13831,7 +14927,7 @@ async function openEngramStore(path, rankBoost = NO_BOOST, automation = DEFAULT_
|
|
|
13831
14927
|
},
|
|
13832
14928
|
async reinforce(id, note) {
|
|
13833
14929
|
if (sqlGet.get(id) === void 0) return void 0;
|
|
13834
|
-
|
|
14930
|
+
sqlReinforce.run(Date.now(), id);
|
|
13835
14931
|
sqlLog.run(Date.now(), "write-merge", id, note);
|
|
13836
14932
|
return rowToRecord(sqlGet.get(id));
|
|
13837
14933
|
},
|
|
@@ -16025,27 +17121,25 @@ function createEngramTools(baseDeps) {
|
|
|
16025
17121
|
},
|
|
16026
17122
|
async execute(args) {
|
|
16027
17123
|
const input = args;
|
|
16028
|
-
const content = redactSecrets(sanitizeProtocolText(input.content));
|
|
16029
|
-
if (content.trim() === "") throw new Error(message("tool.updateContentEmptyAfterSanitize"));
|
|
16030
17124
|
const scope = scopeOf(input.scope, "project");
|
|
16031
17125
|
const store = await deps.openStore(scope);
|
|
16032
|
-
const
|
|
16033
|
-
|
|
17126
|
+
const imagery = placardOf(input.placard);
|
|
17127
|
+
const record = await updateMemory({
|
|
17128
|
+
store,
|
|
17129
|
+
embedder: deps.embedder
|
|
17130
|
+
}, {
|
|
17131
|
+
id: input.id,
|
|
17132
|
+
scope,
|
|
17133
|
+
content: input.content,
|
|
17134
|
+
...input.kind === void 0 ? {} : { kind: input.kind },
|
|
17135
|
+
...imagery === void 0 ? {} : { imagery }
|
|
17136
|
+
});
|
|
17137
|
+
if (record === void 0) throw new Error(message("tool.updateNotFound", {
|
|
16034
17138
|
id: input.id,
|
|
16035
17139
|
scope
|
|
16036
17140
|
}));
|
|
16037
|
-
const embedder = await deps.embedder;
|
|
16038
|
-
const embeddings = embedder === void 0 ? void 0 : await embedder.embed([content.trim()]);
|
|
16039
|
-
const imagery = placardOf(input.placard);
|
|
16040
17141
|
return {
|
|
16041
|
-
id:
|
|
16042
|
-
id: input.id,
|
|
16043
|
-
scope,
|
|
16044
|
-
kind: input.kind ?? old.kind,
|
|
16045
|
-
content,
|
|
16046
|
-
...embeddings === void 0 ? {} : { embedding: embeddings[0] },
|
|
16047
|
-
...imagery === void 0 ? {} : { imagery }
|
|
16048
|
-
})).id,
|
|
17142
|
+
id: record.id,
|
|
16049
17143
|
superseded: input.id
|
|
16050
17144
|
};
|
|
16051
17145
|
}
|
|
@@ -17393,7 +18487,7 @@ function buildSelectionRationale(records) {
|
|
|
17393
18487
|
];
|
|
17394
18488
|
for (const record of records) {
|
|
17395
18489
|
const reasons = classifyRecord(record, now);
|
|
17396
|
-
lines.push(`- #${record.
|
|
18490
|
+
lines.push(`- #${record.memoryId.slice(0, 8)} [${record.kind}/${record.scope}] ${reasonsLabel(reasons)}:${record.content.slice(0, 40)}${record.content.length > 40 ? "…" : ""}`);
|
|
17397
18491
|
}
|
|
17398
18492
|
lines.push("", message("core.rationaleFooter"), "</engram_selection_rationale>");
|
|
17399
18493
|
return lines.join("\n");
|
|
@@ -17455,7 +18549,7 @@ function estimateTokens(text) {
|
|
|
17455
18549
|
return Math.ceil(wide * WIDE_TOKENS_PER_CHAR + narrow / 4);
|
|
17456
18550
|
}
|
|
17457
18551
|
// package.json
|
|
17458
|
-
var version = "0.
|
|
18552
|
+
var version = "0.13.0";
|
|
17459
18553
|
// src/index.ts
|
|
17460
18554
|
/**
|
|
17461
18555
|
* dsh-engram:DeepSeek Harness 跨会话长期记忆插件(host 半)。
|
|
@@ -17616,6 +18710,18 @@ async function compressProfileOverflow(ctx, agent, routeOverride, overflow, sign
|
|
|
17616
18710
|
return;
|
|
17617
18711
|
}
|
|
17618
18712
|
}
|
|
18713
|
+
function preStepSession(state, sessionId) {
|
|
18714
|
+
const existing = state.sessions.get(sessionId);
|
|
18715
|
+
if (existing !== void 0) return existing;
|
|
18716
|
+
const created = {
|
|
18717
|
+
lastProfileHash: null,
|
|
18718
|
+
lastProfileCompactions: null,
|
|
18719
|
+
lastAssessReminder: null,
|
|
18720
|
+
route: void 0
|
|
18721
|
+
};
|
|
18722
|
+
state.sessions.set(sessionId, created);
|
|
18723
|
+
return created;
|
|
18724
|
+
}
|
|
17619
18725
|
/**
|
|
17620
18726
|
* agent/pre-step waterfall:每轮第一步注入画像(内容与上次相同则跳过重复注入);
|
|
17621
18727
|
* 同时 fire-and-forget 触发上一轮的自动摄取(不阻塞请求);进程内首次第一步
|
|
@@ -17625,11 +18731,16 @@ async function compressProfileOverflow(ctx, agent, routeOverride, overflow, sign
|
|
|
17625
18731
|
async function preStep(ctx, openStore, openStoreForProjectCwd, resolved, embedder, state, logRequest, onDialogueLanguage, { agent, step, turn, signal }, next) {
|
|
17626
18732
|
const decision = await next();
|
|
17627
18733
|
if (decision.kind === "reject") return decision;
|
|
18734
|
+
const sessionId = String(agent.session.id);
|
|
18735
|
+
const sessionState = preStepSession(state, sessionId);
|
|
17628
18736
|
const observed = dominantLanguage(userTexts(agent.session.snapshotEvents()));
|
|
17629
18737
|
if (observed !== void 0) onDialogueLanguage(observed.language);
|
|
17630
18738
|
if (step === 1) {
|
|
17631
18739
|
const currentRoute = resolved.routeOverride ?? routeFromEvents(agent.session.snapshotEvents());
|
|
17632
|
-
if (currentRoute !== void 0)
|
|
18740
|
+
if (currentRoute !== void 0) {
|
|
18741
|
+
sessionState.route = currentRoute;
|
|
18742
|
+
state.route = currentRoute;
|
|
18743
|
+
}
|
|
17633
18744
|
}
|
|
17634
18745
|
const mode = resolved.ingest;
|
|
17635
18746
|
const routing = ingestWriteRouting(sessionCwd(agent.session), openStoreForProjectCwd, openStore);
|
|
@@ -17643,7 +18754,7 @@ async function preStep(ctx, openStore, openStoreForProjectCwd, resolved, embedde
|
|
|
17643
18754
|
embedder,
|
|
17644
18755
|
mode,
|
|
17645
18756
|
routeOverride: resolved.routeOverride,
|
|
17646
|
-
...resolveJevField(ctx, resolved.jev, resolved.dbDir, () =>
|
|
18757
|
+
...resolveJevField(ctx, resolved.jev, resolved.dbDir, () => sessionState.route?.provider),
|
|
17647
18758
|
call: (params) => streamText(ctx, {
|
|
17648
18759
|
...params,
|
|
17649
18760
|
sessionId: agent.session.id
|
|
@@ -17664,7 +18775,7 @@ async function preStep(ctx, openStore, openStoreForProjectCwd, resolved, embedde
|
|
|
17664
18775
|
embedder,
|
|
17665
18776
|
mode,
|
|
17666
18777
|
routeOverride: resolved.routeOverride,
|
|
17667
|
-
...resolveJevField(ctx, resolved.jev, resolved.dbDir, () =>
|
|
18778
|
+
...resolveJevField(ctx, resolved.jev, resolved.dbDir, () => sessionState.route?.provider),
|
|
17668
18779
|
call: (params) => streamText(ctx, {
|
|
17669
18780
|
...params,
|
|
17670
18781
|
sessionId: agent.session.id
|
|
@@ -17676,11 +18787,11 @@ async function preStep(ctx, openStore, openStoreForProjectCwd, resolved, embedde
|
|
|
17676
18787
|
});
|
|
17677
18788
|
}
|
|
17678
18789
|
if (step !== 1 && resolved.assessReminder) {
|
|
17679
|
-
const sessionId = String(agent.session.id);
|
|
17680
18790
|
const pending = evidenceBatches.pendingBatches(sessionId).length;
|
|
17681
18791
|
const reminder = buildAssessReminder(pending, evidenceBatches.insufficientStreak(sessionId));
|
|
17682
|
-
if (reminder
|
|
17683
|
-
|
|
18792
|
+
if (reminder === void 0) sessionState.lastAssessReminder = null;
|
|
18793
|
+
if (reminder !== void 0 && reminder !== sessionState.lastAssessReminder) {
|
|
18794
|
+
sessionState.lastAssessReminder = reminder;
|
|
17684
18795
|
return {
|
|
17685
18796
|
...decision,
|
|
17686
18797
|
messages: [...decision.messages, createUserMessage({
|
|
@@ -17700,9 +18811,10 @@ async function preStep(ctx, openStore, openStoreForProjectCwd, resolved, embedde
|
|
|
17700
18811
|
};
|
|
17701
18812
|
}
|
|
17702
18813
|
}
|
|
18814
|
+
if (!resolved.injectProfile) return decision;
|
|
17703
18815
|
const compactionCount = agent.session.snapshotEvents().filter((event) => event.type === "compaction/end").length;
|
|
17704
|
-
const compacted =
|
|
17705
|
-
if (
|
|
18816
|
+
const compacted = sessionState.lastProfileCompactions !== null && compactionCount > sessionState.lastProfileCompactions;
|
|
18817
|
+
if (sessionState.lastProfileCompactions === null) sessionState.lastProfileCompactions = compactionCount;
|
|
17706
18818
|
if (step !== 1 && !compacted) return decision;
|
|
17707
18819
|
const store = await openStore("user");
|
|
17708
18820
|
const curated = await store.getProfileBlock("user");
|
|
@@ -17747,13 +18859,24 @@ async function preStep(ctx, openStore, openStoreForProjectCwd, resolved, embedde
|
|
|
17747
18859
|
});
|
|
17748
18860
|
const textWithRationale = wrapWithRationale(text, top) + dueLine;
|
|
17749
18861
|
const hash = createHash("sha256").update(`${parts.curated ?? ""}\n${textWithRationale}`).digest("hex");
|
|
17750
|
-
if (!compacted &&
|
|
17751
|
-
|
|
17752
|
-
|
|
17753
|
-
|
|
17754
|
-
const requestText = currentUserRequestText(decision.messages);
|
|
17755
|
-
const memoryPacket = renderMemoryPacket(text, "turn_start", requestText);
|
|
18862
|
+
if (!compacted && hash === sessionState.lastProfileHash) return decision;
|
|
18863
|
+
sessionState.lastProfileHash = hash;
|
|
18864
|
+
sessionState.lastProfileCompactions = compactionCount;
|
|
18865
|
+
const memoryPacket = renderMemoryPacket(textWithRationale, "turn_start", currentUserRequestText(decision.messages));
|
|
17756
18866
|
const packet = parts.curated === void 0 ? memoryPacket : `${renderProfilePacket(parts.curated)}\n\n${memoryPacket}`;
|
|
18867
|
+
const packetHash = createHash("sha256").update(packet).digest("hex");
|
|
18868
|
+
try {
|
|
18869
|
+
await store.recordInjection({
|
|
18870
|
+
sessionId,
|
|
18871
|
+
packetHash,
|
|
18872
|
+
packet,
|
|
18873
|
+
memoryIds: top.map((record) => record.memoryId),
|
|
18874
|
+
hasCurated: parts.curated !== void 0,
|
|
18875
|
+
compactionCount
|
|
18876
|
+
});
|
|
18877
|
+
} catch (error) {
|
|
18878
|
+
console.warn(message("core.warnInjectionSnapshotFailed"), error);
|
|
18879
|
+
}
|
|
17757
18880
|
return {
|
|
17758
18881
|
...decision,
|
|
17759
18882
|
messages: [...decision.messages, createUserMessage({
|
|
@@ -18167,7 +19290,12 @@ async function apply(ctx, config = {}) {
|
|
|
18167
19290
|
}));
|
|
18168
19291
|
stores.clear();
|
|
18169
19292
|
};
|
|
18170
|
-
|
|
19293
|
+
let stopReflectJobs;
|
|
19294
|
+
let reflectJobs;
|
|
19295
|
+
ctx.effect(() => async () => {
|
|
19296
|
+
await stopReflectJobs?.();
|
|
19297
|
+
await closeStores();
|
|
19298
|
+
}, "dsh-engram: close stores");
|
|
18171
19299
|
/** cwd → 分库文件名(历史回填会对每个历史 cwd 解析一次,避免重复读 git 元数据)。 */
|
|
18172
19300
|
const cwdDbNames = /* @__PURE__ */ new Map();
|
|
18173
19301
|
/**
|
|
@@ -18222,10 +19350,7 @@ async function apply(ctx, config = {}) {
|
|
|
18222
19350
|
};
|
|
18223
19351
|
const preStepState = {
|
|
18224
19352
|
pendingReplayed: false,
|
|
18225
|
-
|
|
18226
|
-
lastProfileHash: null,
|
|
18227
|
-
lastProfileCompactions: null,
|
|
18228
|
-
lastAssessReminder: null,
|
|
19353
|
+
sessions: /* @__PURE__ */ new Map(),
|
|
18229
19354
|
route: void 0
|
|
18230
19355
|
};
|
|
18231
19356
|
/** 会话持久化服务(可选;缺席时历史回填不可用)。 */
|
|
@@ -18905,12 +20030,24 @@ async function apply(ctx, config = {}) {
|
|
|
18905
20030
|
status: historyApi.status,
|
|
18906
20031
|
models: historyApi.models,
|
|
18907
20032
|
defaults: resolved.historyBackfill
|
|
20033
|
+
},
|
|
20034
|
+
jobs: {
|
|
20035
|
+
summary: () => reflectJobs?.summary() ?? {
|
|
20036
|
+
total: 0,
|
|
20037
|
+
queued: 0,
|
|
20038
|
+
running: 0,
|
|
20039
|
+
done: 0,
|
|
20040
|
+
dead: 0
|
|
20041
|
+
},
|
|
20042
|
+
list: (filter) => reflectJobs?.list(filter) ?? []
|
|
18908
20043
|
}
|
|
18909
20044
|
});
|
|
18910
20045
|
});
|
|
18911
|
-
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 });
|
|
20046
|
+
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 });
|
|
18912
20047
|
ctx.on("session/disposed", (session) => {
|
|
18913
|
-
|
|
20048
|
+
const sessionId = String(session.id);
|
|
20049
|
+
evidenceBatches.clear(sessionId);
|
|
20050
|
+
preStepState.sessions.delete(sessionId);
|
|
18914
20051
|
});
|
|
18915
20052
|
if (resolved.ingest !== "off") ctx.on("session/disposed", (session) => {
|
|
18916
20053
|
const mode = resolved.ingest;
|
|
@@ -18956,59 +20093,72 @@ async function apply(ctx, config = {}) {
|
|
|
18956
20093
|
console.warn(message("core.warnDisposeFinalFailed"), error);
|
|
18957
20094
|
});
|
|
18958
20095
|
});
|
|
18959
|
-
if (resolved.reflect
|
|
18960
|
-
const
|
|
20096
|
+
if (resolved.reflect === "suggest") ctx.on("session/disposed", (session) => {
|
|
20097
|
+
const sessionId = String(session.id);
|
|
20098
|
+
const cwd = sessionCwd(session);
|
|
20099
|
+
const targets = [{
|
|
20100
|
+
scope: "user",
|
|
20101
|
+
open: () => openStore("user")
|
|
20102
|
+
}];
|
|
20103
|
+
if (cwd !== void 0 && existsSync(join(resolved.dbDir, dbNameForCwd(cwd)))) targets.push({
|
|
20104
|
+
scope: "project",
|
|
20105
|
+
open: () => openStoreForProjectCwd(cwd)
|
|
20106
|
+
});
|
|
20107
|
+
(async () => {
|
|
20108
|
+
for (const target of targets) try {
|
|
20109
|
+
const store = await target.open();
|
|
20110
|
+
const detail = JSON.stringify({
|
|
20111
|
+
scope: target.scope,
|
|
20112
|
+
sessionId
|
|
20113
|
+
});
|
|
20114
|
+
if (!await store.hasAudit("reflect-pending", detail)) await store.audit("reflect-pending", "AUX", detail);
|
|
20115
|
+
} catch (error) {
|
|
20116
|
+
console.warn(message("core.warnReflectFailed", { scope: target.scope }), error);
|
|
20117
|
+
}
|
|
20118
|
+
})();
|
|
20119
|
+
});
|
|
20120
|
+
if (resolved.reflect === "auto") {
|
|
20121
|
+
const jobs = await startAutoReflectWorker({
|
|
20122
|
+
dbDir: resolved.dbDir,
|
|
20123
|
+
dbNameForCwd,
|
|
20124
|
+
openStore,
|
|
20125
|
+
openProjectStore: openStoreForProjectCwd,
|
|
20126
|
+
embedder: () => embedderAttempt(),
|
|
20127
|
+
call: (sessionId, params) => streamText(ctx, {
|
|
20128
|
+
...params,
|
|
20129
|
+
sessionId
|
|
20130
|
+
})
|
|
20131
|
+
});
|
|
20132
|
+
reflectJobs = jobs;
|
|
20133
|
+
stopReflectJobs = jobs.stop;
|
|
18961
20134
|
ctx.on("session/disposed", (session) => {
|
|
18962
20135
|
const events = session.snapshotEvents();
|
|
18963
|
-
const sessionId = String(session.id);
|
|
18964
|
-
const cwd = sessionCwd(session);
|
|
18965
20136
|
const route = resolved.routeOverride ?? routeFromEvents(events);
|
|
18966
|
-
|
|
18967
|
-
|
|
18968
|
-
|
|
18969
|
-
|
|
18970
|
-
|
|
18971
|
-
|
|
18972
|
-
|
|
20137
|
+
if (route === void 0) return;
|
|
20138
|
+
const eventSeq = events.reduce((max, event) => typeof event.seq === "number" && Number.isInteger(event.seq) && event.seq > max ? event.seq : max, 0);
|
|
20139
|
+
const sessionId = String(session.id);
|
|
20140
|
+
try {
|
|
20141
|
+
jobs.enqueue({
|
|
20142
|
+
sessionId,
|
|
20143
|
+
scope: "user",
|
|
20144
|
+
route,
|
|
20145
|
+
eventSeq
|
|
20146
|
+
});
|
|
20147
|
+
const cwd = sessionCwd(session);
|
|
20148
|
+
if (cwd !== void 0 && existsSync(join(resolved.dbDir, dbNameForCwd(cwd)))) jobs.enqueue({
|
|
20149
|
+
sessionId,
|
|
20150
|
+
scope: "project",
|
|
20151
|
+
cwd,
|
|
20152
|
+
route,
|
|
20153
|
+
eventSeq
|
|
20154
|
+
});
|
|
20155
|
+
} catch (error) {
|
|
20156
|
+
console.warn(message("core.warnReflectFailed", { scope: "enqueue" }), error);
|
|
20157
|
+
return;
|
|
20158
|
+
}
|
|
20159
|
+
jobs.pump().catch((error) => {
|
|
20160
|
+
console.warn(message("core.warnReflectFailed", { scope: "scheduler" }), error);
|
|
18973
20161
|
});
|
|
18974
|
-
(async () => {
|
|
18975
|
-
for (const target of targets) try {
|
|
18976
|
-
const store = await target.open();
|
|
18977
|
-
if (resolved.reflect === "suggest") {
|
|
18978
|
-
const detail = JSON.stringify({
|
|
18979
|
-
scope: target.scope,
|
|
18980
|
-
sessionId
|
|
18981
|
-
});
|
|
18982
|
-
if (!await store.hasAudit("reflect-pending", detail)) await store.audit("reflect-pending", "AUX", detail);
|
|
18983
|
-
continue;
|
|
18984
|
-
}
|
|
18985
|
-
if (route === void 0) continue;
|
|
18986
|
-
const outcome = await reflectObservations({
|
|
18987
|
-
store,
|
|
18988
|
-
embedder: await embedderAttempt(),
|
|
18989
|
-
scope: target.scope,
|
|
18990
|
-
call: (params) => streamText(ctx, {
|
|
18991
|
-
...params,
|
|
18992
|
-
sessionId: session.id
|
|
18993
|
-
}),
|
|
18994
|
-
logRequest: (data) => {
|
|
18995
|
-
store.audit("reflect-request", "AUX", JSON.stringify(data)).catch(() => {});
|
|
18996
|
-
},
|
|
18997
|
-
route,
|
|
18998
|
-
signal: AbortSignal.timeout(REFLECT_TIMEOUT_MS)
|
|
18999
|
-
});
|
|
19000
|
-
if (outcome.formed + outcome.refined + outcome.confirmed + outcome.refuted > 0) console.log(message("core.logReflectDone", {
|
|
19001
|
-
scope: target.scope,
|
|
19002
|
-
formed: outcome.formed,
|
|
19003
|
-
refined: outcome.refined,
|
|
19004
|
-
confirmed: outcome.confirmed,
|
|
19005
|
-
refuted: outcome.refuted
|
|
19006
|
-
}));
|
|
19007
|
-
if (outcome.dropped > 0) console.warn(message("core.warnReflectBatchDropped", { count: outcome.dropped }));
|
|
19008
|
-
} catch (error) {
|
|
19009
|
-
console.warn(message("core.warnReflectFailed", { scope: target.scope }), error);
|
|
19010
|
-
}
|
|
19011
|
-
})();
|
|
19012
20162
|
});
|
|
19013
20163
|
}
|
|
19014
20164
|
const OP_LOG_RETENTION_DAYS = 366;
|
|
@@ -19037,6 +20187,7 @@ async function apply(ctx, config = {}) {
|
|
|
19037
20187
|
}));
|
|
19038
20188
|
try {
|
|
19039
20189
|
await store.pruneOps(pruneBefore, LOG_KEEP_OPS);
|
|
20190
|
+
await store.pruneInjections(pruneBefore);
|
|
19040
20191
|
} catch (error) {
|
|
19041
20192
|
console.warn(message("core.warnDecayPeriodicFailed"), error);
|
|
19042
20193
|
}
|