@wwkit/harness 1.0.37 → 1.0.38

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 (108) hide show
  1. package/commands/{tsl.md → translate.md} +2 -2
  2. package/package.json +2 -2
  3. package/skills/better-skill/SKILL.md +3 -3
  4. package/skills/better-skill-test/SKILL.md +1 -1
  5. package/skills/better-tool/SKILL.md +2 -2
  6. package/skills/better-tool-test/SKILL.md +1 -1
  7. package/skills/blame-scrum-skill/SKILL.md +218 -0
  8. package/skills/blame-scrum-skill/demo.md +11 -0
  9. package/skills/blame-scrum-skill/references/planning_template.md +86 -0
  10. package/skills/blame-scrum-skill/references/progress_template.md +30 -0
  11. package/skills/blame-scrum-skill/references/scoring_rules.md +63 -0
  12. package/skills/blame-skill/references/scoring-rules.md +52 -11
  13. package/skills/blame-sprint-agent/SKILL.md +7 -1
  14. package/skills/blame-sprint-agent/references/demos/demo.md +40 -0
  15. package/skills/blame-sprint-agent/references/demos/fixed-traversal/SKILL.md +198 -0
  16. package/skills/blame-sprint-agent/references/demos/fixed-traversal/references/failure-diagnosis.md +19 -0
  17. package/skills/blame-sprint-agent/references/demos/fixed-traversal/references/global-review-rules.md +23 -0
  18. package/skills/blame-sprint-agent/references/demos/fixed-traversal/references/prepare-prompt.md +28 -0
  19. package/skills/blame-sprint-agent/references/demos/fixed-traversal/references/resume-detection.md +19 -0
  20. package/skills/blame-sprint-agent/references/demos/fixed-traversal/references/translation-prompt.md +32 -0
  21. package/skills/blame-sprint-agent/references/demos/multi-override/SKILL.md +209 -0
  22. package/skills/blame-sprint-agent/references/demos/multi-override/references/review-rules.md +38 -0
  23. package/skills/blame-sprint-agent/references/demos/routing/SKILL.md +163 -0
  24. package/skills/blame-sprint-agent/references/demos/single-list/SKILL.md +133 -0
  25. package/skills/blame-sprint-agent/references/demos/single-list/references/translation-rules.md +35 -0
  26. package/skills/blame-sprint-agent/references/demos/single-list-internal-loop/SKILL.md +158 -0
  27. package/skills/blame-sprint-agent/references/demos/single-list-internal-loop/references/glossary-rules.md +31 -0
  28. package/skills/blame-sprint-agent/references/scoring-rules.md +5 -0
  29. package/skills/blame-sprint-skill/SKILL.md +8 -1
  30. package/skills/blame-sprint-skill/references/demos/demo.md +40 -0
  31. package/skills/blame-sprint-skill/references/demos/fixed-traversal/SKILL.md +198 -0
  32. package/skills/blame-sprint-skill/references/demos/fixed-traversal/references/failure-diagnosis.md +19 -0
  33. package/skills/blame-sprint-skill/references/demos/fixed-traversal/references/global-review-rules.md +23 -0
  34. package/skills/blame-sprint-skill/references/demos/fixed-traversal/references/prepare-prompt.md +28 -0
  35. package/skills/blame-sprint-skill/references/demos/fixed-traversal/references/resume-detection.md +19 -0
  36. package/skills/blame-sprint-skill/references/demos/fixed-traversal/references/translation-prompt.md +32 -0
  37. package/skills/blame-sprint-skill/references/demos/multi-override/SKILL.md +209 -0
  38. package/skills/blame-sprint-skill/references/demos/multi-override/references/review-rules.md +38 -0
  39. package/skills/blame-sprint-skill/references/demos/routing/SKILL.md +163 -0
  40. package/skills/blame-sprint-skill/references/demos/single-list/SKILL.md +133 -0
  41. package/skills/blame-sprint-skill/references/demos/single-list/references/translation-rules.md +35 -0
  42. package/skills/blame-sprint-skill/references/demos/single-list-internal-loop/SKILL.md +158 -0
  43. package/skills/blame-sprint-skill/references/demos/single-list-internal-loop/references/glossary-rules.md +31 -0
  44. package/skills/blame-sprint-skill/references/scoring-rules.md +6 -1
  45. package/skills/blame-sprint-skill/references/state-management-rules.md +194 -0
  46. package/skills/extract/README.md +86 -0
  47. package/skills/extract/SKILL.md +177 -110
  48. package/skills/extract/references/{detail.md → detail_workflow.md} +2 -2
  49. package/skills/extract/references/{list.md → list_workflow.md} +4 -4
  50. package/skills/extract/references/{navi.md → navi_workflow.md} +2 -2
  51. package/skills/extract/references/planning_template.md +197 -0
  52. package/skills/extract/references/progress_template.md +29 -0
  53. package/skills/extract/references/{text.md → text_workflow.md} +2 -2
  54. package/skills/extract/scripts/{extract-sample.js → extract_sample.js} +1 -1
  55. package/skills/revise/SKILL.md +1 -1
  56. package/skills/translate/SKILL.md +391 -0
  57. package/skills/translate/app.json5 +66 -0
  58. package/skills/{tsl → translate}/package.json +1 -1
  59. package/skills/translate/references/failure-diagnosis.md +43 -0
  60. package/skills/translate/references/format-prompt.md +62 -0
  61. package/skills/translate/references/format-rules.md +39 -0
  62. package/skills/{tsl → translate}/references/global-review-rules.md +4 -6
  63. package/skills/translate/references/glossary-prompt.md +86 -0
  64. package/skills/translate/references/glossary-rules.md +44 -0
  65. package/skills/translate/references/prepare-prompt.md +110 -0
  66. package/skills/translate/references/prepare-rules.md +20 -0
  67. package/skills/translate/references/resume-detection.md +51 -0
  68. package/skills/translate/references/rulings.md +15 -0
  69. package/skills/translate/references/translation-prompt.md +73 -0
  70. package/skills/translate/references/translation-rules.md +51 -0
  71. package/skills/{tsl → translate}/scripts/check-boundaries.js +43 -14
  72. package/skills/translate/scripts/chunk-bilingual.js +123 -0
  73. package/skills/{tsl → translate}/scripts/chunk-text.js +7 -6
  74. package/skills/translate/scripts/count-terms.js +54 -0
  75. package/skills/{tsl → translate}/scripts/generate-review.js +3 -3
  76. package/skills/translate/scripts/init-progress.js +144 -0
  77. package/skills/{tsl → translate}/scripts/md-to-docx.js +87 -16
  78. package/skills/{tsl → translate}/scripts/merge-format.js +16 -11
  79. package/skills/translate/scripts/merge-result.js +113 -0
  80. package/skills/{tsl → translate}/scripts/verify-chunk.js +21 -6
  81. package/skills/translate/todos.md +38 -0
  82. package/skills/{tsl-format → translate-format}/SKILL.md +33 -41
  83. package/skills/tsl/SKILL.md +0 -486
  84. package/skills/tsl/references/format-prompt.md +0 -99
  85. package/skills/tsl/references/format-rules.md +0 -55
  86. package/skills/tsl/references/prepare-prompt.md +0 -150
  87. package/skills/tsl/references/terminology-rules.md +0 -93
  88. package/skills/tsl/references/translation-guide.md +0 -23
  89. package/skills/tsl/references/translation-prompt.md +0 -116
  90. package/skills/tsl/references/translation-rules.md +0 -46
  91. package/skills/tsl/references/verification-rules.md +0 -58
  92. package/skills/tsl/scripts/chunk-bilingual.js +0 -96
  93. package/skills/tsl/scripts/cleanup-glossary.js +0 -160
  94. package/skills/tsl/scripts/merge-result.js +0 -164
  95. /package/skills/extract/references/{detail.schema.json5 → detail_schema.json5} +0 -0
  96. /package/skills/extract/references/{list-rule-gen.md → list_rule_gen.md} +0 -0
  97. /package/skills/extract/references/{list.schema.json5 → list_schema.json5} +0 -0
  98. /package/skills/extract/references/{navi.schema.json5 → navi_schema.json5} +0 -0
  99. /package/skills/extract/references/{text.schema.json5 → text_schema.json5} +0 -0
  100. /package/skills/extract/scripts/{build-xpath.js → build_xpath.js} +0 -0
  101. /package/skills/extract/scripts/{clean-html.js → clean_html.js} +0 -0
  102. /package/skills/extract/scripts/{extract-detail.js → extract_detail.js} +0 -0
  103. /package/skills/extract/scripts/{extract-regex.js → extract_regex.js} +0 -0
  104. /package/skills/extract/scripts/{to-text.js → to_text.js} +0 -0
  105. /package/skills/extract/scripts/{validate-schema.js → validate_schema.js} +0 -0
  106. /package/skills/{tsl → translate}/scripts/check-paragraphs.js +0 -0
  107. /package/skills/{tsl → translate}/scripts/clean-text.js +0 -0
  108. /package/skills/{tsl → translate}/scripts/extract-pdf.js +0 -0
@@ -2,8 +2,8 @@
2
2
  /**
3
3
  * chunk-text.js — 文本分块脚本(ESM,段落感知)
4
4
  *
5
- * 输入:argv[2] = source.txt 路径,argv[3] = 每块最大词数(默认 4000),argv[4] = 输出目录
6
- * 输出:p001.txt, p002.txt, ... 写入输出目录,stdout 打印总块数
5
+ * 输入:argv[2] = 工作目录(含 source.txt),argv[3] = 每块最大词数(默认 4000)
6
+ * 输出:p001.txt, p002.txt, ... 写入工作目录,stdout 打印总块数
7
7
  *
8
8
  * 分块策略:
9
9
  * - PDF 文本(含 \f):按 \f 切分页面,按 chunk_words 分组
@@ -12,24 +12,25 @@
12
12
  */
13
13
 
14
14
  import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'fs';
15
- import { join, dirname } from 'path';
15
+ import { join } from 'path';
16
16
 
17
17
  const args = process.argv.slice(2);
18
18
 
19
19
  if (args.length < 1) {
20
- console.error('usage: chunk-text.js <source.txt> [chunk_words=4000] [output_dir]');
20
+ console.error('usage: chunk-text.js <work_dir> [chunk_words=4000]');
21
21
  process.exit(2);
22
22
  }
23
23
 
24
- const sourcePath = args[0];
24
+ const workDir = args[0];
25
25
  const chunkWords = Math.max(100, parseInt(args[1] || '4000', 10));
26
- const outputDir = args[2] || dirname(sourcePath);
26
+ const sourcePath = join(workDir, 'source.txt');
27
27
 
28
28
  if (!existsSync(sourcePath)) {
29
29
  console.error(`ERROR: source file not found: ${sourcePath}`);
30
30
  process.exit(2);
31
31
  }
32
32
 
33
+ const outputDir = workDir;
33
34
  mkdirSync(outputDir, { recursive: true });
34
35
 
35
36
  const content = readFileSync(sourcePath, 'utf-8');
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * count-terms.js — 词频统计脚本(ESM)
4
+ *
5
+ * 输入:argv[2] = 工作目录(.tsl/,含各子目录的 source.txt),argv[3] = 术语列表(逗号分隔)
6
+ * 输出:stdout 每行 "次数\t术语",按次数降序
7
+ *
8
+ * 统计方式:大小写不敏感子串计数,扫描 .tsl/ 下所有子目录的 source.txt 全文。
9
+ */
10
+
11
+ import { readFileSync, existsSync, readdirSync, statSync } from 'fs';
12
+ import { join } from 'path';
13
+
14
+ const args = process.argv.slice(2);
15
+ const workDir = args[0];
16
+ const termsCsv = args[1];
17
+
18
+ if (!workDir || !termsCsv) {
19
+ console.error('Usage: node count-terms.js <work_dir> <terms_csv>');
20
+ process.exit(2);
21
+ }
22
+
23
+ const terms = termsCsv.split(',').map(t => t.trim()).filter(t => t.length > 0);
24
+
25
+ // 扫描所有子目录的 source.txt,合并全文
26
+ const subdirs = readdirSync(workDir)
27
+ .filter(name => {
28
+ const p = join(workDir, name);
29
+ return statSync(p).isDirectory() && existsSync(join(p, 'source.txt'));
30
+ })
31
+ .sort();
32
+
33
+ let fullText = '';
34
+ for (const name of subdirs) {
35
+ fullText += readFileSync(join(workDir, name, 'source.txt'), 'utf-8') + '\n';
36
+ }
37
+
38
+ const lower = fullText.toLowerCase();
39
+ const result = [];
40
+ for (const term of terms) {
41
+ const tl = term.toLowerCase();
42
+ let count = 0;
43
+ let idx = lower.indexOf(tl);
44
+ while (idx !== -1) {
45
+ count++;
46
+ idx = lower.indexOf(tl, idx + tl.length);
47
+ }
48
+ result.push({ term, count });
49
+ }
50
+
51
+ result.sort((a, b) => b.count - a.count);
52
+ for (const r of result) {
53
+ console.log(`${r.count}\t${r.term}`);
54
+ }
@@ -7,8 +7,8 @@
7
7
  * 功能(纯脚本,不需要 LLM):
8
8
  * 1. 读取 progress.md,解析每 chunk 的状态和重试次数
9
9
  * 2. 读取 bilingual.md,统计行数和 [CONT] 标记数
10
- * 3. 生成 review-draft.md(逐块自检结果 + 统计 + 轻量结构校验 + 结论)
11
- * 4. 覆写 <work-dir>/review-draft.md(每次调用反映当前状态 = 增量更新)
10
+ * 3. 生成 review.md(逐块自检结果 + 统计 + 轻量结构校验 + 结论)
11
+ * 4. 覆写 <work-dir>/review.md(每次调用反映当前状态 = 增量更新)
12
12
  *
13
13
  * 自检日志目的:提供人工审计能力,让人确信每个 chunk 都经过了自检。
14
14
  */
@@ -152,7 +152,7 @@ ${rows.join('\n')}
152
152
  ${conclusion}
153
153
  `;
154
154
 
155
- writeFileSync(join(workDir, 'review-draft.md'), md);
155
+ writeFileSync(join(workDir, 'review.md'), md);
156
156
 
157
157
  return {
158
158
  total,
@@ -0,0 +1,144 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * init-progress.js — 翻译进度初始化(ESM,纯 JS,无依赖)
4
+ *
5
+ * 用法:node init-progress.js <translate_dir>
6
+ * <translate_dir> = {{input_dir}}/.tsl 目录
7
+ *
8
+ * 功能:
9
+ * 1. 读取 <translate_dir>/prepare-result.md,解析 Per-File Summary 表(文件名 + chunk_count)
10
+ * 2. 逐文件创建 <translate_dir>/<文件名>/progress.md(身份行 + chunk 状态表)
11
+ * 3. 创建 <translate_dir>/progress-global.md(身份行 + 文件状态表,三态:pending → translated → done)
12
+ *
13
+ * 短路:progress.md 已存在 → 跳过该文件;progress-global.md 已存在 → 跳过
14
+ */
15
+
16
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
17
+ import { join, basename } from 'path';
18
+
19
+ /**
20
+ * 解析 prepare-result.md,提取文件名和 chunk_count。
21
+ * @param {string} translateDir — .tsl 目录路径
22
+ * @returns {{ filename: string, chunkCount: number }[]} 文件列表
23
+ */
24
+ export function parsePrepareResult(translateDir) {
25
+ const resultPath = join(translateDir, 'prepare-result.md');
26
+ if (!existsSync(resultPath)) {
27
+ throw new Error(`prepare-result.md not found: ${resultPath}`);
28
+ }
29
+
30
+ const content = readFileSync(resultPath, 'utf-8');
31
+
32
+ const statusMatch = content.match(/^## status\s*\n\s*(\w+)/m);
33
+ if (!statusMatch) {
34
+ throw new Error('No ## status found in prepare-result.md');
35
+ }
36
+ if (statusMatch[1] !== 'complete') {
37
+ throw new Error(`prepare-result.md status is "${statusMatch[1]}", expected "complete"`);
38
+ }
39
+
40
+ const summaryMatch = content.match(/## Per-File Summary\s*\n([\s\S]*?)(?:\n## |\n$|$)/);
41
+ if (!summaryMatch) {
42
+ throw new Error('No ## Per-File Summary found in prepare-result.md');
43
+ }
44
+
45
+ const files = [];
46
+ const lines = summaryMatch[1].split('\n');
47
+ for (const line of lines) {
48
+ const row = line.match(/^\|\s*(.+?)\s*\|\s*(\d+)\s*\|$/);
49
+ if (row && row[1] !== '文件' && row[1] !== '---' && !row[1].startsWith('-')) {
50
+ files.push({ filename: row[1].trim(), chunkCount: parseInt(row[2], 10) });
51
+ }
52
+ }
53
+
54
+ if (files.length === 0) {
55
+ throw new Error('No files found in Per-File Summary table');
56
+ }
57
+
58
+ return files;
59
+ }
60
+
61
+ /**
62
+ * 生成 chunk 级 progress.md 内容。
63
+ * @param {string} bookName — 书名(input_dir basename)
64
+ * @param {string} filename — 文件名
65
+ * @param {number} chunkCount — chunk 数量
66
+ * @returns {string} progress.md 内容
67
+ */
68
+ export function buildProgressContent(bookName, filename, chunkCount) {
69
+ const lines = [
70
+ `# tsl progress — book: ${bookName}, file: ${filename}`,
71
+ '',
72
+ '| Chunk | 状态 | 重试 |',
73
+ '|-------|------|------|',
74
+ ];
75
+ for (let i = 0; i < chunkCount; i++) {
76
+ const num = String(i + 1).padStart(3, '0');
77
+ lines.push(`| p${num} | pending | 0 |`);
78
+ }
79
+ return lines.join('\n') + '\n';
80
+ }
81
+
82
+ /**
83
+ * 生成文件级 progress-global.md 内容。
84
+ * @param {string} bookName — 书名(input_dir basename)
85
+ * @param {{ filename: string, chunkCount: number }[]} files — 文件列表
86
+ * @returns {string} progress-global.md 内容
87
+ */
88
+ export function buildGlobalProgressContent(bookName, files) {
89
+ const lines = [
90
+ `# tsl global progress — book: ${bookName}`,
91
+ '',
92
+ '| 文件 | 状态 |',
93
+ '|------|------|',
94
+ ];
95
+ for (const f of files) {
96
+ lines.push(`| ${f.filename} | pending |`);
97
+ }
98
+ return lines.join('\n') + '\n';
99
+ }
100
+
101
+ // --- CLI ---
102
+
103
+ const isMain = import.meta.url === `file://${process.argv[1]}`;
104
+
105
+ if (isMain) {
106
+ const [,, translateDir] = process.argv;
107
+
108
+ if (!translateDir) {
109
+ console.error('Usage: node init-progress.js <translate_dir>');
110
+ process.exit(2);
111
+ }
112
+
113
+ try {
114
+ const files = parsePrepareResult(translateDir);
115
+ const bookName = basename(join(translateDir, '..'));
116
+
117
+ let created = 0;
118
+ let skipped = 0;
119
+
120
+ for (const f of files) {
121
+ const fileWorkDir = join(translateDir, f.filename);
122
+ const progressPath = join(fileWorkDir, 'progress.md');
123
+
124
+ if (existsSync(progressPath)) {
125
+ skipped++;
126
+ continue;
127
+ }
128
+
129
+ mkdirSync(fileWorkDir, { recursive: true });
130
+ writeFileSync(progressPath, buildProgressContent(bookName, f.filename, f.chunkCount), 'utf-8');
131
+ created++;
132
+ }
133
+
134
+ const globalPath = join(translateDir, 'progress-global.md');
135
+ if (!existsSync(globalPath)) {
136
+ writeFileSync(globalPath, buildGlobalProgressContent(bookName, files), 'utf-8');
137
+ }
138
+
139
+ console.log(`created: ${created}, skipped: ${skipped}`);
140
+ } catch (e) {
141
+ console.error(e.message);
142
+ process.exit(1);
143
+ }
144
+ }
@@ -3,13 +3,13 @@
3
3
  * md-to-docx.js — Markdown 转 docx 脚本(ESM)
4
4
  *
5
5
  * 将 Markdown 内容/文件转换为 Microsoft Word (.docx)。
6
- * 被 tsl(Item 5 docx 段)和 tsl-format(Item 6)共同引用。
6
+ * 被 translate(Item 7 docx 生成)引用。
7
7
  *
8
8
  * 三道转换前/后修正(缺一不可,都针对 Word 打开 docx 报错):
9
9
  * 1. sanitizeMarkdownUrls(转换前):把"裸 URL + 全角标点/CJK 紧贴"的畸形转成
10
10
  * 标准 Markdown 链接,防止 marked 的 GFM autolink 把全角标点/中文吞入 href
11
11
  * 生成非法 URI(Word 打开报超链接错误)。
12
- * 2. normalizeFootnoteLabels(转换前):tsl/tsl-format 产物中每章脚注重新编号
12
+ * 2. normalizeFootnoteLabels(转换前):translate/translate-format 产物中每章脚注重新编号
13
13
  * ([^1]..[^N]),全书 label 大量复用。markdown-docx 用 label 作 key,后章
14
14
  * 定义覆盖前章定义,生成大量"孤儿定义 + 重复引用",Word 报成百上千个脚注
15
15
  * 错误。本函数按"正文引用 → 之后最近的同 label 定义"配对,把 label 重写为
@@ -21,28 +21,48 @@
21
21
  * continuationSeparator id=0,并保留 XML 声明与完整 xmlns——两者缺失都会让
22
22
  * Word 报 xml parsing error),删除无引用的孤儿定义。
23
23
  *
24
- * 用法:node md-to-docx.js <input.md> <output.docx> [--ignore-image]
24
+ * 用法:node md-to-docx.js <input_dir|input.md> [--ignore-image]
25
+ * node md-to-docx.js --check # 仅检查 markdown-docx 依赖可用性
26
+ * - 目录模式:扫描 <input_dir>/dist/*-fmt.md(translate 的 -tsl-fmt.md)或 <input_dir>/*-fmt.md(translate-format 的 -fmt.md),逐个转同名 .docx
27
+ * - 文件模式:<input.md> → 同名 .docx
28
+ * 短路:输出 docx 已存在且非空 → 打印 skipped(避免重复创建)
25
29
  * stdout: docx: <input> → <output> (bytes=N)
26
- * 退出码:0 成功 / 2 参数或输入错误 / 1 转换或写入失败
30
+ * 退出码:0 成功/短路 / 2 参数或输入错误 / 3 依赖缺失 / 1 转换或写入失败
27
31
  */
28
32
 
29
- import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'fs';
30
- import { dirname } from 'path';
31
- import markdownDocx, { Packer } from 'markdown-docx';
33
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, statSync, readdirSync } from 'fs';
34
+ import { dirname, join, basename } from 'path';
35
+ import { createRequire } from 'module';
32
36
  import JSZip from 'jszip';
33
37
 
38
+ const require = createRequire(import.meta.url);
39
+
34
40
  // markdown-docx 默认选项:启用 GFM(脚注/表格/删除线等扩展语法依赖)
35
41
  const DEFAULTS = { gfm: true };
36
42
 
43
+ /**
44
+ * 惰性加载 markdown-docx(依赖检查用)。
45
+ * @returns {{ default: Function, Packer: object }} markdown-docx 模块
46
+ * @throws {Error} markdown-docx 不可用时抛出,附带安装提示
47
+ */
48
+ function loadMarkdownDocx() {
49
+ try {
50
+ const mod = require('markdown-docx');
51
+ return { default: mod.default || mod, Packer: mod.Packer };
52
+ } catch {
53
+ throw new Error('ERROR: markdown-docx not available. Run: npm install (in skills/translate)');
54
+ }
55
+ }
56
+
37
57
  /**
38
58
  * 将跨章节复用的脚注 label 归一化为全局唯一(转换前预处理)。
39
59
  *
40
- * 背景:tsl/tsl-format 产物中每章脚注重新编号([^1]..[^N]),全书 label 大量
60
+ * 背景:translate/translate-format 产物中每章脚注重新编号([^1]..[^N]),全书 label 大量
41
61
  * 复用(实测 141 个定义行只有 14 个唯一 label)。markdown-docx 的 label→id Map
42
62
  * 被后章定义覆盖,导致前章脚注内容丢失、生成大量孤儿定义与重复引用,Word 打开
43
63
  * 报"成百上千个脚注错误"。
44
64
  *
45
- * 配对规则:正文引用 [^x] 对应其"之后最近"的同 label 定义(tsl-format 产物中
65
+ * 配对规则:正文引用 [^x] 对应其"之后最近"的同 label 定义(translate-format 产物中
46
66
  * 脚注定义位于各章末尾,正文引用在前)。定义在前、引用在后的罕见场景回退到
47
67
  * "之前最近"的同 label 定义。无法配对的引用保留原样(不报错,按普通文本处理)。
48
68
  *
@@ -249,6 +269,7 @@ export function sanitizeMarkdownUrls(markdown) {
249
269
  * @returns {Promise<Buffer>} docx 文件 buffer
250
270
  */
251
271
  export async function mdToDocxBuffer(markdown, options = {}) {
272
+ const { default: markdownDocx, Packer } = loadMarkdownDocx();
252
273
  const cleaned = normalizeFootnoteLabels(sanitizeMarkdownUrls(markdown));
253
274
  const doc = await markdownDocx(cleaned, { ...DEFAULTS, ...options });
254
275
  const rawBuf = await Packer.toBuffer(doc);
@@ -283,23 +304,73 @@ const isMain = import.meta.url === `file://${process.argv[1]}`;
283
304
 
284
305
  if (isMain) {
285
306
  const args = process.argv.slice(2);
286
- const inputPath = args[0];
287
- const outputPath = args[1];
307
+
308
+ // --check 模式:仅检查 markdown-docx 依赖可用性
309
+ if (args[0] === '--check') {
310
+ try {
311
+ loadMarkdownDocx();
312
+ console.log('markdown-docx: OK');
313
+ process.exit(0);
314
+ } catch {
315
+ console.error('ERROR: markdown-docx not available. Run: npm install (in skills/translate)');
316
+ process.exit(3);
317
+ }
318
+ }
319
+
320
+ const target = args[0];
288
321
  const options = args.includes('--ignore-image') ? { ignoreImage: true } : {};
289
322
 
290
- if (!inputPath || !outputPath) {
291
- console.error('Usage: node md-to-docx.js <input.md> <output.docx> [--ignore-image]');
323
+ if (!target) {
324
+ console.error('Usage: node md-to-docx.js <input_dir|input.md> [--ignore-image]');
292
325
  process.exit(2);
293
326
  }
294
- if (!inputPath.endsWith('.md')) {
295
- console.error(`ERROR: input must be a .md file: ${inputPath}`);
296
- process.exit(2);
327
+
328
+ // 目录模式:扫描 <distDir>/*-fmt.md 批量转换(覆盖 translate 的 -tsl-fmt.md 与 translate-format 的 -fmt.md)
329
+ if (!target.endsWith('.md')) {
330
+ if (!existsSync(target) || !statSync(target).isDirectory()) {
331
+ console.error(`ERROR: input must be a .md file or directory: ${target}`);
332
+ process.exit(2);
333
+ }
334
+ const distDir = existsSync(join(target, 'dist')) ? join(target, 'dist') : target;
335
+ const mdFiles = readdirSync(distDir)
336
+ .filter((f) => f.endsWith('-fmt.md'))
337
+ .sort();
338
+ if (mdFiles.length === 0) {
339
+ console.error(`ERROR: no *-fmt.md found in ${distDir}`);
340
+ process.exit(2);
341
+ }
342
+ for (const f of mdFiles) {
343
+ const inputPath = join(distDir, f);
344
+ const outputPath = inputPath.replace(/\.md$/, '.docx');
345
+ if (existsSync(outputPath) && statSync(outputPath).size > 0) {
346
+ console.log(`skipped: ${outputPath} (bytes=${statSync(outputPath).size})`);
347
+ continue;
348
+ }
349
+ try {
350
+ const result = await mdToDocx(inputPath, outputPath, options);
351
+ console.log(`docx: ${result.inputPath} → ${result.outputPath} (bytes=${result.bytes})`);
352
+ } catch (e) {
353
+ console.error(e.message);
354
+ process.exit(1);
355
+ }
356
+ }
357
+ process.exit(0);
297
358
  }
359
+
360
+ // 单文件模式:输出 = 输入同名 .docx
361
+ const inputPath = target;
362
+ const outputPath = inputPath.replace(/\.md$/, '.docx');
298
363
  if (!existsSync(inputPath)) {
299
364
  console.error(`ERROR: input file not found: ${inputPath}`);
300
365
  process.exit(2);
301
366
  }
302
367
 
368
+ // 短路:输出 docx 已存在且非空 → 跳过(避免重复创建)
369
+ if (existsSync(outputPath) && statSync(outputPath).size > 0) {
370
+ console.log(`skipped: ${outputPath} (bytes=${statSync(outputPath).size})`);
371
+ process.exit(0);
372
+ }
373
+
303
374
  try {
304
375
  const result = await mdToDocx(inputPath, outputPath, options);
305
376
  console.log(`docx: ${result.inputPath} → ${result.outputPath} (bytes=${result.bytes})`);
@@ -2,8 +2,8 @@
2
2
  /**
3
3
  * merge-format.js — 合并 subagent 格式化结果到主产物(ESM)
4
4
  *
5
- * 用法:node merge-format.js <result-file> <work-dir> <chunk-id>
6
- * <chunk-id> = chunk 编号,如 p001(与 result 文件名和 progress.md 行匹配)
5
+ * 用法:node merge-format.js <result-file>
6
+ * workDir = result 文件所在目录,chunkId = 文件名解析(result-pNNN.md → pNNN)
7
7
  *
8
8
  * 功能(全部在脚本内完成,主 Agent 上下文只获得一行输出):
9
9
  * 1. 解析 result-pNNN.md:格式化内容 / status
@@ -16,25 +16,30 @@
16
16
  */
17
17
 
18
18
  import { readFileSync, writeFileSync, unlinkSync, existsSync } from 'fs';
19
- import { join } from 'path';
19
+ import { join, dirname, basename } from 'path';
20
20
 
21
21
  /**
22
22
  * 合并单个 result 文件到主产物。
23
- * @param {string} resultFile - result-pNNN.md 路径
24
- * @param {string} workDir - 工作目录(含 formatted.md 和 progress.md)
25
- * @param {string} chunkId - chunk 编号(如 p001)
23
+ * @param {string} resultFile - result-pNNN.md 路径(workDir 和 chunkId 自动推导)
26
24
  * @returns {{ chunkId: string, status: string }} 合并结果
27
25
  * @throws {Error} 参数缺失 / 文件不存在 / 格式错误
28
26
  */
29
- export function mergeFormat(resultFile, workDir, chunkId) {
30
- if (!resultFile || !workDir || !chunkId) {
31
- throw new Error('Usage: node merge-format.js <result-file> <work-dir> <chunk-id>');
27
+ export function mergeFormat(resultFile) {
28
+ if (!resultFile) {
29
+ throw new Error('Usage: node merge-format.js <result-file>');
32
30
  }
33
31
 
34
32
  if (!existsSync(resultFile)) {
35
33
  throw new Error(`Result file not found: ${resultFile}`);
36
34
  }
37
35
 
36
+ const workDir = dirname(resultFile);
37
+ const chunkMatch = basename(resultFile).match(/^result-(p\d+)\.md$/);
38
+ if (!chunkMatch) {
39
+ throw new Error(`Invalid result file name (expected result-pNNN.md): ${basename(resultFile)}`);
40
+ }
41
+ const chunkId = chunkMatch[1];
42
+
38
43
  const content = readFileSync(resultFile, 'utf-8');
39
44
 
40
45
  // --- Parse result file ---
@@ -94,9 +99,9 @@ export function mergeFormat(resultFile, workDir, chunkId) {
94
99
 
95
100
  const isMain = import.meta.url === `file://${process.argv[1]}`;
96
101
  if (isMain) {
97
- const [,, resultFile, workDir, chunkId] = process.argv;
102
+ const resultFile = process.argv[2];
98
103
  try {
99
- const result = mergeFormat(resultFile, workDir, chunkId);
104
+ const result = mergeFormat(resultFile);
100
105
  console.log(`${result.chunkId} ${result.status}`);
101
106
  } catch (e) {
102
107
  console.error(e.message);
@@ -0,0 +1,113 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * merge-result.js — 合并 subagent 翻译结果到主产物(ESM)
4
+ *
5
+ * 用法:node merge-result.js <result-file>
6
+ * workDir = result 文件所在目录,chunkId = 文件名解析(result-pNNN.md → pNNN)
7
+ *
8
+ * 功能(全部在脚本内完成,主 Agent 上下文只获得一行输出):
9
+ * 1. 解析 result-pNNN.md:双语内容 / status
10
+ * 2. VALID → 追加双语内容到 <work-dir>/bilingual.md
11
+ * 3. 更新 <work-dir>/progress.md(VALID→done,FAILED→failed+retry+1)
12
+ * 4. 删除 result 文件
13
+ * 5. stdout:`pNNN VALID` 或 `pNNN FAILED`
14
+ *
15
+ * 主 Agent 上下文只获得一行 status 输出,完整译文(~30KB/chunk)不进入上下文。
16
+ */
17
+
18
+ import { readFileSync, writeFileSync, unlinkSync, existsSync } from 'fs';
19
+ import { join, dirname, basename } from 'path';
20
+
21
+ /**
22
+ * 合并单个 result 文件到主产物。
23
+ * @param {string} resultFile - result-pNNN.md 路径(workDir 和 chunkId 自动推导)
24
+ * @returns {{ chunkId: string, status: string }} 合并结果
25
+ * @throws {Error} 参数缺失 / 文件不存在 / 格式错误
26
+ */
27
+ export function mergeResult(resultFile) {
28
+ if (!resultFile) {
29
+ throw new Error('Usage: node merge-result.js <result-file>');
30
+ }
31
+
32
+ if (!existsSync(resultFile)) {
33
+ throw new Error(`Result file not found: ${resultFile}`);
34
+ }
35
+
36
+ const workDir = dirname(resultFile);
37
+ const chunkMatch = basename(resultFile).match(/^result-(p\d+)\.md$/);
38
+ if (!chunkMatch) {
39
+ throw new Error(`Invalid result file name (expected result-pNNN.md): ${basename(resultFile)}`);
40
+ }
41
+ const chunkId = chunkMatch[1];
42
+
43
+ const content = readFileSync(resultFile, 'utf-8');
44
+
45
+ // --- Parse result file ---
46
+
47
+ const statusMatch = content.match(/^## status\s*\n\s*(VALID|FAILED)/m);
48
+ if (!statusMatch) {
49
+ throw new Error(`No ## status found in ${resultFile}`);
50
+ }
51
+ const status = statusMatch[1];
52
+ const statusPos = content.indexOf('## status');
53
+
54
+ // Bilingual content = everything before ## status
55
+ const bilingualContent = content.substring(0, statusPos).trim();
56
+
57
+ // --- 1. Append bilingual content (VALID only) ---
58
+
59
+ if (status === 'VALID' && bilingualContent) {
60
+ const bilingualPath = join(workDir, 'bilingual.md');
61
+ const existing = readFileSync(bilingualPath, 'utf-8');
62
+ const sep = existing.endsWith('\n') ? '' : '\n';
63
+ writeFileSync(bilingualPath, existing + sep + bilingualContent + '\n');
64
+ }
65
+
66
+ // --- 2. Update progress.md ---
67
+
68
+ const progressPath = join(workDir, 'progress.md');
69
+ const progress = readFileSync(progressPath, 'utf-8');
70
+ const lines = progress.split('\n');
71
+ const updatedLines = lines.map(line => {
72
+ const newFmt = line.match(/^\| (p\d+) \| (\w+) \| (\d+) \|$/);
73
+ if (newFmt && newFmt[1] === chunkId) {
74
+ if (status === 'VALID') {
75
+ return `| ${chunkId} | done | ${newFmt[3]} |`;
76
+ } else {
77
+ return `| ${chunkId} | failed | ${parseInt(newFmt[3]) + 1} |`;
78
+ }
79
+ }
80
+ const oldFmt = line.match(/^\| (p\d+) \| (\w+) \|$/);
81
+ if (oldFmt && oldFmt[1] === chunkId) {
82
+ if (status === 'VALID') {
83
+ return `| ${chunkId} | done |`;
84
+ } else {
85
+ return `| ${chunkId} | failed |`;
86
+ }
87
+ }
88
+ return line;
89
+ });
90
+ writeFileSync(progressPath, updatedLines.join('\n'));
91
+
92
+ // --- 3. Delete result file ---
93
+
94
+ unlinkSync(resultFile);
95
+
96
+ // --- 4. Return result ---
97
+
98
+ return { chunkId, status };
99
+ }
100
+
101
+ // --- CLI entry point ---
102
+
103
+ const isMain = import.meta.url === `file://${process.argv[1]}`;
104
+ if (isMain) {
105
+ const resultFile = process.argv[2];
106
+ try {
107
+ const result = mergeResult(resultFile);
108
+ console.log(`${result.chunkId} ${result.status}`);
109
+ } catch (e) {
110
+ console.error(e.message);
111
+ process.exit(1);
112
+ }
113
+ }
@@ -4,15 +4,18 @@
4
4
  *
5
5
  * 输入:stdin JSON { "original": "<原文>", "translated": "<译文>" }
6
6
  * 可选:stdin JSON 增加字段 "glossary": "<术语表内容>" 启用术语检查
7
+ * 也可用参数传入输入文件:node verify-chunk.js <input.json>(兼容 stdin)
7
8
  * 输出:stdout "VALID" 或 "INVALID: <原因>"
8
9
  *
9
- * 校验项:
10
- * 1. 段落数一致(原文段落数 = 译文段落数 / 2,因为译文含原文+译文交替)
11
- * 2. 脚注 ID 一致(原文脚注 ID 集合 = 译文脚注 ID 集合)
12
- * 3. [CONT] 标记偶数配对(双语格式中每个 [CONT] 出现在原文段+译文段 = 2 的倍数)
13
- * 4. 术语一致性(可选,提供 glossary 字段时启用)
10
+ * 校验项(全部通过 = VALID,任一不过 = INVALID):
11
+ * 1. 段落数一致:原文段落数 = 译文段落数 / 2(双语交替格式)
12
+ * 2. 脚注 ID 一致:原文脚注 ID 集合 = 译文脚注 ID 集合
13
+ * 3. [CONT] 标记配对:每个 [CONT] 在原文段 + 译文段各出现一次(偶数配对)
14
+ * 4. 术语一致性:术语表中的术语在译文中使用正确(需传入 glossary 字段)
14
15
  */
15
16
 
17
+ import { readFileSync, existsSync } from 'fs';
18
+
16
19
  function readStdin() {
17
20
  return new Promise((resolve) => {
18
21
  let data = '';
@@ -83,7 +86,19 @@ function checkGlossary(translated, glossary) {
83
86
  }
84
87
 
85
88
  async function main() {
86
- const input = await readStdin();
89
+ // argv[2] = 可选输入文件路径(替代 stdin),无参数时保持读 stdin 兼容
90
+ const inputFile = process.argv[2];
91
+ let input;
92
+ if (inputFile) {
93
+ if (!existsSync(inputFile)) {
94
+ console.log('INVALID: input file not found: ' + inputFile);
95
+ return;
96
+ }
97
+ input = readFileSync(inputFile, 'utf-8');
98
+ } else {
99
+ input = await readStdin();
100
+ }
101
+
87
102
  let data;
88
103
 
89
104
  try {