dsh-memu-memory 1.4.3 → 1.4.5
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/AGENTS.md +3 -1
- package/CHANGELOG.md +15 -0
- package/README.md +34 -15
- package/README.zh.md +35 -13
- package/assets/screenshots/drawer.jpg +0 -0
- package/assets/screenshots/libraries.jpg +0 -0
- package/assets/screenshots/mobile.jpg +0 -0
- package/assets/screenshots/relations.jpg +0 -0
- package/assets/screenshots/settings.jpg +0 -0
- package/assets/screenshots/webui-dark.jpg +0 -0
- package/assets/screenshots/webui-memory.jpg +0 -0
- package/docs/client-conventions.md +19 -3
- package/docs/contributing.md +4 -2
- package/docs/env-and-commands.md +9 -1
- package/docs/graph-scale.md +214 -0
- package/docs/lexicon-recall.md +100 -0
- package/docs/mcp-porting.md +8 -6
- package/docs/memory-semantics.md +35 -3
- package/docs/pending-work.md +3 -1
- package/docs/retention.md +83 -0
- package/docs/rt-index.md +452 -0
- package/docs/scale-performance.md +101 -0
- package/docs/token-budget.md +92 -0
- package/docs/troubleshooting.md +50 -11
- package/lib/auto-link/apply.js +7 -2
- package/lib/auto-link/candidates.js +32 -10
- package/lib/backup.js +67 -32
- package/lib/binding-diagnostics.js +1 -1
- package/lib/bounded-cache.js +80 -0
- package/lib/client.js +2096 -409
- package/lib/consolidation-ledger.js +21 -4
- package/lib/consolidation-worker.js +14 -1
- package/lib/cycle.js +16 -11
- package/lib/diagnostic-context.js +372 -0
- package/lib/diagnostics.js +147 -61
- package/lib/embedding-download.js +7 -8
- package/lib/engine-sources.js +286 -0
- package/lib/engine.js +23 -10
- package/lib/entity-repair.js +43 -13
- package/lib/entity-review.js +64 -0
- package/lib/environment-check.js +348 -36
- package/lib/feedback.js +25 -0
- package/lib/global-graph.js +46 -2
- package/lib/graph-adjacency-index.js +525 -0
- package/lib/graph-overview.js +293 -0
- package/lib/graph.js +658 -105
- package/lib/inbound.js +44 -15
- package/lib/index-pages.js +57 -0
- package/lib/index.js +44 -6
- package/lib/inject.js +119 -50
- package/lib/lexicon-rt-source.js +25 -0
- package/lib/lexicon-rt-worker.js +26 -0
- package/lib/lexicon-rt.js +224 -0
- package/lib/lexicon-scope.js +56 -5
- package/lib/lexicon.js +143 -54
- package/lib/local-vector-service.js +3 -0
- package/lib/maintenance-ledger.js +542 -12
- package/lib/managed-runtime.js +260 -80
- package/lib/media.js +1 -1
- package/lib/memory.js +564 -131
- package/lib/port-surface.js +96 -11
- package/lib/preset-mount.js +13 -7
- package/lib/private.js +47 -21
- package/lib/recall-cache.js +20 -34
- package/lib/retention.js +173 -0
- package/lib/rpc.js +135 -52
- package/lib/rt-index/builder.js +209 -0
- package/lib/rt-index/format.js +231 -0
- package/lib/rt-index/manifest.js +105 -0
- package/lib/rt-index/reader.js +673 -0
- package/lib/rt-index-retention.js +151 -0
- package/lib/rt-index-service.js +283 -0
- package/lib/rt-index-worker.js +21 -0
- package/lib/salient-wake.js +55 -4
- package/lib/state.js +195 -24
- package/lib/temporal.js +39 -13
- package/lib/token-measurement.js +126 -0
- package/lib/tools.js +101 -6
- package/lib/turn-log.js +108 -3
- package/lib/webui/graph-layout-worker.js +68 -0
- package/lib/webui/graph-local-physics.js +390 -0
- package/lib/webui/graph-spatial-grid.js +64 -0
- package/lib/webui/graph-view.bundle.js +6 -1
- package/lib/webui/graph-view.js +478 -135
- package/lib/webui/graph-webgl-renderer.js +74 -0
- package/lib/webui/standalone.js +1 -1
- package/lib/worker-pool.js +38 -7
- package/package.json +3 -2
- package/scripts/acceptance-local.mjs +4 -10
- package/scripts/bench-all-libraries.mjs +47 -0
- package/scripts/check-classic-graph-browser.mjs +189 -0
- package/scripts/check-client-browser.mjs +929 -0
- package/scripts/check-graph-browser.mjs +6 -0
- package/scripts/check-graph-elastic-browser.mjs +139 -0
- package/scripts/check-memory-review-browser.mjs +124 -0
- package/scripts/entity-dedupe.mjs +19 -3
- package/scripts/graph-artifact-provenance.mjs +30 -0
- package/scripts/graph-freeze-manifest.mjs +129 -0
- package/scripts/graph-geometry-fixture.mjs +40 -0
- package/scripts/graph-physics-bench.mjs +218 -0
- package/scripts/graph-scale-bench.mjs +213 -0
- package/scripts/graph-scale-memory.mjs +48 -0
- package/scripts/graph-service-bench.mjs +72 -0
- package/scripts/make-readme-shots.mjs +17 -5
- package/scripts/preview.mjs +1 -0
- package/scripts/rebuild-rt.mjs +18 -0
- package/scripts/scale-bench.mjs +183 -0
- package/scripts/simulate-injection.mjs +47 -8
- package/scripts/verify-host-fixtures.mjs +108 -0
- package/scripts/verify-host-recovery.mjs +565 -0
- package/scripts/verify-vector-recovery.mjs +740 -0
- package/tests/auto-link-candidates.test.mjs +20 -0
- package/tests/browser.test.mjs +16 -2
- package/tests/client-export.test.mjs +16 -1
- package/tests/client-pagination.test.mjs +1495 -0
- package/tests/client-render.test.mjs +223 -28
- package/tests/consolidation-fork.test.mjs +97 -13
- package/tests/consolidation-ledger.test.mjs +17 -1
- package/tests/diagnostic-entity-candidates.test.mjs +54 -0
- package/tests/diagnostic-report.test.mjs +429 -0
- package/tests/diagnostic-wiring.test.mjs +88 -0
- package/tests/diagnostics.test.mjs +27 -0
- package/tests/embedding-download.test.mjs +44 -0
- package/tests/engine-source-settings.test.mjs +69 -0
- package/tests/engine-sources.test.mjs +145 -0
- package/tests/entity-dedupe.test.mjs +143 -0
- package/tests/entity-merge-review.test.mjs +363 -0
- package/tests/entity-merge.test.mjs +12 -4
- package/tests/entity-review.test.mjs +87 -0
- package/tests/environment-check.test.mjs +51 -1
- package/tests/feedback.test.mjs +95 -0
- package/tests/graph-adjacency-index.test.mjs +536 -0
- package/tests/graph-cascade.test.mjs +229 -0
- package/tests/graph-import-diagnostic.test.mjs +25 -0
- package/tests/graph-overview.test.mjs +709 -0
- package/tests/graph-session-authorization.test.mjs +419 -0
- package/tests/graph-view-geometry.test.mjs +426 -0
- package/tests/graph-view-scale.test.mjs +88 -0
- package/tests/graph-view.test.mjs +444 -5
- package/tests/graph.test.mjs +43 -0
- package/tests/help-page.test.mjs +128 -54
- package/tests/inbound.test.mjs +19 -0
- package/tests/index-pagination.test.mjs +113 -0
- package/tests/index-read-view.test.mjs +212 -0
- package/tests/inject-guide.test.mjs +9 -0
- package/tests/injection-dedupe.test.mjs +213 -0
- package/tests/lexicon-recall.test.mjs +641 -0
- package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
- package/tests/lexicon-rt.test.mjs +468 -0
- package/tests/local-embedding-worker.test.mjs +38 -0
- package/tests/local-vector-service.test.mjs +32 -3
- package/tests/maintenance-compat.test.mjs +128 -0
- package/tests/maintenance-settlement.test.mjs +1003 -0
- package/tests/managed-memory.test.mjs +39 -11
- package/tests/managed-runtime.test.mjs +109 -0
- package/tests/memory-fields.test.mjs +24 -12
- package/tests/observed-evidence.test.mjs +52 -0
- package/tests/port-surface.test.mjs +93 -1
- package/tests/preset-mount.test.mjs +12 -4
- package/tests/recall-cache.test.mjs +56 -3
- package/tests/recall-dedup.test.mjs +63 -2
- package/tests/retention.test.mjs +260 -0
- package/tests/rt-index-cross-library.test.mjs +230 -0
- package/tests/rt-index-integration.test.mjs +194 -0
- package/tests/rt-index-retention.test.mjs +552 -0
- package/tests/rt-index-scale.test.mjs +204 -0
- package/tests/rt-index.test.mjs +705 -0
- package/tests/salient-date-boundaries.test.mjs +121 -0
- package/tests/salient-wake.test.mjs +29 -0
- package/tests/scale-bench.test.mjs +53 -0
- package/tests/settings-plumbing.test.mjs +25 -0
- package/tests/simulate-injection.test.mjs +15 -1
- package/tests/standalone-navigation.test.mjs +44 -0
- package/tests/state.test.mjs +51 -0
- package/tests/temporal-precision.test.mjs +102 -0
- package/tests/temporal.test.mjs +10 -6
- package/tests/token-measurement.test.mjs +98 -0
- package/tests/tool-schema.test.mjs +41 -5
- package/tests/tools.test.mjs +6 -3
- package/tests/turn-token-budget.test.mjs +149 -0
- package/tests/webui-auth.test.mjs +57 -1
- package/tests/webui.test.mjs +40 -15
- package/tests/worker-lifecycle.test.mjs +2 -1
|
@@ -135,7 +135,7 @@ export function noteEvidence({ sessionId, throughSeq, fromSeq = null, at = Date.
|
|
|
135
135
|
* 开始一个任务。租约没到期就拒绝:这是「同一会话只有一个进行中任务」的持久化版本,
|
|
136
136
|
* 进程重启后仍然有效(in-memory 的 inFlight Map 重启就没了)。
|
|
137
137
|
*/
|
|
138
|
-
export function beginJob({ sessionId, jobId, snapshot, binding, now = Date.now(), leaseMs = DEFAULT_LEASE_MS }) {
|
|
138
|
+
export function beginJob({ sessionId, jobId, snapshot, binding, now = Date.now(), leaseMs = DEFAULT_LEASE_MS, kind = 'consolidate' }) {
|
|
139
139
|
return mutateLedger((ledger) => {
|
|
140
140
|
const entry = ensureEntry(ledger, sessionId)
|
|
141
141
|
const leaseUntil = Number(entry.inflight?.leaseUntil) || 0
|
|
@@ -145,6 +145,7 @@ export function beginJob({ sessionId, jobId, snapshot, binding, now = Date.now()
|
|
|
145
145
|
const generation = scopeGenerationOf(binding)
|
|
146
146
|
entry.inflight = {
|
|
147
147
|
jobId,
|
|
148
|
+
kind,
|
|
148
149
|
snapshot: snapshot || null,
|
|
149
150
|
startedAt: now,
|
|
150
151
|
leaseUntil: now + leaseMs,
|
|
@@ -158,6 +159,17 @@ export function beginJob({ sessionId, jobId, snapshot, binding, now = Date.now()
|
|
|
158
159
|
})
|
|
159
160
|
}
|
|
160
161
|
|
|
162
|
+
// Entity-only maintenance shares the session lease, never its transcript cursor.
|
|
163
|
+
export function releaseEntityReviewJob({ sessionId, jobId }) {
|
|
164
|
+
return mutateLedger(ledger => {
|
|
165
|
+
const entry = ensureEntry(ledger, sessionId)
|
|
166
|
+
if (entry.inflight?.jobId !== jobId || entry.inflight.kind !== 'entity-review') return false
|
|
167
|
+
entry.inflight = null
|
|
168
|
+
entry.updatedAt = stamp()
|
|
169
|
+
return true
|
|
170
|
+
})
|
|
171
|
+
}
|
|
172
|
+
|
|
161
173
|
export function renewLease({ sessionId, jobId, now = Date.now(), leaseMs = DEFAULT_LEASE_MS }) {
|
|
162
174
|
return mutateLedger((ledger) => {
|
|
163
175
|
const entry = ensureEntry(ledger, sessionId)
|
|
@@ -197,7 +209,7 @@ export function completeJob({
|
|
|
197
209
|
return mutateLedger((ledger) => {
|
|
198
210
|
const entry = ensureEntry(ledger, sessionId)
|
|
199
211
|
const job = entry.inflight && entry.inflight.jobId === jobId ? entry.inflight : null
|
|
200
|
-
if (!job || job.leaseUntil <= now || job.checkedVersion !== JSON.stringify(entry.checked)
|
|
212
|
+
if (!job || job.kind === 'entity-review' || job.leaseUntil <= now || job.checkedVersion !== JSON.stringify(entry.checked)
|
|
201
213
|
|| (snapshot && (snapshot.hash !== job.snapshot?.hash || snapshot.fromSeq !== job.snapshot?.fromSeq || snapshot.throughSeq !== job.snapshot?.throughSeq))) {
|
|
202
214
|
return { advanced: false, reasonCode: 'stale-job', checked: entry.checked, pending: entry.pending }
|
|
203
215
|
}
|
|
@@ -260,6 +272,7 @@ export function failJob({ sessionId, jobId, reasonCode = 'failed', retryable = t
|
|
|
260
272
|
const job = entry.inflight && entry.inflight.jobId === jobId ? entry.inflight : null
|
|
261
273
|
if (!job) return { stale: true, reasonCode: 'stale-job', pending: entry.pending, retryAt: entry.retryAt || null, attempts: entry.attempts }
|
|
262
274
|
entry.inflight = null
|
|
275
|
+
if (job.kind === 'entity-review') return { entityReview: true, reasonCode }
|
|
263
276
|
entry.pending = pendingFromSnapshot(job.snapshot, entry.checked, entry.pending)
|
|
264
277
|
if (retryable) {
|
|
265
278
|
entry.attempts = (Number(entry.attempts) || 0) + 1
|
|
@@ -310,6 +323,10 @@ export function recoverStaleJobs({ now = Date.now(), leaseMs = DEFAULT_LEASE_MS
|
|
|
310
323
|
if (Number.isSafeInteger(leaseUntil) && leaseUntil > now) continue
|
|
311
324
|
const job = entry.inflight
|
|
312
325
|
entry.inflight = null
|
|
326
|
+
if (job.kind === 'entity-review') {
|
|
327
|
+
recovered.push({ sessionId, jobId: job.jobId, entityReview: true, leaseUntil })
|
|
328
|
+
continue
|
|
329
|
+
}
|
|
313
330
|
entry.pending = pendingFromSnapshot(job?.snapshot || null, entry.checked, entry.pending)
|
|
314
331
|
entry.attempts = (Number(entry.attempts) || 0) + 1
|
|
315
332
|
entry.retryAt = retryAtFrom(now, entry.attempts)
|
|
@@ -431,5 +448,5 @@ export function setCarryCandidates(sessionId, rows) {
|
|
|
431
448
|
export default {
|
|
432
449
|
CONSOLIDATION_LEDGER_VERSION, DEFAULT_LEASE_MS, ledgerPath, loadLedger, sessionState, scopeGenerationOf,
|
|
433
450
|
noteEvidence, beginJob, renewLease, completeJob, failJob, recoverStaleJobs, operationKey, findOperation,
|
|
434
|
-
recordOperation, clearSessionState, readCarryCandidates, setCarryCandidates,
|
|
435
|
-
}
|
|
451
|
+
recordOperation, releaseEntityReviewJob, clearSessionState, readCarryCandidates, setCarryCandidates,
|
|
452
|
+
}
|
|
@@ -24,10 +24,11 @@ export const WORKER_WRITE_TOOLS = Object.freeze([
|
|
|
24
24
|
'memu_private_update',
|
|
25
25
|
'memu_private_link',
|
|
26
26
|
'memu_private_link_suggest',
|
|
27
|
+
'memu_private_entity_merge_decide',
|
|
27
28
|
])
|
|
28
29
|
// 1.3.1:已有记忆目录与本地召回命中都由插件在种子开头注入(零模型调用),
|
|
29
30
|
// worker 不再需要 list / recall / status 任何一个只读回合。
|
|
30
|
-
export const WORKER_READ_TOOLS = Object.freeze([])
|
|
31
|
+
export const WORKER_READ_TOOLS = Object.freeze(['memu_private_entity_merge_suggest'])
|
|
31
32
|
export const WORKER_TOOL_ALLOW = Object.freeze([...WORKER_WRITE_TOOLS, ...WORKER_READ_TOOLS])
|
|
32
33
|
// 只有这两件能单独证明"worker 有写记忆的能力"。link / link_suggest / lexicon
|
|
33
34
|
// 是辅助面:一条只列出辅助工具的头(例如后台审计会话)不能据此 fork 一个整理
|
|
@@ -202,6 +203,7 @@ export function buildWorkerBrief({ snapshot, probe = null, contract = '', reason
|
|
|
202
203
|
'先清欠账再查过时:目录「欠账」里 open 且已过 due_at 的承诺,按本窗证据结案(done/cancelled/expired),没有证据就保留 open 并写明仍欠着谁;valid_to 已过或已被明确取代的旧条目用 memu_private_update 归档或补正窗口,旧正文保留。',
|
|
203
204
|
// State when link-candidate review is required so the worker need not infer it from tool descriptions.
|
|
204
205
|
'写完条目后用本轮创建/更新的 id 调一次 memu_private_link_suggest,返回的候选【逐条】裁决:有具体证据的用 memu_private_link 连(note 引用转录原句作依据),没有证据的明确放弃,不许全部留着不裁决。触发时机:同一事实的新版本→连到旧条(取代关系);同一个人的多条记忆→挂到命名实体 entity {name, kind};承诺/约定→commitment;两条互斥→conflict。相似≠相连,宁缺毋滥。',
|
|
206
|
+
'完成本窗记忆写入后,用实体候选读取工具检查当前库提供的候选批次,并逐条调用实体裁决工具:只有记忆内容、明确称呼/别名与关系证据能证明是同一人物/物件时才 merge;仅名字接近、同姓、同名、兄妹关系、角色设定相似都不够。明确是不同主体且证据充分时 reject;证据不足、候选涉及敏感身份混淆或可能造成严重人物/物件错配时 hold,写明缺哪条证据。已 hold 且证据未变的候选会自动跳过,不要反复把同一批候选交给用户。每处理完一批重新从首批读取(合并/排除会使旧游标失效),优先消化未审候选;空批次且 scanComplete=false 时才用 nextCursor 继续扫描,预算不足时留到下窗。只处理工具返回的候选,不猜候选外实体;令牌过期就重新读取。复用当前整理 worker,不另开 fork。',
|
|
205
207
|
coding
|
|
206
208
|
? 'content 写 150–350 字,按「结论 / 作用范围与定位(路径 + 符号,行号只作辅助)/ 条件与原因 / 验证状态」排;标题写结论本身(模块、符号、错误签名或命令),不要「修复了异步问题」这类空话;不写人物地点与原文模板,不复述整段对话。emotion 与 dominance 只属于人物侧条目,工程事实省略。'
|
|
207
209
|
: 'content 写 50–150 字,只保留人物、地点、时间、事情、原话/说话人;emotion 只在叙事确实有情绪瞬间时填写,普通事实省略;不要复述整段对话,不要写成行为日志。',
|
|
@@ -234,6 +236,17 @@ export function buildWorkerBrief({ snapshot, probe = null, contract = '', reason
|
|
|
234
236
|
return lines.filter((line) => line && String(line).trim()).join('\n')
|
|
235
237
|
}
|
|
236
238
|
|
|
239
|
+
export function buildEntityReviewBrief({ pairs = [] } = {}) {
|
|
240
|
+
return [
|
|
241
|
+
'[实体候选自动裁决] 你是当前会话的后台记忆整理 worker,沿用该会话的模型与可见范围。',
|
|
242
|
+
'本轮只处理下面这一个批次的实体身份候选,不整理转录、不新增或改写记忆、不删除记忆、不操作全局记忆。',
|
|
243
|
+
'用 memu_private_entity_merge_suggest 读取可见记忆及关系证据,逐条用 memu_private_entity_merge_decide 裁决。',
|
|
244
|
+
'有明确同一身份/别名证据且置信度 >=0.85 才 merge;明确不同主体且置信度 >=0.85 时 reject;证据不足或严重身份错配风险时 hold,理由说明缺哪条证据。名字相似、同姓、亲属关系本身不构成同一身份证据。',
|
|
245
|
+
'每一对都要调用裁决工具,不能只口头总结。工具报凭据变化就停止该对,等待下一批重读。处理完这批即结束,不再开 fork、不要接手候选以外的任务。',
|
|
246
|
+
JSON.stringify(pairs.map(({ sourceId, targetId, reviewToken }) => ({ sourceId, targetId, reviewToken }))),
|
|
247
|
+
].join('\n')
|
|
248
|
+
}
|
|
249
|
+
|
|
237
250
|
export default {
|
|
238
251
|
WORKER_WRITE_TOOLS, WORKER_READ_TOOLS, CORE_WRITE_TOOLS, WORKER_WRAPUP_ROUND, WORKER_HARD_STOP_ROUND,
|
|
239
252
|
workerRoundGuidance, toolNamesFromTools, lastHeaderTools, liveHeaderTools, ptcSurface, probeToolSurface, buildWorkerBrief,
|
package/lib/cycle.js
CHANGED
|
@@ -6,10 +6,12 @@ import {
|
|
|
6
6
|
import { expireShortTerm, archiveExpiredDrafts, overdueOpenCommitments, EXPIRED_DRAFT_RETENTION_DAYS } from './memory.js'
|
|
7
7
|
import { requestPrivateConsolidation, archivedSessionIdsOf, CONSOLIDATION_BACKLOG_EVENTS, CONSOLIDATION_PROBE_MINUTES } from './private.js'
|
|
8
8
|
import { gcTurnLogs } from './turn-log.js'
|
|
9
|
+
import { runRetentionPass } from './retention.js'
|
|
9
10
|
import { startGlobalCuration } from './curator.js'
|
|
10
11
|
import { runVisibilityMigrationPass } from './migrate.js'
|
|
11
12
|
import { runSalientWakePass } from './salient-wake.js'
|
|
12
13
|
import { runMaintenancePass } from './maintenance-runner.js'
|
|
14
|
+
import { runEntityReviewPass } from './entity-review.js'
|
|
13
15
|
export { runMaintenancePass } from './maintenance-runner.js'
|
|
14
16
|
import { record } from './activity-log.js'
|
|
15
17
|
import { ACTIVE_MEMORY_POLICY, suppressionReason } from './active-memory.js'
|
|
@@ -323,18 +325,20 @@ export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limi
|
|
|
323
325
|
return { ran, considered: candidates.length }
|
|
324
326
|
}
|
|
325
327
|
|
|
326
|
-
//
|
|
327
|
-
//
|
|
328
|
-
// 只读绑定表 + 文件 stat/mtime,仅对已闲置满期的少数绑定才读日志内容找 max seqEnd;
|
|
329
|
-
// 没有日志文件的绑定直接跳过。异常只 warn,绝不绊倒 sweep 的其他 pass。
|
|
328
|
+
// Compatibility surface: the unified retention pass is used by the cycle; direct callers
|
|
329
|
+
// of the legacy turn-log helper only inspect or prune bound turn logs under the same gate.
|
|
330
330
|
export function runTurnLogGcPass(_ctx, { now = Date.now(), log = () => {} } = {}) {
|
|
331
331
|
try {
|
|
332
|
-
const
|
|
333
|
-
if (
|
|
334
|
-
|
|
332
|
+
const settings = getSettings()
|
|
333
|
+
if (settings.retentionBoundTurnLogsEnabled === false) return { deleted: [], kept: [], skipped: 'disabled', dryRun: settings.retentionDryRun !== false }
|
|
334
|
+
const result = gcTurnLogs(listSessionBindings(), {
|
|
335
|
+
now, olderThanDays: settings.retentionBoundTurnLogDays, dryRun: settings.retentionDryRun !== false,
|
|
336
|
+
})
|
|
337
|
+
if (result.deleted.length > 0) log(`turn-log gc ${settings.retentionDryRun !== false ? 'would delete' : 'deleted'} ${result.deleted.length} idle turn log(s)`)
|
|
338
|
+
return { ...result, dryRun: settings.retentionDryRun !== false }
|
|
335
339
|
} catch (error) {
|
|
336
340
|
log(`turn-log gc failed: ${error?.message || error}`)
|
|
337
|
-
return { deleted: [], kept: [], error: String(error?.message || error) }
|
|
341
|
+
return { deleted: [], kept: [], error: String(error?.message || error), dryRun: true }
|
|
338
342
|
}
|
|
339
343
|
}
|
|
340
344
|
|
|
@@ -459,10 +463,11 @@ export function runLibraryHousekeeping(ctx, { now = Date.now(), log = () => {} }
|
|
|
459
463
|
export async function runCyclePasses(ctx, options = {}) {
|
|
460
464
|
const shortTerm = runShortTermPass(ctx, options)
|
|
461
465
|
const overdue = runOverdueReviewPass(ctx, options)
|
|
462
|
-
|
|
463
|
-
const turnLogs =
|
|
466
|
+
const retention = runRetentionPass(ctx, options)
|
|
467
|
+
const turnLogs = retention.boundTurnLogs
|
|
464
468
|
const maintenance = await runMaintenancePass(ctx, options)
|
|
465
469
|
const sleep = await runSleepPass(ctx, options)
|
|
470
|
+
const entityReview = await runEntityReviewPass(ctx, options)
|
|
466
471
|
const curate = await runCurationPass(ctx, options)
|
|
467
472
|
const libraries = runLibraryHousekeeping(ctx, options)
|
|
468
473
|
// A library can still be on disk in the removed `session` format when the plugin
|
|
@@ -476,7 +481,7 @@ export async function runCyclePasses(ctx, options = {}) {
|
|
|
476
481
|
try { options.log?.(`salient wake pass failed: ${error?.message || error}`) } catch {}
|
|
477
482
|
return { created: 0, cleaned: 0, skipped: 0, errors: 1 }
|
|
478
483
|
})
|
|
479
|
-
return { shortTerm, overdue, turnLogs, maintenance, sleep, curate, libraries, migrated, salientWake }
|
|
484
|
+
return { shortTerm, overdue, turnLogs, retention, maintenance, sleep, entityReview, curate, libraries, migrated, salientWake }
|
|
480
485
|
}
|
|
481
486
|
|
|
482
487
|
// DSH has no host scheduler a plugin can register a *global* job with
|
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import os from 'node:os'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import crypto from 'node:crypto'
|
|
5
|
+
import { fileURLToPath } from 'node:url'
|
|
6
|
+
import { dataDir, redactSecrets } from './paths.js'
|
|
7
|
+
import { hostSurface } from './host-surface.js'
|
|
8
|
+
|
|
9
|
+
const PRIVATE_FIELD = /^(?:body|content|title|text|prompt|systemprompt|query|dialogue|dialog|transcript|conversation|messages|history|input|output|stdout|request|response|payload|state|profile|env|environment|headers)$/i
|
|
10
|
+
const SECRET_FIELD = /(?:apikey|accesstoken|refreshtoken|authorization|cookie|password|passwd|credential|secret|privatekey|^token$)/i
|
|
11
|
+
const REF_FIELD = /^(?:sessionId|libraryId|scopeKey|cwd)$/i
|
|
12
|
+
const hash = value => crypto.createHash('sha256').update(String(value)).digest('hex').slice(0, 16)
|
|
13
|
+
const fieldName = value => String(value).replace(/[-_\s]/g, '')
|
|
14
|
+
const withheld = value => `Exception text withheld (chars=${String(value).length}, sha256=${hash(value)}); inspect code and stack`
|
|
15
|
+
const safeCode = value => /^[A-Z][A-Z0-9_]{0,79}$/.test(String(value || '')) ? String(value) : 'MEMU_ERROR'
|
|
16
|
+
|
|
17
|
+
// Match signatures, never the whole foreign sentence. Even a genuine native
|
|
18
|
+
// exception can append a request, a model response or user-controlled SQL.
|
|
19
|
+
function exceptionMessage(raw) {
|
|
20
|
+
if (raw === 'SQLite failure' || raw === 'Node.js runtime failure') return raw
|
|
21
|
+
if (/^Exception text withheld \(chars=\d+, sha256=[a-f0-9]{16}\); inspect code and stack$/.test(raw)) return raw
|
|
22
|
+
const patterns = [
|
|
23
|
+
[/\b(ENOENT|EACCES|EPERM|EBUSY|ETIMEDOUT|ECONNREFUSED|ECONNRESET|MODULE_NOT_FOUND)\b/, match => match[1]],
|
|
24
|
+
[/\bSQLITE_[A-Z_]+\b/, () => 'SQLite failure'],
|
|
25
|
+
[/\bERR_[A-Z_]+\b/, () => 'Node.js runtime failure'],
|
|
26
|
+
[/\b(ModuleNotFoundError|ImportError|SyntaxError|TypeError|RangeError)\b/, match => match[1]],
|
|
27
|
+
[/cannot find (module|package)\b/i, match => `Cannot find ${match[1].toLowerCase()}`],
|
|
28
|
+
[/no module named\b/i, () => 'ModuleNotFoundError'],
|
|
29
|
+
[/database (is locked|disk image is malformed)\b/i, match => `database ${match[1].toLowerCase()}`],
|
|
30
|
+
[/failed to (load|start|read|write|open|spawn|connect)\s+(?:the\s+)?(runtime|python|engine|worker|module|package|database|manifest|metadata|index)\b/i, match => `failed to ${match[1].toLowerCase()} ${match[2].toLowerCase()}`],
|
|
31
|
+
[/\b(worker|runtime|engine|vector|python)\s+(timeout|timed out|not installed|not ready|not active|exited|failed)\b/i, match => `${match[1].toLowerCase()} ${match[2].toLowerCase()}`],
|
|
32
|
+
[/\b(invalid JSON|no such file|permission denied|unknown repair action)\b/i, match => match[1].toLowerCase()],
|
|
33
|
+
]
|
|
34
|
+
for (const [pattern, format] of patterns) {
|
|
35
|
+
const match = raw.match(pattern)
|
|
36
|
+
if (match) return format(match)
|
|
37
|
+
}
|
|
38
|
+
return withheld(raw)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function stackFrames(stack) {
|
|
42
|
+
return String(stack || '').split(/\r?\n/).flatMap(line => {
|
|
43
|
+
// Drop the function display name as well as the first error/source line.
|
|
44
|
+
const js = line.match(/^\s+at (?:.*? \()?((?:file:\/\/\/|[A-Za-z]:[\\/]|\/|node:|<(?:data|user|plugin)>[\\/])[^\r\n()]+:\d+:\d+)\)?$/)
|
|
45
|
+
if (js) return [` at ${diagnosticText(js[1], 500)}`]
|
|
46
|
+
const py = line.match(/^\s*File "([^"\r\n]+\.(?:py|pyc))", line (\d+)(?:, in [A-Za-z0-9_<>.]+)?$/)
|
|
47
|
+
return py ? [` File "${diagnosticText(py[1], 500)}", line ${py[2]}`] : []
|
|
48
|
+
}).slice(0, 24).join('\n') || null
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export const diagnosticRef = value => value == null ? null : /^ref:[a-f0-9]{16}$/.test(String(value)) ? String(value) : `ref:${hash(value)}`
|
|
52
|
+
|
|
53
|
+
const TECHNICAL_VALUES = new Set(['ok', 'ready', 'failed', 'error', 'warn', 'info', 'observed', 'unknown', 'absent', 'missing', 'pending', 'running', 'booting', 'closed', 'idle', 'installing', 'verified', 'active', 'inactive', 'degraded', 'skipped', 'not-built', 'download', 'extract', 'verify', 'install', 'load', 'start', 'stop', 'spawn', 'connect', 'read', 'write', 'pip', 'lexical', 'managed-local', 'remote-api', 'api', 'local', 'agent', 'fork', 'worker', 'off', 'shadow', 'on', 'admit', 'requestRejection'])
|
|
54
|
+
const TECHNICAL_FIELDS = new Set(['action', 'repair', 'code', 'name', 'version', 'source', 'operation', 'stage', 'status', 'step', 'phase', 'route', 'mode', 'kind', 'type', 'message', 'reason', 'error', 'lastError', 'stack', 'causes', 'messageRef', 'sessionRef', 'libraryRef', 'sessionId', 'libraryId', 'scopeKey', 'cwd', 'expected', 'actual', 'changedFields', 'catalogId', 'fingerprint', 'file', 'path', 'lockPath', 'modelDir', 'runtimeDir', 'stderr', 'stderrTail', 'owner', 'ageMs', 'at', 'lastAt', 'detail', 'context', 'versions', 'host', 'plugin', 'node', 'runtime', 'model', 'stage', 'retry', 'retryable', 'afterMs', 'errno', 'syscall', 'signal', 'exitCode', 'statusCode'])
|
|
55
|
+
const TECHNICAL_IDS = new Set(['onnxruntime-node', 'memu-cli', 'dsh-memu-memory', '@deepseek-ai/dsh', 'runtime', 'sources', 'dimension', 'pooling', 'prefixes', 'files', 'model', 'tokenizer', 'fingerprint', 'embed', 'recall', 'consolidation', 'inbound', 'engine-backend', 'worker-status', 'engine-metadata', 'vector-profile', 'state-metadata', 'environment-check', 'warn-sink', 'embedding-worker', 'vector-bootstrap', 'engine-bootstrap', 'startup-check', 'entity-repair', 'repair', 'pre-step', 'guide', 'rollback', 'listener', 'final-flush', 'prompts', 'startup', 'dispatch', 'register', 'accounting', 'write', 'start', 'read', 'export', 'import', 'injection-turn', 'session-event', 'state-flush', 'prompt-sync', 'turn-log-recorder', 'startup-summary', 'inject', 'index', 'rpc', 'rpc.dispatch', 'rpc.register', 'paths.withFileLock'])
|
|
56
|
+
|
|
57
|
+
const ENTITY_MERGE_REASONS = new Set(['containment', 'edit-distance', 'name-core'])
|
|
58
|
+
const ENTITY_KINDS = new Set(['person', 'place', 'thing', 'org'])
|
|
59
|
+
const ENTITY_MERGE_DETAIL_VERSION = 1
|
|
60
|
+
const ENTITY_MERGE_NAME_LIMIT = 160
|
|
61
|
+
const ENTITY_MERGE_CANDIDATE_LIMIT = 20
|
|
62
|
+
|
|
63
|
+
function safeEntityName(value) {
|
|
64
|
+
if (typeof value !== 'string') return null
|
|
65
|
+
const raw = value.slice(0, ENTITY_MERGE_NAME_LIMIT * 4)
|
|
66
|
+
const text = diagnosticText(raw, ENTITY_MERGE_NAME_LIMIT)
|
|
67
|
+
.replace(/[\r\n\t]+/g, ' ')
|
|
68
|
+
.trim()
|
|
69
|
+
return text || null
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function safeEntityRef(value) {
|
|
73
|
+
return typeof value === 'string' && (/^ent[-_][a-z0-9_-]{1,150}$/i.test(value) || /^ref:[a-f0-9]{16}$/.test(value))
|
|
74
|
+
? diagnosticRef(value) : null
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Names are intentionally retained here: this is the one diagnostic payload
|
|
79
|
+
* that is meant to let a person identify a graph candidate. The caller must
|
|
80
|
+
* obtain the pair through the graph visibility API before using this projection.
|
|
81
|
+
* The write-capable reviewToken is never exported; signature is only its stable
|
|
82
|
+
* diagnostic reference.
|
|
83
|
+
*/
|
|
84
|
+
export function diagnosticEntityMergeCandidate(value) {
|
|
85
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return null
|
|
86
|
+
const source = value.source && typeof value.source === 'object' ? value.source : value
|
|
87
|
+
const target = value.target && typeof value.target === 'object' ? value.target : value
|
|
88
|
+
const sourceName = safeEntityName(source.name ?? value.sourceName)
|
|
89
|
+
const targetName = safeEntityName(target.name ?? value.targetName)
|
|
90
|
+
const sourceKind = ENTITY_KINDS.has(source.kind) ? source.kind : null
|
|
91
|
+
const targetKind = ENTITY_KINDS.has(target.kind) ? target.kind : null
|
|
92
|
+
const kind = sourceKind && sourceKind === targetKind && (!value.kind || value.kind === sourceKind) ? sourceKind : null
|
|
93
|
+
const reason = ENTITY_MERGE_REASONS.has(value.reason) ? value.reason : null
|
|
94
|
+
const rawSignature = value.signature ?? value.reviewToken
|
|
95
|
+
const signature = /^ref:[a-f0-9]{16}$/.test(String(rawSignature || ''))
|
|
96
|
+
? String(rawSignature) : /^[a-f0-9]{64}$/i.test(String(rawSignature || '')) ? diagnosticRef(rawSignature) : null
|
|
97
|
+
if (!sourceName || !targetName || !kind || !reason || !signature) return null
|
|
98
|
+
return {
|
|
99
|
+
source: { name: sourceName, kind: sourceKind || kind, ref: safeEntityRef(source.id ?? source.ref ?? value.sourceId) },
|
|
100
|
+
target: { name: targetName, kind: targetKind || kind, ref: safeEntityRef(target.id ?? target.ref ?? value.targetId) },
|
|
101
|
+
kind, reason, signature,
|
|
102
|
+
pending: value.pending !== false,
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function nonNegativeCount(value) {
|
|
107
|
+
return Number.isSafeInteger(value) && value >= 0 ? value : null
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function safeCursor(value) {
|
|
111
|
+
return typeof value === 'string' && value.length <= 180 && /^m1\.[a-f0-9]{64}\.\d{1,9}\.\d{1,9}$/.test(value) ? value : null
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Fixed schema for the graph candidate part of ENTITY_FRAGMENT_SUSPECTED. */
|
|
115
|
+
export function diagnosticEntityMergeCandidates(value) {
|
|
116
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return null
|
|
117
|
+
const candidates = Array.isArray(value.candidates)
|
|
118
|
+
? value.candidates.slice(0, ENTITY_MERGE_CANDIDATE_LIMIT).map(diagnosticEntityMergeCandidate).filter(Boolean)
|
|
119
|
+
: []
|
|
120
|
+
const libraries = Array.isArray(value.libraries)
|
|
121
|
+
? value.libraries.slice(0, 20).map(library => {
|
|
122
|
+
if (!library || typeof library !== 'object') return null
|
|
123
|
+
const rows = Array.isArray(library.candidates)
|
|
124
|
+
? library.candidates.slice(0, ENTITY_MERGE_CANDIDATE_LIMIT).map(diagnosticEntityMergeCandidate).filter(Boolean)
|
|
125
|
+
: []
|
|
126
|
+
return {
|
|
127
|
+
libraryRef: diagnosticRef(library.libraryId ?? library.libraryRef),
|
|
128
|
+
returned: nonNegativeCount(library.returned) ?? rows.length,
|
|
129
|
+
total: nonNegativeCount(library.total),
|
|
130
|
+
totalExact: library.totalExact === true,
|
|
131
|
+
discoveredTotal: nonNegativeCount(library.discoveredTotal),
|
|
132
|
+
scanComplete: library.scanComplete === true,
|
|
133
|
+
nextCursor: safeCursor(library.nextCursor),
|
|
134
|
+
scannedPairs: nonNegativeCount(library.scannedPairs),
|
|
135
|
+
pairSpace: nonNegativeCount(library.pairSpace),
|
|
136
|
+
candidates: rows,
|
|
137
|
+
}
|
|
138
|
+
}).filter(Boolean)
|
|
139
|
+
: []
|
|
140
|
+
const flat = candidates.length ? candidates : libraries.flatMap(library => library.candidates)
|
|
141
|
+
return {
|
|
142
|
+
schemaVersion: ENTITY_MERGE_DETAIL_VERSION,
|
|
143
|
+
limit: nonNegativeCount(value.limit) ?? ENTITY_MERGE_CANDIDATE_LIMIT,
|
|
144
|
+
returned: nonNegativeCount(value.returned) ?? flat.length,
|
|
145
|
+
total: nonNegativeCount(value.total),
|
|
146
|
+
totalExact: value.totalExact === true,
|
|
147
|
+
truncated: value.truncated === true,
|
|
148
|
+
scanComplete: value.scanComplete === true,
|
|
149
|
+
libraryRef: value.libraryId == null ? null : diagnosticRef(value.libraryId),
|
|
150
|
+
sessionRef: value.sessionId == null ? null : diagnosticRef(value.sessionId),
|
|
151
|
+
librariesTruncated: value.librariesTruncated === true,
|
|
152
|
+
visibility: value.sessionId == null ? 'management' : 'session',
|
|
153
|
+
candidates: flat.slice(0, ENTITY_MERGE_CANDIDATE_LIMIT),
|
|
154
|
+
libraries,
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function evidenceString(value, key) {
|
|
159
|
+
if (/^\[value withheld; chars=\d+, sha256=[a-f0-9]{16}\]$/.test(value)) return value
|
|
160
|
+
if (/^(?:message|reason|error|lastError)$/i.test(key)) return exceptionMessage(value)
|
|
161
|
+
if (/^(?:sessionRef|libraryRef|messageRef)$/i.test(key)) return diagnosticRef(value)
|
|
162
|
+
if (/^(?:stage|status|step|phase|route|mode|kind|type)$/i.test(key) && TECHNICAL_VALUES.has(value)) return value
|
|
163
|
+
if (/^(?:code)$/i.test(key)) return safeCode(value)
|
|
164
|
+
if (/^(?:version|host|plugin|node|expected|actual)$/i.test(key) && /^(?:v?\d+(?:\.\d+){1,3}(?:[-+.][A-Za-z0-9.-]+)?|[a-f0-9]{16,64})$/.test(value)) return value
|
|
165
|
+
if (/^(?:action|repair)$/i.test(key) && /^(?:release-stale-locks|resign-vector-profile|repoint-runtime-dir|reinstall-runtime|reinstall-model|rebuild-vector-index|reinstall-engine|merge-entity-fragments)$/.test(value)) return value
|
|
166
|
+
if (/^(?:source|operation|catalogId|name|changedFields)$/i.test(key) && TECHNICAL_IDS.has(value)) return value
|
|
167
|
+
if (/^(?:at|lastAt)$/i.test(key) && /^\d{4}-\d\d-\d\dT[0-9:.+-]+Z?$/.test(value)) return value.slice(0, 40)
|
|
168
|
+
if (/fingerprint/i.test(key) && /^[a-f0-9]{16,64}$/.test(value)) return value
|
|
169
|
+
// File paths, arbitrary labels and unknown string fields can be user data.
|
|
170
|
+
return `[value withheld; chars=${value.length}, sha256=${hash(value)}]`
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** No environment/config dump: only secret values are consulted for redaction. */
|
|
174
|
+
export function diagnosticText(value, limit = 2000) {
|
|
175
|
+
let text = redactSecrets(String(value ?? ''))
|
|
176
|
+
const secrets = Object.entries(process.env).filter(([key, val]) => SECRET_FIELD.test(fieldName(key)) && typeof val === 'string' && val.length >= 4)
|
|
177
|
+
for (const [, secret] of secrets) text = text.split(secret).join('[REDACTED]')
|
|
178
|
+
text = text
|
|
179
|
+
.replace(/\b(Bearer|Basic)\s+[^\s,;"']+/gi, '$1 [REDACTED]')
|
|
180
|
+
.replace(/((?:api[-_]?key|access[-_]?token|refresh[-_]?token|authorization|cookie|password|passwd|secret|credential|token)\s*["']?\s*[:=]\s*["']?)[^\s"',;&}\]]+/gi, '$1[REDACTED]')
|
|
181
|
+
.replace(/([?&])[^=&#\s]+=[^&#\s]*/g, '$1[REDACTED_QUERY]')
|
|
182
|
+
.replace(/(?:<\s*(?:memory|conversation|dialogue|prompt)[^>]*>)[\s\S]*/gi, '[REDACTED_CONTENT]')
|
|
183
|
+
.replace(/(["']?(?:body|content|prompt|query|dialogue|transcript|messages|stdout)["']?\s*[:=]\s*)[\s\S]*/gi, '$1[REDACTED_CONTENT]')
|
|
184
|
+
const roots = [[dataDir(), '<data>'], [os.homedir(), '<user>']].filter(([root]) => root && root.length > 3).sort((a, b) => b[0].length - a[0].length)
|
|
185
|
+
for (const [root, label] of roots) {
|
|
186
|
+
const escaped = root.replace(/\\/g, '/').replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\//g, '[\\\\/]')
|
|
187
|
+
text = text.replace(new RegExp(escaped, process.platform === 'win32' ? 'gi' : 'g'), label)
|
|
188
|
+
}
|
|
189
|
+
return text.slice(0, limit)
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export function diagnosticValue(value, { maxDepth = 6 } = {}) {
|
|
193
|
+
const seen = new WeakSet()
|
|
194
|
+
const visit = (item, depth, key = '') => {
|
|
195
|
+
const name = fieldName(key)
|
|
196
|
+
if (SECRET_FIELD.test(name) || PRIVATE_FIELD.test(name)) return '[REDACTED]'
|
|
197
|
+
if (REF_FIELD.test(key)) return diagnosticRef(item)
|
|
198
|
+
if (depth > maxDepth) return '[depth]'
|
|
199
|
+
if (item == null || typeof item === 'boolean') return item ?? null
|
|
200
|
+
if (typeof item === 'number') return Number.isFinite(item) ? item : null
|
|
201
|
+
if (typeof item === 'string' && /^stderr(?:Tail)?$/i.test(key)) {
|
|
202
|
+
const lines = item.split(/\r?\n/).slice(-40)
|
|
203
|
+
const technical = lines.map(line => /^(?:[A-Z][A-Z0-9_]*_API_KEY|API_KEY)\s*=/.test(line) ? line.replace(/=.*/, '=[REDACTED]') : exceptionMessage(line))
|
|
204
|
+
.filter(line => !line.startsWith('Exception text withheld'))
|
|
205
|
+
return technical.length ? [...new Set(technical)].join('\n').slice(0, 2000) : `[process output withheld; chars=${item.length}, sha256=${hash(item)}]`
|
|
206
|
+
}
|
|
207
|
+
if (typeof item === 'string' && /stack/i.test(key)) return stackFrames(item)
|
|
208
|
+
if (typeof item === 'string') return evidenceString(item, key)
|
|
209
|
+
if (typeof item !== 'object') return null
|
|
210
|
+
if (seen.has(item)) return '[circular]'
|
|
211
|
+
seen.add(item)
|
|
212
|
+
if (item instanceof Error || (typeof item.message === 'string' && ('stack' in item || 'causes' in item))) return diagnosticError(item)
|
|
213
|
+
if (Array.isArray(item)) return item.slice(0, 40).map(child => visit(child, depth + 1, key))
|
|
214
|
+
const out = {}
|
|
215
|
+
for (const field of Object.keys(item).slice(0, 64)) {
|
|
216
|
+
if (['__proto__', 'constructor', 'prototype'].includes(field)) continue
|
|
217
|
+
const safeField = TECHNICAL_FIELDS.has(field) || /^field:[a-f0-9]{16}$/.test(field) || PRIVATE_FIELD.test(fieldName(field)) || SECRET_FIELD.test(fieldName(field)) ? field : `field:${hash(field)}`
|
|
218
|
+
try { out[safeField] = visit(item[field], depth + 1, field) } catch { out[safeField] = '[unreadable]' }
|
|
219
|
+
}
|
|
220
|
+
return out
|
|
221
|
+
}
|
|
222
|
+
try { return visit(value, 0) } catch { return null }
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Token schema v1 contains counters and fixed labels, never message payloads. */
|
|
226
|
+
export function diagnosticDetail(code, value) {
|
|
227
|
+
if (code === 'ENTITY_FRAGMENT_SUSPECTED' && value && typeof value === 'object' && !Array.isArray(value)) {
|
|
228
|
+
const count = item => nonNegativeCount(item)
|
|
229
|
+
return {
|
|
230
|
+
...(count(value.similar) !== null ? { similar: count(value.similar) } : {}),
|
|
231
|
+
...(count(value.libraries) !== null ? { libraries: count(value.libraries) } : {}),
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (code !== 'MEMU_TOKEN_BUDGET' || value?.schemaVersion !== 1) return diagnosticValue(value)
|
|
235
|
+
const count = item => Number.isSafeInteger(item) && item >= 0 ? item : null
|
|
236
|
+
const exact = (item, expected) => item === expected ? expected : null
|
|
237
|
+
const counters = (object, fields) => Object.fromEntries(fields.map(key => [key, count(object?.[key])]))
|
|
238
|
+
const attribution = item => exact(item, 'whole-request')
|
|
239
|
+
const unverified = item => exact(item, 'unverified')
|
|
240
|
+
const usage = value.requestUsage?.last
|
|
241
|
+
const reason = 'public usage is whole-request; no memory-block attribution or public tokenizer verified'
|
|
242
|
+
try {
|
|
243
|
+
return {
|
|
244
|
+
schemaVersion: 1,
|
|
245
|
+
...(value.sessionId != null ? { sessionId: diagnosticRef(value.sessionId) } : {}),
|
|
246
|
+
...counters(value, ['turn', 'limit', 'estimated', 'remaining', 'messages', 'admittedEstimated', 'reservedEstimated']),
|
|
247
|
+
estimator: exact(value.estimator, 'budget.estTokens'), memoryActual: null,
|
|
248
|
+
calibration: unverified(value.calibration), calibrationFactor: null,
|
|
249
|
+
reason: exact(value.reason, reason),
|
|
250
|
+
ratioBuckets: Object.fromEntries(['latin', 'mixed', 'cjk'].map(bucket => [bucket, {
|
|
251
|
+
...counters(value.ratioBuckets?.[bucket], ['messages', 'estimated']),
|
|
252
|
+
actual: null, status: unverified(value.ratioBuckets?.[bucket]?.status),
|
|
253
|
+
}])),
|
|
254
|
+
requestUsage: {
|
|
255
|
+
requests: count(value.requestUsage?.requests), attribution: attribution(value.requestUsage?.attribution),
|
|
256
|
+
last: usage && typeof usage === 'object' ? {
|
|
257
|
+
...counters(usage, ['inputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'outputTokens', 'reasoningTokens', 'totalTokens', 'promptTokens']),
|
|
258
|
+
source: exact(usage.source, 'session/event.assistant/message.data.usage'), attribution: attribution(usage.attribution),
|
|
259
|
+
} : null,
|
|
260
|
+
},
|
|
261
|
+
}
|
|
262
|
+
} catch { return null }
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Only process counters and fixed codes; never adjacency keys or graph data. */
|
|
266
|
+
export function diagnosticGraphAdjacency(value) {
|
|
267
|
+
const counters = (object, fields) => Object.fromEntries(fields.map(key => [key,
|
|
268
|
+
Number.isSafeInteger(object?.[key]) && object[key] >= 0 ? object[key] : null]))
|
|
269
|
+
return {
|
|
270
|
+
...counters(value, ['loads', 'hits', 'fallbacks', 'published', 'publishFailures', 'evictedIdentities']),
|
|
271
|
+
lastError: /^GRAPH_ADJACENCY_(?:MISSING|STALE|CORRUPT|UNSAFE|IO|CAPACITY)$/.test(value?.lastError) ? value.lastError : null,
|
|
272
|
+
cache: { ...counters(value?.cache, ['size', 'bytes', 'maxBytes', 'maxEntries', 'ttlMs', 'hits', 'misses', 'evictions', 'expirations', 'oversized']),
|
|
273
|
+
byteAccounting: value?.cache?.byteAccounting === 'estimate' ? 'estimate' : null },
|
|
274
|
+
limits: counters(value?.limits, ['maxBytes', 'maxEntries', 'ttlMs', 'maxDiskBytes', 'maxIdentities', 'maxIndexBytes', 'maxNodesBytes', 'maxNodes', 'maxEdges', 'slots']),
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Foreign exception text may quote user input. Retain technical evidence only. */
|
|
279
|
+
export function diagnosticError(error) {
|
|
280
|
+
const seen = new Set()
|
|
281
|
+
const shape = current => {
|
|
282
|
+
const raw = String(current?.message || current || 'unknown failure')
|
|
283
|
+
const code = safeCode(current?.code || String(current?.name || 'MEMU_ERROR').toUpperCase())
|
|
284
|
+
const name = /^(?:Error|[A-Za-z][A-Za-z0-9]{0,60}(?:Error|Exception))$/.test(current?.name) ? current.name : 'Error'
|
|
285
|
+
const facts = {}
|
|
286
|
+
for (const key of ['errno', 'exitCode', 'status', 'statusCode']) if (Number.isFinite(current?.[key])) facts[key] = current[key]
|
|
287
|
+
if (/^(?:open|read|write|stat|access|rename|mkdir|spawn|connect|listen|unlink|scandir)$/.test(current?.syscall)) facts.syscall = current.syscall
|
|
288
|
+
if (/^SIG[A-Z0-9]{1,12}$/.test(current?.signal)) facts.signal = current.signal
|
|
289
|
+
return { name, code, message: exceptionMessage(raw), stack: stackFrames(current?.stack),
|
|
290
|
+
messageRef: /^ref:[a-f0-9]{16}$/.test(current?.messageRef) ? current.messageRef : diagnosticRef(raw), ...facts }
|
|
291
|
+
}
|
|
292
|
+
try {
|
|
293
|
+
const result = { ...shape(error), causes: [] }
|
|
294
|
+
let current = error
|
|
295
|
+
for (let i = 0; i < 4; i++) {
|
|
296
|
+
if (!current || typeof current !== 'object' || seen.has(current)) break
|
|
297
|
+
seen.add(current)
|
|
298
|
+
current = current.cause || current.detail?.error
|
|
299
|
+
if (!current || seen.has(current)) break
|
|
300
|
+
result.causes.push(shape(current))
|
|
301
|
+
}
|
|
302
|
+
// Persisted structured errors use an array instead of native Error.cause.
|
|
303
|
+
for (const cause of Array.isArray(error?.causes) ? error.causes : []) {
|
|
304
|
+
if (result.causes.length >= 4) break
|
|
305
|
+
if (!cause || seen.has(cause)) continue
|
|
306
|
+
seen.add(cause)
|
|
307
|
+
result.causes.push(shape(cause))
|
|
308
|
+
}
|
|
309
|
+
return result
|
|
310
|
+
} catch { return { name: 'Error', code: 'MEMU_ERROR', message: 'Exception could not be inspected safely', stack: null, causes: [] } }
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function publicPackage(file) {
|
|
314
|
+
const stat = fs.statSync(file)
|
|
315
|
+
if (!stat.isFile() || stat.size > 256 * 1024) throw new Error('invalid package metadata')
|
|
316
|
+
const value = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
317
|
+
return { name: String(value.name || ''), version: typeof value.version === 'string' ? value.version : null }
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** Only the running entry's package ancestry is evidence of host identity. */
|
|
321
|
+
export function detectDiagnosticHost({ entrypoint = process.argv[1] } = {}) {
|
|
322
|
+
if (entrypoint) {
|
|
323
|
+
try {
|
|
324
|
+
let directory = path.dirname(fs.realpathSync(entrypoint))
|
|
325
|
+
for (let i = 0; i < 12; i++) {
|
|
326
|
+
const file = path.join(directory, 'package.json')
|
|
327
|
+
try {
|
|
328
|
+
const meta = publicPackage(file)
|
|
329
|
+
if (meta.name === '@deepseek-ai/dsh') return { version: meta.version, package: meta.name, source: 'running-entry/package.json', evidence: diagnosticText(file), status: meta.version ? 'observed' : 'unknown' }
|
|
330
|
+
} catch {}
|
|
331
|
+
const parent = path.dirname(directory)
|
|
332
|
+
if (parent === directory) break
|
|
333
|
+
directory = parent
|
|
334
|
+
}
|
|
335
|
+
} catch {}
|
|
336
|
+
}
|
|
337
|
+
return { version: null, package: null, source: 'unavailable', evidence: 'The running entry could not be associated with @deepseek-ai/dsh package metadata; installed copies and folder names are not runtime evidence.', status: 'unknown' }
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
let identity = null
|
|
341
|
+
export function diagnosticRuntime() {
|
|
342
|
+
if (!identity) {
|
|
343
|
+
let plugin = { name: 'dsh-memu-memory', version: null, source: 'unavailable' }
|
|
344
|
+
try { plugin = { ...publicPackage(fileURLToPath(new URL('../package.json', import.meta.url))), source: 'plugin/package.json' } } catch {}
|
|
345
|
+
identity = {
|
|
346
|
+
host: detectDiagnosticHost(), plugin,
|
|
347
|
+
node: { version: process.version, modules: process.versions.modules, napi: process.versions.napi },
|
|
348
|
+
os: { platform: process.platform, arch: process.arch, release: os.release() },
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
// This projection contains only package/process metadata and registered probe
|
|
352
|
+
// labels; applying the foreign-payload redactor would erase useful identities.
|
|
353
|
+
return { ...identity, host: { ...identity.host, capabilities: hostSurface() } }
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
export function diagnosticPolicy(code, scope = 'plugin') {
|
|
357
|
+
const text = String(code || '').toUpperCase()
|
|
358
|
+
const layer = /^(?:LOCAL_VECTOR|VECTOR_)/.test(text) ? 'vector'
|
|
359
|
+
: /^(?:MEMU_(?:ENGINE|COMMAND|SPAWN|RESIDENT)|ENGINE_)/.test(text) ? 'engine'
|
|
360
|
+
: /^(?:RT_|WORKER_|CONSOLIDATION_)/.test(text) ? 'workers'
|
|
361
|
+
: /(?:STORE|LOCK|JOURNAL|STORAGE|INDEX_READ|STATE_)/.test(text) ? 'state'
|
|
362
|
+
: /^(?:RPC_|HOST_)/.test(text) ? text.startsWith('RPC_') ? 'rpc' : 'host'
|
|
363
|
+
: ['engine', 'vector', 'host', 'rpc', 'workers', 'state'].includes(scope) ? scope : 'plugin'
|
|
364
|
+
const retryable = /(?:BUSY|TIMEOUT|TIMEDOUT|ECONN|WORKER_EXITED|BUILD_STALE|SOURCE_CHANGED|ARTIFACT_CHANGED)/.test(text)
|
|
365
|
+
const action = layer === 'engine' ? 'Inspect the engine metadata and executable; reinstall only after confirming the failure.'
|
|
366
|
+
: layer === 'vector' ? 'Inspect the active profile, runtime/model files and embedding worker; use the matching confirmed repair.'
|
|
367
|
+
: layer === 'state' ? 'Preserve the affected data; inspect read protection, disk permissions and locks before retrying.'
|
|
368
|
+
: layer === 'host' || layer === 'rpc' ? 'Compare the observed host capabilities and admission/registration evidence; preserve the request correlation id.'
|
|
369
|
+
: layer === 'workers' ? 'Inspect worker lifecycle and source fallback; retry after backoff or rebuild the disposable index.'
|
|
370
|
+
: 'Use the operation, cause codes and stack call sites to locate the plugin failure.'
|
|
371
|
+
return { layer, retry: { retryable, afterMs: retryable ? 30000 : null }, action }
|
|
372
|
+
}
|