@yolk_vat-y/dsh-project-memory 0.5.14 → 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/CHANGELOG.md +115 -0
- package/README.md +77 -108
- package/README.zh-CN.md +71 -100
- package/package.json +3 -1
- package/scripts/file-peak.mjs +356 -0
- package/scripts/tool-schema-size.mjs +131 -0
- package/src/doc-pipeline.js +3 -6
- package/src/enhancer.js +105 -41
- package/src/index.js +4 -1
- package/src/ops.js +11 -13
- package/src/parsers/pdfjs-parser.js +0 -30
- package/src/readiness.js +5 -12
- package/src/store.js +48 -7
- package/src/symbols.js +2 -1
- package/src/tools/forget.js +1 -1
- package/src/tools/index-doc.js +1 -1
- package/src/tools/index-repo.js +19 -5
- package/src/tools/lesson-tools.js +19 -16
- package/src/tools/query-memory.js +1 -1
- package/src/tools/remember.js +1 -1
- package/src/tools/stats.js +1 -1
- package/src/tools/task-tools.js +6 -5
- package/src/tools/watch-repo.js +1 -1
- package/src/util/entry-id.js +32 -0
- package/src/util/fs.js +18 -2
- package/src/util/path-token.js +40 -0
- package/src/watch.js +15 -3
|
@@ -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/doc-pipeline.js
CHANGED
|
@@ -6,8 +6,9 @@ import { summarizeText } from './util/text.js'
|
|
|
6
6
|
import { parsePdf } from './parsers/pdfjs-parser.js'
|
|
7
7
|
import { chunkText } from './chunker.js'
|
|
8
8
|
import { extractKeywords, extractTermText } from './doc-index.js'
|
|
9
|
+
import { entryIdPrefix } from './util/entry-id.js'
|
|
9
10
|
|
|
10
|
-
export async function extractTextFromFile(filePath, { maxFileSizeMb =
|
|
11
|
+
export async function extractTextFromFile(filePath, { maxFileSizeMb = 10, maxPdfPages = 1000 } = {}) {
|
|
11
12
|
const ext = path.extname(filePath).toLowerCase()
|
|
12
13
|
if (ext === '.pdf') {
|
|
13
14
|
if (maxFileSizeMb) {
|
|
@@ -40,7 +41,7 @@ export async function buildDocEntries(relPath, filePath, opts = {}) {
|
|
|
40
41
|
|
|
41
42
|
const chunks = chunkText(text, opts.chunkChars, opts.maxChunks)
|
|
42
43
|
return chunks.map((chunk, i) => ({
|
|
43
|
-
id: `${
|
|
44
|
+
id: `${entryIdPrefix(relPath)}#${i}`,
|
|
44
45
|
sourcePath: relPath,
|
|
45
46
|
sourceLine: chunk.line,
|
|
46
47
|
type: 'doc',
|
|
@@ -52,7 +53,3 @@ export async function buildDocEntries(relPath, filePath, opts = {}) {
|
|
|
52
53
|
hash,
|
|
53
54
|
}))
|
|
54
55
|
}
|
|
55
|
-
|
|
56
|
-
function relativeId(filePath) {
|
|
57
|
-
return String(filePath).replace(/[\\/:\s]/g, '_')
|
|
58
|
-
}
|