deep-read-summarize 0.3.1 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,110 +1,131 @@
1
- # Changelog
2
-
3
- All notable changes to this project will be documented in this file.
4
- The format is based on [Keep a Changelog](https://keepachangelog.com/).
5
-
6
- ## [0.3.1] — 2026-08-21
7
-
8
- ### Fixed
9
- - 发布前检查:移除 README 中的本地 Obsidian 仓库绝对路径(改为参数化描述)
10
- - 移除 docs/RELEASE.md 中的本机绝对路径(改为通用写法)
11
- - README 同步版本号:tgz 0.2.0 → 0.3.0、测试 17 → 21 项
12
-
13
- ## [0.3.0] — 2026-08-21
14
-
15
- ### Added
16
- - 幂等缓存 URL 规范化(normalizeInput):host 大小写 / 默认端口 / fragment / 尾部斜杠归一,同一 URL 不同写法共享指纹
17
- - 安全扫描覆盖 .env.example 与 forward-slash 用户路径;导出 scanDir 供测试调用
18
- - 测试 17 → 21:parser 模板回归、URL 规范化、安全扫描正/负样本
19
-
20
- ### Changed
21
- - parsers 四解析器去重:抽取共享提示词模板 parsers/_prompt.js(buildPrompt 输出逐字不变,经新旧对比验证)
22
- - lint 排除 .tmp*/dist/coverage 等临时目录
23
- - CI 增加 Node 18/20/22 版本矩阵
24
- - package.json 增加 publishConfig.access=public(显式公开发布)
25
- - docs/RELEASE.md 增加 npm 发布流程与版本速览;README 开发节补充发布门禁说明
26
-
27
- ### Fixed
28
- - security-check 对测试样本误报(样本改为拼接构造,源码不含完整密钥模式)
29
-
30
- ## [0.2.0] — 2026-08-21
31
-
32
- ### Added
33
- - 首次发布到 npm registry(`npm install deep-read-summarize`),含此前未发布的 0.1.1 变更
34
- - prepublishOnly 质量门禁:发布前自动跑 17 项测试 + lint + 安全检查
35
-
36
- ### Changed
37
- - package.json version 对齐 git tag(0.1.0 → 0.2.0)
38
- - keywords 移除 `deepseek-harness` 商标词(安全合规要求,与 v0.1.0 决策一致)
39
- - README 补充 npm 安装方式
40
-
41
- ### Fixed
42
- - git 历史整理:以本地完整开发历史为准 force push 覆盖 API 拼凑历史,补上缺失的 `.github/workflows/ci.yml`
43
-
44
- ## [0.1.1] — 2026-08-19
45
-
46
- ### Added
47
- - DSH 插件化:cordis.patch.yml(bundle patch)、index.js 插件入口、skills/ 打包
48
- - node:test 风格测试(tests/index.test.js,`npm run test:node`)
49
-
50
- ### Changed
51
- - package.json:dsh.bundle 字段、exports、repository、keywords 完善
52
- - 废弃 cordis.yml → 由 cordis.patch.yml 替代
53
-
54
- ## [0.1.0] — 2026-08-18
55
-
56
- ### Added
57
- - 首个公开预发布版(pre-release)
58
- - 四种输入解析器插件:书籍/论文/视频/网页
59
- - 三波次 MapReduce 精读流水线
60
- - JSON Schema 结构化输出约束
61
- - 幂等缓存(lib/cache.js)
62
- - 失败分级(FATAL vs 可降级)
63
- - 质量校验循环
64
- - CI(lint + 测试 + Gitleaks 密钥扫描)
65
- - README/SECURITY/CONTRIBUTING/CHANGELOG 文档
66
-
67
- ## [3.0.0] — 2026-08-18
68
-
69
- ### Added
70
- - Plugin parser architecture: `parsers/` registry with book/paper/video/web adapters
71
- - JSON Schema structured output constraints (`schemas/index.js`)
72
- - Failure discipline: FATAL (config) vs degradable (content) error classes
73
- - Quality control loop with retry (`maxRetries`)
74
- - Configurable citations (`requireCitations`) and video timestamps (`includeTimestamps`)
75
- - Fixture-driven test suite (`npm test`, 10 tests)
76
- - Quick validation script (`npm run validate`)
77
- - CI workflow (lint + tests)
78
- - cordis.yml plugin tree example
79
-
80
- ### Changed
81
- - Workflow reduced to 3 serial waves (fetch/chunk → parallel read → merge+QC)
82
- - Subagent count reduced to N+2~3
83
- - Defaults changed to general-purpose: `requireCitations: true`, `includeTimestamps: false`
84
-
85
- ### Removed
86
- - Standalone quality-check subagent (merged into wave 3 + optional lightweight retry)
87
-
88
- ## [2.1.0] — 2026-08-18
89
-
90
- ### Added
91
- - One-click write-to-Obsidian from the draft agent
92
- - fastMode (skip sections 5-7)
93
-
94
- ## [2.0.0] — 2026-08-18
95
-
96
- ### Changed
97
- - Merged identify+fetch+chunk into one subagent (3 waves total)
98
- - Removed standalone QC subagent
99
-
100
- ## [1.1.0] — 2026-08-18
101
-
102
- ### Fixed
103
- - Long-content overflow: write-to-temp-file + line-range chunking
104
-
105
- ## [1.0.0] — 2026-08-18
106
-
107
- ### Added
108
- - Initial deep-reading pipeline (5 serial waves)
109
- - Template prompts for books/papers/videos/web
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+ The format is based on [Keep a Changelog](https://keepachangelog.com/).
5
+
6
+ ## [0.3.4] — 2026-08-28
7
+
8
+ ### Fixed
9
+ - **DSH rc7(Cordis)兼容修复**:插件入口改为标准 Cordis 插件契约(导出 `name` + `inject: ['skills']` + `apply(ctx)`),apply 时将自带 SKILL.md 注册为运行时技能(含 workflow meta + 自包含 script + args 示例),修复 0.3.3 在 rc7 上「invalid plugin / 插件树加载失败 / harness 无法启动」的问题(旧入口只导出 load/workflow/parsers/schemas,无 apply)。
10
+ - **workflow script 自包含**:四个解析器(book/paper/video/web)的 `buildPrompt` 及其依赖的 `buildFetchPrompt` 在构建时内联进 script(修正内联后的 `prompt` 闭包引用),不再依赖宿主注入 `args._parsers`(rc7 的 workflow 工具只暴露 args JSON,不会注入);保留 `args._parsers` 回退(宿主注入时优先)。
11
+ - 旧的 `load()` 接口保留以兼容旧式读取;minVersion 0.1.0。
12
+
13
+ ## [0.3.3] — 2026-08-25
14
+
15
+ ### Fixed
16
+ - lib/cache.js:URL 归一化真正去掉尾部空 query(`doc` 与 `doc?` 现在共享指纹;此前 `url.search === "?"` 是死代码,`doc?` 会生成不同指纹导致幂等缓存失效)
17
+ - lib/cache.js:`fingerprint` 用 `??` 替代 `||`,空文件(size=0)不再与「无 meta」混淆
18
+ - workflow.js:`tempFile` 拼接先去掉 `tempDir` 尾部斜杠,避免 `./.tmp//input.txt` 双斜杠路径(与 parsers/_prompt.js 的 0.3.2 修复对齐)
19
+ - tests:+2 用例(URL 尾部 `?` 归一、size=0 指纹区分),25/25 通过;均由 DSH 代码审查发现
20
+
21
+ ## [0.3.2] — 2026-08-23
22
+
23
+ ### Fixed
24
+ - parsers/_prompt.js:目标文件路径优先使用调用方传入的 `tempFile`,回退路径统一正斜杠,修复 macOS/Linux 上硬编码 Windows 反斜杠导致的路径错误(issue #1,由 DSH 代码审查发现)
25
+ - lib/cache.js:`markProcessed` 写缓存失败不再抛错中断主流程(降级为告警并返回 false);`hasProcessed` 支持可选 TTL(`maxAgeMs`)过期判定(issue #2,由 DSH 代码审查发现)
26
+
27
+ ## [0.3.1] — 2026-08-21
28
+
29
+ ### Fixed
30
+ - 发布前检查:移除 README 中的本地 Obsidian 仓库绝对路径(改为参数化描述)
31
+ - 移除 docs/RELEASE.md 中的本机绝对路径(改为通用写法)
32
+ - README 同步版本号:tgz 0.2.0 → 0.3.0、测试 17 → 21 项
33
+
34
+ ## [0.3.0] — 2026-08-21
35
+
36
+ ### Added
37
+ - 幂等缓存 URL 规范化(normalizeInput):host 大小写 / 默认端口 / fragment / 尾部斜杠归一,同一 URL 不同写法共享指纹
38
+ - 安全扫描覆盖 .env.example 与 forward-slash 用户路径;导出 scanDir 供测试调用
39
+ - 测试 17 → 21:parser 模板回归、URL 规范化、安全扫描正/负样本
40
+
41
+ ### Changed
42
+ - parsers 四解析器去重:抽取共享提示词模板 parsers/_prompt.js(buildPrompt 输出逐字不变,经新旧对比验证)
43
+ - lint 排除 .tmp*/dist/coverage 等临时目录
44
+ - CI 增加 Node 18/20/22 版本矩阵
45
+ - package.json 增加 publishConfig.access=public(显式公开发布)
46
+ - docs/RELEASE.md 增加 npm 发布流程与版本速览;README 开发节补充发布门禁说明
47
+
48
+ ### Fixed
49
+ - security-check 对测试样本误报(样本改为拼接构造,源码不含完整密钥模式)
50
+
51
+ ## [0.2.0] — 2026-08-21
52
+
53
+ ### Added
54
+ - 首次发布到 npm registry(`npm install deep-read-summarize`),含此前未发布的 0.1.1 变更
55
+ - prepublishOnly 质量门禁:发布前自动跑 17 项测试 + lint + 安全检查
56
+
57
+ ### Changed
58
+ - package.json version 对齐 git tag(0.1.0 → 0.2.0)
59
+ - keywords 移除 `deepseek-harness` 商标词(安全合规要求,与 v0.1.0 决策一致)
60
+ - README 补充 npm 安装方式
61
+
62
+ ### Fixed
63
+ - git 历史整理:以本地完整开发历史为准 force push 覆盖 API 拼凑历史,补上缺失的 `.github/workflows/ci.yml`
64
+
65
+ ## [0.1.1] — 2026-08-19
66
+
67
+ ### Added
68
+ - DSH 插件化:cordis.patch.yml(bundle patch)、index.js 插件入口、skills/ 打包
69
+ - node:test 风格测试(tests/index.test.js,`npm run test:node`)
70
+
71
+ ### Changed
72
+ - package.json:dsh.bundle 字段、exports、repository、keywords 完善
73
+ - 废弃 cordis.yml → 由 cordis.patch.yml 替代
74
+
75
+ ## [0.1.0] — 2026-08-18
76
+
77
+ ### Added
78
+ - 首个公开预发布版(pre-release)
79
+ - 四种输入解析器插件:书籍/论文/视频/网页
80
+ - 三波次 MapReduce 精读流水线
81
+ - JSON Schema 结构化输出约束
82
+ - 幂等缓存(lib/cache.js)
83
+ - 失败分级(FATAL vs 可降级)
84
+ - 质量校验循环
85
+ - CI(lint + 测试 + Gitleaks 密钥扫描)
86
+ - README/SECURITY/CONTRIBUTING/CHANGELOG 文档
87
+
88
+ ## [3.0.0] — 2026-08-18
89
+
90
+ ### Added
91
+ - Plugin parser architecture: `parsers/` registry with book/paper/video/web adapters
92
+ - JSON Schema structured output constraints (`schemas/index.js`)
93
+ - Failure discipline: FATAL (config) vs degradable (content) error classes
94
+ - Quality control loop with retry (`maxRetries`)
95
+ - Configurable citations (`requireCitations`) and video timestamps (`includeTimestamps`)
96
+ - Fixture-driven test suite (`npm test`, 10 tests)
97
+ - Quick validation script (`npm run validate`)
98
+ - CI workflow (lint + tests)
99
+ - cordis.yml plugin tree example
100
+
101
+ ### Changed
102
+ - Workflow reduced to 3 serial waves (fetch/chunk → parallel read → merge+QC)
103
+ - Subagent count reduced to N+2~3
104
+ - Defaults changed to general-purpose: `requireCitations: true`, `includeTimestamps: false`
105
+
106
+ ### Removed
107
+ - Standalone quality-check subagent (merged into wave 3 + optional lightweight retry)
108
+
109
+ ## [2.1.0] — 2026-08-18
110
+
111
+ ### Added
112
+ - One-click write-to-Obsidian from the draft agent
113
+ - fastMode (skip sections 5-7)
114
+
115
+ ## [2.0.0] — 2026-08-18
116
+
117
+ ### Changed
118
+ - Merged identify+fetch+chunk into one subagent (3 waves total)
119
+ - Removed standalone QC subagent
120
+
121
+ ## [1.1.0] — 2026-08-18
122
+
123
+ ### Fixed
124
+ - Long-content overflow: write-to-temp-file + line-range chunking
125
+
126
+ ## [1.0.0] — 2026-08-18
127
+
128
+ ### Added
129
+ - Initial deep-reading pipeline (5 serial waves)
130
+ - Template prompts for books/papers/videos/web
110
131
  - Obsidian note template with YAML frontmatter
package/README.md CHANGED
@@ -1,4 +1,10 @@
1
1
  # deep-read-summarize
2
+
3
+ [![MIT license](https://img.shields.io/github/license/PensiveFei/deep-read-summarize)](https://github.com/PensiveFei/deep-read-summarize/blob/main/LICENSE)
4
+ [![release](https://img.shields.io/github/v/release/PensiveFei/deep-read-summarize)](https://github.com/PensiveFei/deep-read-summarize/releases)
5
+ [![CI](https://img.shields.io/github/actions/workflow/status/PensiveFei/deep-read-summarize/ci.yml)](https://github.com/PensiveFei/deep-read-summarize/actions/workflows/ci.yml)
6
+ [![npm downloads](https://img.shields.io/npm/dw/deep-read-summarize)](https://www.npmjs.com/package/deep-read-summarize)
7
+
2
8
  > **Disclaimer**: This is an **unofficial third-party tool**. It is not affiliated with, endorsed by, or sponsored by DeepSeek or the DeepSeek Harness project. "DeepSeek" and "DeepSeek Harness" are trademarks of their respective owners. This project only orchestrates the workflow tool available in your DSH environment; it does not redistribute any DeepSeek software.
3
9
 
4
10
  给 DSH(DeepSeek Harness)写的一个精读工作流:输入一本书、一篇论文、一个视频链接或网页,输出一份结构化的 Obsidian 笔记。
@@ -77,7 +83,7 @@ deep-read-summarize 是 DSH 插件,可通过 npm、dsh.so 生态或本地安
77
83
  npm install deep-read-summarize
78
84
 
79
85
  # 或本地安装(dsh profile 目录)
80
- pnpm add ./deep-read-summarize-0.3.0.tgz
86
+ pnpm add ./deep-read-summarize-0.3.4.tgz
81
87
  # 然后在 dsh 配置的 dsh.profile.bundles 追加:
82
88
  # - deep-read-summarize
83
89
  # 重启 dsh web 即可(POST /dsh-market/restart)
@@ -106,10 +112,10 @@ npm install # 无第三方依赖,仅初始化
106
112
  ### 2. 验证环境(离线,不需要任何 API key)
107
113
 
108
114
  ```bash
109
- npm test # 21 项 fixture 测试,全部离线跑通
115
+ npm test # 25 项 fixture 测试,全部离线跑通
110
116
  ```
111
117
 
112
- 看到 `TOTAL: 21 passed, 0 failed` 即环境就绪。
118
+ 看到 `TOTAL: 25 passed, 0 failed` 即环境就绪。
113
119
 
114
120
  ### 3. 一行命令喂入 demo 文件
115
121
 
@@ -198,7 +204,7 @@ parsers: book, paper, video, web
198
204
  ```bash
199
205
  npm install
200
206
  npm run lint # node --check 全部 JS
201
- npm test # fixture 测试(21 项,全部离线)
207
+ npm test # fixture 测试(25 项,全部离线)
202
208
  npm run validate # 发布前验证(含安全检查)
203
209
  ```
204
210
 
package/index.js CHANGED
@@ -1,32 +1,73 @@
1
1
  // ============================================================================
2
2
  // deep-read-summarize — DSH plugin entry
3
3
  // ============================================================================
4
- // 导出 workflow (meta + script) 和解析器注册表,供 dsh 加载器识别。
4
+ // 标准 Cordis 插件(DSH 0.1.x / rc7 契约):导出 name + inject + apply(ctx)。
5
+ // apply() 将插件自带的 SKILL.md 注册为运行时技能,并把 workflow 的
6
+ // meta + 自包含 script + args 示例嵌入技能内容,使模型可直接用 workflow
7
+ // 工具执行精读流程。
8
+ //
9
+ // 同时保留 load / workflow / parsers / schemas 导出,兼容旧式加载读取。
5
10
  // 安装方式(dsh profile 目录): pnpm add ./xxx.tgz → dsh.profile.bundles 追加
6
11
  // ============================================================================
7
12
 
13
+ const { readFileSync } = require('node:fs');
14
+ const path = require('node:path');
15
+
8
16
  const workflow = require('./workflow');
9
17
  const parsers = require('./parsers');
10
18
  const schemas = require('./schemas');
11
19
 
12
- /**
13
- * 插件主入口:返回 dsh 可加载的插件定义
14
- * - name: 插件名(对应 cordis.patch.yml 的 id)
15
- * - meta: workflow 元信息(name/description/whenToUse/phases)
16
- * - script: workflow 脚本(供 workflow 工具执行)
17
- * - parsers: 解析器注册表(resolve/list)
18
- * - schemas: JSON Schema 约束
19
- */
20
- function load() {
21
- return {
20
+ module.exports.name = 'deep-read-summarize';
21
+ module.exports.inject = ['skills'];
22
+
23
+ /** 组装技能内容:SKILL.md + workflow meta/script/args 示例(script 为自包含版本)。 */
24
+ function buildSkillContent() {
25
+ const skillDir = path.join(__dirname, 'skills', 'deep-read-summarize');
26
+ const body = readFileSync(path.join(skillDir, 'SKILL.md'), 'utf8');
27
+ return [
28
+ body.trim(),
29
+ '',
30
+ '## 使用 workflow 工具执行',
31
+ '当用户给出书籍/论文/视频/网页并要求深度精读时,调用 `workflow` 工具,按下面的 meta + script + args 提交。',
32
+ '',
33
+ 'meta:',
34
+ '```json',
35
+ JSON.stringify(workflow.meta, null, 2),
36
+ '```',
37
+ '',
38
+ 'script(完整脚本,原样填入 script 参数;脚本已自包含四个解析器,无需宿主注入):',
39
+ '```javascript',
40
+ workflow.script,
41
+ '```',
42
+ '',
43
+ 'args 示例:',
44
+ '```json',
45
+ '{ "input": "<链接或本地路径>", "type": "auto", "options": { "minWords": 2500, "fastMode": false, "maxChunks": 6, "requireCitations": true, "includeTimestamps": false, "outputDir": "./output", "tempDir": "./.tmp" } }',
46
+ '```'
47
+ ].join('\n');
48
+ }
49
+
50
+ /** rc7 Cordis 插件入口:注册运行时技能,使模型可直接执行精读 workflow。 */
51
+ function apply(ctx, config = {}) {
52
+ const skillDir = path.join(__dirname, 'skills', 'deep-read-summarize');
53
+ return ctx.skills.register({
22
54
  name: 'deep-read-summarize',
23
- workflow: workflow,
24
- parsers: parsers,
25
- schemas: schemas
26
- };
55
+ description: workflow.meta.description,
56
+ whenToUse: workflow.meta.whenToUse,
57
+ content: buildSkillContent(),
58
+ resourceBase: { kind: 'directory', path: skillDir },
59
+ source: 'plugin:deep-read-summarize'
60
+ });
27
61
  }
28
62
 
29
- module.exports = { load, workflow, parsers, schemas };
63
+ // 兼容旧式加载(部分工具按 load() 读取插件定义)
64
+ function load() {
65
+ return { name: 'deep-read-summarize', workflow, parsers, schemas };
66
+ }
30
67
 
31
- // 兼容直接 require:插件系统可能直接读取 exports
32
- module.exports.default = load;
68
+ module.exports.apply = apply;
69
+ module.exports.load = load;
70
+ module.exports.workflow = workflow;
71
+ module.exports.parsers = parsers;
72
+ module.exports.schemas = schemas;
73
+ module.exports.buildSkillContent = buildSkillContent;
package/lib/cache.js CHANGED
@@ -1,87 +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.search === "?") url.search = "";
35
- if (url.pathname.length > 1 && url.pathname.endsWith("/")) {
36
- url.pathname = url.pathname.slice(0, -1);
37
- }
38
- return url.toString();
39
- } catch (e) {
40
- return s; // 非法 URL 原样处理
41
- }
42
- }
43
-
44
- /** 计算输入指纹:URL 规范化后 hash;本地文件加大小 + 修改时间 */
45
- function fingerprint(input, fileMeta) {
46
- const base = normalizeInput(input);
47
- if (!base) return null;
48
- const metaStr = fileMeta
49
- ? "|" + (fileMeta.size || "") + "|" + (fileMeta.mtimeMs || "")
50
- : "";
51
- return crypto.createHash("sha256").update(base + metaStr).digest("hex").slice(0, 16);
52
- }
53
-
54
- /** 从缓存文件读取已处理记录(JSONL) */
55
- function readCache(cacheFile) {
56
- if (!fs.existsSync(cacheFile)) return new Map();
57
- const map = new Map();
58
- try {
59
- const lines = fs.readFileSync(cacheFile, "utf8").split("\n");
60
- for (const line of lines) {
61
- if (!line.trim()) continue;
62
- try {
63
- const rec = JSON.parse(line);
64
- if (rec && rec.key) map.set(rec.key, rec);
65
- } catch (e) { /* 跳过损坏行 */ }
66
- }
67
- } catch (e) { /* 缓存不可读则视为空 */ }
68
- return map;
69
- }
70
-
71
- /** 是否已处理过该指纹 */
72
- function hasProcessed(cacheFile, key) {
73
- if (!key) return false;
74
- return readCache(cacheFile).has(key);
75
- }
76
-
77
- /** 标记已处理(追加 JSONL 记录) */
78
- function markProcessed(cacheFile, key, outputPath, meta) {
79
- if (!key) return false;
80
- const dir = path.dirname(cacheFile);
81
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
82
- const rec = { key, outputPath, ts: new Date().toISOString(), ...(meta || {}) };
83
- fs.appendFileSync(cacheFile, JSON.stringify(rec) + "\n", "utf8");
84
- return true;
85
- }
86
-
87
- 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 };
package/package.json CHANGED
@@ -1,69 +1,69 @@
1
- {
2
- "name": "deep-read-summarize",
3
- "version": "0.3.1",
4
- "description": "Deep reading & summarization for DSH: books/papers/videos/web → structured Obsidian notes. Plugin parsers, MapReduce deep-read, JSON Schema output, idempotent cache.",
5
- "type": "commonjs",
6
- "main": "index.js",
7
- "exports": {
8
- ".": "./index.js",
9
- "./workflow": "./workflow.js",
10
- "./parsers": "./parsers/index.js",
11
- "./schemas": "./schemas/index.js",
12
- "./package.json": "./package.json"
13
- },
14
- "files": [
15
- "index.js",
16
- "workflow.js",
17
- "parsers",
18
- "schemas",
19
- "lib",
20
- "skills",
21
- "scripts",
22
- "tests",
23
- "docs",
24
- "cordis.patch.yml",
25
- "CHANGELOG.md",
26
- "README.md",
27
- "LICENSE",
28
- "SECURITY.md",
29
- ".env.example"
30
- ],
31
- "scripts": {
32
- "test": "node tests/run-tests.js",
33
- "lint": "node scripts/lint.js",
34
- "validate": "node tests/quick_validate.js && node scripts/security-check.js",
35
- "security": "node scripts/security-check.js",
36
- "test:node": "node --test tests/",
37
- "prepublishOnly": "node tests/run-tests.js && node scripts/lint.js && node scripts/security-check.js"
38
- },
39
- "dsh": {
40
- "bundle": {
41
- "patch": "./cordis.patch.yml"
42
- },
43
- "lockedRuntime": "workflow tool semantics — see CHANGELOG.md",
44
- "minVersion": "0.1.0",
45
- "breakingPolicy": "re-validate with npm test after each DSH upgrade"
46
- },
47
- "keywords": [
48
- "dsh",
49
- "workflow",
50
- "summarization",
51
- "deep-read",
52
- "obsidian",
53
- "llm",
54
- "subagent",
55
- "mapreduce",
56
- "parsers"
57
- ],
58
- "license": "MIT",
59
- "publishConfig": {
60
- "access": "public"
61
- },
62
- "engines": {
63
- "node": ">=18"
64
- },
65
- "repository": {
66
- "type": "git",
67
- "url": "git+https://github.com/PensiveFei/deep-read-summarize.git"
68
- }
69
- }
1
+ {
2
+ "name": "deep-read-summarize",
3
+ "version": "0.3.4",
4
+ "description": "Deep reading & summarization for DSH: books/papers/videos/web → structured Obsidian notes. Plugin parsers, MapReduce deep-read, JSON Schema output, idempotent cache.",
5
+ "type": "commonjs",
6
+ "main": "index.js",
7
+ "exports": {
8
+ ".": "./index.js",
9
+ "./workflow": "./workflow.js",
10
+ "./parsers": "./parsers/index.js",
11
+ "./schemas": "./schemas/index.js",
12
+ "./package.json": "./package.json"
13
+ },
14
+ "files": [
15
+ "index.js",
16
+ "workflow.js",
17
+ "parsers",
18
+ "schemas",
19
+ "lib",
20
+ "skills",
21
+ "scripts",
22
+ "tests",
23
+ "docs",
24
+ "cordis.patch.yml",
25
+ "CHANGELOG.md",
26
+ "README.md",
27
+ "LICENSE",
28
+ "SECURITY.md",
29
+ ".env.example"
30
+ ],
31
+ "scripts": {
32
+ "test": "node tests/run-tests.js",
33
+ "lint": "node scripts/lint.js",
34
+ "validate": "node tests/quick_validate.js && node scripts/security-check.js",
35
+ "security": "node scripts/security-check.js",
36
+ "test:node": "node --test tests/",
37
+ "prepublishOnly": "node tests/run-tests.js && node scripts/lint.js && node scripts/security-check.js"
38
+ },
39
+ "dsh": {
40
+ "bundle": {
41
+ "patch": "./cordis.patch.yml"
42
+ },
43
+ "lockedRuntime": "workflow tool semantics — see CHANGELOG.md",
44
+ "minVersion": "0.1.0",
45
+ "breakingPolicy": "re-validate with npm test after each DSH upgrade"
46
+ },
47
+ "keywords": [
48
+ "dsh",
49
+ "workflow",
50
+ "summarization",
51
+ "deep-read",
52
+ "obsidian",
53
+ "llm",
54
+ "subagent",
55
+ "mapreduce",
56
+ "parsers"
57
+ ],
58
+ "license": "MIT",
59
+ "publishConfig": {
60
+ "access": "public"
61
+ },
62
+ "engines": {
63
+ "node": ">=18"
64
+ },
65
+ "repository": {
66
+ "type": "git",
67
+ "url": "git+https://github.com/PensiveFei/deep-read-summarize.git"
68
+ }
69
+ }
@@ -1,44 +1,44 @@
1
- // ============================================================================
2
- // parsers/_prompt.js — 共享「获取+分块」提示词模板(内部模块)
3
- // ============================================================================
4
- // 四个内置解析器共用同一提示词骨架,各自只提供差异化配置:
5
- // - label/kindLabel:类型名称(中文 / 中英混合)
6
- // - steps:获取文本的具体步骤(不含分块步骤,模板自动编号)
7
- // - chunkRule:分块规则描述
8
- // - jsonExample:输出 JSON 示例(含 kind 字段)
9
- // 保持各解析器 buildPrompt(input, opts) 插件接口不变;fork 时仍可整体重写。
10
- // ============================================================================
11
-
12
- /**
13
- * 构建「获取+分块」提示词。
14
- * @param {object} cfg
15
- * @param {string} cfg.input 输入(URL 或本地路径)
16
- * @param {object} [cfg.opts] 选项(tempDir/tempFile/maxChunks)
17
- * @param {string} cfg.fetchTarget 获取对象描述(如「书籍全文」「视频字幕/转写」)
18
- * @param {string} cfg.kindLabel 内容类型描述(如「书籍(book)」)
19
- * @param {string[]} cfg.steps 获取步骤(不含分块步骤;模板统一编号并追加分块步骤)
20
- * @param {string} cfg.chunkRule 分块规则(如「章节(或章节内小节)」)
21
- * @param {string} cfg.jsonExample 输出 JSON 示例
22
- * @returns {string} 完整提示词
23
- */
24
- function buildFetchPrompt(cfg) {
25
- const opts = cfg.opts || {};
26
- const tempDir = opts.tempDir || "./.tmp";
27
- const tempFile = tempDir + "\\input.txt";
28
- const maxChunks = opts.maxChunks || 6;
29
- const steps = (cfg.steps || []).map(function (s, i) { return (i + 1) + ". " + s; });
30
- return [
31
- "你的任务:获取" + cfg.fetchTarget + "并保存为纯文本,然后给出分块计划。",
32
- "内容类型:" + cfg.kindLabel,
33
- "输入来源:" + cfg.input,
34
- "目标文件:" + tempFile + "(先创建目录 " + tempDir + ",用 write 工具写入)",
35
- "步骤:"
36
- ].concat(steps, [
37
- (steps.length + 1) + ". 分块:按" + cfg.chunkRule + "切分,每块约 100-200 行或 4000-6000 字,块数不超过 " + maxChunks + " 块;每块给 id/topic/startLine/endLine。",
38
- "输出 JSON:",
39
- cfg.jsonExample,
40
- "若无法获取文本输出 { \"saved\": false, \"message\": \"原因\" }。只输出 JSON。"
41
- ]).join("\n");
42
- }
43
-
44
- module.exports = { buildFetchPrompt };
1
+ // ============================================================================
2
+ // parsers/_prompt.js — 共享「获取+分块」提示词模板(内部模块)
3
+ // ============================================================================
4
+ // 四个内置解析器共用同一提示词骨架,各自只提供差异化配置:
5
+ // - label/kindLabel:类型名称(中文 / 中英混合)
6
+ // - steps:获取文本的具体步骤(不含分块步骤,模板自动编号)
7
+ // - chunkRule:分块规则描述
8
+ // - jsonExample:输出 JSON 示例(含 kind 字段)
9
+ // 保持各解析器 buildPrompt(input, opts) 插件接口不变;fork 时仍可整体重写。
10
+ // ============================================================================
11
+
12
+ /**
13
+ * 构建「获取+分块」提示词。
14
+ * @param {object} cfg
15
+ * @param {string} cfg.input 输入(URL 或本地路径)
16
+ * @param {object} [cfg.opts] 选项(tempDir/tempFile/maxChunks)
17
+ * @param {string} cfg.fetchTarget 获取对象描述(如「书籍全文」「视频字幕/转写」)
18
+ * @param {string} cfg.kindLabel 内容类型描述(如「书籍(book)」)
19
+ * @param {string[]} cfg.steps 获取步骤(不含分块步骤;模板统一编号并追加分块步骤)
20
+ * @param {string} cfg.chunkRule 分块规则(如「章节(或章节内小节)」)
21
+ * @param {string} cfg.jsonExample 输出 JSON 示例
22
+ * @returns {string} 完整提示词
23
+ */
24
+ function buildFetchPrompt(cfg) {
25
+ const opts = cfg.opts || {};
26
+ const tempDir = opts.tempDir || "./.tmp";
27
+ const tempFile = opts.tempFile || (tempDir.replace(/[\\/]+$/, "") + "/input.txt");
28
+ const maxChunks = opts.maxChunks || 6;
29
+ const steps = (cfg.steps || []).map(function (s, i) { return (i + 1) + ". " + s; });
30
+ return [
31
+ "你的任务:获取" + cfg.fetchTarget + "并保存为纯文本,然后给出分块计划。",
32
+ "内容类型:" + cfg.kindLabel,
33
+ "输入来源:" + cfg.input,
34
+ "目标文件:" + tempFile + "(先创建目录 " + tempDir + ",用 write 工具写入)",
35
+ "步骤:"
36
+ ].concat(steps, [
37
+ (steps.length + 1) + ". 分块:按" + cfg.chunkRule + "切分,每块约 100-200 行或 4000-6000 字,块数不超过 " + maxChunks + " 块;每块给 id/topic/startLine/endLine。",
38
+ "输出 JSON:",
39
+ cfg.jsonExample,
40
+ "若无法获取文本输出 { \"saved\": false, \"message\": \"原因\" }。只输出 JSON。"
41
+ ]).join("\n");
42
+ }
43
+
44
+ module.exports = { buildFetchPrompt };
@@ -1,83 +1,117 @@
1
- // tests/cache.test.js — idempotency cache tests
2
- const assert = require('assert');
3
- const fs = require('fs');
4
- const os = require('os');
5
- const path = require('path');
6
- const cache = require('../lib/cache');
7
-
8
- let passed = 0, failed = 0;
9
- function test(name, fn) {
10
- try { fn(); passed++; console.log(' ✅', name); }
11
- catch (e) { failed++; console.error(' ❌', name, '—', e.message); }
12
- }
13
-
14
- const tmp = path.join(os.tmpdir(), 'drs-cache-test-' + Date.now());
15
- const cacheFile = path.join(tmp, 'cache.jsonl');
16
-
17
- test('fingerprint is deterministic for same input', () => {
18
- const a = cache.fingerprint('https://arxiv.org/abs/2307.09042');
19
- const b = cache.fingerprint('https://arxiv.org/abs/2307.09042');
20
- assert.strictEqual(a, b);
21
- assert.ok(a && a.length >= 16);
22
- });
23
-
24
- test('fingerprint differs for different inputs', () => {
25
- const a = cache.fingerprint('input-a');
26
- const b = cache.fingerprint('input-b');
27
- assert.notStrictEqual(a, b);
28
- });
29
-
30
- test('fingerprint normalizes URL variants', () => {
31
- const a = cache.fingerprint('https://EXAMPLE.com/doc/');
32
- const b = cache.fingerprint('https://example.com/doc#frag');
33
- assert.strictEqual(a, b, 'URL variants (case/slash/fragment) should share fingerprint');
34
- const c = cache.fingerprint('https://example.com/doc?x=1');
35
- assert.notStrictEqual(a, c, 'different query should produce different fingerprint');
36
- });
37
-
38
- test('normalizeInput keeps non-URL input and root path unchanged', () => {
39
- assert.strictEqual(cache.normalizeInput('C:\\Users\\x\\doc.md'), 'C:\\Users\\x\\doc.md');
40
- assert.strictEqual(cache.normalizeInput('https://example.com/'), 'https://example.com/');
41
- assert.strictEqual(cache.normalizeInput(' '), '');
42
- });
43
-
44
- test('fingerprint includes file meta for local files', () => {
45
- const f = path.join(tmp, 'sample.txt');
46
- fs.mkdirSync(tmp, { recursive: true });
47
- fs.writeFileSync(f, 'hello');
48
- const st = fs.statSync(f);
49
- const a = cache.fingerprint(f, { size: st.size, mtimeMs: st.mtimeMs });
50
- const b = cache.fingerprint(f, { size: st.size + 1, mtimeMs: st.mtimeMs });
51
- assert.notStrictEqual(a, b, 'size change should change fingerprint');
52
- });
53
-
54
- test('hasProcessed returns false for unknown key', () => {
55
- assert.strictEqual(cache.hasProcessed(cacheFile, 'unknown-key'), false);
56
- });
57
-
58
- test('markProcessed then hasProcessed returns true', () => {
59
- const key = cache.fingerprint('https://example.com/doc');
60
- cache.markProcessed(cacheFile, key, '/tmp/out.md');
61
- assert.strictEqual(cache.hasProcessed(cacheFile, key), true);
62
- });
63
-
64
- test('cache file is JSONL (append-only)', () => {
65
- const raw = fs.readFileSync(cacheFile, 'utf8').trim().split('\n');
66
- assert.ok(raw.length >= 1);
67
- const rec = JSON.parse(raw[0]);
68
- assert.ok(rec.key && rec.outputPath && rec.ts);
69
- });
70
-
71
- test('corrupted line is skipped', () => {
72
- fs.appendFileSync(cacheFile, '{broken json}\n', 'utf8');
73
- const map = cache.readCache(cacheFile);
74
- assert.ok(map.size >= 1, 'should still read valid lines');
75
- });
76
-
77
- // cleanup
78
- fs.rmSync(tmp, { recursive: true, force: true });
79
-
80
- console.log('');
81
- console.log(passed + ' cache tests passed, ' + failed + ' failed');
82
- if (require.main === module) process.exit(failed ? 1 : 0);
1
+ // tests/cache.test.js — idempotency cache tests
2
+ const assert = require('assert');
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+ const cache = require('../lib/cache');
7
+
8
+ let passed = 0, failed = 0;
9
+ function test(name, fn) {
10
+ try { fn(); passed++; console.log(' ✅', name); }
11
+ catch (e) { failed++; console.error(' ❌', name, '—', e.message); }
12
+ }
13
+
14
+ const tmp = path.join(os.tmpdir(), 'drs-cache-test-' + Date.now());
15
+ const cacheFile = path.join(tmp, 'cache.jsonl');
16
+
17
+ test('fingerprint is deterministic for same input', () => {
18
+ const a = cache.fingerprint('https://arxiv.org/abs/2307.09042');
19
+ const b = cache.fingerprint('https://arxiv.org/abs/2307.09042');
20
+ assert.strictEqual(a, b);
21
+ assert.ok(a && a.length >= 16);
22
+ });
23
+
24
+ test('fingerprint differs for different inputs', () => {
25
+ const a = cache.fingerprint('input-a');
26
+ const b = cache.fingerprint('input-b');
27
+ assert.notStrictEqual(a, b);
28
+ });
29
+
30
+ test('fingerprint normalizes URL variants', () => {
31
+ const a = cache.fingerprint('https://EXAMPLE.com/doc/');
32
+ const b = cache.fingerprint('https://example.com/doc#frag');
33
+ assert.strictEqual(a, b, 'URL variants (case/slash/fragment) should share fingerprint');
34
+ const c = cache.fingerprint('https://example.com/doc?x=1');
35
+ assert.notStrictEqual(a, c, 'different query should produce different fingerprint');
36
+ });
37
+
38
+ test('fingerprint normalizes trailing empty query (doc vs doc?)', () => {
39
+ const a = cache.fingerprint('https://example.com/doc');
40
+ const b = cache.fingerprint('https://example.com/doc?');
41
+ assert.strictEqual(a, b, 'trailing "?" (empty query) should not create a distinct fingerprint');
42
+ assert.strictEqual(cache.normalizeInput('https://example.com/doc?'), 'https://example.com/doc');
43
+ });
44
+
45
+ test('fingerprint keeps size 0 distinct from absent meta', () => {
46
+ // 空文件(size=0)与「无 meta」不应共享指纹;0 值必须参与拼接
47
+ const zero = cache.fingerprint('path-to-empty-file', { size: 0, mtimeMs: 123 });
48
+ const absent = cache.fingerprint('path-to-empty-file');
49
+ assert.notStrictEqual(zero, absent, 'size=0 must not collapse into absent meta');
50
+ const five = cache.fingerprint('path-to-empty-file', { size: 5, mtimeMs: 123 });
51
+ assert.notStrictEqual(zero, five, 'size 0 vs 5 must differ');
52
+ });
53
+
54
+ test('normalizeInput keeps non-URL input and root path unchanged', () => {
55
+ assert.strictEqual(cache.normalizeInput('C:\\Users\\x\\doc.md'), 'C:\\Users\\x\\doc.md');
56
+ assert.strictEqual(cache.normalizeInput('https://example.com/'), 'https://example.com/');
57
+ assert.strictEqual(cache.normalizeInput(' '), '');
58
+ });
59
+
60
+ test('fingerprint includes file meta for local files', () => {
61
+ const f = path.join(tmp, 'sample.txt');
62
+ fs.mkdirSync(tmp, { recursive: true });
63
+ fs.writeFileSync(f, 'hello');
64
+ const st = fs.statSync(f);
65
+ const a = cache.fingerprint(f, { size: st.size, mtimeMs: st.mtimeMs });
66
+ const b = cache.fingerprint(f, { size: st.size + 1, mtimeMs: st.mtimeMs });
67
+ assert.notStrictEqual(a, b, 'size change should change fingerprint');
68
+ });
69
+
70
+ test('hasProcessed returns false for unknown key', () => {
71
+ assert.strictEqual(cache.hasProcessed(cacheFile, 'unknown-key'), false);
72
+ });
73
+
74
+ test('markProcessed then hasProcessed returns true', () => {
75
+ const key = cache.fingerprint('https://example.com/doc');
76
+ cache.markProcessed(cacheFile, key, '/tmp/out.md');
77
+ assert.strictEqual(cache.hasProcessed(cacheFile, key), true);
78
+ });
79
+
80
+ test('cache file is JSONL (append-only)', () => {
81
+ const raw = fs.readFileSync(cacheFile, 'utf8').trim().split('\n');
82
+ assert.ok(raw.length >= 1);
83
+ const rec = JSON.parse(raw[0]);
84
+ assert.ok(rec.key && rec.outputPath && rec.ts);
85
+ });
86
+
87
+ test('corrupted line is skipped', () => {
88
+ fs.appendFileSync(cacheFile, '{broken json}\n', 'utf8');
89
+ const map = cache.readCache(cacheFile);
90
+ assert.ok(map.size >= 1, 'should still read valid lines');
91
+ });
92
+
93
+ test('hasProcessed TTL: stale record is treated as unprocessed', () => {
94
+ const key = cache.fingerprint('https://example.com/stale');
95
+ cache.markProcessed(cacheFile, key, '/tmp/stale.md', { ts: '2020-01-01T00:00:00.000Z' });
96
+ assert.strictEqual(cache.hasProcessed(cacheFile, key), true, 'no TTL -> still processed');
97
+ assert.strictEqual(cache.hasProcessed(cacheFile, key, { maxAgeMs: 60 * 1000 }), false, 'stale -> unprocessed');
98
+ assert.strictEqual(cache.hasProcessed(cacheFile, key, { maxAgeMs: 1e12 }), true, 'recent enough -> processed');
99
+ });
100
+
101
+ test('markProcessed tolerates unwritable cache location', () => {
102
+ const blocker = path.join(tmp, 'blocked-file');
103
+ fs.writeFileSync(blocker, 'x');
104
+ const badFile = path.join(blocker, 'cache.jsonl');
105
+ let threw = false, ret = null;
106
+ try { ret = cache.markProcessed(badFile, 'some-key', '/out.md'); } catch (e) { threw = true; }
107
+ assert.strictEqual(threw, false, 'should not throw');
108
+ assert.strictEqual(ret, false, 'should report failure instead');
109
+ });
110
+
111
+ // cleanup
112
+ fs.rmSync(tmp, { recursive: true, force: true });
113
+
114
+ console.log('');
115
+ console.log(passed + ' cache tests passed, ' + failed + ' failed');
116
+ if (require.main === module) process.exit(failed ? 1 : 0);
83
117
  module.exports = { passed, failed };
package/workflow.js CHANGED
@@ -35,9 +35,43 @@ const meta = {
35
35
  };
36
36
 
37
37
  // ===== script(复制到 workflow 工具的 script 参数)=====
38
- const 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 || 6, 12));\nconst requireCitations = options.requireCitations !== false;\nconst includeTimestamps = !!options.includeTimestamps;\nconst maxRetries = options.maxRetries || 1;\nconst cacheEnabled = options.cache !== false;\nconst outputDir = options.outputDir || \"./output\";\nconst tempDir = options.tempDir || \"./.tmp\";\nconst tempFile = tempDir + \"/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 });\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) || {};\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 deepReads = await parallel(chunkPrompts.map(function (p) {\n return function () { return agent(p, { label: \"精读块\", phase: \"并行精读\" }); };\n}));\nconst validReads = deepReads.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 note: verified\n};";
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 || 6, 12));\nconst requireCitations = options.requireCitations !== false;\nconst includeTimestamps = !!options.includeTimestamps;\nconst maxRetries = options.maxRetries || 1;\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 });\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) || {};\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 deepReads = await parallel(chunkPrompts.map(function (p) {\n return function () { return agent(p, { label: \"精读块\", phase: \"并行精读\" }); };\n}));\nconst validReads = deepReads.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 note: verified\n};";
39
39
 
40
40
  // ===== parsers 注册表(运行时注入,实现插件化)=====
41
41
  const parsers = require("./parsers");
42
+ const promptImpl = require("./parsers/_prompt");
43
+ const parserRegistry = parsers.registry;
42
44
 
43
- module.exports = { meta, script, parsers };
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
+
77
+ module.exports = { meta, script, parsers, buildSelfContainedScript };