dsh-memu-memory 1.2.7 → 1.2.9
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 +1 -1
- package/CHANGELOG.md +472 -0
- package/README.md +10 -15
- package/README.zh.md +10 -15
- package/docs/memory-semantics.md +23 -3
- package/lib/backup.js +155 -26
- package/lib/binding-diagnostics.js +1 -2
- package/lib/budget.js +31 -9
- package/lib/client.js +221 -128
- package/lib/commitment.js +138 -0
- package/lib/consolidation-ledger.js +5 -2
- package/lib/consolidation-receipt.js +2 -0
- package/lib/consolidation-worker.js +3 -0
- package/lib/curator-policy.js +23 -0
- package/lib/cycle.js +8 -4
- package/lib/embedding-download.js +168 -28
- package/lib/embedding-runtime.js +76 -17
- package/lib/engine.js +0 -6
- package/lib/freshness.js +24 -0
- package/lib/graph.js +139 -11
- package/lib/index.js +71 -20
- package/lib/inject.js +167 -17
- package/lib/lexicon.js +62 -17
- package/lib/local-vector-service.js +25 -2
- package/lib/media.js +49 -12
- package/lib/memory.js +1202 -123
- package/lib/memu.js +4 -0
- package/lib/paths.js +0 -7
- package/lib/preset-scope.js +6 -1
- package/lib/private.js +50 -10
- package/lib/prompts/private-consolidation.mixed.md +2 -2
- package/lib/prompts/private-consolidation.rp.md +6 -1
- package/lib/prompts/private-policy.rp.md +4 -0
- package/lib/prompts/system-guide.rp.md +3 -0
- package/lib/prompts.js +0 -7
- package/lib/recall-cache.js +10 -2
- package/lib/rpc.js +104 -19
- package/lib/snippet.js +41 -0
- package/lib/state.js +109 -30
- package/lib/stats.js +2 -2
- package/lib/temporal.js +348 -0
- package/lib/text-retrieval.js +191 -44
- package/lib/text-similarity.js +205 -24
- package/lib/tokenizer-v2.js +0 -24
- package/lib/tools.js +81 -4
- package/lib/vector-migration.js +15 -0
- package/lib/vector-profile.js +81 -8
- package/lib/visibility.js +0 -4
- package/lib/webui/standalone.css +17 -22
- package/lib/webui/standalone.js +27 -9
- package/lib/webui.js +4 -4
- package/package.json +3 -2
- package/scripts/acceptance-local.mjs +2 -2
- package/scripts/bench-recall.mjs +2 -2
- package/scripts/check-all.mjs +3 -1
- package/scripts/check-i18n.mjs +35 -1
- package/scripts/check-seed-compat.mjs +1 -1
- package/scripts/migrate-visibility.mjs +3 -3
- package/scripts/prune-sessions.mjs +34 -0
- package/scripts/prune-vectors.mjs +24 -0
- package/tests/appendix-b.test.mjs +5 -4
- package/tests/audit-batch3.test.mjs +247 -0
- package/tests/audit-regression.test.mjs +2 -2
- package/tests/backup.test.mjs +85 -85
- package/tests/browser.test.mjs +6 -1
- package/tests/client-render.test.mjs +2 -2
- package/tests/commitment.test.mjs +144 -0
- package/tests/consolidation-fork.test.mjs +3 -3
- package/tests/curator-clusters.test.mjs +18 -0
- package/tests/curator-pairing.test.mjs +59 -16
- package/tests/disclosure.test.mjs +34 -17
- package/tests/dynamic-rrf.test.mjs +22 -19
- package/tests/dynamic-threshold.test.mjs +52 -0
- package/tests/fact-version.test.mjs +146 -0
- package/tests/fixtures/tokenizer-cases.mjs +27 -0
- package/tests/graph-cascade.test.mjs +29 -0
- package/tests/graph.test.mjs +45 -0
- package/tests/help-page.test.mjs +1 -1
- package/tests/inject-conflict.test.mjs +112 -0
- package/tests/inject-guide.test.mjs +5 -3
- package/tests/inject.test.mjs +2 -2
- package/tests/injection-intent-budget.test.mjs +92 -0
- package/tests/lexical-bm25.test.mjs +171 -0
- package/tests/lexicon-frequency.test.mjs +17 -1
- package/tests/lexicon-inject.test.mjs +21 -0
- package/tests/lexicon-perf.test.mjs +37 -9
- package/tests/lexicon-scope.test.mjs +2 -2
- package/tests/lexicon-ui.test.mjs +1 -1
- package/tests/managed-memory.test.mjs +19 -0
- package/tests/memory-chain.test.mjs +140 -0
- package/tests/memory-fields.test.mjs +134 -0
- package/tests/memu-resident.test.mjs +33 -0
- package/tests/ops-hardening.test.mjs +209 -0
- package/tests/package-shipping.test.mjs +4 -0
- package/tests/prompt-semantics.test.mjs +51 -0
- package/tests/query-decompose.test.mjs +62 -0
- package/tests/recall-cache.test.mjs +4 -2
- package/tests/recall-intent.test.mjs +123 -0
- package/tests/slot-similarity.test.mjs +153 -0
- package/tests/speaker-provenance.test.mjs +120 -0
- package/tests/state-gc.test.mjs +34 -0
- package/tests/state.test.mjs +2 -2
- package/tests/temporal.test.mjs +124 -0
- package/tests/tokenizer-v2.test.mjs +1 -1
- package/tests/vector-gc.test.mjs +37 -0
- package/tests/webui.test.mjs +27 -0
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// 承诺 / 欠账。
|
|
2
|
+
//
|
|
3
|
+
// `commitment.status` 是权威,`open_loop` 只保留做旧数据兼容:
|
|
4
|
+
// open → 还没兑现;done → 已兑现;cancelled → 明确取消;expired → 过期未完成。
|
|
5
|
+
// due_at 接受 YYYY-MM-DD 或 ISO 时间;比较按“到期那一天”算,不按时分秒。
|
|
6
|
+
|
|
7
|
+
import { localCalendarDay } from './temporal.js'
|
|
8
|
+
|
|
9
|
+
export const COMMITMENT_STATUSES = ['open', 'done', 'cancelled', 'expired']
|
|
10
|
+
|
|
11
|
+
const DAY_MS = 86_400_000
|
|
12
|
+
const DATE_ONLY_RE = /^(\d{4})-(\d{2})-(\d{2})$/
|
|
13
|
+
|
|
14
|
+
function cleanText(value, max) {
|
|
15
|
+
if (value === undefined || value === null) return ''
|
|
16
|
+
return String(value).replace(/\s+/g, ' ').trim().slice(0, max)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function validDateOnly(text) {
|
|
20
|
+
const match = DATE_ONLY_RE.exec(text)
|
|
21
|
+
if (!match) return false
|
|
22
|
+
const year = Number(match[1])
|
|
23
|
+
const month = Number(match[2])
|
|
24
|
+
const day = Number(match[3])
|
|
25
|
+
if (month < 1 || month > 12 || day < 1) return false
|
|
26
|
+
return day <= new Date(Date.UTC(year, month, 0)).getUTCDate()
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** YYYY-MM-DD or an ISO timestamp; anything else is refused. */
|
|
30
|
+
export function normalizeDueAt(value) {
|
|
31
|
+
if (value === undefined || value === null) return null
|
|
32
|
+
const text = String(value).trim()
|
|
33
|
+
if (!text) return null
|
|
34
|
+
if (DATE_ONLY_RE.test(text)) {
|
|
35
|
+
if (!validDateOnly(text)) throw new Error('commitment.due_at must be YYYY-MM-DD or an ISO date/time')
|
|
36
|
+
return text
|
|
37
|
+
}
|
|
38
|
+
const at = Date.parse(text)
|
|
39
|
+
if (!Number.isFinite(at)) throw new Error('commitment.due_at must be YYYY-MM-DD or an ISO date/time')
|
|
40
|
+
return new Date(at).toISOString()
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function dueDateText(value) {
|
|
44
|
+
if (!value) return null
|
|
45
|
+
if (DATE_ONLY_RE.test(value)) return value
|
|
46
|
+
const at = new Date(value)
|
|
47
|
+
return Number.isFinite(at.getTime()) ? `${at.getUTCFullYear()}-${String(at.getUTCMonth() + 1).padStart(2, '0')}-${String(at.getUTCDate()).padStart(2, '0')}` : null
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function localDateKey(now) {
|
|
51
|
+
return localCalendarDay(now)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function daysBetween(fromKey, toKey) {
|
|
55
|
+
if (!fromKey || !toKey) return null
|
|
56
|
+
const from = Date.UTC(...fromKey.split('-').map((part, index) => index === 1 ? Number(part) - 1 : Number(part)))
|
|
57
|
+
const to = Date.UTC(...toKey.split('-').map((part, index) => index === 1 ? Number(part) - 1 : Number(part)))
|
|
58
|
+
return Math.round((to - from) / DAY_MS)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 归一一条承诺。显式传对象时字段错误会抛(写盘前拒绝,不静默改),
|
|
63
|
+
* 读取旧数据用 commitmentOf 的宽容口径。
|
|
64
|
+
*/
|
|
65
|
+
export function normalizeCommitment(value, { fallbackAction = '', fallbackDueAt = null } = {}) {
|
|
66
|
+
if (value === undefined || value === null) return null
|
|
67
|
+
if (typeof value !== 'object' || Array.isArray(value)) throw new Error('commitment must be an object')
|
|
68
|
+
const status = value.status === undefined || value.status === null || value.status === ''
|
|
69
|
+
? 'open' : String(value.status)
|
|
70
|
+
if (!COMMITMENT_STATUSES.includes(status)) {
|
|
71
|
+
throw new Error(`commitment.status must be ${COMMITMENT_STATUSES.join(', ')}`)
|
|
72
|
+
}
|
|
73
|
+
const action = cleanText(value.action ?? fallbackAction, 500)
|
|
74
|
+
if (!action) throw new Error('commitment.action is required')
|
|
75
|
+
const counterparty = cleanText(value.counterparty, 128) || null
|
|
76
|
+
const due = value.due_at ?? value.dueAt ?? fallbackDueAt
|
|
77
|
+
const dueAt = normalizeDueAt(due)
|
|
78
|
+
const closedByRaw = value.closed_by ?? value.closedBy ?? null
|
|
79
|
+
const evidenceRaw = value.evidence_seq ?? value.evidenceSeq ?? null
|
|
80
|
+
return {
|
|
81
|
+
counterparty,
|
|
82
|
+
action,
|
|
83
|
+
due_at: dueAt,
|
|
84
|
+
status,
|
|
85
|
+
closed_by: closedByRaw === null || closedByRaw === undefined || closedByRaw === ''
|
|
86
|
+
? null : String(closedByRaw).slice(0, 128),
|
|
87
|
+
evidence_seq: evidenceRaw === null || evidenceRaw === undefined || evidenceRaw === ''
|
|
88
|
+
? null : (Number.isSafeInteger(Number(evidenceRaw)) ? Number(evidenceRaw) : String(evidenceRaw).slice(0, 128)),
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Tolerant read for stored entries; a malformed object never crashes recall. */
|
|
93
|
+
export function commitmentOf(entry) {
|
|
94
|
+
if (!entry || typeof entry !== 'object' || !entry.commitment || typeof entry.commitment !== 'object') return null
|
|
95
|
+
try {
|
|
96
|
+
return normalizeCommitment(entry.commitment)
|
|
97
|
+
} catch {
|
|
98
|
+
return null
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** open_loop 兼容口径:有 commitment 就看 status,没有才看旧布尔值。 */
|
|
103
|
+
export function isOpenThread(entry) {
|
|
104
|
+
const commitment = commitmentOf(entry)
|
|
105
|
+
if (commitment) return commitment.status === 'open'
|
|
106
|
+
return entry?.openLoop === true
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** 承诺的到期日(YYYY-MM-DD);没有 due_at 返回 null。 */
|
|
110
|
+
export function commitmentDueDate(entry) {
|
|
111
|
+
const commitment = commitmentOf(entry)
|
|
112
|
+
if (!commitment) return null
|
|
113
|
+
return dueDateText(commitment.due_at)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* 到期状态。`dueSoon` 只覆盖今天和明天:一张每回合都出现的承诺卡会变成噪声,
|
|
118
|
+
* 真正的“到期/逾期”才值得占预算。
|
|
119
|
+
*/
|
|
120
|
+
export function commitmentDueState(entryOrCommitment, { now = Date.now() } = {}) {
|
|
121
|
+
const commitment = entryOrCommitment?.status && entryOrCommitment?.action
|
|
122
|
+
? entryOrCommitment
|
|
123
|
+
: commitmentOf(entryOrCommitment)
|
|
124
|
+
if (!commitment || commitment.status !== 'open' || !commitment.due_at) {
|
|
125
|
+
return { open: commitment?.status === 'open', dueAt: null, daysUntil: null, overdue: false, dueSoon: false }
|
|
126
|
+
}
|
|
127
|
+
const dueAt = dueDateText(commitment.due_at)
|
|
128
|
+
const daysUntil = daysBetween(localDateKey(now), dueAt)
|
|
129
|
+
return {
|
|
130
|
+
open: true,
|
|
131
|
+
dueAt,
|
|
132
|
+
daysUntil,
|
|
133
|
+
overdue: daysUntil !== null && daysUntil < 0,
|
|
134
|
+
dueSoon: daysUntil !== null && daysUntil <= 1,
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export { DAY_MS }
|
|
@@ -268,8 +268,11 @@ export function failJob({ sessionId, jobId, reasonCode = 'failed', retryable = t
|
|
|
268
268
|
entry.attempts = (Number(entry.attempts) || 0) + 1
|
|
269
269
|
entry.retryAt = retryAtFrom(now, entry.attempts)
|
|
270
270
|
} else {
|
|
271
|
-
//
|
|
272
|
-
|
|
271
|
+
// 重试也不会变好(父授权变了、工具面不存在)。这里仍然要写一个退避,只是
|
|
272
|
+
// 取上限而不是从 1 分钟起:null 在 cycle 的读侧等于「随时可以再试」,于是
|
|
273
|
+
// 「不要每小时再试一次」变成了「每 5 分钟再试一次」。一小时是同一个上界,
|
|
274
|
+
// 语义却是真的「别再急着试」。
|
|
275
|
+
entry.retryAt = retryAtFrom(now, 6)
|
|
273
276
|
}
|
|
274
277
|
entry.lastReasonCode = reasonCode
|
|
275
278
|
entry.lastError = clampText(error || reasonCode)
|
|
@@ -197,6 +197,8 @@ export function reconcileReceipt({ receipt, index = null, beforeIds = null, befo
|
|
|
197
197
|
for (const id of receipt?.heldIds || []) {
|
|
198
198
|
const entry = entries[id]
|
|
199
199
|
if (!entry) { missing.push(id); continue }
|
|
200
|
+
// S7.3:heldIds 只表示“仅 pending_review”。已经以 active 落库的矛盾条目属于
|
|
201
|
+
// 正常写入证据,应写在 createdIds/updatedIds,不能混进 held。
|
|
200
202
|
if (entry.status !== 'pending_review') { problems.push('held id ' + id + ' is not pending_review'); continue }
|
|
201
203
|
heldIds.push(id)
|
|
202
204
|
}
|
|
@@ -153,6 +153,9 @@ export function buildWorkerBrief({ snapshot, probe = null, contract = '', reason
|
|
|
153
153
|
'转录开头的 [memory-catalog · 已有记忆目录] 是本库已有条目,只用来去重/合并,不是对话内容,也不是用户发言。',
|
|
154
154
|
'本轮可用的工具:' + tools + '。',
|
|
155
155
|
'要做的:先按主题检索相关旧条目去重;同一事实的补充用 memu_private_update 合并(先拿到 id);真正新增、或与已有说法矛盾的内容用 memu_private_remember 一条一件;矛盾不要自己裁决,让它进待复核。',
|
|
156
|
+
'写库前必须落 speaker_id、source_kind、absolute_date:今天/明天/下周X/月底这类相对日期要按本轮时间算成绝对日期,不能只留原文;解析不了就标 date_precision=unknown,不要猜。',
|
|
157
|
+
'同一事实有两种说法时各写一条,用 conflicts_with 互指,不合并、不自行裁决;只有明确取代才用 supersedes,旧正文保留。助手说过的承诺、计划、事实同样要写,source_kind=assistant_said,不能记成用户说的。',
|
|
158
|
+
'承诺/约定写 commitment(对谁/做什么/due_at/status);到期未完成的承诺要留在库里,让后续注入能看到。每窗最多新增 10 条,值得留的日常事实即使琐碎也要写。',
|
|
156
159
|
'写完(remember/update 拿到 id)后调用 memu_private_link_suggest({ids:[...]}),把本轮创建/更新的 id 都传进去:高置信的记忆↔记忆关联与实体枢纽算法已经自动连好,只有不确定的候选交给你裁决。不回读整段会话,也不为这个另起一次整理。',
|
|
157
160
|
'候选只用 memu_private_link 裁决:note 要引用转录原话,同一实体或同一事件确有证据才 link;证据不足或拿不准就 noop;互相矛盾就 conflict,不 link。每轮最多确认 5 条,不要为每一对都连;不要为了这件事把整个记忆库读一遍。',
|
|
158
161
|
'词典抽取:遇到稳定、可复用、有证据的黑话/梗/术语,先用 memu_lexicon_search 查重,再用 memu_lexicon_propose 一条一词写入。term 是索引键(短、稳定、用户的真实写法),meaning 才是解释;不写 sensitive trigger,也不写只属于这一次剧情的一次性词。',
|
package/lib/curator-policy.js
CHANGED
|
@@ -8,6 +8,10 @@
|
|
|
8
8
|
// gate already owns the value (DUP_DICE / DUP_REJECT_DICE / TOPIC_DICE), so
|
|
9
9
|
// the write-side duplicate ruler and the curator pair bands can never
|
|
10
10
|
// drift apart.
|
|
11
|
+
// 3. 相似度尺度的阈值(Dice 分带、长度剪枝比、包含探针下限)在
|
|
12
|
+
// lib/text-similarity.js 的 SIMILARITY_THRESHOLDS 里集中定义;本文件的常量
|
|
13
|
+
// 是「策展策略」——即哪些相似度分带触发 absorb/link/duplicate——而不是
|
|
14
|
+
// 相似度尺度本身。两处文档的分工以此为准。
|
|
11
15
|
import { DUP_DICE, DUP_REJECT_DICE, TOPIC_DICE } from './text-similarity.js'
|
|
12
16
|
// 刻意的双向依赖(仅函数体内使用):computeRRFWeights 的近期语义检测要用
|
|
13
17
|
// 「当前生效的 tokenize」,而分词开关(TOKENIZER_V2)就定义在本表,实际实现
|
|
@@ -38,6 +42,11 @@ export const CLUSTER_MIN_PAIR = 0.55
|
|
|
38
42
|
export const CLUSTER_BLOCK_MIN_SHARED = 2
|
|
39
43
|
export const CLUSTER_EXACT_PAIR_LIMIT = 300
|
|
40
44
|
export const CLUSTER_RECENT_LIMIT = 2000
|
|
45
|
+
// 倒排 blocking 的硬上限(防御性,不是主要剪枝):df 剪枝之后仍可能留下大量
|
|
46
|
+
// 共享对(例如每条都含一批中等频率的专有词)。超过这个数量就停止收集新对,
|
|
47
|
+
// 只保留已累积的计数——排序/切片必须有界,簇构建不能退化成 N²。
|
|
48
|
+
// 主要剪枝是 BLOCK_DF_RATIO 的 posting 上限:高频词在倒排层就被跳过。
|
|
49
|
+
export const CLUSTER_MAX_PAIRS = 50000
|
|
41
50
|
|
|
42
51
|
// —— 成对特征(§4.2)——
|
|
43
52
|
export const PAIR_SCAN_LIMIT = 20
|
|
@@ -53,6 +62,20 @@ export const PAIR_W_ENTITY = 0.15
|
|
|
53
62
|
export const BM25_K1 = 1.2
|
|
54
63
|
export const BM25_B = 0.75
|
|
55
64
|
export const BM25_MAX_QUERY_TERMS = 64
|
|
65
|
+
// query 侧的高频词闸(A-2):df 超过 dfCap 的 term 整条不参与打分,dfCap 取
|
|
66
|
+
// 「占比」与「候选池下限」中较大的那个:
|
|
67
|
+
// dfCap = max(BM25_DF_MIN_POOL, ceil(BM25_DF_RATIO × N))
|
|
68
|
+
// 只有占比是不够的:N=12 时 0.3N=3.6,任何被共享的查询词都会被剔光,12 条记忆
|
|
69
|
+
// 都提到「会议」的那次召回直接返回 0 条(实测回归)。下限的意思是「这条 posting
|
|
70
|
+
// 装得进一次召回所用过的最小候选池,就谈不上淹掉谁」。而 N=21 里 df=21 的「版本」
|
|
71
|
+
// 越过下限、被剔掉,decoy 才不会被一个恒正的小分拉进候选池——这正是要修的。
|
|
72
|
+
// 被剔除的是整个 term,不是把分数清零后保留条目(那只是换了个 0 分候选)。
|
|
73
|
+
// idf 下限曾经也有一道闸,但它可触及的条件(df > 0.9N)必然先被 df 闸命中,
|
|
74
|
+
// 剩下的只有 N<9 的极小语料——那正是绝不能剪的那一档,所以删掉。
|
|
75
|
+
export const BM25_DF_RATIO = 0.3
|
|
76
|
+
// 与 memory.js 的 HYBRID_CANDIDATE_MIN 同一口径:任何一次召回至少会看这么多条。
|
|
77
|
+
// posting 不超过它就淹不掉任何东西,剪枝只会白丢召回。
|
|
78
|
+
export const BM25_DF_MIN_POOL = 12
|
|
56
79
|
export const BLOCK_DF_RATIO = 0.3
|
|
57
80
|
export const RRF_K = 60 // 与 memory.js 的 HYBRID_RRF_K 同一口径
|
|
58
81
|
export const RRF_W_BM25 = 0.5
|
package/lib/cycle.js
CHANGED
|
@@ -92,6 +92,11 @@ export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limi
|
|
|
92
92
|
const idle = now - activeAt >= idleMs
|
|
93
93
|
const newActivity = older(lastSleepAt, binding.lastTurnAt) < 0
|
|
94
94
|
const state = ledger ? sessionState(binding.sessionId, ledger) : null
|
|
95
|
+
// The ledger's backoff used to be write-only: failJob stored retryAt and nothing
|
|
96
|
+
// ever read it, so a session that failed three times was retried on the very next
|
|
97
|
+
// sweep, five minutes later, forever. `sleepRetryAt` below is a different clock —
|
|
98
|
+
// that one delays the next *window*, this one delays the retry after a *failure*.
|
|
99
|
+
if ((Date.parse(state?.retryAt || '') || 0) > now) continue
|
|
95
100
|
const pendingEvents = state?.pending && (!state.checked || state.pending.throughSeq > state.checked.throughSeq)
|
|
96
101
|
? Number(state.pending.throughSeq) - (Number.isSafeInteger(Number(state.checked?.throughSeq)) ? Number(state.checked.throughSeq) : -1)
|
|
97
102
|
: 0
|
|
@@ -157,10 +162,9 @@ export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limi
|
|
|
157
162
|
// 证据不足(low-score)不是"已整理":不推进游标、不计数,等空闲越过饥饿阈值
|
|
158
163
|
// 或后续证据变多再检查。否则这句话会被永久跳过。
|
|
159
164
|
if (result.settled === false) {
|
|
160
|
-
//
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
}
|
|
165
|
+
// 任何没结算的结果都要记探针时间,不只是「水位不足」那两种:low-score 也
|
|
166
|
+
// 会读一遍转录并打分,不记就会在每次 5 分钟扫描里把同一段重读一遍。
|
|
167
|
+
setSessionBinding(binding.sessionId, { lastConsolidationProbeAt: new Date(now).toISOString() })
|
|
164
168
|
log(`sleep consolidation deferred for ${binding.sessionId}: ${result.skipped || 'not settled'}`)
|
|
165
169
|
continue
|
|
166
170
|
}
|
|
@@ -17,16 +17,19 @@ import {
|
|
|
17
17
|
// 2. 只从 manifest 里显式固定的 repo+revision 生成 URL;没有固定 revision 的来源不下载。
|
|
18
18
|
// 3. 失败、取消、hash 不符、smoke 不过一律不改动已安装目录——它代表"当前的 profiles",
|
|
19
19
|
// 写 active 是另一个模块的事,本模块永远不写 active/profile 指针(§14.8)。
|
|
20
|
-
// 4.
|
|
21
|
-
|
|
22
|
-
export const DOWNLOAD_STATES = Object.freeze(['unknown', 'absent', 'downloading', 'verifying', 'installed', 'failed', 'cancelled'])
|
|
20
|
+
// 4. 下载走独立 .cache 里的 .part + Range 断点续传,半成品不进 staging;
|
|
21
|
+
// 安装前校验完整总 hash,磁盘写失败清 .part 并给明确错误。
|
|
23
22
|
|
|
24
23
|
const INSTALL_RECORD = 'installed.json'
|
|
25
24
|
const STAGING_DIR = '.staging'
|
|
26
25
|
const TRASH_DIR = '.trash'
|
|
26
|
+
const CACHE_DIR = '.cache'
|
|
27
27
|
// 单文件上限。512 MiB 装不下已经逐字节核实过的 Qwen3-Embedding int8 图(600,223,343 B),
|
|
28
28
|
// 所以按「最大的一条 pin 住制品 + 余量」定;目录条目仍各自带 exact bytes,超限一律拒。
|
|
29
29
|
const DEFAULT_MAX_FILE_BYTES = 1024 * 1024 * 1024
|
|
30
|
+
// S-1:网络总超时与分块 stall 超时,避免半开连接把下载永久挂住。
|
|
31
|
+
const DEFAULT_FETCH_TIMEOUT_MS = 600_000
|
|
32
|
+
const DEFAULT_STALL_TIMEOUT_MS = 30_000
|
|
30
33
|
|
|
31
34
|
function fail(code, message, extra) {
|
|
32
35
|
const error = new Error(message)
|
|
@@ -35,6 +38,37 @@ function fail(code, message, extra) {
|
|
|
35
38
|
return error
|
|
36
39
|
}
|
|
37
40
|
|
|
41
|
+
function sha256FileSync(file) {
|
|
42
|
+
const hash = crypto.createHash('sha256')
|
|
43
|
+
const fd = fs.openSync(file, 'r')
|
|
44
|
+
try {
|
|
45
|
+
const buffer = Buffer.allocUnsafe(64 * 1024)
|
|
46
|
+
let read
|
|
47
|
+
while ((read = fs.readSync(fd, buffer, 0, buffer.length, null)) > 0) hash.update(buffer.subarray(0, read))
|
|
48
|
+
} finally {
|
|
49
|
+
fs.closeSync(fd)
|
|
50
|
+
}
|
|
51
|
+
return hash.digest('hex')
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// S-16:下载前预检目标盘剩余空间。statfsSync 抛错/回报 0 时不拦(fail-open),
|
|
55
|
+
// 让写入路径自己报错,别因为一个探针就挡住本来能装成功的下载。
|
|
56
|
+
function ensureFreeSpace(dir, requiredBytes) {
|
|
57
|
+
if (!Number.isFinite(requiredBytes) || requiredBytes <= 0) return
|
|
58
|
+
let available = null
|
|
59
|
+
try {
|
|
60
|
+
const stat = fs.statfsSync(dir)
|
|
61
|
+
available = Number(stat.bavail) * Number(stat.bsize)
|
|
62
|
+
} catch {
|
|
63
|
+
return
|
|
64
|
+
}
|
|
65
|
+
if (!Number.isFinite(available) || available <= 0) return
|
|
66
|
+
// 留一倍余量给 .part + staging 双份与安装副本,别把盘压到 0。
|
|
67
|
+
if (available < requiredBytes * 2) {
|
|
68
|
+
throw fail('EMBEDDING_DISK_FULL', `not enough free space to download the model: need ~${requiredBytes * 2} bytes, only ${available} available`)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
38
72
|
function isAbort(error, signal) {
|
|
39
73
|
return Boolean(signal?.aborted) || error?.name === 'AbortError' || error?.code === 'ABORT_ERR' || error?.code === 'UND_ERR_ABORTED' || error?.code === 'EMBEDDING_DOWNLOAD_ABORTED'
|
|
40
74
|
}
|
|
@@ -186,6 +220,8 @@ export function createEmbeddingDownloadManager(options = {}) {
|
|
|
186
220
|
const { root, fetchImpl = fetch, verifyModel, maxFileBytes = DEFAULT_MAX_FILE_BYTES, now = () => new Date().toISOString() } = options
|
|
187
221
|
if (typeof root !== 'string' || !root.trim()) throw new TypeError('createEmbeddingDownloadManager requires a root directory')
|
|
188
222
|
const baseDir = path.resolve(root)
|
|
223
|
+
const fetchTimeoutMs = Number.isInteger(options.fetchTimeoutMs) ? options.fetchTimeoutMs : DEFAULT_FETCH_TIMEOUT_MS
|
|
224
|
+
const stallTimeoutMs = Number.isInteger(options.stallTimeoutMs) ? options.stallTimeoutMs : DEFAULT_STALL_TIMEOUT_MS
|
|
189
225
|
const extraCatalog = Array.isArray(options.catalog) ? options.catalog : []
|
|
190
226
|
const jobs = new Map()
|
|
191
227
|
// 失败/取消结果单独记账:jobs 只表示「在途」,所以重试不会被误判成 BUSY,
|
|
@@ -204,6 +240,12 @@ export function createEmbeddingDownloadManager(options = {}) {
|
|
|
204
240
|
|
|
205
241
|
const modelDir = id => insideRoot(path.join(baseDir, id))
|
|
206
242
|
const recordPath = id => path.join(modelDir(id), INSTALL_RECORD)
|
|
243
|
+
// S-16:续传用的稳定 .part 放在独立 .cache,与 .staging 隔离(staging 仍保持
|
|
244
|
+
// 「安装成功后必须为空」的既有语义)。文件名带 sha256,换源/换版本不会误复用。
|
|
245
|
+
const partPathFor = file => {
|
|
246
|
+
const safe = String(file.path).split('/').pop().replace(/[^A-Za-z0-9._-]+/g, '-')
|
|
247
|
+
return path.join(insideRoot(path.join(baseDir, CACHE_DIR)), `${safe}-${file.sha256}.part`)
|
|
248
|
+
}
|
|
207
249
|
|
|
208
250
|
function readInstall(entry) {
|
|
209
251
|
const dir = modelDir(entry.id)
|
|
@@ -328,7 +370,11 @@ export function createEmbeddingDownloadManager(options = {}) {
|
|
|
328
370
|
outcomes.delete(entry.id)
|
|
329
371
|
let staging = null
|
|
330
372
|
let installed = false
|
|
373
|
+
const parts = []
|
|
331
374
|
try {
|
|
375
|
+
// S-16:下载前预检磁盘空间,避免 ENOSPC 留下 .part 占空间。
|
|
376
|
+
fs.mkdirSync(baseDir, { recursive: true })
|
|
377
|
+
ensureFreeSpace(baseDir, entry.totalBytes)
|
|
332
378
|
const stagingRoot = insideRoot(path.join(baseDir, STAGING_DIR))
|
|
333
379
|
fs.mkdirSync(stagingRoot, { recursive: true })
|
|
334
380
|
staging = fs.mkdtempSync(path.join(stagingRoot, `${entry.id}-`))
|
|
@@ -340,51 +386,138 @@ export function createEmbeddingDownloadManager(options = {}) {
|
|
|
340
386
|
if (!path.resolve(target).startsWith(path.resolve(staging) + path.sep)) throw fail('EMBEDDING_PATH_ESCAPE', `file ${file.path} escapes the staging directory`)
|
|
341
387
|
fs.mkdirSync(path.dirname(target), { recursive: true })
|
|
342
388
|
job.progress.current = file.path
|
|
389
|
+
|
|
390
|
+
// S-16:稳定 .part 缓存(独立于 .staging)+ Range 续传。半成品只进 .cache,
|
|
391
|
+
// 保持 staging「安装成功后必须为空」的既有语义。
|
|
392
|
+
const part = partPathFor(file)
|
|
393
|
+
parts.push(part)
|
|
394
|
+
fs.mkdirSync(path.dirname(part), { recursive: true })
|
|
395
|
+
let existing = 0
|
|
396
|
+
try { existing = fs.statSync(part).size } catch {}
|
|
397
|
+
if (existing > file.bytes) {
|
|
398
|
+
try { fs.rmSync(part, { force: true }) } catch {}
|
|
399
|
+
existing = 0
|
|
400
|
+
}
|
|
401
|
+
if (existing > 0 && existing === file.bytes) {
|
|
402
|
+
let reusable = false
|
|
403
|
+
try { reusable = sha256FileSync(part) === file.sha256 } catch { reusable = false }
|
|
404
|
+
if (reusable) {
|
|
405
|
+
fs.copyFileSync(part, target)
|
|
406
|
+
job.progress.bytes += file.bytes
|
|
407
|
+
job.progress.done += 1
|
|
408
|
+
continue
|
|
409
|
+
}
|
|
410
|
+
// 长度对但 hash 不符:这份半成品不可信,从头下。
|
|
411
|
+
try { fs.rmSync(part, { force: true }) } catch {}
|
|
412
|
+
existing = 0
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// S-1:总超时 + 分块 stall 超时。任一触发都中断响应体流,避免 CDN 半开
|
|
416
|
+
// 连接让 for-await 永久 pending;超时单独记账,别被误判成用户取消。
|
|
417
|
+
let timedOut = false
|
|
418
|
+
const totalSignal = AbortSignal.timeout(fetchTimeoutMs)
|
|
419
|
+
totalSignal.addEventListener('abort', () => { timedOut = true }, { once: true })
|
|
420
|
+
const stallController = new AbortController()
|
|
421
|
+
let stallTimer = null
|
|
422
|
+
const armStall = () => {
|
|
423
|
+
if (stallTimer) clearTimeout(stallTimer)
|
|
424
|
+
stallTimer = setTimeout(() => { timedOut = true; stallController.abort() }, stallTimeoutMs)
|
|
425
|
+
stallTimer.unref?.()
|
|
426
|
+
}
|
|
427
|
+
const clearStall = () => { if (stallTimer) { clearTimeout(stallTimer); stallTimer = null } }
|
|
428
|
+
const timeoutFailure = cause => fail('EMBEDDING_DOWNLOAD_TIMEOUT', `download of ${file.path} timed out (total ${fetchTimeoutMs}ms / stall ${stallTimeoutMs}ms)`, { cause })
|
|
429
|
+
const abortedFailure = cause => fail('EMBEDDING_DOWNLOAD_ABORTED', `download of ${entry.id} was aborted`, { cause })
|
|
430
|
+
// 磁盘写失败清 .part;超时/取消保留 .part 供下次 Range 续传。
|
|
431
|
+
let removePart = false
|
|
432
|
+
const streamFailure = error => {
|
|
433
|
+
if (timedOut && !controller.signal.aborted) return timeoutFailure(error)
|
|
434
|
+
if (error?.name === 'AbortError' || error?.code === 'ABORT_ERR' || error?.code === 'UND_ERR_ABORTED') return abortedFailure(error)
|
|
435
|
+
if (['ENOSPC', 'EIO', 'EROFS', 'EDQUOT', 'EFBIG'].includes(String(error?.code || ''))) {
|
|
436
|
+
removePart = true
|
|
437
|
+
return fail('EMBEDDING_DISK_FULL', `cannot write ${file.path}: ${error.code}; partial download removed`, { cause: error })
|
|
438
|
+
}
|
|
439
|
+
return error
|
|
440
|
+
}
|
|
441
|
+
armStall()
|
|
442
|
+
const signal = AbortSignal.any([controller.signal, totalSignal, stallController.signal])
|
|
443
|
+
const headers = { 'accept-encoding': 'identity' }
|
|
444
|
+
if (existing > 0) headers.Range = `bytes=${existing}-`
|
|
343
445
|
let response
|
|
344
446
|
try {
|
|
345
|
-
response = await fetchImpl(file.url, { signal
|
|
447
|
+
response = await fetchImpl(file.url, { signal, redirect: 'follow', headers })
|
|
346
448
|
} catch (error) {
|
|
347
|
-
if (
|
|
449
|
+
if (timedOut && !controller.signal.aborted) throw timeoutFailure(error)
|
|
450
|
+
if (isAbort(error, controller.signal)) throw abortedFailure(error)
|
|
348
451
|
throw fail('EMBEDDING_NETWORK_ERROR', `cannot fetch ${file.path} from ${source.provider}: ${error?.message || error}`, { cause: error })
|
|
349
452
|
}
|
|
350
453
|
if (!response || !response.ok) {
|
|
351
454
|
throw fail('EMBEDDING_HTTP_ERROR', `${source.provider} returned ${response?.status ?? 'no response'} for ${file.path}`)
|
|
352
455
|
}
|
|
456
|
+
let append = existing > 0
|
|
457
|
+
if (append && response.status === 200) {
|
|
458
|
+
// 源忽略了 Range,丢弃 .part 从头下,避免把整段内容追加到半成品后面。
|
|
459
|
+
job.progress.bytes = Math.max(0, job.progress.bytes - existing)
|
|
460
|
+
try { fs.rmSync(part, { force: true }) } catch {}
|
|
461
|
+
append = false
|
|
462
|
+
existing = 0
|
|
463
|
+
} else if (append) {
|
|
464
|
+
const contentRange = String(response.headers?.get?.('content-range') || '')
|
|
465
|
+
const match = /^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(contentRange)
|
|
466
|
+
if (response.status !== 206 || !match || Number(match[1]) !== existing || Number(match[3]) !== file.bytes) {
|
|
467
|
+
throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} returned an unexpected Content-Range for resume: ${contentRange || '(missing)'}`)
|
|
468
|
+
}
|
|
469
|
+
}
|
|
353
470
|
// 没有 content-length(hf-mirror 对小文件用 chunked 传输)等于「未知」,不是 0:
|
|
354
471
|
// 当成 0 会把每个小文件都误判成大小不符。真正的门槛是下面落盘后的 sha256。
|
|
355
472
|
const declaredHeader = response.headers?.get?.('content-length')
|
|
356
473
|
const declaredLength = Number(declaredHeader)
|
|
357
|
-
|
|
358
|
-
|
|
474
|
+
const expectedLength = file.bytes - existing
|
|
475
|
+
if (declaredHeader != null && Number.isInteger(declaredLength) && declaredLength > 0 && declaredLength !== expectedLength) {
|
|
476
|
+
throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} content-length ${declaredLength} does not match the expected ${expectedLength} bytes`)
|
|
359
477
|
}
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
const fd = fs.openSync(target, 'wx', 0o600)
|
|
478
|
+
let size = existing
|
|
479
|
+
const fd = fs.openSync(part, append ? 'a' : 'w', 0o600)
|
|
363
480
|
try {
|
|
364
481
|
const body = response.body
|
|
365
482
|
if (body && typeof body[Symbol.asyncIterator] === 'function') {
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
483
|
+
try {
|
|
484
|
+
for await (const chunk of body) {
|
|
485
|
+
if (controller.signal.aborted) throw abortedFailure(null)
|
|
486
|
+
armStall()
|
|
487
|
+
size += chunk.length
|
|
488
|
+
if (size > file.bytes) throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} exceeded the pinned ${file.bytes} bytes`)
|
|
489
|
+
fs.writeSync(fd, chunk)
|
|
490
|
+
job.progress.bytes += chunk.length
|
|
491
|
+
}
|
|
492
|
+
} catch (error) { throw streamFailure(error) }
|
|
374
493
|
} else {
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
494
|
+
try {
|
|
495
|
+
const buffer = Buffer.from(await response.arrayBuffer())
|
|
496
|
+
size += buffer.length
|
|
497
|
+
if (size > file.bytes) throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} exceeded the pinned ${file.bytes} bytes`)
|
|
498
|
+
fs.writeSync(fd, buffer)
|
|
499
|
+
job.progress.bytes += buffer.length
|
|
500
|
+
} catch (error) { throw streamFailure(error) }
|
|
381
501
|
}
|
|
382
502
|
} finally {
|
|
383
|
-
|
|
503
|
+
clearStall()
|
|
504
|
+
try { fs.closeSync(fd) } catch {}
|
|
505
|
+
if (removePart) { try { fs.rmSync(part, { force: true }) } catch {} }
|
|
506
|
+
}
|
|
507
|
+
if (size !== file.bytes) {
|
|
508
|
+
try { fs.rmSync(part, { force: true }) } catch {}
|
|
509
|
+
throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} is ${size} bytes, expected ${file.bytes}`)
|
|
510
|
+
}
|
|
511
|
+
const digest = sha256FileSync(part)
|
|
512
|
+
if (digest !== file.sha256) {
|
|
513
|
+
try { fs.rmSync(part, { force: true }) } catch {}
|
|
514
|
+
throw fail('EMBEDDING_HASH_MISMATCH', `${file.path} sha256 ${digest} does not match the pinned ${file.sha256}`)
|
|
515
|
+
}
|
|
516
|
+
try {
|
|
517
|
+
fs.copyFileSync(part, target)
|
|
518
|
+
} catch (error) {
|
|
519
|
+
throw fail('EMBEDDING_INSTALL_FAILED', `cannot stage ${file.path}: ${error?.code || error?.message || error}; partial download removed`, { cause: error })
|
|
384
520
|
}
|
|
385
|
-
if (size !== file.bytes) throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} is ${size} bytes, expected ${file.bytes}`)
|
|
386
|
-
const digest = hash.digest('hex')
|
|
387
|
-
if (digest !== file.sha256) throw fail('EMBEDDING_HASH_MISMATCH', `${file.path} sha256 ${digest} does not match the pinned ${file.sha256}`)
|
|
388
521
|
job.progress.done += 1
|
|
389
522
|
}
|
|
390
523
|
job.state = 'verifying'
|
|
@@ -441,6 +574,11 @@ export function createEmbeddingDownloadManager(options = {}) {
|
|
|
441
574
|
const aborted = isAbort(error, controller.signal)
|
|
442
575
|
const code = aborted ? 'EMBEDDING_DOWNLOAD_ABORTED' : (typeof error?.code === 'string' && error.code.startsWith('EMBEDDING_') ? error.code : 'EMBEDDING_DOWNLOAD_FAILED')
|
|
443
576
|
const failed = code === error?.code ? error : fail(code, `download of ${entry.id} failed: ${error?.message || error}`, { cause: error })
|
|
577
|
+
// S-16:非可续传类失败清掉 .part,别让半成品占空间;网络错误/超时/取消
|
|
578
|
+
// 保留 .part 供下次 Range 续传(S-1)。
|
|
579
|
+
if (!['EMBEDDING_DOWNLOAD_ABORTED', 'EMBEDDING_NETWORK_ERROR', 'EMBEDDING_DOWNLOAD_TIMEOUT'].includes(code)) {
|
|
580
|
+
for (const part of parts) { try { fs.rmSync(part, { force: true }) } catch {} }
|
|
581
|
+
}
|
|
444
582
|
job.state = aborted ? 'cancelled' : 'failed'
|
|
445
583
|
job.error = { code, message: String(failed.message || error) }
|
|
446
584
|
jobs.delete(entry.id)
|
|
@@ -449,6 +587,8 @@ export function createEmbeddingDownloadManager(options = {}) {
|
|
|
449
587
|
} finally {
|
|
450
588
|
signal?.removeEventListener('abort', onAbort)
|
|
451
589
|
if (staging && !installed) { try { fs.rmSync(staging, { recursive: true, force: true }) } catch {} }
|
|
590
|
+
// 安装成功后本次的 .part 已完成使命,清掉避免长期占空间。
|
|
591
|
+
if (installed) { for (const part of parts) { try { fs.rmSync(part, { force: true }) } catch {} } }
|
|
452
592
|
}
|
|
453
593
|
}
|
|
454
594
|
|