dsh-memu-memory 1.1.2 → 1.2.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/AGENTS.md +8 -6
- package/README.md +50 -5
- package/README.zh.md +49 -5
- package/docs/active-memory-ab.md +385 -0
- package/docs/binding-lifecycle.md +99 -0
- package/docs/contributing.md +6 -4
- package/docs/emotion-model-spec.md +281 -0
- package/docs/env-and-commands.md +13 -0
- package/docs/host-api.md +35 -3
- package/docs/memory-semantics.md +40 -11
- package/docs/recall-benchmark.md +238 -0
- package/docs/troubleshooting.md +395 -366
- package/lib/active-memory.js +165 -0
- package/lib/activity-log.js +190 -0
- package/lib/backup.js +1103 -0
- package/lib/binding-diagnostics.js +635 -0
- package/lib/client.js +728 -58
- package/lib/consolidation-ledger.js +347 -0
- package/lib/consolidation-receipt.js +284 -0
- package/lib/consolidation-snapshot.js +274 -0
- package/lib/consolidation-worker.js +115 -0
- package/lib/curator.js +81 -37
- package/lib/cycle.js +43 -6
- package/lib/embedding-catalog.js +763 -0
- package/lib/embedding-download.js +407 -0
- package/lib/embedding-runtime.js +710 -0
- package/lib/engine.js +2 -2
- package/lib/index.js +36 -0
- package/lib/inject.js +232 -103
- package/lib/local-embedding-entry.js +145 -0
- package/lib/local-embedding-manager.js +267 -0
- package/lib/local-embedding-protocol.js +173 -0
- package/lib/local-embedding-worker.js +652 -0
- package/lib/local-vector-service.js +283 -0
- package/lib/memory.js +599 -57
- package/lib/memu-config.js +10 -22
- package/lib/memu.js +53 -19
- package/lib/mood.js +268 -39
- package/lib/paths.js +24 -0
- package/lib/preset-scope.js +1 -1
- package/lib/private.js +450 -29
- package/lib/prompts/private-consolidation.coding.md +1 -0
- package/lib/prompts/private-consolidation.md +1 -0
- package/lib/prompts/private-consolidation.mixed.md +1 -0
- package/lib/prompts/private-consolidation.rp.md +1 -0
- package/lib/prompts.js +4 -4
- package/lib/remote-summary.js +51 -25
- package/lib/rpc.js +54 -5
- package/lib/state.js +137 -172
- package/lib/tools.js +58 -7
- package/lib/vector-migration.js +878 -0
- package/lib/vector-profile.js +968 -0
- package/package.json +4 -2
- package/scripts/acceptance-local.mjs +7 -5
- package/scripts/active-memory-ab-live.mjs +655 -0
- package/scripts/active-memory-ab.mjs +1302 -0
- package/scripts/chain-matrix.mjs +537 -0
- package/scripts/check-all.mjs +29 -1
- package/scripts/check-doc-drift.mjs +353 -0
- package/scripts/diagnose-bindings.mjs +176 -0
- package/scripts/local-runtime-install.mjs +142 -0
- package/scripts/local-runtime-verify.mjs +56 -0
- package/scripts/local-vector-verify.mjs +93 -0
- package/scripts/recall-bench.mjs +813 -0
- package/scripts/repetition-ab-scenarios.mjs +93 -0
- package/scripts/repetition-detector-snapshot.mjs +314 -0
- package/scripts/repetition-eval-live.mjs +360 -0
- package/scripts/repetition-eval.mjs +702 -0
- package/tests/activation.test.mjs +89 -0
- package/tests/active-memory-ab.test.mjs +745 -0
- package/tests/active-memory.test.mjs +129 -0
- package/tests/activity-log.test.mjs +126 -0
- package/tests/activity-wiring.test.mjs +103 -0
- package/tests/appendix-b.test.mjs +212 -0
- package/tests/appendix-b2.test.mjs +166 -0
- package/tests/audit-regression.test.mjs +272 -0
- package/tests/audit-safety.test.mjs +227 -0
- package/tests/backend-compensation.test.mjs +272 -0
- package/tests/backup.test.mjs +793 -0
- package/tests/binding-diagnostics.test.mjs +720 -0
- package/tests/browser.test.mjs +366 -0
- package/tests/client-render.test.mjs +892 -0
- package/tests/coalesce.test.mjs +113 -0
- package/tests/config.test.mjs +159 -0
- package/tests/consolidation-credential.test.mjs +320 -0
- package/tests/consolidation-fork.test.mjs +357 -0
- package/tests/consolidation-ledger.test.mjs +298 -0
- package/tests/consolidation-snapshot.test.mjs +321 -0
- package/tests/consolidation-value.test.mjs +89 -0
- package/tests/context-scope.test.mjs +40 -0
- package/tests/cue.test.mjs +44 -0
- package/tests/curator-probe.test.mjs +433 -0
- package/tests/curator.test.mjs +150 -0
- package/tests/cycle.test.mjs +411 -0
- package/tests/disclosure.test.mjs +231 -0
- package/tests/doc-drift.test.mjs +222 -0
- package/tests/embedding-catalog.test.mjs +266 -0
- package/tests/embedding-download.test.mjs +391 -0
- package/tests/embedding-runtime.test.mjs +389 -0
- package/tests/emotion-chain.test.mjs +84 -0
- package/tests/emotion-contract.test.mjs +445 -0
- package/tests/engine.test.mjs +35 -0
- package/tests/fixtures/active-memory-ab/README.md +56 -0
- package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -0
- package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -0
- package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -0
- package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -0
- package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -0
- package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -0
- package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -0
- package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -0
- package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -0
- package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -0
- package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -0
- package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -0
- package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -0
- package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -0
- package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -0
- package/tests/fixtures/active-memory-ab/manifest.json +199 -0
- package/tests/fixtures/recall-bench/01-paraphrase.json +184 -0
- package/tests/fixtures/recall-bench/02-exact.json +153 -0
- package/tests/fixtures/recall-bench/03-negation.json +173 -0
- package/tests/fixtures/recall-bench/04-no-answer.json +162 -0
- package/tests/fixtures/recall-bench/05-conflict.json +194 -0
- package/tests/fixtures/recall-bench/06-boundary.json +273 -0
- package/tests/fixtures/recall-bench/07-secret.json +191 -0
- package/tests/fixtures/recall-bench/08-coding.json +164 -0
- package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -0
- package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -0
- package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -0
- package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -0
- package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -0
- package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -0
- package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -0
- package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -0
- package/tests/fixtures/repetition-eval/01-zh-rp.json +93 -0
- package/tests/fixtures/repetition-eval/02-en.json +97 -0
- package/tests/fixtures/repetition-eval/03-code.json +91 -0
- package/tests/fixtures/repetition-eval/04-names.json +116 -0
- package/tests/fixtures/repetition-eval/05-user-quote.json +96 -0
- package/tests/fixtures/repetition-eval/06-agreement.json +86 -0
- package/tests/graph-view.test.mjs +187 -0
- package/tests/graph.test.mjs +77 -0
- package/tests/hook-order.test.mjs +72 -0
- package/tests/humanlike.test.mjs +232 -0
- package/tests/hybrid-recall.test.mjs +92 -0
- package/tests/inbound.test.mjs +393 -0
- package/tests/inject-guide.test.mjs +364 -0
- package/tests/inject.test.mjs +222 -0
- package/tests/injection-budget-settings.test.mjs +35 -0
- package/tests/injection-budget.test.mjs +64 -0
- package/tests/injection-chain.test.mjs +191 -0
- package/tests/loader-register.mjs +3 -0
- package/tests/loader.mjs +12 -0
- package/tests/local-embedding-entry.test.mjs +95 -0
- package/tests/local-embedding-manager.test.mjs +476 -0
- package/tests/local-embedding-protocol.test.mjs +95 -0
- package/tests/local-embedding-worker.test.mjs +346 -0
- package/tests/managed-memory.test.mjs +536 -0
- package/tests/managed-runtime.test.mjs +40 -0
- package/tests/media.test.mjs +132 -0
- package/tests/migration-payload.test.mjs +42 -0
- package/tests/mood.test.mjs +109 -0
- package/tests/multiprocess.test.mjs +29 -0
- package/tests/new-session-gate.test.mjs +361 -0
- package/tests/package-shipping.test.mjs +84 -0
- package/tests/preset-scope.test.mjs +212 -0
- package/tests/prompts.test.mjs +250 -0
- package/tests/react-snapshot.test.mjs +23 -0
- package/tests/recall-bench.test.mjs +306 -0
- package/tests/remote.test.mjs +140 -0
- package/tests/rename.test.mjs +30 -0
- package/tests/repetition-detector-snapshot.test.mjs +231 -0
- package/tests/repetition-eval-live.test.mjs +177 -0
- package/tests/repetition-eval.test.mjs +373 -0
- package/tests/salient-date.test.mjs +142 -0
- package/tests/settings-beat.test.mjs +221 -0
- package/tests/short-term.test.mjs +166 -0
- package/tests/sidebar-beat.test.mjs +208 -0
- package/tests/sidebar-refresh.test.mjs +123 -0
- package/tests/sidebar.test.mjs +70 -0
- package/tests/snippet.test.mjs +47 -0
- package/tests/source-kind.test.mjs +52 -0
- package/tests/state.test.mjs +150 -0
- package/tests/stats.test.mjs +112 -0
- package/tests/storage.test.mjs +125 -0
- package/tests/stubs/dsh-llm.js +5 -0
- package/tests/stubs/dsh-session.js +7 -0
- package/tests/stubs/dsh-tools.js +101 -0
- package/tests/tool-schema.test.mjs +73 -0
- package/tests/tools.test.mjs +184 -0
- package/tests/ui-defaults.test.mjs +57 -0
- package/tests/update-fields.test.mjs +138 -0
- package/tests/vector-migration.test.mjs +733 -0
- package/tests/vector-profile.test.mjs +425 -0
- package/tests/visibility-migration.test.mjs +152 -0
- package/tests/webui-auth.test.mjs +454 -0
- package/tests/webui.test.mjs +164 -0
- package/tests/windows-env.test.mjs +89 -0
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
import test from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import os from 'node:os'
|
|
5
|
+
import path from 'node:path'
|
|
6
|
+
import crypto from 'node:crypto'
|
|
7
|
+
import { Buffer } from 'node:buffer'
|
|
8
|
+
import { profileFingerprint, resolveEmbeddingSources } from '../lib/embedding-catalog.js'
|
|
9
|
+
import { createEmbeddingDownloadManager, verifyStagedArtifacts } from '../lib/embedding-download.js'
|
|
10
|
+
|
|
11
|
+
const REVISION = 'a'.repeat(40)
|
|
12
|
+
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-embed-dl-'))
|
|
13
|
+
test.after(() => fs.rmSync(scratch, { recursive: true, force: true }))
|
|
14
|
+
|
|
15
|
+
const sha256 = buffer => crypto.createHash('sha256').update(buffer).digest('hex')
|
|
16
|
+
|
|
17
|
+
function varint(value) {
|
|
18
|
+
const bytes = []
|
|
19
|
+
let rest = value
|
|
20
|
+
while (rest > 127) { bytes.push((rest & 0x7f) | 0x80); rest = Math.floor(rest / 128) }
|
|
21
|
+
bytes.push(rest)
|
|
22
|
+
return Buffer.from(bytes)
|
|
23
|
+
}
|
|
24
|
+
const tag = (field, wire) => varint((field << 3) | wire)
|
|
25
|
+
const bytesField = (field, buffer) => Buffer.concat([tag(field, 2), varint(buffer.length), buffer])
|
|
26
|
+
const textField = (field, text) => bytesField(field, Buffer.from(text, 'utf8'))
|
|
27
|
+
const intField = (field, value) => Buffer.concat([tag(field, 0), varint(value)])
|
|
28
|
+
const dimension = dim => (typeof dim === 'number' ? intField(1, dim) : textField(2, String(dim)))
|
|
29
|
+
function valueInfo(name, elemType, shape) {
|
|
30
|
+
const shapeMessage = Buffer.concat(shape.map(dim => bytesField(1, dimension(dim))))
|
|
31
|
+
const tensorType = Buffer.concat([intField(1, elemType), bytesField(2, shapeMessage)])
|
|
32
|
+
return Buffer.concat([textField(1, name), bytesField(2, bytesField(1, tensorType))])
|
|
33
|
+
}
|
|
34
|
+
function tinyOnnxGraph(outputDim = 8) {
|
|
35
|
+
const initializer = Buffer.concat([intField(1, 1), intField(2, 1), textField(8, 'w'), bytesField(9, Buffer.from('quantized-weights-fixture'))])
|
|
36
|
+
const graph = Buffer.concat([
|
|
37
|
+
bytesField(5, initializer),
|
|
38
|
+
bytesField(11, valueInfo('input_ids', 7, ['batch_size', 'sequence_length'])),
|
|
39
|
+
bytesField(11, valueInfo('attention_mask', 7, ['batch_size', 'sequence_length'])),
|
|
40
|
+
bytesField(11, valueInfo('token_type_ids', 7, ['batch_size', 'sequence_length'])),
|
|
41
|
+
bytesField(12, valueInfo('last_hidden_state', 1, ['batch_size', 'sequence_length', outputDim])),
|
|
42
|
+
])
|
|
43
|
+
return Buffer.concat([intField(1, 6), textField(2, 'onnx.quantize'), bytesField(7, graph), bytesField(8, Buffer.concat([textField(1, ''), intField(2, 11)]))])
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// fixture 目录:结构同真实 BGE 条目,但体积小、可在离线环境里跑完整个生命周期。
|
|
47
|
+
function fixtureManifest(overrides = {}) {
|
|
48
|
+
const payloads = {
|
|
49
|
+
'config.json': Buffer.from(JSON.stringify({ hidden_size: 8, max_position_embeddings: 32, vocab_size: 3, model_type: 'bert' })),
|
|
50
|
+
'vocab.txt': Buffer.from('[PAD]\n[UNK]\n[CLS]\n'),
|
|
51
|
+
'onnx/tiny.onnx': tinyOnnxGraph(8),
|
|
52
|
+
}
|
|
53
|
+
const files = Object.keys(payloads).map(filePath => ({
|
|
54
|
+
path: filePath,
|
|
55
|
+
role: filePath.endsWith('.onnx') ? 'graph' : filePath === 'config.json' ? 'config' : 'vocab',
|
|
56
|
+
bytes: payloads[filePath].length,
|
|
57
|
+
sha256: sha256(payloads[filePath]),
|
|
58
|
+
}))
|
|
59
|
+
const entry = {
|
|
60
|
+
id: 'fixture-tiny-int8',
|
|
61
|
+
displayName: 'Fixture tiny int8',
|
|
62
|
+
languages: ['zh'],
|
|
63
|
+
availability: 'available',
|
|
64
|
+
pendingReasons: [],
|
|
65
|
+
parameters: 1000,
|
|
66
|
+
dimension: 8,
|
|
67
|
+
maxTokens: 32,
|
|
68
|
+
pooling: 'cls',
|
|
69
|
+
normalization: 'l2',
|
|
70
|
+
prefixes: { query: '', document: '' },
|
|
71
|
+
quantization: { weights: 'qint8', scheme: 'dynamic-per-channel' },
|
|
72
|
+
runtime: { engine: 'onnxruntime-node', version: null, abi: 'napi-v6', os: 'win32', arch: 'x64', verified: false },
|
|
73
|
+
license: { base: { id: 'mit', source: 'fixture' }, onnxExport: { id: 'undeclared', source: 'fixture' } },
|
|
74
|
+
verification: { status: 'verified', method: 'sha256+onnx-header', checkedAt: '2026-10-30T00:00:00.000Z' },
|
|
75
|
+
sources: {
|
|
76
|
+
modelscope: { repo: 'fixture/tiny', revision: REVISION },
|
|
77
|
+
'hf-mirror': { repo: 'fixture/tiny', revision: REVISION },
|
|
78
|
+
huggingface: { repo: 'fixture/tiny', revision: REVISION },
|
|
79
|
+
},
|
|
80
|
+
graph: {
|
|
81
|
+
path: 'onnx/tiny.onnx',
|
|
82
|
+
opset: 11,
|
|
83
|
+
selfContained: true,
|
|
84
|
+
externalData: [],
|
|
85
|
+
inputs: [
|
|
86
|
+
{ name: 'input_ids', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
|
|
87
|
+
{ name: 'attention_mask', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
|
|
88
|
+
{ name: 'token_type_ids', dtype: 'int64', shape: ['batch_size', 'sequence_length'] },
|
|
89
|
+
],
|
|
90
|
+
outputs: [{ name: 'last_hidden_state', dtype: 'float32', shape: ['batch_size', 'sequence_length', 8] }],
|
|
91
|
+
},
|
|
92
|
+
files,
|
|
93
|
+
}
|
|
94
|
+
entry.totalBytes = files.reduce((sum, file) => sum + file.bytes, 0)
|
|
95
|
+
entry.profileFingerprint = profileFingerprint(entry)
|
|
96
|
+
return { entry: { ...entry, ...overrides.entry }, payloads: { ...payloads, ...(overrides.payloads || {}) } }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function responseFor(bytes, options = {}) {
|
|
100
|
+
const status = options.status ?? 200
|
|
101
|
+
const split = options.chunk ?? 7
|
|
102
|
+
return {
|
|
103
|
+
ok: status >= 200 && status < 300,
|
|
104
|
+
status,
|
|
105
|
+
headers: { get: name => {
|
|
106
|
+
const lowered = String(name).toLowerCase()
|
|
107
|
+
if (lowered === 'content-length') return options.contentLength === undefined ? String(bytes.length) : options.contentLength
|
|
108
|
+
return null
|
|
109
|
+
} },
|
|
110
|
+
body: (async function* body() { for (let index = 0; index < bytes.length; index += split) yield bytes.subarray(index, index + split) })(),
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function makeFetch(entry, payloads, options = {}) {
|
|
115
|
+
const resolved = resolveEmbeddingSources(entry)
|
|
116
|
+
const routes = new Map(resolved.primary.files.map(file => [file.url, file.path]))
|
|
117
|
+
const calls = []
|
|
118
|
+
const fetchImpl = async (url, init) => {
|
|
119
|
+
calls.push({ url, init })
|
|
120
|
+
if (options.gate) await options.gate
|
|
121
|
+
if (init?.signal?.aborted) { const error = new Error('aborted'); error.name = 'AbortError'; throw error }
|
|
122
|
+
const filePath = routes.get(url)
|
|
123
|
+
if (!filePath) return { ok: false, status: 404, headers: { get: () => null }, body: null }
|
|
124
|
+
const payload = options.transform ? options.transform(filePath, payloads[filePath]) : payloads[filePath]
|
|
125
|
+
return responseFor(payload, options.responseFor ? options.responseFor(filePath) : {})
|
|
126
|
+
}
|
|
127
|
+
return { fetchImpl, calls, routes, resolved }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function managerFor(entry, fetchImpl, extra = {}) {
|
|
131
|
+
const root = fs.mkdtempSync(path.join(scratch, 'root-'))
|
|
132
|
+
return { root, manager: createEmbeddingDownloadManager({ root, catalog: [entry], fetchImpl, ...extra }) }
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
test('没有明确确认就绝不下模型,也不发任何请求', async () => {
|
|
136
|
+
const { entry, payloads } = fixtureManifest()
|
|
137
|
+
const { fetchImpl, calls } = makeFetch(entry, payloads)
|
|
138
|
+
const { manager } = managerFor(entry, fetchImpl)
|
|
139
|
+
await assert.rejects(manager.download(entry.id, {}), error => error.code === 'EMBEDDING_CONFIRMATION_REQUIRED')
|
|
140
|
+
await assert.rejects(manager.download(entry.id, { confirmed: 'yes' }), error => error.code === 'EMBEDDING_CONFIRMATION_REQUIRED')
|
|
141
|
+
assert.equal(calls.length, 0)
|
|
142
|
+
const status = manager.getStatus(entry.id)
|
|
143
|
+
assert.equal(status.state, 'absent')
|
|
144
|
+
assert.equal(status.installed, false)
|
|
145
|
+
assert.equal(status.active, false)
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
test('pending 模型与未知 id 都被拒绝,且不会联网', async () => {
|
|
149
|
+
const { entry, payloads } = fixtureManifest()
|
|
150
|
+
const { fetchImpl, calls } = makeFetch(entry, payloads)
|
|
151
|
+
const { manager } = managerFor(entry, fetchImpl)
|
|
152
|
+
await assert.rejects(manager.download('all-minilm-l6-v2-int8', { confirmed: true }), error => {
|
|
153
|
+
assert.equal(error.code, 'EMBEDDING_MODEL_UNAVAILABLE')
|
|
154
|
+
assert.ok(error.pendingReasons.length > 0)
|
|
155
|
+
return true
|
|
156
|
+
})
|
|
157
|
+
await assert.rejects(manager.download('does-not-exist', { confirmed: true }), error => error.code === 'EMBEDDING_MODEL_UNKNOWN')
|
|
158
|
+
assert.equal(calls.length, 0)
|
|
159
|
+
assert.equal(manager.getStatus('does-not-exist').state, 'unknown')
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
test('校验通过的制品原子安装:staging 清空、installed.json 记录 active:false', async () => {
|
|
163
|
+
const { entry, payloads } = fixtureManifest()
|
|
164
|
+
const { fetchImpl, calls } = makeFetch(entry, payloads)
|
|
165
|
+
const { root, manager } = managerFor(entry, fetchImpl)
|
|
166
|
+
const status = await manager.download(entry.id, { confirmed: true })
|
|
167
|
+
assert.equal(status.state, 'installed')
|
|
168
|
+
assert.equal(status.installed, true)
|
|
169
|
+
assert.equal(status.active, false)
|
|
170
|
+
assert.equal(status.fingerprintMatches, true)
|
|
171
|
+
assert.equal(status.revision, REVISION)
|
|
172
|
+
assert.equal(status.provider, 'modelscope')
|
|
173
|
+
assert.ok(status.checks.includes('graph.opset=11'))
|
|
174
|
+
assert.equal(calls.length, entry.files.length)
|
|
175
|
+
assert.deepEqual(calls.map(call => call.url).sort(), resolveEmbeddingSources(entry).primary.files.map(file => file.url).sort())
|
|
176
|
+
for (const file of entry.files) {
|
|
177
|
+
const target = path.join(root, entry.id, ...file.path.split('/'))
|
|
178
|
+
assert.equal(fs.statSync(target).size, file.bytes)
|
|
179
|
+
assert.equal(sha256(fs.readFileSync(target)), file.sha256)
|
|
180
|
+
}
|
|
181
|
+
const record = JSON.parse(fs.readFileSync(path.join(root, entry.id, 'installed.json'), 'utf8'))
|
|
182
|
+
assert.equal(record.active, false)
|
|
183
|
+
assert.equal(record.fingerprint, entry.profileFingerprint)
|
|
184
|
+
assert.equal(record.verifiedBy, 'sha256+structural-smoke')
|
|
185
|
+
assert.deepEqual(fs.readdirSync(path.join(root, '.staging')), [])
|
|
186
|
+
assert.equal(manager.getStatus(entry.id, { deep: true }).verified, true)
|
|
187
|
+
// 磁盘上不允许出现 active/profile 指针文件:激活是迁移模块的事。
|
|
188
|
+
const names = fs.readdirSync(path.join(root, entry.id))
|
|
189
|
+
assert.ok(names.every(name => !/active|profile/i.test(name)))
|
|
190
|
+
})
|
|
191
|
+
|
|
192
|
+
test('hash 不符立即失败,不安装,也不碰已有安装', async () => {
|
|
193
|
+
const { entry, payloads } = fixtureManifest()
|
|
194
|
+
const good = makeFetch(entry, payloads)
|
|
195
|
+
const { root, manager } = managerFor(entry, good.fetchImpl)
|
|
196
|
+
const first = await manager.download(entry.id, { confirmed: true })
|
|
197
|
+
assert.equal(first.state, 'installed')
|
|
198
|
+
const recordPath = path.join(root, entry.id, 'installed.json')
|
|
199
|
+
const before = fs.readFileSync(recordPath, 'utf8')
|
|
200
|
+
|
|
201
|
+
const tampered = makeFetch(entry, payloads, { transform: (filePath, buffer) => (filePath === 'onnx/tiny.onnx' ? Buffer.concat([buffer, Buffer.from('tampered')]) : buffer) })
|
|
202
|
+
const { manager: brokenManager } = managerFor(entry, tampered.fetchImpl, {})
|
|
203
|
+
const brokenRoot = brokenManager.root
|
|
204
|
+
await assert.rejects(brokenManager.download(entry.id, { confirmed: true }), error => {
|
|
205
|
+
assert.equal(error.code, 'EMBEDDING_SIZE_MISMATCH')
|
|
206
|
+
return true
|
|
207
|
+
})
|
|
208
|
+
assert.deepEqual(fs.readdirSync(path.join(brokenRoot, '.staging')), [])
|
|
209
|
+
assert.equal(fs.existsSync(path.join(brokenRoot, entry.id)), false)
|
|
210
|
+
|
|
211
|
+
const sameSizeTamper = makeFetch(entry, payloads, { transform: (filePath, buffer) => {
|
|
212
|
+
if (filePath !== 'onnx/tiny.onnx') return buffer
|
|
213
|
+
const copy = Buffer.from(buffer)
|
|
214
|
+
copy[copy.length - 1] = copy[copy.length - 1] ^ 0xff
|
|
215
|
+
return copy
|
|
216
|
+
} })
|
|
217
|
+
const { manager: sameSizeManager } = managerFor(entry, sameSizeTamper.fetchImpl, {})
|
|
218
|
+
await assert.rejects(sameSizeManager.download(entry.id, { confirmed: true }), error => error.code === 'EMBEDDING_HASH_MISMATCH')
|
|
219
|
+
assert.equal(fs.existsSync(path.join(sameSizeManager.root, entry.id)), false)
|
|
220
|
+
assert.deepEqual(fs.readdirSync(path.join(sameSizeManager.root, '.staging')), [])
|
|
221
|
+
|
|
222
|
+
// 原有安装一字未动。
|
|
223
|
+
assert.equal(fs.readFileSync(recordPath, 'utf8'), before)
|
|
224
|
+
assert.equal(manager.getStatus(entry.id).state, 'installed')
|
|
225
|
+
})
|
|
226
|
+
|
|
227
|
+
test('content-length 与固定字节数不符时代理响应被拒绝', async () => {
|
|
228
|
+
const { entry, payloads } = fixtureManifest()
|
|
229
|
+
const { fetchImpl } = makeFetch(entry, payloads, { responseFor: filePath => (filePath === 'config.json' ? { contentLength: '999' } : {}) })
|
|
230
|
+
const { root, manager } = managerFor(entry, fetchImpl)
|
|
231
|
+
await assert.rejects(manager.download(entry.id, { confirmed: true }), error => error.code === 'EMBEDDING_SIZE_MISMATCH')
|
|
232
|
+
assert.equal(manager.getStatus(entry.id).state, 'failed')
|
|
233
|
+
assert.equal(fs.existsSync(path.join(root, entry.id)), false)
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
test('模型 smoke 不通过(结构或自定义 verifyModel)时同样不安装', async () => {
|
|
237
|
+
const { entry, payloads } = fixtureManifest()
|
|
238
|
+
const badGraph = Buffer.from(tinyOnnxGraph(16))
|
|
239
|
+
const wrongDim = fixtureManifest({ payloads: { 'onnx/tiny.onnx': badGraph }, entry: {} })
|
|
240
|
+
wrongDim.entry.files.find(file => file.path === 'onnx/tiny.onnx').bytes = badGraph.length
|
|
241
|
+
wrongDim.entry.files.find(file => file.path === 'onnx/tiny.onnx').sha256 = sha256(badGraph)
|
|
242
|
+
wrongDim.entry.totalBytes = wrongDim.entry.files.reduce((sum, file) => sum + file.bytes, 0)
|
|
243
|
+
wrongDim.entry.profileFingerprint = profileFingerprint(wrongDim.entry)
|
|
244
|
+
const structural = makeFetch(wrongDim.entry, wrongDim.payloads)
|
|
245
|
+
const { root, manager } = managerFor(wrongDim.entry, structural.fetchImpl)
|
|
246
|
+
await assert.rejects(manager.download(wrongDim.entry.id, { confirmed: true }), error => {
|
|
247
|
+
assert.equal(error.code, 'EMBEDDING_SMOKE_FAILED')
|
|
248
|
+
assert.match(error.message, /last dim 16/)
|
|
249
|
+
return true
|
|
250
|
+
})
|
|
251
|
+
assert.equal(fs.existsSync(path.join(root, wrongDim.entry.id)), false)
|
|
252
|
+
|
|
253
|
+
const custom = makeFetch(entry, payloads)
|
|
254
|
+
const { root: customRoot, manager: customManager } = managerFor(entry, custom.fetchImpl, { verifyModel: async () => { throw new Error('tokenizer smoke says no') } })
|
|
255
|
+
await assert.rejects(customManager.download(entry.id, { confirmed: true }), error => error.code === 'EMBEDDING_SMOKE_FAILED')
|
|
256
|
+
assert.equal(customManager.getStatus(entry.id).state, 'failed')
|
|
257
|
+
assert.equal(fs.existsSync(path.join(customRoot, entry.id)), false)
|
|
258
|
+
})
|
|
259
|
+
|
|
260
|
+
test('verifyStagedArtifacts 直接核对图头、config 与词表', async () => {
|
|
261
|
+
const { entry, payloads } = fixtureManifest()
|
|
262
|
+
const dir = fs.mkdtempSync(path.join(scratch, 'staged-'))
|
|
263
|
+
for (const [filePath, buffer] of Object.entries(payloads)) {
|
|
264
|
+
fs.mkdirSync(path.dirname(path.join(dir, filePath)), { recursive: true })
|
|
265
|
+
fs.writeFileSync(path.join(dir, filePath), buffer)
|
|
266
|
+
}
|
|
267
|
+
const result = await verifyStagedArtifacts({ entry, dir })
|
|
268
|
+
assert.equal(result.ok, true)
|
|
269
|
+
assert.ok(result.checks.includes('graph.initializerBytes=' + Buffer.from('quantized-weights-fixture').length))
|
|
270
|
+
assert.ok(result.checks.includes('vocab.txt=3'))
|
|
271
|
+
fs.writeFileSync(path.join(dir, 'vocab.txt'), '[PAD]\n')
|
|
272
|
+
await assert.rejects(verifyStagedArtifacts({ entry, dir }), /vocab\.txt/)
|
|
273
|
+
})
|
|
274
|
+
|
|
275
|
+
test('取消下载:状态 cancelled、半成品不留在 staging、旧安装保留', async () => {
|
|
276
|
+
const { entry, payloads } = fixtureManifest()
|
|
277
|
+
const good = makeFetch(entry, payloads)
|
|
278
|
+
const { root, manager } = managerFor(entry, good.fetchImpl)
|
|
279
|
+
await manager.download(entry.id, { confirmed: true })
|
|
280
|
+
const before = manager.getStatus(entry.id)
|
|
281
|
+
|
|
282
|
+
let release
|
|
283
|
+
const gate = new Promise(resolve => { release = resolve })
|
|
284
|
+
const slow = makeFetch(entry, payloads, { gate })
|
|
285
|
+
const { manager: slowManager } = managerFor(entry, slow.fetchImpl, {})
|
|
286
|
+
const controller = new AbortController()
|
|
287
|
+
const pending = slowManager.download(entry.id, { confirmed: true, signal: controller.signal })
|
|
288
|
+
await new Promise(resolve => setTimeout(resolve, 20))
|
|
289
|
+
assert.equal(slowManager.getStatus(entry.id).state, 'downloading')
|
|
290
|
+
controller.abort()
|
|
291
|
+
release()
|
|
292
|
+
await assert.rejects(pending, error => error.code === 'EMBEDDING_DOWNLOAD_ABORTED')
|
|
293
|
+
assert.equal(slowManager.getStatus(entry.id).state, 'cancelled')
|
|
294
|
+
assert.deepEqual(fs.readdirSync(path.join(slowManager.root, '.staging')), [])
|
|
295
|
+
assert.equal(fs.existsSync(path.join(slowManager.root, entry.id)), false)
|
|
296
|
+
assert.equal(manager.getStatus(entry.id).installedAt, before.installedAt)
|
|
297
|
+
assert.equal(manager.getStatus(entry.id).state, 'installed')
|
|
298
|
+
})
|
|
299
|
+
|
|
300
|
+
test('同一模型并发下载被拒绝,进度可查', async () => {
|
|
301
|
+
const { entry, payloads } = fixtureManifest()
|
|
302
|
+
let release
|
|
303
|
+
const gate = new Promise(resolve => { release = resolve })
|
|
304
|
+
const slow = makeFetch(entry, payloads, { gate })
|
|
305
|
+
const { manager } = managerFor(entry, slow.fetchImpl)
|
|
306
|
+
const first = manager.download(entry.id, { confirmed: true })
|
|
307
|
+
await new Promise(resolve => setTimeout(resolve, 20))
|
|
308
|
+
const progress = manager.getStatus(entry.id)
|
|
309
|
+
assert.equal(progress.state, 'downloading')
|
|
310
|
+
assert.equal(progress.progress.files, entry.files.length)
|
|
311
|
+
await assert.rejects(manager.download(entry.id, { confirmed: true }), error => error.code === 'EMBEDDING_DOWNLOAD_BUSY')
|
|
312
|
+
release()
|
|
313
|
+
const status = await first
|
|
314
|
+
assert.equal(status.state, 'installed')
|
|
315
|
+
})
|
|
316
|
+
|
|
317
|
+
test('越界文件路径在 manifest 阶段就被拒绝,写不出 root', async () => {
|
|
318
|
+
for (const badPath of ['../escape.bin', 'nested/../../escape.bin', 'C:/windows/evil.bin', '/etc/passwd', 'onnx\\evil.onnx']) {
|
|
319
|
+
const { entry, payloads } = fixtureManifest()
|
|
320
|
+
entry.files = entry.files.map(file => (file.role === 'graph' ? { ...file, path: badPath } : file))
|
|
321
|
+
entry.graph = { ...entry.graph, path: badPath }
|
|
322
|
+
entry.profileFingerprint = profileFingerprint(entry)
|
|
323
|
+
const { fetchImpl, calls } = makeFetch(entry, payloads)
|
|
324
|
+
const { root, manager } = managerFor(entry, fetchImpl)
|
|
325
|
+
await assert.rejects(manager.download(entry.id, { confirmed: true }), error => {
|
|
326
|
+
assert.equal(error.code, 'EMBEDDING_MANIFEST_INVALID')
|
|
327
|
+
assert.ok(error.errors.some(item => item.code === 'FILE_PATH_UNSAFE'))
|
|
328
|
+
return true
|
|
329
|
+
})
|
|
330
|
+
assert.equal(calls.length, 0)
|
|
331
|
+
assert.deepEqual(fs.readdirSync(root), [])
|
|
332
|
+
assert.equal(fs.existsSync(path.join(scratch, 'escape.bin')), false)
|
|
333
|
+
}
|
|
334
|
+
})
|
|
335
|
+
|
|
336
|
+
test('重新下载同一模型时旧安装被替换,不留 trash 残渣', async () => {
|
|
337
|
+
const { entry, payloads } = fixtureManifest()
|
|
338
|
+
const good = makeFetch(entry, payloads)
|
|
339
|
+
const { root, manager } = managerFor(entry, good.fetchImpl)
|
|
340
|
+
const first = await manager.download(entry.id, { confirmed: true })
|
|
341
|
+
assert.equal(first.state, 'installed')
|
|
342
|
+
const nextRevision = 'd'.repeat(40)
|
|
343
|
+
const upgraded = { ...entry, sources: { modelscope: { repo: 'fixture/tiny', revision: nextRevision } } }
|
|
344
|
+
upgraded.profileFingerprint = profileFingerprint(upgraded)
|
|
345
|
+
const again = makeFetch(upgraded, payloads)
|
|
346
|
+
// 同一个 root:旧安装必须先被原子替换,而不是并存或半途丢失。
|
|
347
|
+
const freshManager = createEmbeddingDownloadManager({ root, catalog: [upgraded], fetchImpl: again.fetchImpl })
|
|
348
|
+
const second = await freshManager.download(entry.id, { confirmed: true })
|
|
349
|
+
assert.equal(second.revision, nextRevision)
|
|
350
|
+
assert.equal(second.state, 'installed')
|
|
351
|
+
assert.deepEqual(fs.readdirSync(path.join(freshManager.root, '.trash')), [])
|
|
352
|
+
assert.equal(JSON.parse(fs.readFileSync(path.join(freshManager.root, entry.id, 'installed.json'), 'utf8')).revision, nextRevision)
|
|
353
|
+
assert.equal(manager.getStatus(entry.id).state, 'installed')
|
|
354
|
+
})
|
|
355
|
+
|
|
356
|
+
test('fetchImpl 失败时状态是 failed,错误码可展示且不伪造安装', async () => {
|
|
357
|
+
const { entry } = fixtureManifest()
|
|
358
|
+
const failing = async () => { throw new Error('ECONNRESET') }
|
|
359
|
+
const { root, manager } = managerFor(entry, failing)
|
|
360
|
+
await assert.rejects(manager.download(entry.id, { confirmed: true }), error => error.code === 'EMBEDDING_NETWORK_ERROR')
|
|
361
|
+
const status = manager.getStatus(entry.id)
|
|
362
|
+
assert.equal(status.state, 'failed')
|
|
363
|
+
assert.equal(status.installed, false)
|
|
364
|
+
assert.equal(status.error.code, 'EMBEDDING_NETWORK_ERROR')
|
|
365
|
+
assert.equal(fs.existsSync(path.join(root, entry.id)), false)
|
|
366
|
+
})
|
|
367
|
+
|
|
368
|
+
test('dispose 中止在途下载,不留下崩溃痕迹', async () => {
|
|
369
|
+
const { entry, payloads } = fixtureManifest()
|
|
370
|
+
let release
|
|
371
|
+
const gate = new Promise(resolve => { release = resolve })
|
|
372
|
+
const slow = makeFetch(entry, payloads, { gate })
|
|
373
|
+
const { manager } = managerFor(entry, slow.fetchImpl)
|
|
374
|
+
const pending = manager.download(entry.id, { confirmed: true })
|
|
375
|
+
await new Promise(resolve => setTimeout(resolve, 20))
|
|
376
|
+
manager.dispose()
|
|
377
|
+
release()
|
|
378
|
+
await assert.rejects(pending, error => error.code === 'EMBEDDING_DOWNLOAD_ABORTED')
|
|
379
|
+
assert.equal(manager.getStatus(entry.id).state, 'cancelled')
|
|
380
|
+
})
|
|
381
|
+
|
|
382
|
+
test('root 必须是显式目录;模型根目录之外的路径被拒绝', async () => {
|
|
383
|
+
assert.throws(() => createEmbeddingDownloadManager({}), TypeError)
|
|
384
|
+
assert.throws(() => createEmbeddingDownloadManager({ root: '' }), TypeError)
|
|
385
|
+
const { entry } = fixtureManifest()
|
|
386
|
+
const root = fs.mkdtempSync(path.join(scratch, 'root-guard-'))
|
|
387
|
+
const manager = createEmbeddingDownloadManager({ root, catalog: [entry], fetchImpl: async () => { throw new Error('unused') } })
|
|
388
|
+
assert.equal(manager.root, path.resolve(root))
|
|
389
|
+
assert.ok(manager.catalogIds.includes('bge-small-zh-v1.5-int8'))
|
|
390
|
+
assert.equal(manager.getStatus('bge-small-zh-v1.5-int8').state, 'absent')
|
|
391
|
+
})
|