@wwkit/harness 1.0.42 → 1.0.43

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.
Files changed (44) hide show
  1. package/package.json +1 -1
  2. package/skills/better-class/SKILL.md +1 -1
  3. package/skills/better-class/references/subagent-prompt.md +1 -1
  4. package/skills/better-class/scripts/init.js +1 -1
  5. package/skills/better-class/scripts/resolve_run_vars.js +11 -8
  6. package/skills/better-skill/SKILL.md +1 -1
  7. package/skills/better-skill/references/planning_spec.md +37 -13
  8. package/skills/blame-skill/SKILL.md +1 -1
  9. package/skills/blame-tool/SKILL.md +1 -1
  10. package/skills/blame-tool/scripts/init.js +1 -1
  11. package/skills/blame-tool/scripts/resolve_run_vars.js +10 -7
  12. package/skills/convert-files/SKILL.md +1 -1
  13. package/skills/convert-files/scripts/init.js +1 -1
  14. package/skills/convert-files/scripts/resolve_run_vars.js +13 -14
  15. package/skills/create-ppt/SKILL.md +1 -1
  16. package/skills/create-ppt/scripts/init.js +1 -1
  17. package/skills/create-ppt/scripts/resolve_run_vars.js +10 -7
  18. package/skills/shared/references/rules/blame-skill-rules.md +4 -5
  19. package/skills/shared/references/run/run_sprint_eo.md +11 -10
  20. package/skills/shared/references/template/prompt/subagent.md +1 -1
  21. package/skills/shared/references/template/sprint-pe/skill.md +8 -1
  22. package/skills/shared/references/template/sprint-peo/skill.md +8 -1
  23. package/skills/shared/references/template/sprint-peo/spec.md +5 -5
  24. package/skills/shared/references/template/sprint-seq/skill.md +9 -1
  25. package/skills/shared/references/template/sprint-workflow-menu.md +4 -4
  26. package/skills/shared/scripts/resolve_system_vars.js +3 -1
  27. package/skills/shared/scripts/utils.js +24 -1
  28. package/skills/translate-file/SKILL.md +1 -1
  29. package/skills/translate-file/scripts/init.js +1 -1
  30. package/skills/translate-file/scripts/merge_results.js +1 -8
  31. package/skills/translate-file/scripts/resolve_run_vars.js +10 -7
  32. package/skills/translate-format/SKILL.md +21 -282
  33. package/skills/translate-format/references/format-prompt.md +80 -0
  34. package/skills/translate-format/references/format-rules.md +39 -0
  35. package/skills/translate-format/references/sprint_for_format.md +208 -0
  36. package/skills/translate-format/scripts/check-paragraphs.js +81 -0
  37. package/skills/translate-format/scripts/check_input_vars.js +51 -0
  38. package/skills/translate-format/scripts/chunk-bilingual.js +135 -0
  39. package/skills/translate-format/scripts/count-words.js +38 -0
  40. package/skills/translate-format/scripts/diagnose-failure.js +54 -0
  41. package/skills/translate-format/scripts/init.js +71 -0
  42. package/skills/translate-format/scripts/md-to-docx.js +398 -0
  43. package/skills/translate-format/scripts/merge-format.js +118 -0
  44. package/skills/translate-format/scripts/resolve_run_vars.js +78 -0
@@ -0,0 +1,80 @@
1
+ # 格式重建 dispatch prompt 模板
2
+
3
+ 主 Agent 使用此模板派发格式重建任务。**每个任务执行者只处理 1 个 chunk,并发最多 5 个。**
4
+
5
+ **只替换 `{{变量}}`,不修改其他内容。**
6
+
7
+ ## 变量
8
+
9
+ | 变量 | 说明 | 示例 |
10
+ |---|---|---|
11
+ | `{{file_work_dir}}` | 当前文件的格式重建工作目录 | `<input_dir>/.tsl/<文件名>/fmt/` |
12
+ | `{{chunk_file}}` | chunk 文件路径 | `<file_work_dir>/p001.md` |
13
+ | `{{chunk_id}}` | chunk 编号 | `p001` |
14
+ | `{{skill_dir}}` | 技能目录(脚本/规则路径) | `~/.config/opencode/skills/translate-format` |
15
+
16
+ ---
17
+
18
+ # dispatch prompt 正文
19
+
20
+ 你是格式重建任务执行者。只处理 1 个 chunk,处理完即结束。
21
+ 按固定 Sprint 范式执行,不执行步骤以外的操作。
22
+
23
+ ## Business Rules
24
+
25
+ | ID | Category | Rule |
26
+ |---|---|---|
27
+ | R1 | scope | 只处理 1 个 chunk,处理完即结束 |
28
+ | R2 | content | 不修改译文内容(不改字词、不调语序) |
29
+ | R3 | format | 按 format-rules.md 添加 Markdown 标记 |
30
+ | R4 | output | result 文件格式遵循 format-rules.md「result 文件格式」节 |
31
+ | R5 | retry | 重试上限 3 次:若输出 INVALID,主 Agent 将重试本 chunk 最多 3 次,超过后标记 FAILED 退出 |
32
+
33
+ ## Sprint Goal
34
+
35
+ 将 1 个 chunk 的双语对照内容按格式规则添加 Markdown 标记,写入 result 文件供主 Agent 合并。
36
+
37
+ ## Increment
38
+
39
+ 格式重建结果文件 `{{file_work_dir}}/result-{{chunk_id}}.md`。
40
+
41
+ ## 固定 Sprint Backlog(3 项,todowrite 落单)
42
+
43
+ 1. 读取参考文件 | DoD: <<格式规则>> 已读取
44
+ 2. 格式重建 | DoD: chunk 已按 <<格式规则>> 添加 Markdown 标记
45
+ 3. 写入 result 文件 | DoD: result-{{chunk_id}}.md 已写入,格式符合 <<格式规则>>
46
+
47
+ ## Sprint Execution
48
+
49
+ 按 Backlog 逐项执行。进入 Item 前标记 in_progress → 执行 → 验证 DoD → 标记 completed。
50
+
51
+ ### Item 1:读取参考文件
52
+
53
+ 用 `read` 工具读取以下文件(记为 <<xx>> 引用,后续步骤按引用使用):
54
+ 1. <<格式规则>>:{{skill_dir}}/references/format-rules.md
55
+
56
+ ### Item 2:格式重建
57
+
58
+ 1. `read` {{chunk_file}}
59
+ 2. 按 <<格式规则>> 添加 Markdown 标记
60
+
61
+ ### Item 3:写入 result 文件
62
+
63
+ 按 <<格式规则>>「result 文件格式」节,用 `write` 工具写入 `{{file_work_dir}}/result-{{chunk_id}}.md`。
64
+
65
+ ## Sprint Review
66
+
67
+ 验证 Increment(`result-{{chunk_id}}.md`)已写入且符合 <<格式规则>>「result 文件格式」节。
68
+
69
+ ## 禁止事项
70
+
71
+ - 不写 `/tmp/` 下任何文件
72
+ - 不执行格式重建以外的操作(不翻译、不清洗、不输出到 dist/)
73
+
74
+ # Sprint Standards
75
+
76
+ Read **Sprint Standards** `{{shared_dir}}/references/sprint_standards.md`.
77
+
78
+ # Sprint Now!
79
+
80
+ Follow **Sprint One Workflow** `{{shared_dir}}/references/run/run_sprint_one.md`, then *sprint*.
@@ -0,0 +1,39 @@
1
+ # 格式规则(Format Rules)
2
+
3
+ ## 1. 格式规则
4
+
5
+ | ID | 类别 | 规则定义 |
6
+ |---|---|---|
7
+ | F1 | 标题 | 根据文档结构和语义识别标题层级,用 `#`~`######` 标记,原文段与译文段均添加 |
8
+ | F2 | 粗体 | 关键术语和重要概念用 `**` 标记 |
9
+ | F3 | 斜体 | 用 `*` 标记:作品名(书名/文章名/期刊名)、外来语(非目标语言的词)、强调 |
10
+ | F4 | 引用 | 引用段落用 `>` 标记 |
11
+ | F5 | 列表 | 枚举项用 `-`,有序项用 `1.` |
12
+ | F6 | 链接 | 超链接用 `[URL](URL)` 标记 |
13
+
14
+ ## 2. 保留与禁止
15
+
16
+ | 类别 | 规则 |
17
+ |---|---|
18
+ | 保留 | 双语对照结构、脚注 `[^N]`、`[CONT]` 标记、段落分隔 |
19
+ | 禁止 | 不创造原文内容中没有的结构;不合并或拆分段落;不修改译文内容(不改字词、不调语序);不添加解释、注释或总结;不删除任何内容 |
20
+
21
+ ## 3. result 文件格式
22
+
23
+ **VALID** 时:
24
+
25
+ ```
26
+ (格式重建后的双语对照内容)
27
+
28
+ ## status
29
+
30
+ VALID
31
+ ```
32
+
33
+ **FAILED** 时(无内容):
34
+
35
+ ```
36
+ ## status
37
+
38
+ FAILED
39
+ ```
@@ -0,0 +1,208 @@
1
+ ## Contents
2
+
3
+ - [Sprint Goal](#sprint-goal)
4
+ - [Sprint Increment](#sprint-increment)
5
+ - [路径约定](#路径约定)
6
+ - [Sprint Backlog Items](#sprint-backlog-items)
7
+ - [Sprint Review](#sprint-review)
8
+ - [Sprint Retrospective](#sprint-retrospective)
9
+ - [Red Flags — STOP](#red-flags--stop)
10
+
11
+ # Sprint Backlog for format
12
+
13
+ ## Sprint Goal
14
+
15
+ 对已翻译的双语对照 .txt 文件执行格式重建(标题/粗体/斜体),输出格式化后的单个 .md 文件及同名 .docx 文件。
16
+
17
+ ## Sprint Increment
18
+
19
+ | 产物 | 类型 | 说明 |
20
+ |---|---|---|
21
+ | `<input_dir>/<文件名>.md` | file | 格式化后的 Markdown 文件(原文件内容 + Markdown 格式标记) |
22
+ | `<input_dir>/<文件名>.docx` | file | Word 成品 |
23
+
24
+ ## 路径约定
25
+
26
+ - `<input_dir>` = input 文件所在目录
27
+ - `<文件名>` = input 文件名去掉 .txt 扩展名
28
+ - `{{skill_dir}}` = translate-format skill 安装目录
29
+ - `<tmp>` = `<input_dir>/.tsl/<文件名>/fmt/`
30
+
31
+ ## Sprint Backlog Items
32
+
33
+ ### Item1: 解析入参 + 文件检查
34
+
35
+ - Short-circuit: input 为空/路径不存在/非 .txt → stderr 结束
36
+ - Implement: 检查 input 路径存在且为 .txt 文件,统计词数供 Item 2 判断是否需要分块
37
+ - DoD check: input 路径存在、是 .txt 文件、词数已统计(或 stderr 结束)
38
+
39
+ ### Item2: 分块
40
+
41
+ - Short-circuit: 文件词数 ≤ chunk_words → 单块,跳过分块。创建 `<tmp>` 目录 + 复制 input 为 `<tmp>/p001.md`,直接进入 Item 3
42
+ - Short-circuit: `<tmp>/` 已存在且 `p001.md` 已存在 → skip(分块已完成)
43
+ - Implement: 运行 `node '{{skill_dir}}/scripts/chunk-bilingual.js' '<input_dir>/.tsl/<文件名>' <chunk_words> '<input>'`,按段落边界分块,输出到 `<tmp>/`,创建 `<tmp>/progress.md`(身份行 + chunk 状态表)。stdout 打印总块数
44
+ - DoD check: 文件已按段落边界分块、每块 ≤ chunk_words 词数、chunk 数已知
45
+
46
+ ### Item3: 进度初始化
47
+
48
+ - Short-circuit: `<tmp>/progress.md` 已存在 → **绝不覆盖,直接 skip**。重新初始化会丢失所有 `done` 状态,导致已完成的 chunk 全部重做
49
+ - Implement: 仅单块场景需手动创建 progress.md(多块场景已由 chunk-bilingual.js 创建,`<tmp>/p001.md` 已在 Item 2 复制):
50
+
51
+ ```
52
+ # tsl format progress — book: <input_dir basename>, file: <文件名>
53
+
54
+ | Chunk | 状态 | 重试 |
55
+ |-------|------|------|
56
+ | p001 | pending | 0 |
57
+ ```
58
+
59
+ 行数 = chunk 数(单块 = 1 行)
60
+ - DoD check: `progress.md` 已创建、所有 chunk 标记为 pending
61
+
62
+ ### Item4: Prepare loop resources
63
+
64
+ - Implement:
65
+ 1. `read` `{{skill_dir}}/references/format-prompt.md` → 确认 dispatch prompt 模板已加载
66
+ 2. 准备变量表:
67
+
68
+ | Variable | Value | Description |
69
+ |---|---|---|
70
+ | `file_work_dir` | `<tmp>` | 格式重建工作目录 |
71
+ | `chunk_file` | `<tmp>/pNNN.md` | per chunk |
72
+ | `chunk_id` | `pNNN` | per chunk |
73
+ | `skill_dir` | `{{skill_dir}}` | skill 目录 |
74
+ - DoD check: dispatch prompt 和变量表已就绪
75
+
76
+ ### Item5: 逐块格式重建 + 合并(subagent 并行)
77
+
78
+ - Short-circuit: `<tmp>/progress.md` 全 done → skip
79
+ - Implement:
80
+
81
+ **断点续跑**:从 `<tmp>/progress.md` 读取已完成 chunk,从第一个 `pending` chunk 续跑。如果所有 chunk 都是 `done`,跳过格式化步骤。
82
+
83
+ **模式选择**:
84
+
85
+ | 条件 | 模式 | 说明 |
86
+ |---|---|---|
87
+ | chunk 数 ≤ 5 | 顺序模式 | 无 subagent 并发,逐块格式化 + 合并 |
88
+ | chunk 数 > 5 | 批量并行模式 | 批量 subagent 并发,每批最多 5 个 |
89
+
90
+ **顺序模式**(chunk 数 ≤ 5):
91
+
92
+ 每个 chunk:`read` `<tmp>/pNNN.md` + `read` `{{skill_dir}}/references/format-rules.md` → LLM 格式化 → `write` `<tmp>/result-pNNN.md`(格式同批量模式)→ 运行 `merge-format.js` 合并 → 输出 `[pNNN/总块数] done`。
93
+
94
+ **批量并行模式**(chunk 数 > 5):
95
+
96
+ ```
97
+ # dispatch prompt and variable table prepared in Item4
98
+ while true:
99
+ # read up to 5 pending/failed(retry<3) chunks from progress.md
100
+ batch = read from progress.md where status != done and retry < 3, up to 5
101
+
102
+ # exit when no pending chunks
103
+ if batch is empty:
104
+ break
105
+
106
+ # failed chunk 优先入批:按重试次数降序排列 failed chunk,再追加 pending chunk
107
+ # dispatch one subagent per chunk, all in a single message
108
+ parallel dispatch_subagent(subagent_type: "general", description: "Format chunk pNNN", prompt: <dispatch prompt with variables replaced>)
109
+
110
+ # merge results per chunk
111
+ for chunk in batch:
112
+ node '{{skill_dir}}/scripts/merge-format.js' '<tmp>/result-pNNN.md'
113
+
114
+ # update status per chunk (done by merge-format.js)
115
+ print batch status: [pNNN:VALID/FAILED, ...]
116
+ ```
117
+
118
+ **dispatch prompt**:`read` `{{skill_dir}}/references/format-prompt.md` → 替换 `{{变量}}`(`{{file_work_dir}}`、`{{chunk_file}}`、`{{chunk_id}}`、`{{skill_dir}}`)→ 作为 task prompt 发送。
119
+
120
+ **subagent 执行**:`read` 格式规则 + `read` chunk 文件 → LLM 格式化 → `write` `<tmp>/result-pNNN.md`。subagent 不直接写 `formatted.md`、`progress.md`。
121
+
122
+ **result 文件格式**:详见 `{{skill_dir}}/references/format-rules.md`。
123
+
124
+ **合并**(每批 subagent 完成后立即合并,不跨批积累):
125
+
126
+ 对每个 result 文件运行:
127
+ ```
128
+ node '{{skill_dir}}/scripts/merge-format.js' '<tmp>/result-pNNN.md'
129
+ ```
130
+
131
+ 脚本自动完成:追加格式化内容到 `formatted.md`(VALID)、更新 `progress.md`(VALID→done,FAILED→failed+retry+1)、删除 result 文件。stdout 仅输出 `OK: pNNN VALID` 或 `OK: pNNN FAILED`——完整格式化内容不进入主 Agent 上下文。
132
+
133
+ 合并完本批所有 result 后:若有待处理 chunk(pending 或 failed&重试<3),进入批间失败诊断;所有 chunk 处理完毕后进入格式化完成后步骤。
134
+
135
+ **批间失败诊断(铁律:发现 FAILED chunk 时不可跳过)**:
136
+
137
+ 每批合并后若存在 FAILED chunk,发起下一批前必须查询 subagent session 数据定位根因:
138
+
139
+ 1. 获取 subagent session ID:从 task 工具返回值中提取
140
+ 2. 查询失败原因:`node '{{skill_dir}}/scripts/diagnose-failure.js' '<subagent_session_id>'`
141
+ 3. 根据查询结果判定根因并选择策略:
142
+
143
+ | 查询结果 | 根因 | 策略 |
144
+ |---|---|---|
145
+ | `reason=length`,output_tokens 达上限 | LLM 输出 token 超限 | 将该 chunk 按段落边界拆分为 2 个子 chunk,分别重新分派 subagent |
146
+ | `reason=stop`,但无 `write` 工具调用 | subagent 未走到写入步骤就结束 | 在 dispatch prompt 中追加"减少分析,直接输出格式化内容" |
147
+ | 有 `write` 调用但 status=error | write 工具执行失败 | 检查 error 信息,可能是路径/权限问题;修正后原样重试 |
148
+ | `reason=stop`,有 `write` 调用 status=completed,但 merge 报 FAILED | result 文件格式问题 | `read` result 文件检查格式,修正后重新合并 |
149
+ | 工具调用序列不完整(如只有 read,无 write) | subagent 中途异常退出 | 检查 chunk 内容是否有 OCR 损坏;在 dispatch prompt 中追加针对性提示后重试 |
150
+
151
+ 4. 连续失败保护:同一 chunk 重试 ≥ 2 次仍失败,必须更换策略(拆分 chunk / 调整 dispatch prompt / 更换 subagent 类型),不可第三次以相同方式重试
152
+
153
+ **Rulings, not stalls**:格式化过程中遇到歧义(不确定是否为标题、术语是否标记),主 Agent 自行裁决并继续,不停下来问用户。裁决原则:根据文档结构和语义判断是否为标题;术语不确定 → 首次出现标记。唯一需要停下来问用户的是:源文件本身有损坏或缺失。
154
+
155
+ **连续执行**:批次间不暂停、不向用户汇报中间进度、不问"要继续吗"。每个 chunk 完成后输出一行状态(`[pNNN/总块数] done`)即可。只有全部 chunk 完成、遇到不可恢复错误时才停止。
156
+
157
+ **compact 恢复**:若上下文被 compact 压缩,重新 `read` SKILL.md + `read` `<tmp>/progress.md` 恢复执行上下文。先验证第一行身份声明匹配当前任务(file),再从 progress.md 中第一个 pending chunk 继续。磁盘状态(progress.md、formatted.md)不受 compact 影响。
158
+
159
+ **关键约束**:`<tmp>/formatted.md` 只追加不重写。
160
+
161
+ **格式化完成后**:
162
+ 0. FAILED chunk 补处理:对重试次数 ≥ 3 仍标记为 failed 的 chunk,重新分派 subagent 处理——在 dispatch prompt 中追加针对性提示,subagent 完成后运行 `merge-format.js` 合并。确保最终输出无缺失块。
163
+ 1. 确认 `<tmp>/progress.md` 全部 `done`。
164
+
165
+ - DoD check: 所有 chunk 格式化完成、`progress.md` 全 done、`formatted.md` 已生成
166
+
167
+ ### Item6: 合并 + 输出
168
+
169
+ - Implement:
170
+ 1. `read` `<tmp>/formatted.md` → `write` `<input_dir>/<文件名>.md`
171
+ 2. 清理临时文件(删除 `<tmp>` 目录)
172
+ 3. `node '{{skill_dir}}/scripts/check-paragraphs.js' '<input>' '<input_dir>/<文件名>.md'` 统计段落数差异。段落数差异 > 5% → 报警(可能有内容丢失),但仍输出文件
173
+ - DoD check: `<文件名>.md` 已写入、段落数与原文件一致(±5%)、临时文件已清理
174
+
175
+ ### Item7: 生成同名 docx
176
+
177
+ - Short-circuit: 输出已存在非空 → skip(脚本内短路)
178
+ - Implement: 运行 `node '{{skill_dir}}/scripts/md-to-docx.js' '<input_dir>'`(脚本自动完成依赖检查与转换:扫描 `<input_dir>/*-fmt.md` 转同名 docx,输出已存在非空时短路 skip)
179
+ - DoD check: `<文件名>.docx` 已生成、文件非空
180
+ - 失败处理:脚本 exit 4 → stderr 有错误信息 → 修正后重跑(脚本幂等,可安全重试)
181
+
182
+ ## Sprint Review
183
+
184
+ 所有 Backlog Items 完成后:
185
+
186
+ - **对照 Sprint Goal 验证**:双语对照文档是否已添加 Markdown 格式标记?输出文件是否已生成?
187
+ - **验证 Increment**:`<文件名>.md` 存在且非空?段落数与原文件一致(±5%)?`<文件名>.docx` 存在且非空?
188
+
189
+ ## Sprint Retrospective
190
+
191
+ 本 skill 每次调用 = 无状态独立 Sprint,进度持久化在 `.tsl/<文件名>/fmt/` 文件中。Retrospective 聚焦本次执行过程:
192
+
193
+ - **做得好的**:分块策略是否合理?并行效率是否达标?段落数校验是否通过?
194
+ - **需要改进的**:是否有 FAILED chunk?失败根因是什么?dispatch prompt 是否需要调整?
195
+ - **改进计划**:记录失败模式,优化下一批 dispatch prompt 或 chunk 大小
196
+
197
+ ## Red Flags — STOP
198
+
199
+ - 即将跳过 `<tmp>/progress.md` 检查
200
+ - 即将覆盖已有的 `<tmp>/progress.md`(铁律:绝不覆盖)
201
+ - 即将重写 `<tmp>/formatted.md` 全文而非追加
202
+ - 即将逐个发起 task 调用(非并行)
203
+ - 即将并发超过 5 个 subagent
204
+ - 即将让 subagent 直接写 `formatted.md` 或 `progress.md`
205
+ - 即将修改译文内容
206
+ - 即将跳过批间失败诊断,无脑重试 FAILED chunk
207
+
208
+ **停下来。回到流水线起点。先进度检查,再逐块格式化+合并,再输出,再生成 docx。**
@@ -0,0 +1,81 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * check-paragraphs.js — 段落数对比检查(ESM)
4
+ *
5
+ * 对比原文件和格式化文件的段落数,差异 > 5% 时报警(可能有内容丢失),但仍输出文件。
6
+ * 段落定义与 chunk-bilingual.js 一致:按空行(\n\n+)分隔的非空文本块。
7
+ *
8
+ * 用法:node check-paragraphs.js <original> <formatted>
9
+ * stdout: status 行 + data 块
10
+ * 退出码:0 成功 / 2 参数错误 / 4 执行失败
11
+ */
12
+
13
+ import { readFileSync, existsSync } from 'fs'
14
+
15
+ const OK_CHECK = 'OK: 段落检查完成'
16
+ const WARN_CHECK = 'OK: 段落检查完成(差异超阈值)'
17
+ const INVALID_USAGE = 'INVALID: 用法 node check-paragraphs.js <original> <formatted>'
18
+ const INVALID_ORIG_NOT_FOUND = 'INVALID: 原文件不存在'
19
+ const INVALID_FMT_NOT_FOUND = 'INVALID: 格式化文件不存在'
20
+
21
+ /**
22
+ * 统计文本的段落数。
23
+ * 段落定义与 chunk-bilingual.js 一致:按 \n\n+ 分隔的非空文本块。
24
+ * @param {string} content — 文本内容
25
+ * @returns {number} 段落数
26
+ */
27
+ export function countParagraphs(content) {
28
+ if (!content || !content.trim()) return 0
29
+ return content.split(/\n\n+/).filter(p => p.trim()).length
30
+ }
31
+
32
+ /**
33
+ * 对比原文件和格式化文件的段落数。
34
+ * @param {string} origContent — 原文件内容
35
+ * @param {string} fmtContent — 格式化文件内容
36
+ * @returns {{ origCount: number, fmtCount: number, diffPercent: number, status: 'OK' | 'WARN' }} 检查结果
37
+ */
38
+ export function checkParagraphs(origContent, fmtContent) {
39
+ const origCount = countParagraphs(origContent)
40
+ const fmtCount = countParagraphs(fmtContent)
41
+
42
+ const diffPercent = origCount === 0
43
+ ? (fmtCount === 0 ? 0 : 100)
44
+ : Math.abs(fmtCount - origCount) / origCount * 100
45
+
46
+ const status = diffPercent > 5 ? 'WARN' : 'OK'
47
+
48
+ return { origCount, fmtCount, diffPercent: Math.round(diffPercent * 10) / 10, status }
49
+ }
50
+
51
+ // --- CLI entry point (only when run directly, not when imported) ---
52
+
53
+ const isMain = import.meta.url === `file://${process.argv[1]}`
54
+ if (isMain) {
55
+ const [,, origPath, fmtPath] = process.argv
56
+
57
+ if (!origPath || !fmtPath) {
58
+ console.error(INVALID_USAGE)
59
+ process.exit(2)
60
+ }
61
+
62
+ if (!existsSync(origPath)) {
63
+ console.error(`${INVALID_ORIG_NOT_FOUND}: ${origPath}`)
64
+ process.exit(2)
65
+ }
66
+
67
+ if (!existsSync(fmtPath)) {
68
+ console.error(`${INVALID_FMT_NOT_FOUND}: ${fmtPath}`)
69
+ process.exit(2)
70
+ }
71
+
72
+ const origContent = readFileSync(origPath, 'utf-8')
73
+ const fmtContent = readFileSync(fmtPath, 'utf-8')
74
+
75
+ const result = checkParagraphs(origContent, fmtContent)
76
+ const statusLine = result.status === 'OK' ? OK_CHECK : WARN_CHECK
77
+ console.log(statusLine)
78
+ console.log()
79
+ console.log(`| orig | fmt | diff% |`)
80
+ console.log(`| ${result.origCount} | ${result.fmtCount} | ${result.diffPercent}% |`)
81
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * check_input_vars.js — 校验输入变量 input(.txt 文件路径)
3
+ *
4
+ * 输入:argv[2] = input(源 .txt 文件路径)
5
+ * 校验:未提供 / 不存在 / 不是文件 / 扩展名非 .txt
6
+ */
7
+
8
+ import { existsSync, statSync } from 'fs'
9
+ import { extname } from 'path'
10
+
11
+ const OK_OUTPUT = 'OK: 输入校验通过'
12
+ const INVALID_TEMPLATE = 'INVALID: ${error}'
13
+ const ERR_INVALID = '请提示用户输入不合法,任务结束'
14
+
15
+ export const OK_INPUT_VALID = OK_OUTPUT
16
+
17
+ /**
18
+ * 校验 input 变量(纯函数,可测试)。
19
+ * @param {string} inputPath — 源 .txt 文件路径
20
+ * @returns {{ok: true} | {error: string}}
21
+ */
22
+ export function checkInputVars(inputPath) {
23
+ if (!inputPath) {
24
+ return { error: `input 未提供,${ERR_INVALID}` }
25
+ }
26
+ if (!existsSync(inputPath)) {
27
+ return { error: `input 不存在:${inputPath},${ERR_INVALID}` }
28
+ }
29
+ if (!statSync(inputPath).isFile()) {
30
+ return { error: `input 不是文件:${inputPath},${ERR_INVALID}` }
31
+ }
32
+ const ext = extname(inputPath).toLowerCase()
33
+ if (ext !== '.txt') {
34
+ return { error: `input 扩展名不支持(期望 .txt):${ext},${ERR_INVALID}` }
35
+ }
36
+ return { ok: true }
37
+ }
38
+
39
+ const isMain = import.meta.url === `file://${process.argv[1]}`
40
+ if (isMain) {
41
+ const inputPath = process.argv[2]
42
+
43
+ const result = checkInputVars(inputPath)
44
+
45
+ if (result.error) {
46
+ console.log(INVALID_TEMPLATE.replace('${error}', result.error))
47
+ process.exit(0)
48
+ }
49
+
50
+ console.log(OK_OUTPUT)
51
+ }
@@ -0,0 +1,135 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * chunk-bilingual.js — 双语文档分块 + 格式重建进度初始化(ESM,纯 JS,无依赖)
4
+ *
5
+ * 用法:node chunk-bilingual.js <work_dir> <chunk_words> [<input_file>]
6
+ * <input_file> 显式传入 = 从指定文件分块
7
+ *
8
+ * 功能:
9
+ * 1. 创建 <work_dir>/fmt/ 目录
10
+ * 2. 按段落边界将输入文档分块,写入 fmt/p001.md...
11
+ * 3. 创建 fmt/progress.md(身份行 + chunk 状态表)
12
+ * 4. stdout 打印 status 行 + data 块
13
+ *
14
+ * 短路:fmt/progress.md 已存在 → 跳过分块和初始化,仅打印已有块数
15
+ */
16
+
17
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync } from 'fs'
18
+ import { join, basename } from 'path'
19
+
20
+ const OK_CHUNKED = 'OK: 分块完成'
21
+ const OK_SKIPPED = 'OK: 已跳过(progress.md 已存在)'
22
+ const INVALID_USAGE = 'INVALID: 用法 node chunk-bilingual.js <work_dir> <chunk_words> [<input_file>]'
23
+ const INVALID_CHUNK_WORDS = 'INVALID: chunk_words 必须为 >= 100 的数字'
24
+ const INVALID_INPUT_NOT_FOUND = 'INVALID: 输入文件不存在'
25
+ const INVALID_INPUT_EMPTY = 'INVALID: 输入为空或无段落'
26
+
27
+ /**
28
+ * 将文本按段落边界分块。
29
+ * @param {string} content — 文本内容
30
+ * @param {number} chunkWords — 每块最大词数
31
+ * @returns {string[]} 分块数组
32
+ */
33
+ export function chunkBilingual(content, chunkWords) {
34
+ if (!content || !content.trim()) return []
35
+
36
+ const paragraphs = content.split(/\n\n+/)
37
+
38
+ const chunks = []
39
+ let currentChunk = []
40
+ let currentWords = 0
41
+
42
+ for (const para of paragraphs) {
43
+ const trimmed = para.trim()
44
+ if (!trimmed) continue
45
+
46
+ const words = trimmed.split(/\s+/).filter(Boolean).length
47
+
48
+ if (currentWords + words > chunkWords && currentChunk.length > 0) {
49
+ chunks.push(currentChunk.join('\n\n'))
50
+ currentChunk = [trimmed]
51
+ currentWords = words
52
+ } else {
53
+ currentChunk.push(trimmed)
54
+ currentWords += words
55
+ }
56
+ }
57
+
58
+ if (currentChunk.length > 0) {
59
+ chunks.push(currentChunk.join('\n\n'))
60
+ }
61
+
62
+ return chunks
63
+ }
64
+
65
+ // --- CLI ---
66
+
67
+ const isMain = import.meta.url === `file://${process.argv[1]}`
68
+
69
+ if (isMain) {
70
+ const args = process.argv.slice(2)
71
+
72
+ if (args.length < 2) {
73
+ console.error(INVALID_USAGE)
74
+ process.exit(2)
75
+ }
76
+
77
+ const [workDir, chunkWordsStr, inputFile] = args
78
+ const chunkWords = parseInt(chunkWordsStr, 10)
79
+ const fmtDir = join(workDir, 'fmt')
80
+ const progressPath = join(fmtDir, 'progress.md')
81
+
82
+ if (isNaN(chunkWords) || chunkWords < 100) {
83
+ console.error(INVALID_CHUNK_WORDS)
84
+ process.exit(2)
85
+ }
86
+
87
+ // 短路:progress.md 已存在 → 仅打印已有块数
88
+ if (existsSync(progressPath)) {
89
+ const existing = readdirSync(fmtDir).filter(f => f.match(/^p\d+\.md$/)).length
90
+ console.log(OK_SKIPPED)
91
+ console.log()
92
+ console.log('| chunks |')
93
+ console.log(`| ${existing} |`)
94
+ process.exit(0)
95
+ }
96
+
97
+ // 输入源:显式 input_file
98
+ const inputPath = inputFile
99
+ if (!inputPath || !existsSync(inputPath)) {
100
+ console.error(INVALID_INPUT_NOT_FOUND + (inputPath ? `: ${inputPath}` : ''))
101
+ process.exit(2)
102
+ }
103
+
104
+ const content = readFileSync(inputPath, 'utf-8')
105
+ const chunks = chunkBilingual(content, chunkWords)
106
+
107
+ if (chunks.length === 0) {
108
+ console.error(`${INVALID_INPUT_EMPTY}: ${inputPath}`)
109
+ process.exit(2)
110
+ }
111
+
112
+ // 1. 创建 fmt/ 目录
113
+ mkdirSync(fmtDir, { recursive: true })
114
+
115
+ // 2. 写分块文件
116
+ chunks.forEach((chunk, i) => {
117
+ const num = String(i + 1).padStart(3, '0')
118
+ writeFileSync(join(fmtDir, `p${num}.md`), chunk + '\n', 'utf-8')
119
+ })
120
+
121
+ // 3. 创建 progress.md
122
+ const inputDirBasename = basename(join(workDir, '..', '..'))
123
+ const fileBasename = basename(workDir)
124
+ const lines = [`# tsl format progress — book: ${inputDirBasename}, file: ${fileBasename}`, '', '| Chunk | 状态 | 重试 |', '|-------|------|------|']
125
+ for (let i = 0; i < chunks.length; i++) {
126
+ const num = String(i + 1).padStart(3, '0')
127
+ lines.push(`| p${num} | pending | 0 |`)
128
+ }
129
+ writeFileSync(progressPath, lines.join('\n') + '\n', 'utf-8')
130
+
131
+ console.log(OK_CHUNKED)
132
+ console.log()
133
+ console.log('| chunks |')
134
+ console.log(`| ${chunks.length} |`)
135
+ }
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * count-words.js — 词数统计(ESM,纯 JS,无依赖)
4
+ *
5
+ * 用法:node count-words.js <input_file>
6
+ * stdout: status 行 + data 块
7
+ * 退出码:0 成功 / 2 参数错误
8
+ */
9
+
10
+ import { readFileSync, existsSync } from 'fs'
11
+
12
+ const OK_COUNTED = 'OK: 词数统计完成'
13
+ const INVALID_USAGE = 'INVALID: 用法 node count-words.js <input_file>'
14
+ const INVALID_NOT_FOUND = 'INVALID: 输入文件不存在'
15
+
16
+ const isMain = import.meta.url === `file://${process.argv[1]}`
17
+
18
+ if (isMain) {
19
+ const inputPath = process.argv[2]
20
+
21
+ if (!inputPath) {
22
+ console.error(INVALID_USAGE)
23
+ process.exit(2)
24
+ }
25
+
26
+ if (!existsSync(inputPath)) {
27
+ console.error(`${INVALID_NOT_FOUND}: ${inputPath}`)
28
+ process.exit(2)
29
+ }
30
+
31
+ const content = readFileSync(inputPath, 'utf-8')
32
+ const words = content.split(/\s+/).filter(Boolean).length
33
+
34
+ console.log(OK_COUNTED)
35
+ console.log()
36
+ console.log('| words |')
37
+ console.log(`| ${words} |`)
38
+ }