deep-read-summarize 0.3.14 → 0.3.16

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.
@@ -1,518 +0,0 @@
1
- // tests/index.test.js — node:test 风格测试(npm 规范)
2
- // 运行: node --test
3
- const { test } = require('node:test');
4
- const assert = require('node:assert');
5
- const fs = require('fs');
6
- const path = require('path');
7
-
8
- // ---------- 插件入口 ----------
9
- test('plugin loads with name deep-read-summarize', () => {
10
- const p = require('../index.js');
11
- const def = p.load();
12
- assert.strictEqual(def.name, 'deep-read-summarize');
13
- assert.strictEqual(def.workflow.meta.name, 'deep-read-summarize');
14
- });
15
-
16
- // ---------- 解析器 ----------
17
- const parsers = require('../parsers');
18
- test('registry exposes 4 built-in parsers', () => {
19
- const names = parsers.list().map(p => p.name).sort();
20
- assert.deepStrictEqual(names, ['book', 'paper', 'video', 'web']);
21
- });
22
-
23
- test('resolve falls back to web for unknown type', () => {
24
- assert.strictEqual(parsers.resolve('unknown').name, 'web');
25
- });
26
-
27
- test('every parser builds a non-empty prompt', () => {
28
- for (const type of ['book', 'paper', 'video', 'web']) {
29
- const prompt = parsers.resolve(type).buildPrompt('https://example.com/x', { tempDir: '/tmp', tempFile: '/tmp/in.txt', maxChunks: 4 });
30
- assert.ok(typeof prompt === 'string' && prompt.length > 50, type + ' prompt too short');
31
- }
32
- });
33
-
34
- // ---------- schemas ----------
35
- const schemas = require('../schemas');
36
- test('fetchResultSchema requires saved', () => {
37
- assert.ok(schemas.fetchResultSchema.required.includes('saved'));
38
- });
39
-
40
- // ---------- workflow ----------
41
- const wf = require('../workflow');
42
- test('workflow meta is valid', () => {
43
- assert.strictEqual(wf.meta.name, 'deep-read-summarize');
44
- assert.ok(wf.meta.phases.length >= 3);
45
- });
46
-
47
- test('workflow script parses as async body', () => {
48
- const fn = new Function('args','phase','agent','parallel','log', 'return (async () => { ' + wf.script + ' })()');
49
- assert.ok(typeof fn === 'function');
50
- });
51
-
52
- // ---------- 幂等缓存 ----------
53
- const cache = require('../lib/cache');
54
- const os = require('os');
55
- test('cache fingerprint is deterministic', () => {
56
- assert.strictEqual(
57
- cache.fingerprint('https://arxiv.org/abs/2307.09042'),
58
- cache.fingerprint('https://arxiv.org/abs/2307.09042')
59
- );
60
- });
61
-
62
- // ---------- 打包完整性 ----------
63
- test('cordis.patch.yml exists and uses insert block', () => {
64
- const patch = fs.readFileSync(path.join(__dirname, '..', 'cordis.patch.yml'), 'utf8');
65
- assert.ok(patch.includes('- insert:'));
66
- assert.ok(patch.includes('deep-read-summarize'));
67
- });
68
-
69
- test('skills bundle exists', () => {
70
- const skill = path.join(__dirname, '..', 'skills', 'deep-read-summarize', 'SKILL.md');
71
- assert.ok(fs.existsSync(skill), 'SKILL.md missing');
72
- const content = fs.readFileSync(skill, 'utf8');
73
- assert.ok(content.includes('name: deep-read-summarize'));
74
- });
75
-
76
- // ---------- fixture 版权 ----------
77
- test('fixture is self-authored public-domain', () => {
78
- const fx = fs.readFileSync(path.join(__dirname, 'fixtures', 'fable.txt'), 'utf8');
79
- assert.ok(fx.includes('released into the public domain'));
80
- });
81
-
82
-
83
- // ============================================================================
84
- // workflow 运行时回归(0.3.8)
85
- // 直接跑自包含脚本(mock 掉 agent / parallel / phase / log),覆盖本次修掉的
86
- // P0:分块计划失控、负数读取区间、frontmatter 注入、幂等早返回丢数据。
87
- // ============================================================================
88
- const plugin = require('../index.js');
89
- const wfScript = wf.script;
90
-
91
- function makeAgent(cfg) {
92
- cfg = cfg || {};
93
- return function (prompt, o) {
94
- const label = (o && o.label) || '';
95
- if (label === '获取+分块') {
96
- if (cfg.fetch !== undefined) return cfg.fetch;
97
- return {
98
- kind: cfg.kind || 'paper',
99
- saved: true,
100
- totalLines: cfg.totalLines === undefined ? 1000 : cfg.totalLines,
101
- metadata: cfg.metadata || { title: cfg.title || 'Sample' },
102
- chunkPlan: cfg.chunkPlan || [
103
- { id: 1, topic: 'T1', startLine: 1, endLine: 500 },
104
- { id: 2, topic: 'T2', startLine: 501, endLine: 1000 }
105
- ]
106
- };
107
- }
108
- if (label === '汇总成稿') return cfg.note === undefined ? '# note' : cfg.note;
109
- if (label === '质量校验') return { pass: cfg.pass !== false, issues: cfg.issues || [] };
110
- return 'chunk text';
111
- };
112
- }
113
-
114
- async function runScript(args, agentImpl, scriptText) {
115
- const calls = [];
116
- const fn = new Function('args', 'phase', 'agent', 'parallel', 'log',
117
- 'return (async () => { ' + (scriptText || wfScript) + ' })()');
118
- const result = await fn(
119
- args,
120
- function () {},
121
- function (p, o) { calls.push({ label: (o && o.label) || '', prompt: p }); return agentImpl(p, o); },
122
- function (fns) { return Promise.all(fns.map(function (f) { return f(); })); },
123
- function () {}
124
- );
125
- return { result: result, calls: calls };
126
- }
127
-
128
- function injectedFetchSchema(scriptText) {
129
- const m = (scriptText || wfScript).match(/const fetchSchema = (\{[\s\S]*?\});\n/);
130
- assert.ok(m, 'fetchSchema is not injected into the script');
131
- return JSON.parse(m[1]);
132
- }
133
-
134
- test('workflow: chunk plan is clamped to maxChunks', async () => {
135
- const plan = [];
136
- for (let i = 1; i <= 10; i++) plan.push({ id: i, topic: 'T' + i, startLine: (i - 1) * 100 + 1, endLine: i * 100 });
137
- const r = await runScript({ input: 'x', type: 'paper', options: { maxChunks: 4 } }, makeAgent({ chunkPlan: plan }));
138
- assert.strictEqual(r.result.chunksCount, 4, 'the plan must be clamped, not passed through');
139
- assert.strictEqual(r.calls.filter(function (c) { return c.label === '精读块'; }).length, 4,
140
- 'one sub-agent per chunk - 10 chunks means 10 sub-agents');
141
- });
142
-
143
- test('workflow: inverted and out-of-range chunks are dropped', async () => {
144
- const r = await runScript({ input: 'x', type: 'paper' }, makeAgent({
145
- totalLines: 500,
146
- chunkPlan: [
147
- { id: 1, topic: 'inverted', startLine: 900, endLine: 100 },
148
- { id: 2, topic: 'beyond-eof', startLine: 9000, endLine: 9500 },
149
- { id: 3, topic: 'ok', startLine: 1, endLine: 500 }
150
- ]
151
- }));
152
- assert.strictEqual(r.result.chunksCount, 1);
153
- const readPrompt = r.calls.find(function (c) { return c.label === '精读块'; }).prompt;
154
- assert.ok(!/limit=-/.test(readPrompt), 'read must never be handed a negative limit');
155
- assert.ok(/limit=500/.test(readPrompt), 'the valid chunk must survive intact');
156
- });
157
-
158
- test('workflow: an all-invalid chunk plan degrades instead of running', async () => {
159
- const r = await runScript({ input: 'x', type: 'paper' },
160
- makeAgent({ chunkPlan: [{ id: 1, topic: 'bad', startLine: 900, endLine: 100 }] }));
161
- assert.strictEqual(r.result.ok, false);
162
- assert.strictEqual(r.result.fatal, false);
163
- assert.strictEqual(r.result.stage, 'fetch');
164
- });
165
-
166
- test('workflow: frontmatter escapes quotes coming from the content title', async () => {
167
- const r = await runScript({ input: 'https://example.com/x', type: 'paper' },
168
- makeAgent({ title: 'The "Best" Method' }));
169
- const draft = r.calls.find(function (c) { return c.label === '汇总成稿'; }).prompt;
170
- assert.ok(!draft.includes('title: "《The "Best" Method》'), 'raw quotes must not reach the frontmatter');
171
- assert.ok(draft.includes('title: "《The \\"Best\\" Method》深度精读笔记"'), 'title must be escaped');
172
- assert.ok(/url: "https:\/\/example\.com\/x"/.test(draft), 'url must be a quoted scalar');
173
- });
174
-
175
- test('workflow: a title of nothing but illegal characters still yields a usable filename', async () => {
176
- const r = await runScript({ input: 'x', type: 'web' }, makeAgent({ kind: 'web', title: '///' }));
177
- assert.ok(!/\/\.md$/.test(r.result.filePath), 'must not write a hidden .md: ' + r.result.filePath);
178
- assert.ok(/未命名内容\.md$/.test(r.result.filePath), r.result.filePath);
179
- });
180
-
181
- test('workflow: unknown kind under type=auto falls back to a registered type', async () => {
182
- const r = await runScript({ input: 'x', type: 'auto' }, makeAgent({
183
- fetch: { saved: true, totalLines: 10, chunkPlan: [{ id: 1, topic: 't', startLine: 1, endLine: 10 }] }
184
- }));
185
- assert.notStrictEqual(r.result.kind, 'auto');
186
- assert.ok(Object.keys(wf.parsers.registry.parsers).indexOf(r.result.kind) !== -1, r.result.kind);
187
- });
188
-
189
- test('workflow: no idempotency early-return is left in the script', () => {
190
- assert.ok(!wfScript.includes('_processedKeys'), 'the unreachable cache-hit branch must be gone');
191
- assert.ok(!/cached: true/.test(wfScript), 'the empty-note early return must be gone');
192
- });
193
-
194
- test('workflow: transcribe=false actually changes the video prompt', () => {
195
- const vp = wf.parsers.resolve('video');
196
- const on = vp.buildPrompt('https://b23.tv/x', { tempDir: './.tmp' });
197
- const off = vp.buildPrompt('https://b23.tv/x', { tempDir: './.tmp', transcribe: false });
198
- assert.notStrictEqual(on, off, 'transcribe:false used to produce a byte-identical prompt');
199
- assert.ok(on.includes('transcribe.js'), 'the prompt must point at the cross-platform script');
200
- assert.ok(!on.includes('transcribe.ps1'), 'the Windows-only PowerShell script must be gone');
201
- assert.ok(!off.includes('--model '), 'transcribe=false must not ask for a transcription run');
202
- assert.ok(off.includes('转写已禁用'));
203
- });
204
-
205
- test('workflow: whisperModel and language reach the transcription command', () => {
206
- const vp = wf.parsers.resolve('video');
207
- assert.ok(vp.buildPrompt('u', { tempDir: './.tmp', whisperModel: 'medium', language: 'en' })
208
- .includes('--device cpu --model medium --language en'), 'documented ASR options must be honoured');
209
- assert.ok(vp.buildPrompt('u', { tempDir: './.tmp' }).includes('--device cpu --model small --language zh'),
210
- 'defaults stay small/zh');
211
- });
212
-
213
- test('workflow: the script forwards whisperModel and language to the parser', async () => {
214
- const r = await runScript({ input: 'https://b23.tv/x', type: 'video', options: { whisperModel: 'base', language: 'ja' } },
215
- makeAgent({ kind: 'video' }));
216
- const fetchPrompt = r.calls.find(function (c) { return c.label === '获取+分块'; }).prompt;
217
- assert.ok(fetchPrompt.includes('--model base --language ja'), 'options must survive the script -> parser boundary');
218
- });
219
-
220
- test('plugin: config is validated and folded into the skill args', () => {
221
- const content = plugin.buildSkillContent({ outputDir: 'D:/vault/notes', maxChunks: 8 });
222
- assert.ok(content.includes('D:/vault/notes'), 'config.outputDir must reach the args example');
223
- assert.ok(content.includes('"maxChunks": 8'));
224
- assert.strictEqual(plugin.normalizeOptions({ maxChunks: 'lots' }).maxChunks, 4, 'wrong type -> default, not crash');
225
- assert.strictEqual(plugin.normalizeOptions({ options: { minWords: 4000 } }).minWords, 4000, 'nested form too');
226
- const registered = [];
227
- plugin.apply({ skills: { register: function (s) { registered.push(s); return function () {}; } } }, { minWords: 4000 });
228
- assert.ok(registered[0].content.includes('"minWords": 4000'), 'apply() must pass config through');
229
- });
230
-
231
- test('workflow: the injected fetch schema comes from schemas/index.js', () => {
232
- const injected = injectedFetchSchema();
233
- assert.deepStrictEqual(injected.required, schemas.fetchResultSchema.required);
234
- assert.strictEqual(injected.additionalProperties, schemas.fetchResultSchema.additionalProperties);
235
- assert.deepStrictEqual(injected.properties.kind.enum, Object.keys(wf.parsers.registry.parsers));
236
- assert.strictEqual((wfScript.match(/const fetchSchema = \{/g) || []).length, 1,
237
- 'no hand-copied duplicate may survive in the script');
238
- });
239
-
240
- test('workflow: a custom parser type is inlined and accepted end to end', async () => {
241
- const reg = wf.parsers.registry;
242
- const had = Object.prototype.hasOwnProperty.call(reg.parsers, 'podcast');
243
- const original = reg.parsers.podcast;
244
- reg.parsers.podcast = {
245
- name: 'podcast',
246
- types: ['podcast'],
247
- buildPrompt: function (input) { return 'PODCAST PROMPT ' + input; }
248
- };
249
- try {
250
- const regenerated = wf.buildSelfContainedScript();
251
- assert.ok(regenerated.includes('"podcast": { buildPrompt:'), 'custom parser must be inlined');
252
- assert.ok(injectedFetchSchema(regenerated).properties.kind.enum.includes('podcast'),
253
- 'the kind enum must follow the parser registry');
254
- assert.ok(!regenerated.includes('auto|book|paper|video|web'),
255
- 'the type whitelist must not be hard-coded to the four built-ins');
256
-
257
- const r = await runScript({ input: 'https://x.test/feed', type: 'podcast' },
258
- makeAgent({ kind: 'podcast', totalLines: 20, chunkPlan: [{ id: 1, topic: 't', startLine: 1, endLine: 20 }] }),
259
- regenerated);
260
- assert.strictEqual(r.result.ok, true);
261
- assert.strictEqual(r.result.kind, 'podcast');
262
- } finally {
263
- if (had) reg.parsers.podcast = original; else delete reg.parsers.podcast;
264
- }
265
- });
266
-
267
- test('workflow: an unknown type is still rejected loudly', async () => {
268
- await assert.rejects(
269
- runScript({ input: 'x', type: 'nope' }, makeAgent({})),
270
- /\[FATAL\] args\.type 非法/
271
- );
272
- });
273
-
274
- test('cache: the utility is reachable through the package exports map', () => {
275
- const pkg = require('../package.json');
276
- assert.strictEqual(pkg.exports['./lib/cache'], './lib/cache.js');
277
- assert.ok(fs.existsSync(path.join(__dirname, '..', 'lib', 'cache.js')));
278
- });
279
-
280
- // ============================================================================
281
- // 跨平台转写引导脚本(0.3.9)
282
- // transcribe.js 只在宿主 shell 里跑(不进 workflow 沙箱),平台差异集中在四个纯函数;
283
- // 它们都接受注入的 platform/env/home,所以任意 OS 上都能跑全平台矩阵断言。
284
- // ============================================================================
285
- const transcribe = require('../scripts/transcribe.js');
286
-
287
- test('transcribe: cache root matches the documented per-platform locations', () => {
288
- // Windows 必须与 0.3.6-0.3.8 的 transcribe.ps1 完全一致:
289
- // 老用户已经下过 484MB 模型,路径一变就要重下。
290
- assert.strictEqual(
291
- transcribe.cacheRoot({ platform: 'win32', env: { LOCALAPPDATA: 'C:/AppData/Local' }, home: 'C:/acct' }),
292
- path.win32.join('C:/AppData/Local', 'deep-read-summarize'));
293
- assert.strictEqual(
294
- transcribe.cacheRoot({ platform: 'win32', env: {}, home: 'C:/acct' }),
295
- path.win32.join('C:/acct/AppData/Local', 'deep-read-summarize'),
296
- 'LOCALAPPDATA absent -> fall back to the standard Windows location');
297
- assert.strictEqual(transcribe.cacheRoot({ platform: 'darwin', env: {}, home: '/Users/me' }),
298
- '/Users/me/Library/Caches/deep-read-summarize');
299
- assert.strictEqual(transcribe.cacheRoot({ platform: 'linux', env: {}, home: '/home/me' }),
300
- '/home/me/.cache/deep-read-summarize');
301
- assert.strictEqual(transcribe.cacheRoot({ platform: 'linux', env: { XDG_CACHE_HOME: '/x' }, home: '/home/me' }),
302
- '/x/deep-read-summarize', 'XDG_CACHE_HOME wins on Linux');
303
- });
304
-
305
- test('transcribe: venv interpreter path is per-platform', () => {
306
- assert.strictEqual(transcribe.venvPython('/v', { platform: 'darwin' }), '/v/bin/python');
307
- assert.strictEqual(transcribe.venvPython('/v', { platform: 'linux' }), '/v/bin/python');
308
- assert.strictEqual(transcribe.venvPython('C:/v', { platform: 'win32' }),
309
- path.win32.join('C:/v', 'Scripts', 'python.exe'));
310
- });
311
-
312
- test('transcribe: the uv install hint follows the platform', () => {
313
- assert.ok(transcribe.uvInstallHint({ platform: 'darwin' }).includes('brew install uv'));
314
- assert.ok(transcribe.uvInstallHint({ platform: 'win32' }).includes('winget install astral-sh.uv'));
315
- assert.ok(transcribe.uvInstallHint({ platform: 'linux' }).includes('astral.sh/uv/install.sh'));
316
- });
317
-
318
- test('transcribe: uv discovery prefers PATH, then the usual install dirs', () => {
319
- const has = (list) => (p) => list.indexOf(p) >= 0;
320
- assert.strictEqual(
321
- transcribe.findUv({ platform: 'linux', env: { PATH: '/usr/bin:/bin' }, home: '/home/me',
322
- isFile: has(['/usr/bin/uv']) }), '/usr/bin/uv');
323
- assert.strictEqual(
324
- transcribe.findUv({ platform: 'darwin', env: { PATH: '/usr/bin' }, home: '/Users/me',
325
- isFile: has(['/opt/homebrew/bin/uv']) }), '/opt/homebrew/bin/uv',
326
- 'Homebrew on Apple silicon must be found even when it is not on PATH');
327
- assert.strictEqual(
328
- transcribe.findUv({ platform: 'darwin', env: { PATH: '/usr/bin' }, home: '/Users/me',
329
- isFile: has(['/Users/me/.local/bin/uv']) }), '/Users/me/.local/bin/uv');
330
- assert.strictEqual(
331
- transcribe.findUv({ platform: 'win32', env: { PATH: 'C:/bin' }, home: 'C:/acct',
332
- isFile: has([path.win32.join('C:/bin', 'uv.exe')]) }), path.win32.join('C:/bin', 'uv.exe'));
333
- assert.strictEqual(transcribe.findUv({ platform: 'darwin', env: { PATH: '/usr/bin' }, home: '/Users/me',
334
- isFile: () => false }), null, 'no uv -> null (the caller degrades with an install hint)');
335
- });
336
-
337
- test('transcribe: CLI parsing accepts long, = and short forms', () => {
338
- const a = transcribe.parseArgs(['--audio', 'a.m4a', '--out', 'o.txt', '--model', 'medium', '--language', 'en']);
339
- assert.deepStrictEqual([a.audio, a.out, a.model, a.language], ['a.m4a', 'o.txt', 'medium', 'en']);
340
- assert.strictEqual(a.device, 'cpu', 'CPU is the default: GPU needs a CUDA runtime we do not install');
341
-
342
- const b = transcribe.parseArgs(['--audio=a.m4a', '--out=o.txt', '--device=auto']);
343
- assert.deepStrictEqual([b.audio, b.out, b.device], ['a.m4a', 'o.txt', 'auto']);
344
-
345
- const c = transcribe.parseArgs(['-a', 'a.m4a', '-o', 'o.txt', '-l', 'ja']);
346
- assert.deepStrictEqual([c.audio, c.out, c.language], ['a.m4a', 'o.txt', 'ja']);
347
-
348
- assert.strictEqual(transcribe.parseArgs(['--self-check']).selfCheck, true);
349
- assert.deepStrictEqual(transcribe.parseArgs(['nonsense']).unknown, ['nonsense']);
350
- });
351
-
352
- test('transcribe: the runner never leaves a half-written transcript behind', () => {
353
- // 调用方按「输出文件非空且稳定」判断转写完成,所以必须先收集全部分段再落盘,
354
- // 否则中途失败会留下半截文本被当成成功。
355
- assert.ok(transcribe.PY_RUNNER.includes('segments, info = run(device)'),
356
- 'segments must be collected before the file is opened');
357
- assert.ok(/with open\(os\.environ\['DRS_OUT'\]/.test(transcribe.PY_RUNNER));
358
- assert.strictEqual(transcribe.PY_RUNNER.indexOf('with open'),
359
- transcribe.PY_RUNNER.lastIndexOf('with open'), 'exactly one write, after collection');
360
- });
361
-
362
- test('skill: the Windows-only transcription caveat is gone', () => {
363
- const content = fs.readFileSync(path.join(__dirname, '..', 'skills', 'deep-read-summarize', 'SKILL.md'), 'utf8');
364
- assert.ok(!content.includes('仅在 Windows 可用'), 'the macOS/Linux limitation must be lifted');
365
- assert.ok(content.includes('transcribe.js'), 'the skill must point at the cross-platform script');
366
- assert.ok(!content.includes('transcribe.ps1'), 'no stale reference to the PowerShell script');
367
- });
368
-
369
- test('video prompt: gives both Windows and POSIX ways to locate the script', () => {
370
- const on = wf.parsers.resolve('video').buildPrompt('u', { tempDir: './.tmp' });
371
- assert.ok(on.includes('Get-ChildItem') && on.includes('$HOME/.dsh'),
372
- 'the agent picks the locate command for its own OS');
373
- assert.ok(on.includes('brew install yt-dlp') && on.includes('winget install yt-dlp'),
374
- 'both package managers must be offered');
375
- assert.ok(!on.includes('--device cuda'), 'GPU is opt-in, never silently requested');
376
- });
377
-
378
- test('workflow: options.device reaches the transcription command', () => {
379
- const vp = wf.parsers.resolve('video');
380
- assert.ok(vp.buildPrompt('u', { tempDir: './.tmp' }).includes('--device cpu'),
381
- 'CPU is the default: GPU needs a CUDA runtime we deliberately do not install');
382
- assert.ok(vp.buildPrompt('u', { tempDir: './.tmp', device: 'auto' }).includes('--device auto'),
383
- 'options.device must be honoured, not documented-and-ignored');
384
- });
385
-
386
- test('workflow: the script forwards device to the parser', async () => {
387
- const r = await runScript({ input: 'https://b23.tv/x', type: 'video', options: { device: 'auto' } },
388
- makeAgent({ kind: 'video' }));
389
- const fetchPrompt = r.calls.find(function (c) { return c.label === '获取+分块'; }).prompt;
390
- assert.ok(fetchPrompt.includes('--device auto'), 'options must survive the script -> parser boundary');
391
- });
392
-
393
- test('video prompt: the transcription block is a single numbered step', () => {
394
- const on = wf.parsers.resolve('video').buildPrompt('u', { tempDir: './.tmp' });
395
- assert.ok(!/[0-9]+\.\s+①/.test(on),
396
- 'the ①-⑥ sub-steps must not be numbered as a top-level step of their own');
397
- assert.ok(/[0-9]+\. 转写执行/.test(on), 'the block still gets exactly one top-level number');
398
- });
399
-
400
- // ============================================================================
401
- // 0.3.10 回归:审计 0.3.9 时查出的三个问题
402
- // ============================================================================
403
- const { spawnSync } = require('node:child_process');
404
-
405
- test('transcribe: the uv mirror is configurable and falls back to a direct download', () => {
406
- // 旧的 ghproxy.com 已 301 到 ghfast.top 并丢掉路径(返回 HTML 而不是资产),
407
- // uv 拿到 HTML 会报 "Invalid gzip header" 且不会自己回退 —— 于是「慢但能装」变成「装不上」。
408
- assert.ok(transcribe.UV_PYTHON_INSTALL_MIRROR_DEFAULT.indexOf('ghproxy.com') === -1,
409
- 'ghproxy.com moved and drops the path; it must not come back as the default');
410
- assert.strictEqual(transcribe.resolveUvMirror({}), transcribe.UV_PYTHON_INSTALL_MIRROR_DEFAULT);
411
- assert.strictEqual(transcribe.resolveUvMirror({ DRS_UV_PYTHON_MIRROR: 'https://mirror.example/' }),
412
- 'https://mirror.example/', 'env override must win');
413
- assert.strictEqual(transcribe.resolveUvMirror({ DRS_UV_PYTHON_MIRROR: '' }), '',
414
- 'empty string = never use a mirror');
415
-
416
- const attempts = transcribe.venvEnvAttempts({ PATH: '/x' }, 'https://mirror.example/');
417
- assert.strictEqual(attempts.length, 2, 'mirror first, then a direct download');
418
- assert.strictEqual(attempts[0].env.UV_PYTHON_INSTALL_MIRROR, 'https://mirror.example/');
419
- assert.ok(!('UV_PYTHON_INSTALL_MIRROR' in attempts[1].env), 'the fallback must not carry the mirror');
420
- assert.strictEqual(attempts[1].env.PATH, '/x', 'the base env must survive');
421
-
422
- const directOnly = transcribe.venvEnvAttempts({}, '');
423
- assert.strictEqual(directOnly.length, 1, 'no mirror configured -> a single direct attempt');
424
- assert.strictEqual(directOnly[0].env.UV_PYTHON_INSTALL_MIRROR, undefined);
425
- });
426
-
427
- test('transcribe: a 0-byte transcript is a failure, not a success', () => {
428
- // 调用方按「输出文件非空且稳定」判断完成,提示词里还有一条「日志出现 DONE」;
429
- // 两者叠加会让纯静音视频的空逐字稿被当成转写成功,再拿去精读。
430
- assert.strictEqual(transcribe.judgeTranscript(57).ok, true);
431
- assert.strictEqual(transcribe.judgeTranscript(57).code, 0);
432
- const empty = transcribe.judgeTranscript(0);
433
- assert.strictEqual(empty.ok, false, 'a silent video must not look like a successful transcription');
434
- assert.notStrictEqual(empty.code, 0, 'a distinct non-zero exit code is what makes the caller degrade');
435
- assert.ok(/降级/.test(empty.message), 'the message must tell the caller to degrade');
436
- });
437
-
438
- test('transcribe: --audio pointing at a directory fails fast and leaves no output', () => {
439
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'drs-audio-'));
440
- const out = path.join(dir, 'out.txt');
441
- try {
442
- const r = spawnSync(process.execPath,
443
- [path.join(__dirname, '..', 'scripts', 'transcribe.js'), '--audio', dir, '--out', out],
444
- { encoding: 'utf8' });
445
- assert.notStrictEqual(r.status, 0, 'a directory must be rejected');
446
- assert.ok(/不是文件/.test(r.stderr), 'expected a clear message, got: ' + r.stderr);
447
- assert.ok(!fs.existsSync(out), 'no output file may be left behind');
448
- } finally { fs.rmSync(dir, { recursive: true, force: true }); }
449
- });
450
-
451
- test('docs: RELEASE.md lists the version we are about to ship', () => {
452
- const rel = fs.readFileSync(path.join(__dirname, '..', 'docs', 'RELEASE.md'), 'utf8');
453
- const ver = require('../package.json').version;
454
- assert.ok(rel.indexOf('v' + ver) >= 0,
455
- 'docs/RELEASE.md 的「当前版本速览」必须包含当前版本 v' + ver + '(每次发版都要更新,别再让它停在旧版本)');
456
- });
457
-
458
- // ============================================================================
459
- // 0.3.14 回归:路径拼接、本地日期、config 白名单
460
- // ============================================================================
461
-
462
- test('workflow: trailing separators in outputDir normalize to a single separator', async () => {
463
- const BS = String.fromCharCode(92);
464
- const cases = [
465
- { dir: 'out/', expect: 'out/Sample.md' },
466
- { dir: 'out//', expect: 'out/Sample.md' },
467
- { dir: 'out' + BS, expect: 'out/Sample.md' },
468
- { dir: 'out' + BS + BS, expect: 'out/Sample.md' },
469
- { dir: './output/', expect: './output/Sample.md' }
470
- ];
471
- for (const c of cases) {
472
- const r = await runScript({ input: 'x', type: 'paper', options: { outputDir: c.dir } }, makeAgent({}));
473
- assert.strictEqual(r.result.filePath, c.expect,
474
- 'outputDir ' + JSON.stringify(c.dir) + ' must normalize to ' + c.expect + ', got ' + r.result.filePath);
475
- }
476
- });
477
-
478
- test('workflow: trailing separators in tempDir normalize into tempFile', async () => {
479
- const BS = String.fromCharCode(92);
480
- const cases = ['./.tmp/', './.tmp//', './.tmp' + BS, './.tmp' + BS + BS];
481
- for (const dir of cases) {
482
- const r = await runScript({ input: 'x', type: 'paper', options: { tempDir: dir } }, makeAgent({}));
483
- const fetchCall = r.calls.find(function (c) { return c.label === '获取+分块'; });
484
- assert.ok(fetchCall, 'the fetch phase must run');
485
- assert.ok(fetchCall.prompt.indexOf('./.tmp/input.txt') >= 0,
486
- 'tempDir ' + JSON.stringify(dir) + ' must normalize to ./.tmp/input.txt');
487
- }
488
- });
489
-
490
- test('workflow: created comes from the local date, not the UTC slice', async () => {
491
- assert.ok(!/toISOString\(\)\s*\.\s*slice\(0,\s*10\)/.test(wf.script),
492
- 'the note date must not be sliced out of the UTC ISO string');
493
- const r = await runScript({ input: 'x', type: 'paper', options: {} }, makeAgent({}));
494
- const draft = r.calls.find(function (c) { return c.label === '汇总成稿'; }).prompt;
495
- const m = draft.match(/created: (\d{4}-\d{2}-\d{2})/);
496
- assert.ok(m, 'created: <date> must appear in the draft prompt');
497
- const d = new Date();
498
- const pad = function (n) { return ('0' + n).slice(-2); };
499
- const local = d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate());
500
- assert.strictEqual(m[1], local, 'created must be the local date (UTC+8 evenings differ from UTC)');
501
- });
502
-
503
- test('plugin config: transcription keys are configurable and unknown keys warn', () => {
504
- const opts = plugin.normalizeOptions({ whisperModel: 'medium', language: 'en', device: 'cpu', maxRetries: 2 });
505
- assert.strictEqual(opts.whisperModel, 'medium', 'whisperModel must be settable per profile');
506
- assert.strictEqual(opts.language, 'en', 'language must be settable per profile');
507
- assert.strictEqual(opts.device, 'cpu');
508
- assert.strictEqual(opts.maxRetries, 2, 'maxRetries must be settable per profile');
509
-
510
- const seen = [];
511
- const origWarn = console.warn;
512
- console.warn = function (msg) { seen.push(String(msg)); };
513
- try { plugin.normalizeOptions({ notAKey: 1 }); } finally { console.warn = origWarn; }
514
- assert.ok(seen.some(function (m) { return m.indexOf('notAKey') >= 0; }),
515
- 'an unknown config key must be reported, not silently dropped');
516
- assert.ok(seen.some(function (m) { return m.indexOf('whisperModel') >= 0; }),
517
- 'the warning should list the keys that are actually accepted');
518
- });
@@ -1,52 +0,0 @@
1
- // tests/quick_validate.js — fast sanity check before release/tag
2
- // 注意:不用 child_process(沙箱环境禁止 spawn),纯 fs 检查
3
- const fs = require('fs');
4
-
5
- console.log('== deep-read-summarize quick validation ==');
6
- let failed = false;
7
-
8
- // 1. All JS files exist
9
- const files = [
10
- 'workflow.js', 'parsers/index.js', 'parsers/book.js', 'parsers/paper.js',
11
- 'parsers/video.js', 'parsers/web.js', 'schemas/index.js'
12
- ];
13
- for (const f of files) {
14
- if (!fs.existsSync(f)) { console.error('MISSING:', f); failed = true; }
15
- }
16
- if (!failed) console.log(' OK: all ' + files.length + ' JS files present');
17
-
18
- // 2. README has compatibility + copyright sections (bilingual)
19
- const readme = fs.readFileSync('README.md', 'utf8');
20
- const hasCompat = readme.includes('兼容性') || readme.includes('Compatibility');
21
- const hasCopyright = readme.includes('版权') || readme.includes('copyright');
22
- if (!hasCompat || !hasCopyright) {
23
- console.error('README must mention compatibility and copyright policy');
24
- failed = true;
25
- }
26
- if (!failed) console.log(' OK: README has compatibility + copyright sections');
27
-
28
- // 3. LICENSE is MIT
29
- const lic = fs.readFileSync('LICENSE', 'utf8');
30
- if (!lic.includes('MIT License')) { console.error('LICENSE must be MIT'); failed = true; }
31
- if (!failed) console.log(' OK: LICENSE is MIT');
32
-
33
- // 4. No secrets in source
34
- let secretFound = false;
35
- const all = files.map(f => fs.readFileSync(f, 'utf8')).join('\n');
36
- const secretPatterns = [
37
- /ghp_[A-Za-z0-9]{20,}/, /gho_[A-Za-z0-9]{20,}/, /sk-[A-Za-z0-9]{20,}/,
38
- /AKIA[0-9A-Z]{16}/, /AIza[0-9A-Za-z_-]{30,}/, /-----BEGIN .*PRIVATE KEY-----/
39
- ];
40
- for (const pat of secretPatterns) {
41
- if (pat.test(all)) { console.error('SECRET PATTERN DETECTED'); secretFound = true; failed = true; }
42
- }
43
- if (!secretFound) console.log(' OK: no secrets in source');
44
-
45
- // 5. SECURITY.md and templates exist
46
- const required = ['SECURITY.md', '.github/ISSUE_TEMPLATE/bug_report.md', '.github/ISSUE_TEMPLATE/feature_request.md', '.github/PULL_REQUEST_TEMPLATE.md', 'docs/RELEASE.md'];
47
- let missing = required.filter(f => !fs.existsSync(f));
48
- if (missing.length) { console.error('MISSING:', missing.join(', ')); failed = true; }
49
- if (!failed) console.log(' OK: SECURITY.md + issue/PR templates present');
50
-
51
- if (failed) { console.error('== validation FAILED =='); process.exit(1); }
52
- console.log('== validation OK — ready to tag ==');