deep-read-summarize 0.3.7 → 0.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -77,4 +77,322 @@ test('skills bundle exists', () => {
77
77
  test('fixture is self-authored public-domain', () => {
78
78
  const fx = fs.readFileSync(path.join(__dirname, 'fixtures', 'fable.txt'), 'utf8');
79
79
  assert.ok(fx.includes('released into the public domain'));
80
- });
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
+ });
@@ -229,11 +229,15 @@ test('workflow: the script never reaches for APIs the sandbox does not provide',
229
229
  }
230
230
  });
231
231
 
232
- test('workflow: the script self-contains all four parsers', () => {
233
- for (const name of ['book', 'paper', 'video', 'web']) {
234
- assert.ok(wfScript.includes(name + ': { buildPrompt:'), 'parser "' + name + '" is not inlined');
232
+ test('workflow: the script self-contains every registered parser', () => {
233
+ // 内联的是注册表里的全部解析器(含 custom-parsers/ 的覆盖与自定义类型),
234
+ // 不是写死的四个 —— 断言跟着注册表走,注册表加了东西这里自动跟着收紧。
235
+ for (const name of Object.keys(workflow.parsers.registry.parsers)) {
236
+ assert.ok(wfScript.includes(JSON.stringify(name) + ': { buildPrompt:'),
237
+ 'parser "' + name + '" is not inlined');
235
238
  }
236
239
  assert.ok(wfScript.includes('const parsers = args._parsers || __parsers;'), 'the args._parsers fallback is missing');
240
+ assert.ok(wfScript.includes('const fetchSchema = {'), 'the fetch schema must be injected, not hand-copied');
237
241
  });
238
242
 
239
243
  // ---------- Test: skill content(复用本文件顶部已有的 plugin 引用)----------
package/workflow.js CHANGED
@@ -1,77 +1,90 @@
1
- // ============================================================================
2
- // deep-read-summarize — Deep reading & summarization workflow for DSH
3
- // Version: 3.0.0
4
- // ============================================================================
5
- // 【用法】meta → workflow meta;script → workflow script;
6
- // args: { "input": "<url|path>", "type": "auto", "options": { "minWords": 2500, "fastMode": false, "maxChunks": 4, "transcribe": true, "requireCitations": true, "includeTimestamps": false, "cache": true, "outputDir": "./output", "tempDir": "./.tmp" } }
7
- // ============================================================================
8
-
9
- const meta = {
10
- "name": "deep-read-summarize",
11
- "description": "Deep reading & summarization of books/papers/videos/web (v3.0)",
12
- "whenToUse": "User provides a book, paper, video link or web page and wants a deep-read summary saved to Obsidian",
13
- "phases": [
14
- {
15
- "title": "解析器选择",
16
- "detail": "按类型选择解析器插件"
17
- },
18
- {
19
- "title": "获取与分块",
20
- "detail": "Parser fetches content, writes temp file, builds chunk plan"
21
- },
22
- {
23
- "title": "并行精读",
24
- "detail": "N subagents deep-read chunks in parallel (Map)"
25
- },
26
- {
27
- "title": "汇总成稿",
28
- "detail": "Merge into final note (Reduce) with embedded self-check"
29
- },
30
- {
31
- "title": "质量校验",
32
- "detail": "Optional QC loop with retries"
33
- }
34
- ]
35
- };
36
-
37
- // ===== script(复制到 workflow 工具的 script 参数)=====
38
- const RAW_SCRIPT = "// ========== deep-read-summarize v3.0 ==========\n// 3 波次:解析器获取分块 → 并行精读 → 成稿+质量校验\n// 特性:解析器插件化 / 失败纪律(fatal vs 降级) / 幂等 / 成本控制\n\n// ---------- 0. 配置校验(fatal 级错误:必须终止) ----------\nconst input = (args && args.input || \"\").trim();\nif (!input) throw new Error(\"[FATAL] args.input 缺失:请输入内容链接或文件路径\");\nconst forcedType = ((args && args.type) || \"auto\").toLowerCase();\nif ([\"auto\",\"book\",\"paper\",\"video\",\"web\"].indexOf(forcedType) === -1)\n throw new Error(\"[FATAL] args.type 非法:必须为 auto|book|paper|video|web\");\nconst options = (args && args.options) || {};\nconst minWords = options.minWords || 2500;\nconst fastMode = !!options.fastMode;\nconst maxChunks = Math.max(1, Math.min(options.maxChunks || 4, 12));\nconst requireCitations = options.requireCitations !== false;\nconst includeTimestamps = !!options.includeTimestamps;\nconst maxRetries = options.maxRetries || 0;\nconst cacheEnabled = options.cache !== false;\nconst outputDir = options.outputDir || \"./output\";\nconst tempDir = options.tempDir || \"./.tmp\";\nconst tempFile = tempDir.replace(/[\\/]+$/, \"\") + \"/input.txt\";\n\n// ---------- 0.5 幂等检查:输入指纹缓存 ----------\nlet cacheHit = false;\nif (cacheEnabled && Array.isArray(args._processedKeys)) {\n const fpKey = input.trim().slice(0, 300);\n cacheHit = args._processedKeys.indexOf(fpKey) !== -1;\n if (cacheHit) log(\"幂等命中:该输入已处理过,跳过\");\n}\nif (cacheHit) {\n return { ok: true, cached: true, kind: forcedType, title: (args && args.title) || \"cached\", filePath: \"\", chunksCount: 0, fastMode: fastMode, qualityPassed: true, qualityIssues: [], failedChunks: 0, note: \"\" };\n}\n\n// ---------- 1. 解析器选择(由 args._parsers 注入) ----------\nphase(\"解析器选择\");\nconst parsers = args._parsers || {};\nconst kindNames = { book: \"书籍\", paper: \"学术论文\", video: \"视频\", web: \"网页/文章\" };\nconst kindFocus = {\n book: \"按章节主题展开核心论点、论证、关键例子、章节间关系,收集关键概念与可引用原文(含页码/章节)\",\n paper: \"四维精读:1)研究问题与方法 2)结论与贡献 3)局限与批判 4)与同类工作比较;收集术语与可引用原文(含章节/段落)\",\n video: \"按主题脉络组织,提取核心论点、证据、例子、可操作建议,收集关键概念与主讲人原话\" + (includeTimestamps ? \"(含时间戳定位)\" : \"(不标时间戳)\"),\n web: \"提取核心论点、结构拆解、关键概念、可引用原文\"\n};\n\n// ---------- 2. 波次1:解析器获取 + 分块 ----------\nphase(\"获取与分块\");\nconst fetchPrompt = (parsers[forcedType !== \"auto\" ? forcedType : \"web\"] || parsers.web || { buildPrompt: function() { return [\"未知解析器\"]; } })\n .buildPrompt(input, { tempDir: tempDir, tempFile: tempFile, maxChunks: maxChunks, transcribe: options.transcribe !== false });\nconst fetchSchema = {\n type: \"object\",\n properties: {\n kind: { type: \"string\" }, saved: { type: \"boolean\" }, message: { type: \"string\" }, totalLines: { type: \"number\" },\n metadata: { type: \"object\", properties: { title: { type: \"string\" }, author: { type: \"string\" }, year: { type: \"string\" }, language: { type: \"string\" } }, required: [], additionalProperties: true },\n chunkPlan: {\n type: \"array\",\n items: { type: \"object\", properties: { id: { type: \"number\" }, topic: { type: \"string\" }, startLine: { type: \"number\" }, endLine: { type: \"number\" } }, required: [\"id\",\"topic\",\"startLine\",\"endLine\"], additionalProperties: false }\n }\n },\n required: [\"saved\"], additionalProperties: false\n};\n\nconst fetched = await agent(fetchPrompt, { schema: fetchSchema, label: \"获取+分块\", phase: \"获取与分块\" });\n\n// 失败纪律:内容获取失败 = 可降级错误(返回失败结果,不抛 fatal)\nif (!fetched || !fetched.saved) {\n return { ok: false, stage: \"fetch\", fatal: false, message: (fetched && fetched.message) || \"获取失败(可降级:检查输入或手动提供文本)\" };\n}\nlet kind = (fetched.kind && forcedType === \"auto\") ? fetched.kind : forcedType;\nconst chunkPlan = (fetched && fetched.chunkPlan) || [];\nif (chunkPlan.length === 0) return { ok: false, stage: \"fetch\", fatal: false, message: \"分块计划为空\" };\nconst metadata = (fetched && fetched.metadata) || {};\nconst textSource = (metadata && metadata.textSource) || \"unknown\";\nconst srcLabels = { desc: \"视频简介/desc\", subtitle: \"平台字幕\", transcription: \"完整语音转写\", manual: \"用户提供转写文本\" };\nconst srcLabel = srcLabels[textSource] || textSource;\nlog(\"[source] \" + textSource + \" -> \" + srcLabel);\nlog(\"类型:\" + kind + \" 行数:\" + fetched.totalLines + \" 块数:\" + chunkPlan.length);\n\n// ---------- 3. 波次2:并行精读(Map) ----------\nphase(\"并行精读\");\nconst chunkPrompts = chunkPlan.map(function (c) {\n return [\n \"请深度精读以下内容块,输出结构化精读笔记。\",\n \"内容类型:\" + (kindNames[kind] || kind) + \" | 本块主题:\" + c.topic,\n \"精读侧重:\" + (kindFocus[kind] || kindFocus.web),\n \"用 read 工具读取 \" + tempFile + \" 第 \" + c.startLine + \" 到 \" + c.endLine + \" 行(offset=\" + c.startLine + \", limit=\" + (c.endLine - c.startLine + 1) + \"),然后输出:\",\n \"## 本块主题:\" + c.topic,\n \"### 要点(详细展开,保留数据/例子/论证)\",\n \"### 关键概念(术语+解释)\",\n \"### 关键引用(最多2句原文+位置)\" + (requireCitations ? \",必须标注页码/章节/段落位置\" : \"\"),\n \"### 批判观察(如有)\"\n ].join(\"\\n\");\n});\n\nconst reads = [];\nconst readBatch = 3;\nfor (let bi = 0; bi < chunkPrompts.length; bi += readBatch) {\n const batch = chunkPrompts.slice(bi, bi + readBatch);\n const batchReads = await parallel(batch.map(function (p) {\n return function () { return agent(p, { label: \"精读块\", phase: \"并行精读\" }); };\n }));\n for (let k = 0; k < batchReads.length; k++) reads.push(batchReads[k]);\n}\nconst validReads = reads.filter(function (r) { return r && r.trim && r.trim().length > 0; });\n\n// 失败纪律:某块精读失败 = 可降级(跳过该块,标记缺口继续)\nconst failedChunks = chunkPlan.length - validReads.length;\nif (validReads.length === 0) return { ok: false, stage: \"read\", fatal: false, message: \"所有分块精读均失败\" };\nif (failedChunks > 0) log(\"警告:\" + failedChunks + \" 块精读失败,标记缺口继续成稿\");\nlog(\"精读完成:\" + validReads.length + \"/\" + chunkPlan.length);\n\n// ---------- 4. 波次3:成稿 + 内嵌质量自检(Reduce) ----------\nphase(\"汇总成稿\");\nconst today = new Date().toISOString().slice(0, 10);\nconst finalTitle = metadata.title || \"未命名内容\";\nconst safeTitle = finalTitle.replace(/[\\\\/:*?\"<>|]/g, \" \").trim();\nconst mdPath = outputDir.replace(/\\\\$/, \"\") + \"/\" + safeTitle + \".md\";\n\nconst extraSections = fastMode ? [] : [\n \"\", \"## 5. 批判性分析(论证强处/弱处/可质疑之处)\", \"\",\n \"## 6. 个人思考与应用(与已有知识联系、如何应用、行动要点)\", \"\",\n \"## 7. 延伸阅读(相关主题/作者其他作品/参考文献)\", \"\"\n];\n\nconst draftPrompt = [\n \"将以下多块精读结果整合为完整 Obsidian 精读笔记,只输出 Markdown(含 YAML frontmatter)。\",\n \"模板:\", \"---\",\n 'title: \"《' + finalTitle + '》深度精读笔记\"',\n \"aliases: [\" + JSON.stringify(finalTitle) + \"]\",\n \"author: \" + (metadata.author || \"\"),\n \"year: \" + (metadata.year || \"\"),\n \"type: \" + kind,\n \"url: \" + (metadata.url || input),\n \"tags: [精读, \" + (kindNames[kind] || kind) + \"]\",\n \"created: \" + today,\n \"status: 已完成\",\n \"---\",\n \"# 《\" + finalTitle + \"》深度精读笔记\", \"\",\n \"> 一句话核心概括。\", \"\",\n \"## 1. 概述(约500字:主题/背景/核心问题/总体结论)\", \"\",\n \"## 2. 结构拆解(按主题组织,含详细要点;关键结论标注原文出处)\", \"\",\n \"## 3. 关键概念与术语表(表格)\", \"\",\n \"## 4. 关键引用(仅关键结论\" + (requireCitations ? \",必须标注页码/章节/段落\" : \"\") + \")\",\n].concat(extraSections, [\n \"---\",\n \"*笔记整理于 \" + today + \"*\", \"\",\n \"硬性要求:总篇幅≥\" + minWords + \"字;语言与原文一致;术语统一;引用必须真实;视频\" + (includeTimestamps ? \"标注时间戳\" : \"不标注时间戳\") + \"。\",\n \"输出前自检:1)覆盖所有块 2)frontmatter完整 3)各小节齐全 4)引用真实 5)篇幅达标 6)语言一致。\",\n \"\",\n \"各块精读结果:\",\n validReads.map(function (r, i) { return \"\\\\n===== 块 \" + (i + 1) + \" =====\\\\n\" + r; }).join(\"\\\\n\")\n]).join(\"\\n\");\n\nlet draft = await agent(draftPrompt, { label: \"汇总成稿\", phase: \"汇总成稿\" });\nif (!draft || !draft.trim) return { ok: false, stage: \"draft\", fatal: false, message: \"成稿失败\" };\n\n// ---------- 5. 质量校验(轻量重试) ----------\nphase(\"质量校验\");\nlet verified = draft;\nlet passed = false;\nlet issues = [];\nfor (let round = 0; round <= maxRetries; round++) {\n const checkPrompt = [\n \"请对总结笔记做质量校验,逐项检查并输出 JSON:\",\n \"1.coverage 2.citationsReal 3.terminologyConsistent 4.formatComplete 5.lengthMet(≥\" + minWords + \"字) 6.languageConsistent\",\n \"输出:{ \\\"pass\\\": true/false, \\\"issues\\\": [\\\"问题\\\"] },只输出 JSON。\",\n \"笔记:\", verified\n ].join(\"\\n\");\n const checkSchema = { type: \"object\", properties: { pass: { type: \"boolean\" }, issues: { type: \"array\", items: { type: \"string\" } } }, required: [\"pass\",\"issues\"], additionalProperties: false };\n const check = await agent(checkPrompt, { schema: checkSchema, label: \"质量校验\", phase: \"质量校验\" });\n passed = !!(check && check.pass);\n issues = (check && check.issues) || [];\n log(\"校验:\" + (passed ? \"通过\" : \"发现问题 \" + issues.length + \" 条\"));\n if (passed) break;\n if (round < maxRetries) {\n const fixPrompt = [\n \"修正以下笔记以解决校验问题,输出完整修正版:\",\n issues.map(function (s) { return \"- \" + s; }).join(\"\\n\"),\n \"当前笔记:\", verified\n ].join(\"\\n\");\n verified = await agent(fixPrompt, { label: \"修正笔记\", phase: \"质量校验\" });\n }\n}\n\n// ---------- 结果 ----------\nreturn {\n ok: true, kind: kind, title: finalTitle,\n filePath: mdPath, chunksCount: chunkPlan.length, fastMode: fastMode,\n qualityPassed: passed, qualityIssues: issues,\n failedChunks: failedChunks,\n textSource: textSource,\n note: verified\n};";
39
-
40
- // ===== parsers 注册表(运行时注入,实现插件化)=====
41
- const parsers = require("./parsers");
42
- const promptImpl = require("./parsers/_prompt");
43
- const parserRegistry = parsers.registry;
44
-
45
- /**
46
- * 把四个内置解析器(buildPrompt)连同其依赖的 buildFetchPrompt 内联进
47
- * workflow script,使其自包含 —— DSH rc7 的 workflow 工具只把 args(JSON)
48
- * 暴露给脚本,不会注入 args._parsers;脚本必须在自身内部解析器可用。
49
- * 若宿主未来注入 args._parsers,优先使用宿主注入值(向后兼容)。
50
- */
51
- function buildSelfContainedScript() {
52
- const parserSource = (name) =>
53
- parserRegistry.parsers[name].buildPrompt
54
- .toString()
55
- // buildPrompt 闭包引用模块级 prompt(parsers/_prompt),内联后改指 __prompt
56
- .replace(/\bprompt\.buildFetchPrompt\b/g, "__prompt.buildFetchPrompt");
57
-
58
- const impl = [
59
- "const __prompt = { buildFetchPrompt: " + promptImpl.buildFetchPrompt.toString() + " };",
60
- "const __parsers = {",
61
- " book: { buildPrompt: " + parserSource("book") + " },",
62
- " paper: { buildPrompt: " + parserSource("paper") + " },",
63
- " video: { buildPrompt: " + parserSource("video") + " },",
64
- " web: { buildPrompt: " + parserSource("web") + " }",
65
- "};"
66
- ].join("\n");
67
-
68
- const marker = "const parsers = args._parsers || {};";
69
- if (!RAW_SCRIPT.includes(marker)) {
70
- throw new Error("workflow script marker not found: " + marker);
71
- }
72
- return RAW_SCRIPT.replace(marker, impl + "\nconst parsers = args._parsers || __parsers;");
73
- }
74
-
75
- const script = buildSelfContainedScript();
76
-
1
+ // ============================================================================
2
+ // deep-read-summarize — Deep reading & summarization workflow for DSH
3
+ // Version: 3.0.0
4
+ // ============================================================================
5
+ // 【用法】meta → workflow meta;script → workflow script;
6
+ // args: { "input": "<url|path>", "type": "auto", "options": { "minWords": 2500, "fastMode": false, "maxChunks": 4, "transcribe": true, "requireCitations": true, "includeTimestamps": false, "cache": true, "outputDir": "./output", "tempDir": "./.tmp" } }
7
+ // ============================================================================
8
+
9
+ const meta = {
10
+ "name": "deep-read-summarize",
11
+ "description": "Deep reading & summarization of books/papers/videos/web (v3.0)",
12
+ "whenToUse": "User provides a book, paper, video link or web page and wants a deep-read summary saved to Obsidian",
13
+ "phases": [
14
+ {
15
+ "title": "解析器选择",
16
+ "detail": "按类型选择解析器插件"
17
+ },
18
+ {
19
+ "title": "获取与分块",
20
+ "detail": "Parser fetches content, writes temp file, builds chunk plan"
21
+ },
22
+ {
23
+ "title": "并行精读",
24
+ "detail": "N subagents deep-read chunks in parallel (Map)"
25
+ },
26
+ {
27
+ "title": "汇总成稿",
28
+ "detail": "Merge into final note (Reduce) with embedded self-check"
29
+ },
30
+ {
31
+ "title": "质量校验",
32
+ "detail": "Optional QC loop with retries"
33
+ }
34
+ ]
35
+ };
36
+
37
+ // ===== script(复制到 workflow 工具的 script 参数)=====
38
+ const RAW_SCRIPT = "// ========== deep-read-summarize v3.0 ==========\n// 3 波次:解析器获取分块 → 并行精读 → 成稿+质量校验\n// 特性:解析器插件化 / 失败纪律(fatal vs 降级) / 成本控制(maxChunks 强制,块数=子代理数)\n\n// YAML 双引号标量:JSON.stringify 的转义规则是 YAML double-quoted 风格的子集,\n// 标题/作者里出现引号时不会再截断 frontmatter(旧版是裸拼 \"...\")。\nfunction yamlStr(v) { return JSON.stringify(v == null ? \"\" : String(v)); }\n\n// ---------- 0. 配置校验(fatal 级错误:必须终止) ----------\nconst input = (args && args.input || \"\").trim();\nconst forcedType = ((args && args.type) || \"auto\").toLowerCase();\nconst options = (args && args.options) || {};\nconst minWords = options.minWords || 2500;\nconst fastMode = !!options.fastMode;\nconst maxChunks = Math.max(1, Math.min(options.maxChunks || 4, 12));\nconst requireCitations = options.requireCitations !== false;\nconst includeTimestamps = !!options.includeTimestamps;\nconst maxRetries = options.maxRetries || 0;\nconst outputDir = options.outputDir || \"./output\";\nconst tempDir = options.tempDir || \"./.tmp\";\nconst tempFile = tempDir.replace(/[\\/]+$/, \"\") + \"/input.txt\";\nconst whisperModel = options.whisperModel || \"small\";\nconst transcribeLanguage = options.language || \"zh\";\nconst transcribeDevice = options.device || \"cpu\";\n\n// 幂等不在这里做:脚本沙箱没有文件系统,写不了指纹记录。\n// 需要幂等的调用方请用 lib/cache.js(fingerprint / hasProcessed / markProcessed)。\n\n// ---------- 1. 解析器表:构建时把解析器内联为 __parsers(自包含);\n// 宿主若注入 args._parsers 则优先使用 ----------\nconst parsers = args._parsers || {};\nconst parserNames = Object.keys(parsers);\n\n// 配置校验依赖解析器表,必须放在其后\nif (!input) throw new Error(\"[FATAL] args.input 缺失:请输入内容链接或文件路径\");\nif (parserNames.length === 0) throw new Error(\"[FATAL] 解析器表为空:脚本没有内联任何解析器\");\nif (forcedType !== \"auto\" && parserNames.indexOf(forcedType) === -1)\n throw new Error(\"[FATAL] args.type 非法:\" + forcedType + \"(可用:\" + [\"auto\"].concat(parserNames).join(\"|\") + \")\");\n\nphase(\"解析器选择\");\nconst kindNames = { book: \"书籍\", paper: \"学术论文\", video: \"视频\", web: \"网页/文章\" };\nconst kindFocus = {\n book: \"按章节主题展开核心论点、论证、关键例子、章节间关系,收集关键概念与可引用原文(含页码/章节)\",\n paper: \"四维精读:1)研究问题与方法 2)结论与贡献 3)局限与批判 4)与同类工作比较;收集术语与可引用原文(含章节/段落)\",\n video: \"按主题脉络组织,提取核心论点、证据、例子、可操作建议,收集关键概念与主讲人原话\" + (includeTimestamps ? \"(含时间戳定位)\" : \"(不标时间戳)\"),\n web: \"提取核心论点、结构拆解、关键概念、可引用原文\"\n};\n\n// ---------- 2. 波次1:解析器获取 + 分块 ----------\nphase(\"获取与分块\");\nconst fetchPrompt = (parsers[forcedType !== \"auto\" ? forcedType : \"web\"] || parsers.web || { buildPrompt: function() { return [\"未知解析器\"]; } })\n .buildPrompt(input, { tempDir: tempDir, tempFile: tempFile, maxChunks: maxChunks, transcribe: options.transcribe !== false, whisperModel: whisperModel, language: transcribeLanguage, device: transcribeDevice });\n// fetchSchema 由插件在构建时从 schemas/index.js 注入(单一真相,避免两份 schema 漂移)。\n\nconst fetched = await agent(fetchPrompt, { schema: fetchSchema, label: \"获取+分块\", phase: \"获取与分块\" });\n\n// 失败纪律:内容获取失败 = 可降级错误(返回失败结果,不抛 fatal)\nif (!fetched || !fetched.saved) {\n return { ok: false, stage: \"fetch\", fatal: false, message: (fetched && fetched.message) || \"获取失败(可降级:检查输入或手动提供文本)\" };\n}\n// 分块计划收敛:块数 = 子代理数,计划失控会顶穿 workflow 单次调用时限;\n// 同时挡掉倒置/越界的行号区间(原样透传会让 read 收到 limit<=0)。\nconst rawPlan = (fetched && fetched.chunkPlan) || [];\nif (rawPlan.length === 0) return { ok: false, stage: \"fetch\", fatal: false, message: \"分块计划为空\" };\nconst declaredLines = Math.floor(Number(fetched.totalLines) || 0);\nconst chunkPlan = [];\nfor (let i = 0; i < rawPlan.length && chunkPlan.length < maxChunks; i++) {\n const c = rawPlan[i] || {};\n const s = Math.floor(Number(c.startLine) || 0);\n const e = Math.floor(Number(c.endLine) || 0);\n if (s < 1 || e < s) continue;\n if (declaredLines > 0 && s > declaredLines) continue;\n chunkPlan.push({\n id: chunkPlan.length + 1,\n topic: String(c.topic || (\"块 \" + (chunkPlan.length + 1))),\n startLine: s,\n endLine: declaredLines > 0 ? Math.min(e, declaredLines) : e\n });\n}\nif (chunkPlan.length === 0) return { ok: false, stage: \"fetch\", fatal: false, message: \"分块计划无效:行号区间缺失或非法\" };\nif (chunkPlan.length < rawPlan.length) log(\"分块计划收敛:\" + rawPlan.length + \" -> \" + chunkPlan.length + \" 块(上限 \" + maxChunks + \")\");\n\n// 类型:auto 时只接受解析器表里真实存在的类型,否则退回回退解析器,\n// 避免 \"auto\" 这种非法值流进 frontmatter 的 type / tags。\nlet kind = forcedType;\nif (forcedType === \"auto\") {\n kind = (typeof fetched.kind === \"string\" && parserNames.indexOf(fetched.kind) !== -1)\n ? fetched.kind\n : (parserNames.indexOf(\"web\") !== -1 ? \"web\" : parserNames[0]);\n}\nconst metadata = (fetched && fetched.metadata) || {};\nconst textSource = (metadata && metadata.textSource) || \"unknown\";\nconst srcLabels = { desc: \"视频简介/desc\", subtitle: \"平台字幕\", transcription: \"完整语音转写\", manual: \"用户提供转写文本\" };\nconst srcLabel = srcLabels[textSource] || textSource;\nlog(\"[source] \" + textSource + \" -> \" + srcLabel);\nlog(\"类型:\" + kind + \" 行数:\" + fetched.totalLines + \" 块数:\" + chunkPlan.length);\n\n// ---------- 3. 波次2:并行精读(Map) ----------\nphase(\"并行精读\");\nconst chunkPrompts = chunkPlan.map(function (c) {\n return [\n \"请深度精读以下内容块,输出结构化精读笔记。\",\n \"内容类型:\" + (kindNames[kind] || kind) + \" | 本块主题:\" + c.topic,\n \"精读侧重:\" + (kindFocus[kind] || kindFocus.web),\n \"用 read 工具读取 \" + tempFile + \" 第 \" + c.startLine + \" 到 \" + c.endLine + \" 行(offset=\" + c.startLine + \", limit=\" + (c.endLine - c.startLine + 1) + \"),然后输出:\",\n \"## 本块主题:\" + c.topic,\n \"### 要点(详细展开,保留数据/例子/论证)\",\n \"### 关键概念(术语+解释)\",\n \"### 关键引用(最多2句原文+位置)\" + (requireCitations ? \",必须标注页码/章节/段落位置\" : \"\"),\n \"### 批判观察(如有)\"\n ].join(\"\\n\");\n});\n\nconst reads = [];\nconst readBatch = 3;\nfor (let bi = 0; bi < chunkPrompts.length; bi += readBatch) {\n const batch = chunkPrompts.slice(bi, bi + readBatch);\n const batchReads = await parallel(batch.map(function (p) {\n return function () { return agent(p, { label: \"精读块\", phase: \"并行精读\" }); };\n }));\n for (let k = 0; k < batchReads.length; k++) reads.push(batchReads[k]);\n}\nconst validReads = reads.filter(function (r) { return r && r.trim && r.trim().length > 0; });\n\n// 失败纪律:某块精读失败 = 可降级(跳过该块,标记缺口继续)\nconst failedChunks = chunkPlan.length - validReads.length;\nif (validReads.length === 0) return { ok: false, stage: \"read\", fatal: false, message: \"所有分块精读均失败\" };\nif (failedChunks > 0) log(\"警告:\" + failedChunks + \" 块精读失败,标记缺口继续成稿\");\nlog(\"精读完成:\" + validReads.length + \"/\" + chunkPlan.length);\n\n// ---------- 4. 波次3:成稿 + 内嵌质量自检(Reduce) ----------\nphase(\"汇总成稿\");\nconst today = new Date().toISOString().slice(0, 10);\n// 标题先折叠换行/制表与连续空白:否则会同时污染 .md 文件名和 frontmatter。\nconst finalTitle = String(metadata.title || \"\").replace(/[\\r\\n\\t]+/g, \" \").replace(/\\s+/g, \" \").trim() || \"未命名内容\";\n// 文件名清洗:去掉 Windows 非法字符;全部非法时兜底,避免写出 ./output/.md 这种隐藏文件。\nconst safeTitle = finalTitle.replace(/[\\\\/:*?\"<>|]/g, \" \").replace(/\\s+/g, \" \").trim() || \"未命名内容\";\nconst mdPath = outputDir.replace(/\\\\$/, \"\") + \"/\" + safeTitle + \".md\";\n\nconst extraSections = fastMode ? [] : [\n \"\", \"## 5. 批判性分析(论证强处/弱处/可质疑之处)\", \"\",\n \"## 6. 个人思考与应用(与已有知识联系、如何应用、行动要点)\", \"\",\n \"## 7. 延伸阅读(相关主题/作者其他作品/参考文献)\", \"\"\n];\n\nconst draftPrompt = [\n \"将以下多块精读结果整合为完整 Obsidian 精读笔记,只输出 Markdown(含 YAML frontmatter)。\",\n \"模板:\", \"---\",\n 'title: ' + yamlStr(\"《\" + finalTitle + \"》深度精读笔记\"),\n \"aliases: [\" + yamlStr(finalTitle) + \"]\",\n \"author: \" + yamlStr(metadata.author),\n \"year: \" + yamlStr(metadata.year),\n \"type: \" + yamlStr(kind),\n \"url: \" + yamlStr(metadata.url || input),\n \"tags: [精读, \" + (kindNames[kind] || kind) + \"]\",\n \"created: \" + today,\n \"status: 已完成\",\n \"---\",\n \"# 《\" + finalTitle + \"》深度精读笔记\", \"\",\n \"> 一句话核心概括。\", \"\",\n \"## 1. 概述(约500字:主题/背景/核心问题/总体结论)\", \"\",\n \"## 2. 结构拆解(按主题组织,含详细要点;关键结论标注原文出处)\", \"\",\n \"## 3. 关键概念与术语表(表格)\", \"\",\n \"## 4. 关键引用(仅关键结论\" + (requireCitations ? \",必须标注页码/章节/段落\" : \"\") + \")\",\n].concat(extraSections, [\n \"---\",\n \"*笔记整理于 \" + today + \"*\", \"\",\n \"硬性要求:总篇幅≥\" + minWords + \"字;语言与原文一致;术语统一;引用必须真实;视频\" + (includeTimestamps ? \"标注时间戳\" : \"不标注时间戳\") + \"。\",\n \"输出前自检:1)覆盖所有块 2)frontmatter完整 3)各小节齐全 4)引用真实 5)篇幅达标 6)语言一致。\",\n \"\",\n \"各块精读结果:\",\n validReads.map(function (r, i) { return \"\\\\n===== 块 \" + (i + 1) + \" =====\\\\n\" + r; }).join(\"\\\\n\")\n]).join(\"\\n\");\n\nlet draft = await agent(draftPrompt, { label: \"汇总成稿\", phase: \"汇总成稿\" });\nif (!draft || !draft.trim) return { ok: false, stage: \"draft\", fatal: false, message: \"成稿失败\" };\n\n// ---------- 5. 质量校验(轻量重试) ----------\nphase(\"质量校验\");\nlet verified = draft;\nlet passed = false;\nlet issues = [];\nfor (let round = 0; round <= maxRetries; round++) {\n const checkPrompt = [\n \"请对总结笔记做质量校验,逐项检查并输出 JSON:\",\n \"1.coverage 2.citationsReal 3.terminologyConsistent 4.formatComplete 5.lengthMet(≥\" + minWords + \"字) 6.languageConsistent\",\n \"输出:{ \\\"pass\\\": true/false, \\\"issues\\\": [\\\"问题\\\"] },只输出 JSON。\",\n \"笔记:\", verified\n ].join(\"\\n\");\n const checkSchema = { type: \"object\", properties: { pass: { type: \"boolean\" }, issues: { type: \"array\", items: { type: \"string\" } } }, required: [\"pass\",\"issues\"], additionalProperties: false };\n const check = await agent(checkPrompt, { schema: checkSchema, label: \"质量校验\", phase: \"质量校验\" });\n passed = !!(check && check.pass);\n issues = (check && check.issues) || [];\n log(\"校验:\" + (passed ? \"通过\" : \"发现问题 \" + issues.length + \" 条\"));\n if (passed) break;\n if (round < maxRetries) {\n const fixPrompt = [\n \"修正以下笔记以解决校验问题,输出完整修正版:\",\n issues.map(function (s) { return \"- \" + s; }).join(\"\\n\"),\n \"当前笔记:\", verified\n ].join(\"\\n\");\n verified = await agent(fixPrompt, { label: \"修正笔记\", phase: \"质量校验\" });\n }\n}\n\n// ---------- 结果 ----------\nreturn {\n ok: true, kind: kind, title: finalTitle,\n filePath: mdPath, chunksCount: chunkPlan.length, fastMode: fastMode,\n qualityPassed: passed, qualityIssues: issues,\n failedChunks: failedChunks,\n textSource: textSource,\n note: verified\n};";
39
+
40
+ // ===== parsers 注册表(运行时注入,实现插件化)=====
41
+ const parsers = require("./parsers");
42
+ const promptImpl = require("./parsers/_prompt");
43
+ const schemas = require("./schemas");
44
+ const parserRegistry = parsers.registry;
45
+
46
+ /**
47
+ * 把注册表里的解析器(buildPrompt)连同其依赖的 buildFetchPrompt 内联进
48
+ * workflow script,使其自包含 —— DSH rc7 的 workflow 工具只把 args(JSON)
49
+ * 暴露给脚本,不会注入 args._parsers;脚本必须在自身内部解析器可用。
50
+ * 若宿主未来注入 args._parsers,优先使用宿主注入值(向后兼容)。
51
+ *
52
+ * 内联的是 **注册表里的全部解析器**,不是写死的四个:custom-parsers/ 里的
53
+ * 覆盖与自定义类型因此都能真正进入脚本(此前自定义新类型在 type 白名单
54
+ * 和这里两道关都被丢掉)。fetchSchema 同样从 schemas/index.js 注入,
55
+ * 保持单一真相,不再和脚本里的副本各自漂移。
56
+ */
57
+ function buildSelfContainedScript() {
58
+ const parserSource = (name) =>
59
+ parserRegistry.parsers[name].buildPrompt
60
+ .toString()
61
+ // buildPrompt 闭包引用模块级 prompt(parsers/_prompt),内联后改指 __prompt
62
+ .replace(/\bprompt\.buildFetchPrompt\b/g, "__prompt.buildFetchPrompt");
63
+
64
+ const parserNames = Object.keys(parserRegistry.parsers);
65
+ // kind 的合法取值跟着解析器表走(含自定义类型),不再写死四个内置类型。
66
+ const fetchSchema = JSON.parse(JSON.stringify(schemas.fetchResultSchema));
67
+ if (fetchSchema.properties && fetchSchema.properties.kind) {
68
+ fetchSchema.properties.kind.enum = parserNames.slice();
69
+ }
70
+
71
+ const impl = [
72
+ "const __prompt = { buildFetchPrompt: " + promptImpl.buildFetchPrompt.toString() + " };",
73
+ "const __parsers = {",
74
+ parserNames
75
+ .map((name) => " " + JSON.stringify(name) + ": { buildPrompt: " + parserSource(name) + " }")
76
+ .join(",\n"),
77
+ "};",
78
+ "const fetchSchema = " + JSON.stringify(fetchSchema) + ";"
79
+ ].join("\n");
80
+
81
+ const marker = "const parsers = args._parsers || {};";
82
+ if (!RAW_SCRIPT.includes(marker)) {
83
+ throw new Error("workflow script marker not found: " + marker);
84
+ }
85
+ return RAW_SCRIPT.replace(marker, impl + "\nconst parsers = args._parsers || __parsers;");
86
+ }
87
+
88
+ const script = buildSelfContainedScript();
89
+
77
90
  module.exports = { meta, script, parsers, buildSelfContainedScript };