@yolk_vat-y/dsh-project-memory 0.5.13 → 0.5.15

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yolk_vat-y/dsh-project-memory",
3
- "version": "0.5.13",
3
+ "version": "0.5.15",
4
4
  "description": "Persistent project memory for dsh agents: index docs (PDF/Markdown/text) and code symbols into a searchable per-workspace store, recall them with cited sources, and keep experience entries (problems -> solutions) searchable on demand.",
5
5
  "author": "00080000 <3388065969@qq.com>",
6
6
  "type": "module",
@@ -19,12 +19,14 @@
19
19
  "url": "https://github.com/00080000/dsh-project-memory.git"
20
20
  },
21
21
  "scripts": {
22
- "test": "node test/run-test.mjs && node test/taskbridge.test.mjs && node test/insight-store.test.mjs && node test/reflection-pipeline.test.mjs && node test/auto-inject.test.mjs && node test/insight-actions.test.mjs && node test/host-contract.test.mjs && node test/llm-route.test.mjs && node test/doc-index.test.mjs && node test/client-hints.test.mjs && node test/recall.test.mjs && node test/readiness.test.mjs && node test/insight-derive.test.mjs && node test/readiness-eval.test.mjs && node test/ops.test.mjs && node test/injection-audit.test.mjs && node test/injection-budget.test.mjs && node test/injection-scenarios.test.mjs && node test/bugfix-0.5.7.test.mjs && node test/client-icons.test.mjs && node test/client-slash.test.mjs && node test/workflow-command.test.mjs && node test/client-session-id.test.mjs && node test/task-view.test.mjs && node test/root-guards.test.mjs && node test/store-gitignore.test.mjs && node test/store-cache.test.mjs && node test/enhancer.test.mjs",
22
+ "test": "node test/run-test.mjs && node test/taskbridge.test.mjs && node test/insight-store.test.mjs && node test/reflection-pipeline.test.mjs && node test/auto-inject.test.mjs && node test/insight-actions.test.mjs && node test/host-contract.test.mjs && node test/llm-route.test.mjs && node test/doc-index.test.mjs && node test/client-hints.test.mjs && node test/recall.test.mjs && node test/readiness.test.mjs && node test/insight-derive.test.mjs && node test/readiness-eval.test.mjs && node test/ops.test.mjs && node test/injection-audit.test.mjs && node test/injection-budget.test.mjs && node test/injection-scenarios.test.mjs && node test/bugfix-0.5.7.test.mjs && node test/client-icons.test.mjs && node test/client-slash.test.mjs && node test/client-toolview.test.mjs && node test/workflow-command.test.mjs && node test/client-session-id.test.mjs && node test/task-view.test.mjs && node test/root-guards.test.mjs && node test/store-gitignore.test.mjs && node test/atomic-write.test.mjs && node test/store-cache.test.mjs && node test/enhancer.test.mjs",
23
23
  "eval:injection": "node test/injection-scenarios.test.mjs",
24
24
  "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.client.json",
25
25
  "selfcheck:triggers": "node test/injection-scenarios.test.mjs --selfcheck",
26
26
  "bench": "node scripts/bench.mjs",
27
27
  "bench:synthetic": "node scripts/bench-synthetic.mjs",
28
+ "bench:peak": "node --expose-gc scripts/file-peak.mjs",
29
+ "schema:size": "node scripts/tool-schema-size.mjs",
28
30
  "build:client": "tsdown"
29
31
  },
30
32
  "keywords": [
@@ -50,12 +52,12 @@
50
52
  },
51
53
  "devDependencies": {
52
54
  "@deepseek-ai/cordis": "^4.0.4",
53
- "@deepseek-ai/dsh-client-locale": "0.2.0-rc.1",
54
- "@deepseek-ai/dsh-client-store": "0.2.0-rc.1",
55
- "@deepseek-ai/dsh-client-ui-primitives": "0.2.0-rc.1",
56
- "@deepseek-ai/dsh-client-ui-slots": "0.2.0-rc.1",
57
- "@deepseek-ai/dsh-llm": "0.2.0-rc.1",
58
- "@deepseek-ai/dsh-tools": "0.2.0-rc.1",
55
+ "@deepseek-ai/dsh-client-locale": "0.2.0-rc.2",
56
+ "@deepseek-ai/dsh-client-store": "0.2.0-rc.2",
57
+ "@deepseek-ai/dsh-client-ui-primitives": "0.2.0-rc.2",
58
+ "@deepseek-ai/dsh-client-ui-slots": "0.2.0-rc.2",
59
+ "@deepseek-ai/dsh-llm": "0.2.0-rc.2",
60
+ "@deepseek-ai/dsh-tools": "0.2.0-rc.2",
59
61
  "@deepseek-ai/schemastery": "^3.18.2",
60
62
  "@tsdown/css": "0.22.14",
61
63
  "@types/react": "^18.3.31",
@@ -0,0 +1,356 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 峰值系数实测 —— 回答 ROADMAP §1 的 #5:
4
+ * 「PDF 与代码共用同一个 maxFileSizeMb,而峰值是它的几倍」——实测是 19–21 倍,不是 2–4 倍。
5
+ *
6
+ * 口径(三条,缺一条数字就不可信):
7
+ * 1. **独立子进程**:父进程只负责生成语料与汇总。同进程量会把上一次的 store / pdfjs 模块
8
+ * 缓存算进第二次读数(见 scripts/bench.mjs 的同一教训)。
9
+ * 2. **heapUsed 与 RSS 都报**:heapUsed 是 V8 堆,RSS 含 ArrayBuffer/外部内存与未归还页。
10
+ * 放大系数按「峰值 / 磁盘字节」给,两个口径各算一份;**以 RSS 为准**——heap 峰值受 GC
11
+ * 时序影响会非单调(同一档符号密集语料 32MB 量出 625MB、50MB 反而 328MB)。
12
+ * 3. **峰值取两处最大**:`setInterval` 采样只在事件循环空闲时跑得到(pdfjs 逐页 await 之间能采到,
13
+ * 一长段同步代码里采不到),所以再叠加「每个阶段结束后尚未回收的 heapUsed」——
14
+ * 这些阶段里的分配都是**同时存活**的,阶段后读数即该阶段的真实驻留。
15
+ *
16
+ * 用法:
17
+ * node --expose-gc scripts/file-peak.mjs # 生成 50MB × 3 语料并跑两种路径
18
+ * node --expose-gc scripts/file-peak.mjs --mb=20 # 换档(默认 50)
19
+ * node --expose-gc scripts/file-peak.mjs code <file> # 子进程:只量代码路径
20
+ * node --expose-gc scripts/file-peak.mjs pdf <file> # 子进程:只量 PDF 路径
21
+ */
22
+ import { spawnSync } from 'node:child_process'
23
+ import { mkdirSync, statSync, writeFileSync, existsSync } from 'node:fs'
24
+ import os from 'node:os'
25
+ import path from 'node:path'
26
+
27
+ const argv = process.argv.slice(2)
28
+ const mode = argv[0] && !argv[0].startsWith('--') ? argv[0] : null
29
+
30
+ // ---------- 子进程:内存读数工具 ----------
31
+
32
+ function mb(n) {
33
+ return +(n / 1048576).toFixed(1)
34
+ }
35
+
36
+ function startSampler() {
37
+ const peak = { heap: 0, rss: 0 }
38
+ const timer = setInterval(() => {
39
+ const m = process.memoryUsage()
40
+ if (m.heapUsed > peak.heap) peak.heap = m.heapUsed
41
+ if (m.rss > peak.rss) peak.rss = m.rss
42
+ }, 2)
43
+ timer.unref?.()
44
+ return { peak, stop: () => clearInterval(timer) }
45
+ }
46
+
47
+ async function measure({ label, stages }) {
48
+ if (typeof globalThis.gc !== 'function') {
49
+ throw new Error('需要 --expose-gc:node --expose-gc bench/file-peak.mjs')
50
+ }
51
+ globalThis.gc()
52
+ const base = process.memoryUsage()
53
+ const sampler = startSampler()
54
+ const rows = []
55
+ let held = base
56
+ for (const [name, fn] of stages) {
57
+ const t0 = process.hrtime.bigint()
58
+ const value = await fn()
59
+ const t1 = process.hrtime.bigint()
60
+ const now = process.memoryUsage()
61
+ if (now.heapUsed > sampler.peak.heap) sampler.peak.heap = now.heapUsed
62
+ if (now.rss > sampler.peak.rss) sampler.peak.rss = now.rss
63
+ rows.push({
64
+ name,
65
+ ms: +(Number(t1 - t0) / 1e6).toFixed(0),
66
+ heap: now.heapUsed,
67
+ rss: now.rss,
68
+ })
69
+ held = now
70
+ if (value !== undefined) rows[rows.length - 1].value = value
71
+ }
72
+ sampler.stop()
73
+ globalThis.gc()
74
+ const after = process.memoryUsage()
75
+ return {
76
+ label,
77
+ base,
78
+ peak: sampler.peak,
79
+ held,
80
+ after,
81
+ rows,
82
+ }
83
+ }
84
+
85
+ function emit(result, extra = {}) {
86
+ process.stdout.write('\nPEAK_JSON ' + JSON.stringify({ ...result, ...extra }) + '\n')
87
+ }
88
+
89
+ // ---------- 子进程:两种路径 ----------
90
+
91
+ async function runCode(file) {
92
+ const { readFileForIndex } = await import('../src/util/fs.js')
93
+ const { scanSymbols } = await import('../src/symbols.js')
94
+ const disk = statSync(file).size
95
+ const st = {}
96
+ const result = await measure({
97
+ label: 'code',
98
+ stages: [
99
+ ['读盘 + 哈希(readFileForIndex)', () => {
100
+ const { buffer, hash } = readFileForIndex(file)
101
+ st.buffer = buffer
102
+ st.hash = hash
103
+ return undefined
104
+ }],
105
+ ["解码 buffer.toString('utf8')", () => {
106
+ st.text = st.buffer.toString('utf8')
107
+ return st.text.length
108
+ }],
109
+ ['符号扫描 scanSymbols', () => {
110
+ // 与 index-pipeline.js 的生产调用逐字一致:scanSymbols(rel, filePath, text)
111
+ st.entries = scanSymbols(path.basename(file), file, st.text)
112
+ return st.entries.length
113
+ }],
114
+ ],
115
+ })
116
+ emit(result, { disk, kind: 'code', symbols: st.entries.length, textChars: st.text.length })
117
+ }
118
+
119
+ async function runPdf(file) {
120
+ const { extractTextFromFile } = await import('../src/doc-pipeline.js')
121
+ const { chunkText } = await import('../src/chunker.js')
122
+ const { extractTermText, extractKeywords } = await import('../src/doc-index.js')
123
+ const { summarizeText } = await import('../src/util/text.js')
124
+ const disk = statSync(file).size
125
+
126
+ const st = {}
127
+ const result = await measure({
128
+ label: 'pdf',
129
+ stages: [
130
+ ['PDF 抽取 + 拼 markdown(parsePdf)', async () => {
131
+ st.text = await extractTextFromFile(file, { maxFileSizeMb: 50, maxPdfPages: 1000 })
132
+ return st.text.length
133
+ }],
134
+ ['分块 chunkText(3000, 40)', () => {
135
+ st.chunks = chunkText(st.text, 3000, 40)
136
+ return st.chunks.length
137
+ }],
138
+ ['建条目(summary + keywords + terms)', () => {
139
+ st.entries = st.chunks.map((c) => ({
140
+ summary: summarizeText(c.text),
141
+ keywords: extractKeywords(c.title, c.text),
142
+ terms: extractTermText(c.text),
143
+ }))
144
+ return st.entries.length
145
+ }],
146
+ ],
147
+ })
148
+ emit(result, {
149
+ disk,
150
+ kind: 'pdf',
151
+ textChars: st.text.length,
152
+ chunks: st.chunks.length,
153
+ entryBytes: st.entries.reduce((s, e) => s + e.summary.length + e.terms.length, 0),
154
+ })
155
+ }
156
+
157
+ // ---------- 语料生成 ----------
158
+
159
+ const WORDS = ('memory index recall insight trigger budget store shard entry symbol document chunk query latency retention project agent context ' +
160
+ 'graph node edge parse stream buffer handle session task archive promote merge token lexical hash window sample ' +
161
+ 'strategy policy ledger receipt coverage decay prune migrate replay projection invariant oracle ratchet gate').split(' ')
162
+
163
+ function* lineSource() {
164
+ let n = 0
165
+ while (true) {
166
+ n++
167
+ const w = []
168
+ for (let i = 0; i < 12; i++) w.push(WORDS[(n * 7 + i * 13) % WORDS.length])
169
+ yield `${n} ${w.join(' ')}`
170
+ }
171
+ }
172
+
173
+ /** 生成 ~targetBytes 的「代码样」文本文件。
174
+ * density 决定**符号密度**(代码路径的峰值主要由它决定,不由字节数决定):
175
+ * typical ≈ 1 个声明 / 1.2 KB(真实源码量级,声明之间有注释填充);dense ≈ 1 个 / 240 B(极端)。
176
+ */
177
+ function genCode(file, targetBytes, density = 'typical') {
178
+ const padLines = density === 'dense' ? 0 : 13
179
+ const parts = []
180
+ let bytes = 0
181
+ let n = 0
182
+ const gen = lineSource()
183
+ while (bytes < targetBytes) {
184
+ n++
185
+ let block =
186
+ `// module ${n}: ${gen.next().value}\n` +
187
+ `export function fn_${n}(a, b) { const x = a + b; return x * ${n % 97} }\n` +
188
+ `export const TABLE_${n} = ['${WORDS[n % WORDS.length]}', '${WORDS[(n + 3) % WORDS.length]}']\n`
189
+ for (let i = 0; i < padLines; i++) block += `// ${gen.next().value}\n`
190
+ parts.push(block)
191
+ bytes += Buffer.byteLength(block)
192
+ }
193
+ writeFileSync(file, parts.join(''))
194
+ return bytes
195
+ }
196
+
197
+ /** 生成最小但合法的 PDF:pages 页、每页 linesPerPage 行文本(未压缩流 → 磁盘大小≈文本量)。 */
198
+ function buildPdf(pages, linesPerPage) {
199
+ const chunks = []
200
+ let pos = 0
201
+ const offsets = {}
202
+ const push = (s) => {
203
+ const b = Buffer.from(s, 'latin1')
204
+ chunks.push(b)
205
+ pos += b.length
206
+ }
207
+ const startObj = (n) => {
208
+ offsets[n] = pos
209
+ push(`${n} 0 obj\n`)
210
+ }
211
+ push('%PDF-1.4\n%\xE2\xE3\xCF\xD3\n')
212
+
213
+ const pageObj = (i) => 3 + i
214
+ const contentObj = (i) => 3 + pages + i
215
+
216
+ startObj(1)
217
+ push(`<< /Type /Catalog /Pages 2 0 R >>\nendobj\n`)
218
+ startObj(2)
219
+ const kids = []
220
+ for (let i = 1; i <= pages; i++) kids.push(`${pageObj(i)} 0 R`)
221
+ push(`<< /Type /Pages /Kids [${kids.join(' ')}] /Count ${pages} >>\nendobj\n`)
222
+ startObj(3)
223
+ push(`<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n`)
224
+
225
+ const gen = lineSource()
226
+ const esc = (s) => s.replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)')
227
+ for (let i = 1; i <= pages; i++) {
228
+ startObj(pageObj(i))
229
+ push(
230
+ `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents ${contentObj(i)} 0 R ` +
231
+ `/Resources << /Font << /F1 3 0 R >> >> >>\nendobj\n`
232
+ )
233
+ let body = ''
234
+ // 每 68 行重新起一个文本对象:y 一旦落到页面外(MediaBox 之下),pdf.js 的
235
+ // getTextContent 就不再返回那些 item(实测每页只抽到 71 行 = 780/11)。真实 PDF
236
+ // 是分页排版的,所以这里也按「一屏一块」重排,保证抽出的正文与流里的文本等量。
237
+ for (let l = 0; l < linesPerPage; l++) {
238
+ if (l % 68 === 0) body += `ET BT /F1 9 Tf 20 780 Td 11 TL\n`
239
+ body += `(${esc(gen.next().value)}) Tj T*\n`
240
+ }
241
+ const stream = `BT /F1 9 Tf 20 780 Td 11 TL\n${body}ET\n`
242
+ startObj(contentObj(i))
243
+ push(`<< /Length ${Buffer.byteLength(stream, 'latin1')} >>\nstream\n${stream}endstream\nendobj\n`)
244
+ }
245
+
246
+ const size = 3 + 2 * pages + 1
247
+ const xrefPos = pos
248
+ let xref = `xref\n0 ${size}\n0000000000 65535 f \n`
249
+ for (let n = 1; n < size; n++) xref += `${String(offsets[n] ?? 0).padStart(10, '0')} 00000 n \n`
250
+ push(xref)
251
+ push(`trailer\n<< /Size ${size} /Root 1 0 R >>\nstartxref\n${xrefPos}\n%%EOF\n`)
252
+
253
+ return Buffer.concat(chunks)
254
+ }
255
+
256
+ function genPdf(file, targetBytes) {
257
+ // 每页正文约 (lineLen + 8) * linesPerPage 字节;先按每页 100KB 估页数,再按实际字节微调。
258
+ const linesPerPage = 1024
259
+ let pages = Math.max(1, Math.round(targetBytes / (linesPerPage * 60)))
260
+ for (let i = 0; i < 8; i++) {
261
+ const buf = buildPdf(pages, linesPerPage)
262
+ if (Math.abs(buf.length - targetBytes) / targetBytes < 0.05) {
263
+ writeFileSync(file, buf)
264
+ return buf.length
265
+ }
266
+ pages = Math.max(1, Math.round((pages * targetBytes) / buf.length))
267
+ }
268
+ const buf = buildPdf(pages, linesPerPage)
269
+ writeFileSync(file, buf)
270
+ return buf.length
271
+ }
272
+
273
+ // ---------- 编排 ----------
274
+
275
+ function runChild(childMode, file) {
276
+ const r = spawnSync(process.execPath, ['--expose-gc', new URL(import.meta.url).pathname, childMode, file], {
277
+ encoding: 'utf8',
278
+ maxBuffer: 64 * 1024 * 1024,
279
+ })
280
+ if (r.status !== 0) {
281
+ process.stderr.write(r.stderr || '')
282
+ throw new Error(`${childMode} 子进程失败 (status=${r.status})`)
283
+ }
284
+ const line = String(r.stdout).split('\n').find((l) => l.startsWith('PEAK_JSON '))
285
+ if (!line) throw new Error(`${childMode} 子进程没有输出 PEAK_JSON`)
286
+ return JSON.parse(line.slice('PEAK_JSON '.length))
287
+ }
288
+
289
+ function report(r) {
290
+ const diskMB = r.disk / 1048576
291
+ const peakHeap = Math.max(r.peak.heap, r.held.heapUsed)
292
+ const peakRss = Math.max(r.peak.rss, r.held.rss)
293
+ console.log(`\n=== ${r.kind}:磁盘 ${mb(r.disk)} MB ===`)
294
+ console.log(' 阶段 耗时 阶段后 heap 阶段后 RSS')
295
+ console.log(' ' + '-'.repeat(68))
296
+ for (const row of r.rows) {
297
+ console.log(
298
+ ` ${row.name.padEnd(32)} ${String(row.ms + ' ms').padStart(8)} ${String(mb(row.heap) + ' MB').padStart(13)} ${String(mb(row.rss) + ' MB').padStart(13)}`
299
+ )
300
+ }
301
+ console.log(' ' + '-'.repeat(68))
302
+ console.log(` 基线 heap ${mb(r.base.heapUsed)} MB / RSS ${mb(r.base.rss)} MB`)
303
+ console.log(
304
+ ` 峰值 heap ${mb(peakHeap)} MB → **放大 ${(peakHeap / r.disk).toFixed(2)}×**(相对磁盘 ${diskMB.toFixed(1)} MB)`
305
+ )
306
+ console.log(
307
+ ` 峰值 RSS ${mb(peakRss)} MB → **放大 ${(peakRss / r.disk).toFixed(2)}×**;操作后 gc 常驻 heap ${mb(r.after.heapUsed)} MB`
308
+ )
309
+ if (r.kind === 'pdf') {
310
+ console.log(` 抽出的正文 ${mb(r.textChars)} M 字符 → ${r.chunks} 个 chunk,条目文本合计 ${r.entryBytes} 字符`)
311
+ } else if (r.kind === 'code') {
312
+ const per = Math.round(r.disk / Math.max(1, r.symbols))
313
+ console.log(` 正文 ${mb(r.textChars)} M 字符 → 符号条目 ${r.symbols} 个(≈ 1 个 / ${per} 字节)`)
314
+ }
315
+ return { heap: peakHeap, rss: peakRss, disk: r.disk }
316
+ }
317
+
318
+ if (mode === 'code') {
319
+ await runCode(argv[1])
320
+ } else if (mode === 'pdf') {
321
+ await runPdf(argv[1])
322
+ } else {
323
+ const mbArg = Number((argv.find((a) => a.startsWith('--mb=')) || '').split('=')[1]) || 50
324
+ const dir = path.join(os.tmpdir(), 'dpm-file-peak')
325
+ mkdirSync(dir, { recursive: true })
326
+ const target = mbArg * 1024 * 1024
327
+ const cases = [
328
+ { kind: 'code', density: 'typical', label: `code/typical ${mbArg}MB`, file: path.join(dir, `code-${mbArg}mb-typical.js`) },
329
+ { kind: 'code', density: 'dense', label: `code/dense ${mbArg}MB`, file: path.join(dir, `code-${mbArg}mb-dense.js`) },
330
+ { kind: 'pdf', density: null, label: `pdf ${mbArg}MB`, file: path.join(dir, `pdf-${mbArg}mb.pdf`) },
331
+ ]
332
+
333
+ for (const c of cases) {
334
+ const ok = existsSync(c.file) && statSync(c.file).size >= target * (c.kind === 'pdf' ? 0.8 : 0.95)
335
+ if (ok) continue
336
+ console.log(`生成语料 ${c.label} → ${c.file} …`)
337
+ if (c.kind === 'code') genCode(c.file, target, c.density)
338
+ else genPdf(c.file, target)
339
+ }
340
+
341
+ const summary = []
342
+ for (const c of cases) {
343
+ const r = runChild(c.kind, c.file)
344
+ const m = report(r)
345
+ summary.push({ label: c.label, ...m, extra: r.kind === 'code' ? `符号 ${r.symbols} 个` : `正文 ${r.textChars} 字符` })
346
+ }
347
+
348
+ console.log('\n=== #5 汇总:峰值 / 磁盘 ===')
349
+ for (const s of summary) {
350
+ console.log(
351
+ ` ${s.label.padEnd(20)} 磁盘 ${String(mb(s.disk)).padStart(5)} MB | ` +
352
+ `heap 峰值 ${String(mb(s.heap)).padStart(6)} MB (${(s.heap / s.disk).toFixed(2)}×) | ` +
353
+ `RSS 峰值 ${String(mb(s.rss)).padStart(6)} MB (${(s.rss / s.disk).toFixed(2)}×) | ${s.extra}`
354
+ )
355
+ }
356
+ }
@@ -0,0 +1,131 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 工具 schema 预算实测 —— 每个工具往每次请求里塞多少字符 / 多少 token。
4
+ *
5
+ * 为什么要有它:工具定义是「每次请求都付」的固定开销。12 个工具轻松吃掉
6
+ * 一万多字符的常驻成本,小上下文模型直接受不了。这个脚本用真实的 defineTool
7
+ * 投影算出每个工具实际发出的 schema 大小,让「描述瘦身」这件事可测、可回归,
8
+ * 而不是靠感觉。
9
+ *
10
+ * 口径:字符数与 token 数分开报,**不要拿一个固定系数去乘混合文本**——
11
+ * 英文约 4 字符/token,CJK 约 1 字符/token。用 1.6 这种中英混合系数去比
12
+ * 「英文改中文」的新旧版本,会把字符数的下降误算成 token 的下降。
13
+ * token 列是同口径的粗估(CJK 字符 1 token、其余 4 字符 1 token),
14
+ * 用于比较两次改动,不是给模型账单用的精确值。
15
+ *
16
+ * 用法: node scripts/tool-schema-size.mjs [--json]
17
+ */
18
+ import { pathToFileURL } from 'node:url'
19
+ import path from 'node:path'
20
+
21
+ const HERE = path.dirname(new URL(import.meta.url).pathname)
22
+ const SRC = path.join(HERE, '..', 'src')
23
+
24
+ // 工厂函数只需要在构造期读少量配置;用 Proxy 兜住所有未定义字段,
25
+ // 这样脚本不会因为某个字段缺失而崩掉(构造期不应依赖运行时状态)。
26
+ const stub = (label) =>
27
+ new Proxy({}, {
28
+ get: (_t, k) => (k === Symbol.toPrimitive || k === 'toString' ? () => `[${label}]` : undefined),
29
+ has: () => true,
30
+ })
31
+
32
+ const config = stub('config')
33
+ const ctx = stub('ctx')
34
+ const host = { llm: stub('llm'), ctx }
35
+ const watchManager = stub('watchManager')
36
+
37
+ const { indexDocTool } = await import(pathToFileURL(path.join(SRC, 'tools/index-doc.js')))
38
+ const { indexRepoTool } = await import(pathToFileURL(path.join(SRC, 'tools/index-repo.js')))
39
+ const { queryMemoryTool } = await import(pathToFileURL(path.join(SRC, 'tools/query-memory.js')))
40
+ const { rememberTool } = await import(pathToFileURL(path.join(SRC, 'tools/remember.js')))
41
+ const { forgetTool } = await import(pathToFileURL(path.join(SRC, 'tools/forget.js')))
42
+ const { watchRepoTool } = await import(pathToFileURL(path.join(SRC, 'tools/watch-repo.js')))
43
+ const { statsTool } = await import(pathToFileURL(path.join(SRC, 'tools/stats.js')))
44
+ const { listTasksTool, selectTaskTool, archiveTaskTool, showTaskPanelTool } = await import(
45
+ pathToFileURL(path.join(SRC, 'tools/task-tools.js'))
46
+ )
47
+ const { lessonTool } = await import(pathToFileURL(path.join(SRC, 'tools/lesson-tools.js')))
48
+
49
+ const BUILDERS = [
50
+ ['list_tasks', () => listTasksTool(config)],
51
+ ['select_task', () => selectTaskTool(config, host)],
52
+ ['archive_task', () => archiveTaskTool(config, host)],
53
+ ['show_task_panel', () => showTaskPanelTool(config)],
54
+ ['index_doc', () => indexDocTool(ctx, config)],
55
+ ['index_repo', () => indexRepoTool(ctx, config)],
56
+ ['query_memory', () => queryMemoryTool(ctx, config)],
57
+ ['remember', () => rememberTool(config)],
58
+ ['forget', () => forgetTool(config)],
59
+ ['watch_repo', () => watchRepoTool(watchManager, config)],
60
+ ['memory_stats', () => statsTool(config)],
61
+ ['save_lesson', () => lessonTool(config)],
62
+ ]
63
+
64
+ // CJK 汉字 + 假名 + 全角/CJK 标点:都按 1 token/字符计。
65
+ const CJK = /[\u2E80-\u9FFF\uF900-\uFAFF\uFF00-\uFF60\u3000-\u303F]/u
66
+
67
+ // 模型实际收到的是 {name, description, parameters}, 与 registry 投影一致。
68
+ function measure(text) {
69
+ let cjk = 0
70
+ let other = 0
71
+ for (const ch of text) CJK.test(ch) ? cjk++ : other++
72
+ return { chars: cjk + other, tokens: Math.round(cjk + other / 4) }
73
+ }
74
+
75
+ function sizeOf(tool) {
76
+ const desc = measure(String(tool.description ?? ''))
77
+ const params = measure(JSON.stringify(tool.parameters ?? {}))
78
+ const name = measure(String(tool.name ?? ''))
79
+ return {
80
+ desc: desc.chars,
81
+ params: params.chars,
82
+ total: desc.chars + params.chars + name.chars,
83
+ tokens: desc.tokens + params.tokens + name.tokens,
84
+ }
85
+ }
86
+
87
+ const rows = []
88
+ const failures = []
89
+ for (const [name, build] of BUILDERS) {
90
+ try {
91
+ const tool = build()
92
+ if (!tool || tool.name !== name) throw new Error(`工厂返回的 name=${tool?.name}`)
93
+ rows.push({ name, ...sizeOf(tool) })
94
+ } catch (err) {
95
+ failures.push(`${name}: ${err.message}`)
96
+ }
97
+ }
98
+
99
+ rows.sort((a, b) => b.total - a.total)
100
+ const sum = (k) => rows.reduce((s, r) => s + r[k], 0)
101
+ const total = sum('total')
102
+ const totalDesc = sum('desc')
103
+ const totalParams = sum('params')
104
+ const totalTokens = sum('tokens')
105
+
106
+ if (process.argv.includes('--json')) {
107
+ console.log(JSON.stringify({ tools: rows, total, totalDesc, totalParams, totalTokens, failures }, null, 2))
108
+ } else {
109
+ console.log('工具 schema 预算(每次请求的固定开销)\n')
110
+ console.log(' 工具 工具描述 参数schema 合计 token')
111
+ console.log(' ' + '-'.repeat(62))
112
+ for (const r of rows) {
113
+ console.log(
114
+ ` ${r.name.padEnd(24)} ${String(r.desc).padStart(8)} ${String(r.params).padStart(10)} ${String(r.total).padStart(10)} ${String(r.tokens).padStart(11)}`
115
+ )
116
+ }
117
+ console.log(' ' + '-'.repeat(62))
118
+ console.log(
119
+ ` ${String(rows.length + ' 个工具').padEnd(24)} ${String(totalDesc).padStart(8)} ${String(totalParams).padStart(10)} ${String(total).padStart(10)} ${String(totalTokens).padStart(11)}`
120
+ )
121
+ console.log(
122
+ `\n 口径:字符 + 同口径粗估 token(CJK 1 token/字符,其余 4 字符/token)。` +
123
+ `\n 不要用固定「字符/token」系数跨语言对比 —— 英文改中文会掉字符数,但 token 未必掉。`
124
+ )
125
+ if (failures.length) {
126
+ console.log('\n [!] 有工具没能构造出来:')
127
+ for (const f of failures) console.log(' ', f)
128
+ }
129
+ }
130
+
131
+ process.exitCode = failures.length ? 1 : 0
package/src/audit.js CHANGED
@@ -19,7 +19,21 @@ const DEFAULT_MAX_BYTES = 256 * 1024
19
19
  // "本该零注入"的步)完全不落痕,于是日志回答不了"换个阈值/换个判据会怎样"。影子记录每步都写,
20
20
  // 带全部候选的特征与判据结果,用来 (a) 离线重放任一阈值、(b) 攒"特征 → 该不该注入"的训练样本。
21
21
  export const SHADOW_FILE = 'admission-shadow.jsonl'
22
- const DEFAULT_SHADOW_MAX_BYTES = 2 * 1024 * 1024
22
+ // 512KB 而不是 2MB:轮转只保留 `.1` 一代,所以单项目日志的硬上限是
23
+ // `2 × shadowMaxBytes + 2 × auditMaxBytes`,之前是 4.6MB(在小项目上比 store 本身还大,
24
+ // 实测本插件自己的 store 里 3.1M/4.2M 是日志)。512KB 下上限降到 ≈1.5MB,
25
+ // 而按每行 ~1.5KB 算仍有 ~680 步的历史窗口 —— 远超"离线重放最近的历史"所需。
26
+ const DEFAULT_SHADOW_MAX_BYTES = 512 * 1024
27
+
28
+ /**
29
+ * 一行影子记录最多保留多少个候选。
30
+ *
31
+ * 影子日志 **90.6% 的体积是 `candidates`**(实测 210 行 / 965KB,候选占 875KB),而真实 store
32
+ * 单步就能产生 40~60 条(中位 42)。候选按分数降序排列,`decision === 'cand'` 必然排在最前
33
+ * (相对阈值就是分数比),所以「**全部 cand + 按排名补足**」既保住离线重放最需要的那批,
34
+ * 又砍掉远处必然被 coverage/relative 拦掉的尾巴。截断量记在 `candidatesTotal`,不静默。
35
+ */
36
+ const SHADOW_MAX_CANDIDATES = 16
23
37
 
24
38
  /** 审计配置:默认开(观测是这个插件唯一的仪表盘),显式 `auditLog: false` 才关。 */
25
39
  export function cfgAudit(config) {
@@ -52,11 +66,34 @@ export function shadowFileFor(memoryDir) {
52
66
  * - **每步都写**(含零注入的静默步与对照组),所以"没注入"也留下了可复盘的事实;
53
67
  * - 带**全部候选**的判据特征(cov/matched/support/relative)与场景(query/ops/writes),
54
68
  * 所以能离线回答"阈值换成 0.40 会注入什么"、并攒出"特征 → 该不该注入"的样本。
55
- * @param {object} input { sessionId, root, step, query, ops, writes, reasons, candidates, silence }
69
+ * @param {object} input { sessionId, root, step, query, scoreQuery, ops, writes, reasons, dropped, candidates, silence }
56
70
  */
57
71
  export function shadowRecordFrom(input) {
58
72
  const reasons = Array.isArray(input.reasons) ? input.reasons : []
59
73
  const candidates = Array.isArray(input.candidates) ? input.candidates : []
74
+ const dropped = Array.isArray(input.dropped) ? input.dropped : []
75
+ // `support` / `terms` 是**查询级**量(语料里有几个词能表示这条查询),同一个 pre-step 内
76
+ // 逐条恒定(实测 139/139 步)。把它们从每条候选提到行级:单候选省 ~25 B,整行省 ~23%。
77
+ const first = candidates[0]
78
+ const slim = candidates.map((c) => ({
79
+ id: c.id,
80
+ rel: c.rel,
81
+ coverage: c.coverage,
82
+ matched: c.matched,
83
+ // `decision` 是门槛层结论,`outcome` 是预算层结论,两者正交(见 auto-inject.js)。
84
+ decision: c.decision,
85
+ outcome: c.outcome,
86
+ }))
87
+ // 候选**只有提示通道**(trigger 的结果在 `injected` / `dropped` 里),所以不再逐条记 channel。
88
+ const bounded = slim.length <= SHADOW_MAX_CANDIDATES ? slim : (() => {
89
+ const keep = new Set()
90
+ for (const c of slim) if (c.decision === 'cand') keep.add(c.id)
91
+ for (const c of slim) {
92
+ if (keep.size >= SHADOW_MAX_CANDIDATES) break
93
+ keep.add(c.id)
94
+ }
95
+ return slim.filter((c) => keep.has(c.id))
96
+ })()
60
97
  return {
61
98
  at: new Date().toISOString(),
62
99
  session: input.sessionId || null,
@@ -64,10 +101,22 @@ export function shadowRecordFrom(input) {
64
101
  step: typeof input.step === 'number' ? input.step : null,
65
102
  // 人类消息截断保存:没有它就判不了"这次注入该不该"——标签要能回放到当时的场景。
66
103
  query: typeof input.query === 'string' ? input.query.slice(0, 300) : '',
104
+ // **实际用于评分**的查询文本(intent + 写目标的拼合)。它和 `query` 不是一回事:
105
+ // 写目标驱动的那些步 `query` 是空的、候选却非空。少了这一栏,判据无法离线重放。
106
+ scoreQuery: typeof input.scoreQuery === 'string' ? input.scoreQuery.slice(0, 300) : '',
67
107
  ops: (Array.isArray(input.ops) ? input.ops : []).slice(0, 12),
68
108
  writes: (Array.isArray(input.writes) ? input.writes : []).slice(0, 12),
69
109
  injected: reasons.map((r) => ({ id: r.id, channel: r.channel, why: r.why })),
70
- candidates,
110
+ // 查询级支持度:语料能表示查询里多少个词(`terms` 是查询词数)—— 通道级沉默判据用的就是它。
111
+ support: typeof first?.support === 'number' ? first.support : null,
112
+ terms: typeof first?.terms === 'number' ? first.terms : null,
113
+ // candidates 的 `decision` 只说明"过没过门槛",进不进上下文看 `outcome`
114
+ // (injected / budget / quota / idle / gate / unscheduled)。两者正交。
115
+ candidates: bounded,
116
+ // 截断前的候选总数:不静默,读日志的人能一眼看出这一步被裁掉了多少。
117
+ candidatesTotal: candidates.length,
118
+ // 触发通道的丢弃不在 candidates 里(候选只收提示通道),单列;有界,避免长候选池撑爆一行。
119
+ dropped: dropped.slice(0, 40),
71
120
  silence: input.silence || null,
72
121
  }
73
122
  }