deep-read-summarize 0.3.13 → 0.3.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/README.en.md CHANGED
@@ -78,11 +78,17 @@ parsers/ Parsers for each input type, dispatched by type
78
78
  web.js Web pages: main-text extraction
79
79
  index.js Registry: parser discovery and fallback
80
80
  schemas/ JSON Schema for the output contract (injected into the script by workflow.js - single source of truth)
81
- scripts/ lint, security checks, cross-platform transcription bootstrap (transcribe.js)
82
- tests/ fixture tests and validation scripts
83
- workflow.js The workflow script itself (meta + script)
81
+ scripts/ lint (incl. line-ending/whitespace hygiene), security checks, cross-platform transcription bootstrap
82
+ lib/ Small standalone helpers
83
+ cache.js input fingerprint and idempotency records (for callers driving the workflow themselves -- the
84
+ workflow sandbox has no filesystem, so it cannot use this)
85
+ workflow-script.txt the workflow script body (plain text: read and edit it directly, no escaping involved)
86
+ tests/ tests and validation scripts (**not published to npm**, repo only)
87
+ workflow.js the workflow meta and assembly logic (parser inlining, schema injection)
84
88
  ```
85
89
 
90
+ > The script body lives in `lib/workflow-script.txt` on purpose: this file was corrupted twice by "escaping on top of escaping". It is plain text now, so reading and editing it needs no encoding step.
91
+
86
92
  To change how an input type is handled, drop a parser with the same interface into `custom-parsers/`; a type with the same name overrides the built-in implementation, and you can also add a brand-new type name (e.g. `podcast`) - every registered parser is inlined into the workflow script, and both the `type` whitelist and the schema's `kind` enum follow the registry. The interface has only three fields: `name`, `types`, `buildPrompt(input, opts)`.
87
93
 
88
94
  ---
@@ -142,7 +148,7 @@ npm install # no third-party dependencies, just initialization
142
148
  ### 2. Verify the environment (offline, no API key needed)
143
149
 
144
150
  ```bash
145
- npm test # 25 fixture tests, all run offline
151
+ npm test # 35 fixture tests, all run offline
146
152
  ```
147
153
 
148
154
  Seeing `TOTAL: 25 passed, 0 failed` means the environment is ready.
@@ -293,7 +299,7 @@ A paper, 6 chunks, full mode: roughly 15–25k tokens. `fastMode` with a lower `
293
299
  ```bash
294
300
  npm install
295
301
  npm run lint # node --check on all JS
296
- npm test # fixture tests (25, all offline)
302
+ npm test # fixture tests (35, all offline)
297
303
  npm run validate # pre-release validation (including security checks)
298
304
  ```
299
305
 
package/README.md CHANGED
@@ -78,11 +78,16 @@ parsers/ 各输入类型的解析器,按类型分发
78
78
  web.js 网页:正文提取
79
79
  index.js 注册表:解析器发现与回退
80
80
  schemas/ 输出约束的 JSON Schema(波次1 由 workflow.js 注入脚本,单一真相)
81
- scripts/ lint、安全检查、跨平台转写引导(transcribe.js)
82
- tests/ fixture 测试与验证脚本
83
- workflow.js workflow 脚本本体(meta + script)
81
+ scripts/ lint(含换行/空白卫生检查)、安全检查、跨平台转写引导(transcribe.js)
82
+ lib/ 独立可用的小工具
83
+ cache.js 输入指纹与幂等记录(供自己驱动流程的调用方使用;workflow 沙箱没有文件系统,用不到它)
84
+ workflow-script.txt workflow 脚本正文(普通文本,可直接读改,不需要任何转义)
85
+ tests/ 测试与验证脚本(**不随 npm 包发布**,仓库里才有)
86
+ workflow.js workflow 的 meta 与组装逻辑(解析器内联、schema 注入)
84
87
  ```
85
88
 
89
+ > 脚本正文单独放 `lib/workflow-script.txt`:这个文件曾经因为「转义套转义」被改坏过两次,现在它是普通文本,读改都不需要编码步骤。
90
+
86
91
  想换某个输入类型的处理方式,在 `custom-parsers/` 放一个同接口的解析器即可,同名类型会覆盖内置实现;用新类型名(如 `podcast`)也可以——注册表里的解析器会全部内联进 workflow 脚本,`type` 白名单与 schema 的 `kind` 枚举都跟着注册表走。接口只有三个字段:`name`、`types`、`buildPrompt(input, opts)`。
87
92
 
88
93
  ---
@@ -142,7 +147,7 @@ npm install # 无第三方依赖,仅初始化
142
147
  ### 2. 验证环境(离线,不需要任何 API key)
143
148
 
144
149
  ```bash
145
- npm test # 25 项 fixture 测试,全部离线跑通
150
+ npm test # 35 项 fixture 测试,全部离线跑通
146
151
  ```
147
152
 
148
153
  看到 `TOTAL: 25 passed, 0 failed` 即环境就绪。
@@ -293,7 +298,7 @@ parsers: book, paper, video, web
293
298
  ```bash
294
299
  npm install
295
300
  npm run lint # node --check 全部 JS
296
- npm test # fixture 测试(25 项,全部离线)
301
+ npm test # fixture 测试(35 项,全部离线)
297
302
  npm run validate # 发布前验证(含安全检查)
298
303
  ```
299
304
 
package/cordis.patch.yml CHANGED
@@ -22,6 +22,10 @@
22
22
  # transcribe: true # video: auto-transcribe when no subtitles (default: true)
23
23
  # requireCitations: true # key conclusions must cite source location (default: true)
24
24
  # includeTimestamps: false # video timestamps (default: false)
25
+ # whisperModel: 'small' # transcription model (default: small)
26
+ # language: 'zh' # transcription language (default: zh)
27
+ # device: 'cpu' # cpu | auto | cuda; GPU needs a CUDA runtime (default: cpu)
28
+ # maxRetries: 0 # quality-check retry rounds (default: 0)
25
29
  #
26
30
  # Idempotency is deliberately NOT a plugin config key: the workflow script runs
27
31
  # without a filesystem, so it cannot write a fingerprint record. Programmatic
package/docs/RELEASE.md CHANGED
@@ -114,7 +114,9 @@ npm view deep-read-summarize --prefer-online # 验证线
114
114
  | v0.3.10 | npm 已发布 | 修:失效的 uv 镜像、空转写被当成成功、发布文档过时 |
115
115
  | v0.3.11 | npm 已发布 | 文档:README 补「支持平台」;CI:三平台跑全套门禁 |
116
116
  | v0.3.12 | npm 已发布 | 文档:定位改为「标准 Markdown」;删 dsh.so 一节;macOS 真机验证转写通过 |
117
- | **v0.3.13** | **npm 已发布(当前)** | 声明:补 `engines.dsh`(此前的 `dsh.minVersion` 非公开字段,市场不读,判定一直是 `undeclared`) |
117
+ | v0.3.13 | npm 已发布 | 声明:补 `engines.dsh`(此前的 `dsh.minVersion` 非公开字段,市场不读,判定一直是 `undeclared`) |
118
+ | v0.3.14 | npm 已发布 | 修:路径尾分隔符、本地日期、config 白名单;README 测试数 |
119
+ | **v0.3.15** | **npm 已发布(当前)** | 工程卫生:锁定 LF、脚本正文独立成文、lint 扩检查、包瘦身、提示词改「标准 Markdown」 |
118
120
  | v1.0.0 | 计划 | API 稳定后发布 |
119
121
 
120
122
  > 早期迭代用 0.x 表达不稳定;API 稳定后再发 1.0.0。
package/index.js CHANGED
@@ -33,7 +33,11 @@ const DEFAULT_OPTIONS = {
33
33
  requireCitations: true,
34
34
  includeTimestamps: false,
35
35
  outputDir: './output',
36
- tempDir: './.tmp'
36
+ tempDir: './.tmp',
37
+ whisperModel: 'small',
38
+ language: 'zh',
39
+ device: 'cpu',
40
+ maxRetries: 0
37
41
  };
38
42
 
39
43
  const OPTION_TYPES = {
@@ -44,7 +48,11 @@ const OPTION_TYPES = {
44
48
  requireCitations: 'boolean',
45
49
  includeTimestamps: 'boolean',
46
50
  outputDir: 'string',
47
- tempDir: 'string'
51
+ tempDir: 'string',
52
+ whisperModel: 'string',
53
+ language: 'string',
54
+ device: 'string',
55
+ maxRetries: 'number'
48
56
  };
49
57
 
50
58
  /**
@@ -64,6 +72,14 @@ function normalizeOptions(config) {
64
72
  }
65
73
  opts[key] = v;
66
74
  }
75
+ // 未知键此前是完全无声的:循环只遍历白名单,写错的键名既不生效也不告警。
76
+ const unknown = Object.keys(raw).filter(function (k) {
77
+ return !Object.prototype.hasOwnProperty.call(DEFAULT_OPTIONS, k);
78
+ });
79
+ if (unknown.length) {
80
+ console.warn('[deep-read-summarize] ignoring unknown config key(s): ' + unknown.join(', '));
81
+ console.warn('[deep-read-summarize] allowed keys: ' + Object.keys(DEFAULT_OPTIONS).join(', '));
82
+ }
67
83
  return opts;
68
84
  }
69
85
 
package/lib/cache.js CHANGED
@@ -1,102 +1,102 @@
1
- // ============================================================================
2
- // lib/cache.js — idempotency: input fingerprint cache
3
- // ============================================================================
4
- // 对输入内容计算指纹(URL 或文件路径 + 文件大小/修改时间),
5
- // 已处理过的输入直接跳过,避免重复消耗 token。
6
- // 指纹记录以 JSONL 追加式存储,支持断点恢复。
7
- // ============================================================================
8
- // 用法:
9
- // const cache = require("./lib/cache");
10
- // const key = cache.fingerprint(input, fileMeta);
11
- // if (cache.hasProcessed(cacheFile, key)) { skip; }
12
- // cache.markProcessed(cacheFile, key, outputPath);
13
- // ============================================================================
14
-
15
- const fs = require("fs");
16
- const path = require("path");
17
- const crypto = require("crypto");
18
-
19
- /**
20
- * 规范化输入:对 http(s) URL 做归一化(host 小写、去默认端口、去 fragment、
21
- * 去空 query 的 "?"、去尾部斜杠),避免同一 URL 的不同写法产生不同指纹;
22
- * 非 URL(本地路径/纯文本)原样返回。
23
- */
24
- function normalizeInput(input) {
25
- const s = typeof input === "string" ? input.trim() : "";
26
- if (!/^https?:\/\//i.test(s)) return s;
27
- try {
28
- const url = new URL(s);
29
- url.hash = "";
30
- url.hostname = url.hostname.toLowerCase();
31
- if ((url.protocol === "http:" && url.port === "80") || (url.protocol === "https:" && url.port === "443")) {
32
- url.port = "";
33
- }
34
- if (url.pathname.length > 1 && url.pathname.endsWith("/")) {
35
- url.pathname = url.pathname.slice(0, -1);
36
- }
37
- // 去掉 URL 尾部的空 query "?"(new URL("...doc?").search 返回 "",无法靠 search 判断,
38
- // 需检查 toString() 输出;同一 URL 的 "doc" 与 "doc?" 两种写法应共享指纹)
39
- let normalized = url.toString();
40
- if (normalized.endsWith("?")) normalized = normalized.slice(0, -1);
41
- return normalized;
42
- } catch (e) {
43
- return s; // 非法 URL 原样处理
44
- }
45
- }
46
-
47
- /** 计算输入指纹:URL 规范化后 hash;本地文件加大小 + 修改时间 */
48
- function fingerprint(input, fileMeta) {
49
- const base = normalizeInput(input);
50
- if (!base) return null;
51
- const metaStr = fileMeta
52
- ? "|" + (fileMeta.size ?? "") + "|" + (fileMeta.mtimeMs ?? "")
53
- : "";
54
- return crypto.createHash("sha256").update(base + metaStr).digest("hex").slice(0, 16);
55
- }
56
-
57
- /** 从缓存文件读取已处理记录(JSONL) */
58
- function readCache(cacheFile) {
59
- if (!fs.existsSync(cacheFile)) return new Map();
60
- const map = new Map();
61
- try {
62
- const lines = fs.readFileSync(cacheFile, "utf8").split("\n");
63
- for (const line of lines) {
64
- if (!line.trim()) continue;
65
- try {
66
- const rec = JSON.parse(line);
67
- if (rec && rec.key) map.set(rec.key, rec);
68
- } catch (e) { /* 跳过损坏行 */ }
69
- }
70
- } catch (e) { /* 缓存不可读则视为空 */ }
71
- return map;
72
- }
73
-
74
- /** 是否已处理过该指纹;opts.maxAgeMs 提供时,过期(记录时间早于阈值)视为未处理 */
75
- function hasProcessed(cacheFile, key, opts) {
76
- if (!key) return false;
77
- const rec = readCache(cacheFile).get(key);
78
- if (!rec) return false;
79
- const maxAgeMs = opts && opts.maxAgeMs;
80
- if (maxAgeMs && rec.ts) {
81
- const age = Date.now() - new Date(rec.ts).getTime();
82
- if (!isFinite(age) || age > maxAgeMs) return false;
83
- }
84
- return true;
85
- }
86
-
87
- /** 标记已处理(追加 JSONL 记录);写缓存失败仅告警,不中断主流程 */
88
- function markProcessed(cacheFile, key, outputPath, meta) {
89
- if (!key) return false;
90
- try {
91
- const dir = path.dirname(cacheFile);
92
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
93
- const rec = { key, outputPath, ts: new Date().toISOString(), ...(meta || {}) };
94
- fs.appendFileSync(cacheFile, JSON.stringify(rec) + "\n", "utf8");
95
- return true;
96
- } catch (e) {
97
- console.warn("[cache] markProcessed failed:", e.message);
98
- return false;
99
- }
100
- }
101
-
102
- module.exports = { fingerprint, normalizeInput, readCache, hasProcessed, markProcessed };
1
+ // ============================================================================
2
+ // lib/cache.js — idempotency: input fingerprint cache
3
+ // ============================================================================
4
+ // 对输入内容计算指纹(URL 或文件路径 + 文件大小/修改时间),
5
+ // 已处理过的输入直接跳过,避免重复消耗 token。
6
+ // 指纹记录以 JSONL 追加式存储,支持断点恢复。
7
+ // ============================================================================
8
+ // 用法:
9
+ // const cache = require("./lib/cache");
10
+ // const key = cache.fingerprint(input, fileMeta);
11
+ // if (cache.hasProcessed(cacheFile, key)) { skip; }
12
+ // cache.markProcessed(cacheFile, key, outputPath);
13
+ // ============================================================================
14
+
15
+ const fs = require("fs");
16
+ const path = require("path");
17
+ const crypto = require("crypto");
18
+
19
+ /**
20
+ * 规范化输入:对 http(s) URL 做归一化(host 小写、去默认端口、去 fragment、
21
+ * 去空 query 的 "?"、去尾部斜杠),避免同一 URL 的不同写法产生不同指纹;
22
+ * 非 URL(本地路径/纯文本)原样返回。
23
+ */
24
+ function normalizeInput(input) {
25
+ const s = typeof input === "string" ? input.trim() : "";
26
+ if (!/^https?:\/\//i.test(s)) return s;
27
+ try {
28
+ const url = new URL(s);
29
+ url.hash = "";
30
+ url.hostname = url.hostname.toLowerCase();
31
+ if ((url.protocol === "http:" && url.port === "80") || (url.protocol === "https:" && url.port === "443")) {
32
+ url.port = "";
33
+ }
34
+ if (url.pathname.length > 1 && url.pathname.endsWith("/")) {
35
+ url.pathname = url.pathname.slice(0, -1);
36
+ }
37
+ // 去掉 URL 尾部的空 query "?"(new URL("...doc?").search 返回 "",无法靠 search 判断,
38
+ // 需检查 toString() 输出;同一 URL 的 "doc" 与 "doc?" 两种写法应共享指纹)
39
+ let normalized = url.toString();
40
+ if (normalized.endsWith("?")) normalized = normalized.slice(0, -1);
41
+ return normalized;
42
+ } catch (e) {
43
+ return s; // 非法 URL 原样处理
44
+ }
45
+ }
46
+
47
+ /** 计算输入指纹:URL 规范化后 hash;本地文件加大小 + 修改时间 */
48
+ function fingerprint(input, fileMeta) {
49
+ const base = normalizeInput(input);
50
+ if (!base) return null;
51
+ const metaStr = fileMeta
52
+ ? "|" + (fileMeta.size ?? "") + "|" + (fileMeta.mtimeMs ?? "")
53
+ : "";
54
+ return crypto.createHash("sha256").update(base + metaStr).digest("hex").slice(0, 16);
55
+ }
56
+
57
+ /** 从缓存文件读取已处理记录(JSONL) */
58
+ function readCache(cacheFile) {
59
+ if (!fs.existsSync(cacheFile)) return new Map();
60
+ const map = new Map();
61
+ try {
62
+ const lines = fs.readFileSync(cacheFile, "utf8").split("\n");
63
+ for (const line of lines) {
64
+ if (!line.trim()) continue;
65
+ try {
66
+ const rec = JSON.parse(line);
67
+ if (rec && rec.key) map.set(rec.key, rec);
68
+ } catch (e) { /* 跳过损坏行 */ }
69
+ }
70
+ } catch (e) { /* 缓存不可读则视为空 */ }
71
+ return map;
72
+ }
73
+
74
+ /** 是否已处理过该指纹;opts.maxAgeMs 提供时,过期(记录时间早于阈值)视为未处理 */
75
+ function hasProcessed(cacheFile, key, opts) {
76
+ if (!key) return false;
77
+ const rec = readCache(cacheFile).get(key);
78
+ if (!rec) return false;
79
+ const maxAgeMs = opts && opts.maxAgeMs;
80
+ if (maxAgeMs && rec.ts) {
81
+ const age = Date.now() - new Date(rec.ts).getTime();
82
+ if (!isFinite(age) || age > maxAgeMs) return false;
83
+ }
84
+ return true;
85
+ }
86
+
87
+ /** 标记已处理(追加 JSONL 记录);写缓存失败仅告警,不中断主流程 */
88
+ function markProcessed(cacheFile, key, outputPath, meta) {
89
+ if (!key) return false;
90
+ try {
91
+ const dir = path.dirname(cacheFile);
92
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
93
+ const rec = { key, outputPath, ts: new Date().toISOString(), ...(meta || {}) };
94
+ fs.appendFileSync(cacheFile, JSON.stringify(rec) + "\n", "utf8");
95
+ return true;
96
+ } catch (e) {
97
+ console.warn("[cache] markProcessed failed:", e.message);
98
+ return false;
99
+ }
100
+ }
101
+
102
+ module.exports = { fingerprint, normalizeInput, readCache, hasProcessed, markProcessed };
@@ -0,0 +1,215 @@
1
+ // ========== deep-read-summarize v3.0 ==========
2
+ // 3 波次:解析器获取分块 → 并行精读 → 成稿+质量校验
3
+ // 特性:解析器插件化 / 失败纪律(fatal vs 降级) / 成本控制(maxChunks 强制,块数=子代理数)
4
+
5
+ // YAML 双引号标量:JSON.stringify 的转义规则是 YAML double-quoted 风格的子集,
6
+ // 标题/作者里出现引号时不会再截断 frontmatter(旧版是裸拼 "...")。
7
+ function yamlStr(v) { return JSON.stringify(v == null ? "" : String(v)); }
8
+
9
+ // ---------- 0. 配置校验(fatal 级错误:必须终止) ----------
10
+ const input = (args && args.input || "").trim();
11
+ const forcedType = ((args && args.type) || "auto").toLowerCase();
12
+ const options = (args && args.options) || {};
13
+ const minWords = options.minWords || 2500;
14
+ const fastMode = !!options.fastMode;
15
+ const maxChunks = Math.max(1, Math.min(options.maxChunks || 4, 12));
16
+ const requireCitations = options.requireCitations !== false;
17
+ const includeTimestamps = !!options.includeTimestamps;
18
+ const maxRetries = options.maxRetries || 0;
19
+ const outputDir = options.outputDir || "./output";
20
+ const tempDir = options.tempDir || "./.tmp";
21
+ const tempFile = tempDir.replace(/[\\/]+$/, "") + "/input.txt";
22
+ const whisperModel = options.whisperModel || "small";
23
+ const transcribeLanguage = options.language || "zh";
24
+ const transcribeDevice = options.device || "cpu";
25
+
26
+ // 幂等不在这里做:脚本沙箱没有文件系统,写不了指纹记录。
27
+ // 需要幂等的调用方请用 lib/cache.js(fingerprint / hasProcessed / markProcessed)。
28
+
29
+ // ---------- 1. 解析器表:构建时把解析器内联为 __parsers(自包含);
30
+ // 宿主若注入 args._parsers 则优先使用 ----------
31
+ const parsers = args._parsers || {};
32
+ const parserNames = Object.keys(parsers);
33
+
34
+ // 配置校验依赖解析器表,必须放在其后
35
+ if (!input) throw new Error("[FATAL] args.input 缺失:请输入内容链接或文件路径");
36
+ if (parserNames.length === 0) throw new Error("[FATAL] 解析器表为空:脚本没有内联任何解析器");
37
+ if (forcedType !== "auto" && parserNames.indexOf(forcedType) === -1)
38
+ throw new Error("[FATAL] args.type 非法:" + forcedType + "(可用:" + ["auto"].concat(parserNames).join("|") + ")");
39
+
40
+ phase("解析器选择");
41
+ const kindNames = { book: "书籍", paper: "学术论文", video: "视频", web: "网页/文章" };
42
+ const kindFocus = {
43
+ book: "按章节主题展开核心论点、论证、关键例子、章节间关系,收集关键概念与可引用原文(含页码/章节)",
44
+ paper: "四维精读:1)研究问题与方法 2)结论与贡献 3)局限与批判 4)与同类工作比较;收集术语与可引用原文(含章节/段落)",
45
+ video: "按主题脉络组织,提取核心论点、证据、例子、可操作建议,收集关键概念与主讲人原话" + (includeTimestamps ? "(含时间戳定位)" : "(不标时间戳)"),
46
+ web: "提取核心论点、结构拆解、关键概念、可引用原文"
47
+ };
48
+
49
+ // ---------- 2. 波次1:解析器获取 + 分块 ----------
50
+ phase("获取与分块");
51
+ const fetchPrompt = (parsers[forcedType !== "auto" ? forcedType : "web"] || parsers.web || { buildPrompt: function() { return ["未知解析器"]; } })
52
+ .buildPrompt(input, { tempDir: tempDir, tempFile: tempFile, maxChunks: maxChunks, transcribe: options.transcribe !== false, whisperModel: whisperModel, language: transcribeLanguage, device: transcribeDevice });
53
+ // fetchSchema 由插件在构建时从 schemas/index.js 注入(单一真相,避免两份 schema 漂移)。
54
+
55
+ const fetched = await agent(fetchPrompt, { schema: fetchSchema, label: "获取+分块", phase: "获取与分块" });
56
+
57
+ // 失败纪律:内容获取失败 = 可降级错误(返回失败结果,不抛 fatal)
58
+ if (!fetched || !fetched.saved) {
59
+ return { ok: false, stage: "fetch", fatal: false, message: (fetched && fetched.message) || "获取失败(可降级:检查输入或手动提供文本)" };
60
+ }
61
+ // 分块计划收敛:块数 = 子代理数,计划失控会顶穿 workflow 单次调用时限;
62
+ // 同时挡掉倒置/越界的行号区间(原样透传会让 read 收到 limit<=0)。
63
+ const rawPlan = (fetched && fetched.chunkPlan) || [];
64
+ if (rawPlan.length === 0) return { ok: false, stage: "fetch", fatal: false, message: "分块计划为空" };
65
+ const declaredLines = Math.floor(Number(fetched.totalLines) || 0);
66
+ const chunkPlan = [];
67
+ for (let i = 0; i < rawPlan.length && chunkPlan.length < maxChunks; i++) {
68
+ const c = rawPlan[i] || {};
69
+ const s = Math.floor(Number(c.startLine) || 0);
70
+ const e = Math.floor(Number(c.endLine) || 0);
71
+ if (s < 1 || e < s) continue;
72
+ if (declaredLines > 0 && s > declaredLines) continue;
73
+ chunkPlan.push({
74
+ id: chunkPlan.length + 1,
75
+ topic: String(c.topic || ("块 " + (chunkPlan.length + 1))),
76
+ startLine: s,
77
+ endLine: declaredLines > 0 ? Math.min(e, declaredLines) : e
78
+ });
79
+ }
80
+ if (chunkPlan.length === 0) return { ok: false, stage: "fetch", fatal: false, message: "分块计划无效:行号区间缺失或非法" };
81
+ if (chunkPlan.length < rawPlan.length) log("分块计划收敛:" + rawPlan.length + " -> " + chunkPlan.length + " 块(上限 " + maxChunks + ")");
82
+
83
+ // 类型:auto 时只接受解析器表里真实存在的类型,否则退回回退解析器,
84
+ // 避免 "auto" 这种非法值流进 frontmatter 的 type / tags。
85
+ let kind = forcedType;
86
+ if (forcedType === "auto") {
87
+ kind = (typeof fetched.kind === "string" && parserNames.indexOf(fetched.kind) !== -1)
88
+ ? fetched.kind
89
+ : (parserNames.indexOf("web") !== -1 ? "web" : parserNames[0]);
90
+ }
91
+ const metadata = (fetched && fetched.metadata) || {};
92
+ const textSource = (metadata && metadata.textSource) || "unknown";
93
+ const srcLabels = { desc: "视频简介/desc", subtitle: "平台字幕", transcription: "完整语音转写", manual: "用户提供转写文本" };
94
+ const srcLabel = srcLabels[textSource] || textSource;
95
+ log("[source] " + textSource + " -> " + srcLabel);
96
+ log("类型:" + kind + " 行数:" + fetched.totalLines + " 块数:" + chunkPlan.length);
97
+
98
+ // ---------- 3. 波次2:并行精读(Map) ----------
99
+ phase("并行精读");
100
+ const chunkPrompts = chunkPlan.map(function (c) {
101
+ return [
102
+ "请深度精读以下内容块,输出结构化精读笔记。",
103
+ "内容类型:" + (kindNames[kind] || kind) + " | 本块主题:" + c.topic,
104
+ "精读侧重:" + (kindFocus[kind] || kindFocus.web),
105
+ "用 read 工具读取 " + tempFile + " 第 " + c.startLine + " 到 " + c.endLine + " 行(offset=" + c.startLine + ", limit=" + (c.endLine - c.startLine + 1) + "),然后输出:",
106
+ "## 本块主题:" + c.topic,
107
+ "### 要点(详细展开,保留数据/例子/论证)",
108
+ "### 关键概念(术语+解释)",
109
+ "### 关键引用(最多2句原文+位置)" + (requireCitations ? ",必须标注页码/章节/段落位置" : ""),
110
+ "### 批判观察(如有)"
111
+ ].join("\n");
112
+ });
113
+
114
+ const reads = [];
115
+ const readBatch = 3;
116
+ for (let bi = 0; bi < chunkPrompts.length; bi += readBatch) {
117
+ const batch = chunkPrompts.slice(bi, bi + readBatch);
118
+ const batchReads = await parallel(batch.map(function (p) {
119
+ return function () { return agent(p, { label: "精读块", phase: "并行精读" }); };
120
+ }));
121
+ for (let k = 0; k < batchReads.length; k++) reads.push(batchReads[k]);
122
+ }
123
+ const validReads = reads.filter(function (r) { return r && r.trim && r.trim().length > 0; });
124
+
125
+ // 失败纪律:某块精读失败 = 可降级(跳过该块,标记缺口继续)
126
+ const failedChunks = chunkPlan.length - validReads.length;
127
+ if (validReads.length === 0) return { ok: false, stage: "read", fatal: false, message: "所有分块精读均失败" };
128
+ if (failedChunks > 0) log("警告:" + failedChunks + " 块精读失败,标记缺口继续成稿");
129
+ log("精读完成:" + validReads.length + "/" + chunkPlan.length);
130
+
131
+ // ---------- 4. 波次3:成稿 + 内嵌质量自检(Reduce) ----------
132
+ phase("汇总成稿");
133
+ const todayDate = new Date();
134
+ const today = todayDate.getFullYear() + "-" + ("0" + (todayDate.getMonth() + 1)).slice(-2) + "-" + ("0" + todayDate.getDate()).slice(-2);
135
+ // 标题先折叠换行/制表与连续空白:否则会同时污染 .md 文件名和 frontmatter。
136
+ const finalTitle = String(metadata.title || "").replace(/[\r\n\t]+/g, " ").replace(/\s+/g, " ").trim() || "未命名内容";
137
+ // 文件名清洗:去掉 Windows 非法字符;全部非法时兜底,避免写出 ./output/.md 这种隐藏文件。
138
+ const safeTitle = finalTitle.replace(/[\\/:*?"<>|]/g, " ").replace(/\s+/g, " ").trim() || "未命名内容";
139
+ const mdPath = outputDir.replace(/[\\/]+$/, "") + "/" + safeTitle + ".md";
140
+
141
+ const extraSections = fastMode ? [] : [
142
+ "", "## 5. 批判性分析(论证强处/弱处/可质疑之处)", "",
143
+ "## 6. 个人思考与应用(与已有知识联系、如何应用、行动要点)", "",
144
+ "## 7. 延伸阅读(相关主题/作者其他作品/参考文献)", ""
145
+ ];
146
+
147
+ const draftPrompt = [
148
+ "将以下多块精读结果整合为完整的结构化精读笔记,只输出标准 Markdown(含 YAML frontmatter)。",
149
+ "模板:", "---",
150
+ 'title: ' + yamlStr("《" + finalTitle + "》深度精读笔记"),
151
+ "aliases: [" + yamlStr(finalTitle) + "]",
152
+ "author: " + yamlStr(metadata.author),
153
+ "year: " + yamlStr(metadata.year),
154
+ "type: " + yamlStr(kind),
155
+ "url: " + yamlStr(metadata.url || input),
156
+ "tags: [精读, " + (kindNames[kind] || kind) + "]",
157
+ "created: " + today,
158
+ "status: 已完成",
159
+ "---",
160
+ "# 《" + finalTitle + "》深度精读笔记", "",
161
+ "> 一句话核心概括。", "",
162
+ "## 1. 概述(约500字:主题/背景/核心问题/总体结论)", "",
163
+ "## 2. 结构拆解(按主题组织,含详细要点;关键结论标注原文出处)", "",
164
+ "## 3. 关键概念与术语表(表格)", "",
165
+ "## 4. 关键引用(仅关键结论" + (requireCitations ? ",必须标注页码/章节/段落" : "") + ")",
166
+ ].concat(extraSections, [
167
+ "---",
168
+ "*笔记整理于 " + today + "*", "",
169
+ "硬性要求:总篇幅≥" + minWords + "字;语言与原文一致;术语统一;引用必须真实;视频" + (includeTimestamps ? "标注时间戳" : "不标注时间戳") + "。",
170
+ "输出前自检:1)覆盖所有块 2)frontmatter完整 3)各小节齐全 4)引用真实 5)篇幅达标 6)语言一致。",
171
+ "",
172
+ "各块精读结果:",
173
+ validReads.map(function (r, i) { return "\\n===== 块 " + (i + 1) + " =====\\n" + r; }).join("\\n")
174
+ ]).join("\n");
175
+
176
+ let draft = await agent(draftPrompt, { label: "汇总成稿", phase: "汇总成稿" });
177
+ if (!draft || !draft.trim) return { ok: false, stage: "draft", fatal: false, message: "成稿失败" };
178
+
179
+ // ---------- 5. 质量校验(轻量重试) ----------
180
+ phase("质量校验");
181
+ let verified = draft;
182
+ let passed = false;
183
+ let issues = [];
184
+ for (let round = 0; round <= maxRetries; round++) {
185
+ const checkPrompt = [
186
+ "请对总结笔记做质量校验,逐项检查并输出 JSON:",
187
+ "1.coverage 2.citationsReal 3.terminologyConsistent 4.formatComplete 5.lengthMet(≥" + minWords + "字) 6.languageConsistent",
188
+ "输出:{ \"pass\": true/false, \"issues\": [\"问题\"] },只输出 JSON。",
189
+ "笔记:", verified
190
+ ].join("\n");
191
+ const checkSchema = { type: "object", properties: { pass: { type: "boolean" }, issues: { type: "array", items: { type: "string" } } }, required: ["pass","issues"], additionalProperties: false };
192
+ const check = await agent(checkPrompt, { schema: checkSchema, label: "质量校验", phase: "质量校验" });
193
+ passed = !!(check && check.pass);
194
+ issues = (check && check.issues) || [];
195
+ log("校验:" + (passed ? "通过" : "发现问题 " + issues.length + " 条"));
196
+ if (passed) break;
197
+ if (round < maxRetries) {
198
+ const fixPrompt = [
199
+ "修正以下笔记以解决校验问题,输出完整修正版:",
200
+ issues.map(function (s) { return "- " + s; }).join("\n"),
201
+ "当前笔记:", verified
202
+ ].join("\n");
203
+ verified = await agent(fixPrompt, { label: "修正笔记", phase: "质量校验" });
204
+ }
205
+ }
206
+
207
+ // ---------- 结果 ----------
208
+ return {
209
+ ok: true, kind: kind, title: finalTitle,
210
+ filePath: mdPath, chunksCount: chunkPlan.length, fastMode: fastMode,
211
+ qualityPassed: passed, qualityIssues: issues,
212
+ failedChunks: failedChunks,
213
+ textSource: textSource,
214
+ note: verified
215
+ };