@wwkit/harness 1.0.46 → 1.0.48

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 (119) hide show
  1. package/package.json +3 -4
  2. package/skills/pea/SKILL.md +14 -4
  3. package/skills/pea/references/tpl-prd/epic.md +7 -2
  4. package/skills/peago/SKILL.md +10 -2
  5. package/skills/peago/references/cleancode/languages/py-ut.md +88 -0
  6. package/skills/peago/references/cleancode/languages/py.md +222 -0
  7. package/skills/{blame-cleancode/references → peago/references/cleancode}/report_template.md +45 -12
  8. package/skills/peago/references/cleancode/rules-ut.md +133 -0
  9. package/skills/peago/references/cleancode/rules.md +477 -0
  10. package/skills/peago/references/cleancode/spec.md +204 -0
  11. package/skills/peago/references/lint/spec.md +160 -0
  12. package/skills/peago/references/test/languages/js.md +74 -0
  13. package/skills/peago/references/test/languages/py.md +68 -0
  14. package/skills/peago/references/test/spec.md +201 -0
  15. package/skills/peago/references/translate/scripts/check-paragraphs.js +71 -0
  16. package/skills/peago/references/translate/scripts/check-structure.js +118 -0
  17. package/skills/peago/references/translate/scripts/chunk-bilingual.js +123 -0
  18. package/skills/peago/references/translate/scripts/chunk-text.js +150 -0
  19. package/skills/peago/references/translate/scripts/clean-text.js +121 -0
  20. package/skills/peago/references/translate/scripts/count-terms.js +54 -0
  21. package/skills/peago/references/translate/scripts/extract-vision.js +267 -0
  22. package/skills/peago/references/translate/scripts/md-to-docx.js +381 -0
  23. package/skills/peago/references/translate/scripts/merge-format.js +110 -0
  24. package/skills/peago/references/translate/scripts/merge-pages.js +202 -0
  25. package/skills/peago/references/translate/scripts/merge-result.js +113 -0
  26. package/skills/peago/references/translate/scripts/verify-chunk.js +200 -0
  27. package/skills/peago/references/translate/spec.md +14 -6
  28. package/skills/better-class/SKILL.md +0 -48
  29. package/skills/better-class/references/planning_spec.md +0 -91
  30. package/skills/better-class/references/report-template.md +0 -65
  31. package/skills/better-class/references/sprint_for_eo.md +0 -83
  32. package/skills/better-class/references/sprint_for_report.md +0 -22
  33. package/skills/better-class/references/subagent-prompt.md +0 -47
  34. package/skills/better-class/references/workflow.md +0 -75
  35. package/skills/better-class/scripts/check-syntax.js +0 -112
  36. package/skills/better-class/scripts/check_input_vars.js +0 -52
  37. package/skills/better-class/scripts/init.js +0 -88
  38. package/skills/better-class/scripts/resolve_run_vars.js +0 -96
  39. package/skills/better-class/scripts/run-tests.js +0 -108
  40. package/skills/better-cleancode/SKILL.md +0 -157
  41. package/skills/better-ut/SKILL.md +0 -236
  42. package/skills/blame-class/SKILL.md +0 -78
  43. package/skills/blame-class/references/report_template.md +0 -98
  44. package/skills/blame-class/references/rules.md +0 -40
  45. package/skills/blame-cleancode/SKILL.md +0 -105
  46. package/skills/blame-cleancode/plan.md +0 -1408
  47. package/skills/blame-cleancode/references/rules.md +0 -630
  48. package/skills/blame-ut/SKILL.md +0 -113
  49. package/skills/blame-ut/references/report_template.md +0 -102
  50. package/skills/blame-ut/references/rules.md +0 -197
  51. package/skills/convert-files/SKILL.md +0 -37
  52. package/skills/convert-files/package.json +0 -11
  53. package/skills/convert-files/references/sprint_for_conversion.md +0 -17
  54. package/skills/convert-files/scripts/check_input_vars.js +0 -54
  55. package/skills/convert-files/scripts/convert.js +0 -331
  56. package/skills/convert-files/scripts/init.js +0 -75
  57. package/skills/convert-files/scripts/resolve_run_vars.js +0 -124
  58. package/skills/create-ppt/SKILL.md +0 -47
  59. package/skills/create-ppt/package.json +0 -9
  60. package/skills/create-ppt/references/ppt-styles.md +0 -287
  61. package/skills/create-ppt/references/sprint_for_ppt_generation.md +0 -81
  62. package/skills/create-ppt/references/sprint_for_source_discovery.md +0 -18
  63. package/skills/create-ppt/scripts/check_input_vars.js +0 -57
  64. package/skills/create-ppt/scripts/find-source-files.js +0 -98
  65. package/skills/create-ppt/scripts/init.js +0 -96
  66. package/skills/create-ppt/scripts/md-to-pptx.js +0 -579
  67. package/skills/create-ppt/scripts/resolve_run_vars.js +0 -91
  68. package/skills/jstest/SKILL.md +0 -561
  69. package/skills/jstest/references/case-create.md +0 -327
  70. package/skills/jstest/references/case-fix.md +0 -273
  71. package/skills/jstest/references/config.md +0 -148
  72. package/skills/jstest/references/coverage-analyze.md +0 -247
  73. package/skills/jstest/references/env-ensure.md +0 -210
  74. package/skills/jstest/references/execute.md +0 -168
  75. package/skills/jstest/references/sample.md +0 -166
  76. package/skills/jstest/references/scoring-rules.md +0 -75
  77. package/skills/jstest/references/suitability-check.md +0 -232
  78. package/skills/jstest/references/test-standards.md +0 -288
  79. package/skills/lint/SKILL.md +0 -440
  80. package/skills/lint/references/ai-fix.md +0 -138
  81. package/skills/lint/references/config-setup.md +0 -103
  82. package/skills/lint/references/config.md +0 -65
  83. package/skills/lint/references/env-ensure.md +0 -89
  84. package/skills/lint/references/language-detect.md +0 -76
  85. package/skills/lint/references/rules-analyze.md +0 -126
  86. package/skills/lint/references/suitability-check.md +0 -82
  87. package/skills/lint/references/tool-fix.md +0 -91
  88. package/skills/peago/references/extract/baseline.md +0 -17
  89. package/skills/peago/references/extract/spec.md +0 -117
  90. package/skills/pytest/SKILL.md +0 -556
  91. package/skills/pytest/references/case-create.md +0 -325
  92. package/skills/pytest/references/case-fix.md +0 -272
  93. package/skills/pytest/references/config.md +0 -145
  94. package/skills/pytest/references/coverage-analyze.md +0 -224
  95. package/skills/pytest/references/env-ensure.md +0 -196
  96. package/skills/pytest/references/execute.md +0 -153
  97. package/skills/pytest/references/sample.md +0 -160
  98. package/skills/pytest/references/scoring-rules.md +0 -57
  99. package/skills/pytest/references/suitability-check.md +0 -221
  100. package/skills/pytest/references/test-standards.md +0 -244
  101. package/skills/query/SKILL.md +0 -72
  102. package/skills/step-extract/SKILL.md +0 -205
  103. /package/skills/{lint/references → peago/references/lint}/languages/js.md +0 -0
  104. /package/skills/{lint/references → peago/references/lint}/languages/py.md +0 -0
  105. /package/skills/{lint/references → peago/references/lint/scripts}/detect-language.js +0 -0
  106. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/Calculator.js +0 -0
  107. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/ConfigManager.js +0 -0
  108. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/FileProcessor.js +0 -0
  109. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/OrderService.js +0 -0
  110. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/TokenGenerator.js +0 -0
  111. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/UserService.js +0 -0
  112. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/index.js +0 -0
  113. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/Calculator.py +0 -0
  114. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/ConfigManager.py +0 -0
  115. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/FileProcessor.py +0 -0
  116. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/OrderService.py +0 -0
  117. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/TokenGenerator.py +0 -0
  118. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/UserService.py +0 -0
  119. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/__init__.py +0 -0
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * merge-format.js — 合并 subagent 格式化结果到主产物(ESM)
4
+ *
5
+ * 用法:node merge-format.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>/formatted.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 输出,完整格式化内容不进入上下文。
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 mergeFormat(resultFile) {
28
+ if (!resultFile) {
29
+ throw new Error('Usage: node merge-format.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
+ // Status: first VALID or FAILED after ## status
48
+ const statusMatch = content.match(/^## status\s*\n\s*(VALID|FAILED)/m);
49
+ if (!statusMatch) {
50
+ throw new Error(`No ## status found in ${resultFile}`);
51
+ }
52
+ const status = statusMatch[1];
53
+ const statusPos = content.indexOf('## status');
54
+
55
+ // Formatted content = everything before ## status
56
+ const formattedContent = content.substring(0, statusPos).trim();
57
+
58
+ // --- 1. Append formatted content (VALID only) ---
59
+
60
+ if (status === 'VALID' && formattedContent) {
61
+ const formattedPath = join(workDir, 'formatted.md');
62
+ if (existsSync(formattedPath)) {
63
+ const existing = readFileSync(formattedPath, 'utf-8');
64
+ const sep = existing.endsWith('\n') ? '' : '\n';
65
+ writeFileSync(formattedPath, existing + sep + formattedContent + '\n');
66
+ } else {
67
+ writeFileSync(formattedPath, formattedContent + '\n');
68
+ }
69
+ }
70
+
71
+ // --- 2. Update progress.md ---
72
+
73
+ const progressPath = join(workDir, 'progress.md');
74
+ const progress = readFileSync(progressPath, 'utf-8');
75
+ const lines = progress.split('\n');
76
+ const updatedLines = lines.map(line => {
77
+ const match = line.match(/^\| (p\d+) \| (\w+) \| (\d+) \|$/);
78
+ if (match && match[1] === chunkId) {
79
+ if (status === 'VALID') {
80
+ return `| ${chunkId} | done | ${match[3]} |`;
81
+ } else {
82
+ return `| ${chunkId} | failed | ${parseInt(match[3], 10) + 1} |`;
83
+ }
84
+ }
85
+ return line;
86
+ });
87
+ writeFileSync(progressPath, updatedLines.join('\n'));
88
+
89
+ // --- 3. Delete result file ---
90
+
91
+ unlinkSync(resultFile);
92
+
93
+ // --- 4. Return result ---
94
+
95
+ return { chunkId, status };
96
+ }
97
+
98
+ // --- CLI entry point (only when run directly, not when imported) ---
99
+
100
+ const isMain = import.meta.url === `file://${process.argv[1]}`;
101
+ if (isMain) {
102
+ const resultFile = process.argv[2];
103
+ try {
104
+ const result = mergeFormat(resultFile);
105
+ console.log(`${result.chunkId} ${result.status}`);
106
+ } catch (e) {
107
+ console.error(e.message);
108
+ process.exit(1);
109
+ }
110
+ }
@@ -0,0 +1,202 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * merge-pages.js — 页级接缝合并与页眉清理脚本(ESM,纯 JS,无依赖)
4
+ *
5
+ * 对按页提取的源文本(页间以 \f 分隔)做机械清洗,消除分页伪影:
6
+ * 1. 跨页段落合并:页 N 末段未以句末标点结尾 + 页 N+1 首段以续接形态开头 → 合并为一段
7
+ * 2. 跨页断词合并:页尾 `xxx-` + 下页首 `yyy` → `xxxyyy`(连字符断词)
8
+ * 3. 页眉页脚清理:在多页首/尾行中重复出现(≥ 半数页)的行视为页眉/页脚,移除
9
+ *
10
+ * 全部为机械规则(字符形态 + 重复统计),单遍扫描,零 LLM 调用。
11
+ *
12
+ * 输入:argv[2] = source.txt 路径(原地修改)
13
+ * 输出:stdout 打印统计;清洗后文本写回原文件
14
+ *
15
+ * 用法:
16
+ * node merge-pages.js "<source.txt>"
17
+ */
18
+
19
+ import { readFileSync, writeFileSync } from 'fs';
20
+
21
+ /**
22
+ * 判断段落是否以完整句子结尾。
23
+ * @param {string} text
24
+ * @returns {boolean}
25
+ */
26
+ export function isParagraphComplete(text) {
27
+ const trimmed = text.trimEnd();
28
+ if (trimmed.length === 0) return true;
29
+ // 注意:) 与 ] 不作为句末完整标志——括号/方括号短语后应有句末标点,
30
+ // 以 ")" 结尾的段(如引用括注)仍可能是断段
31
+ return /[.!?。!?:;;」』)\]»"…]\s*$/.test(trimmed);
32
+ }
33
+
34
+ /**
35
+ * 判断文本是否像上一段的续接(非标题、非新句开头)。
36
+ * @param {string} text
37
+ * @returns {boolean}
38
+ */
39
+ export function looksLikeContinuation(text) {
40
+ const trimmed = text.trimStart();
41
+ if (trimmed.length === 0) return false;
42
+
43
+ // 拉丁字母小写开头 → 续接
44
+ if (/^[a-zà-ÿ]/.test(trimmed)) return true;
45
+
46
+ // 常见续接连词(多语言)
47
+ const continuationStarters = [
48
+ /^(and|but|or|nor|for|yet|so|while|whereas|though|although|because|since|unless|until|when|which|that|who|whom|whose)\s/i,
49
+ /^(et|ou|mais|car|donc|or|ni|que|qui|où|quand|pendant|toutefois|néanmoins)\s/i,
50
+ /^(und|oder|aber|denn|sondern|weil|wenn|während)\s/i,
51
+ /^(y|o|pero|porque|cuando|como|que|pues)\s/i,
52
+ ];
53
+ for (const re of continuationStarters) {
54
+ if (re.test(trimmed)) return true;
55
+ }
56
+
57
+ // CJK 无大小写:排除标题形态(短行、无标点)后视为续接
58
+ if (/^[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/.test(trimmed)) {
59
+ const firstLine = trimmed.split('\n')[0].trim();
60
+ if (firstLine.length < 20 && !/[。!?.!?::]/.test(firstLine)) {
61
+ return false; // 疑似标题
62
+ }
63
+ return true;
64
+ }
65
+
66
+ return false;
67
+ }
68
+
69
+ /**
70
+ * 判断页尾是否为连字符断词(如 "arbi-")。
71
+ * @param {string} text
72
+ * @returns {boolean}
73
+ */
74
+ export function endsWithHyphenBreak(text) {
75
+ const trimmed = text.trimEnd();
76
+ return /[a-zà-ÿ]-$/.test(trimmed);
77
+ }
78
+
79
+ /**
80
+ * 识别页眉/页脚:在页首/页尾行中重复出现(出现页数 ≥ 半数页且 ≥2 页)的行。
81
+ * @param {string[]} pages
82
+ * @returns {{ headers: Set<string>, footers: Set<string> }}
83
+ */
84
+ export function detectRunningHeads(pages) {
85
+ const headers = new Set();
86
+ const footers = new Set();
87
+ if (pages.length < 2) return { headers, footers };
88
+
89
+ const threshold = Math.ceil(pages.length / 2);
90
+ const headCount = new Map();
91
+ const footCount = new Map();
92
+
93
+ for (const page of pages) {
94
+ const lines = page.split('\n').map(l => l.trim()).filter(Boolean);
95
+ // 页眉候选仅取"多行页"(≥3 行)的首 2 行;页脚同理取尾 2 行。
96
+ // 单行/双行页(如断词接缝页)不参与,避免正文被误判为页眉。
97
+ if (lines.length >= 3) {
98
+ for (const l of lines.slice(0, 2)) headCount.set(l, (headCount.get(l) || 0) + 1);
99
+ for (const l of lines.slice(-2)) footCount.set(l, (footCount.get(l) || 0) + 1);
100
+ }
101
+ }
102
+ for (const [l, c] of headCount) if (c >= threshold) headers.add(l);
103
+ for (const [l, c] of footCount) if (c >= threshold) footers.add(l);
104
+ return { headers, footers };
105
+ }
106
+
107
+ /**
108
+ * 主流程:清洗源文本。
109
+ * @param {string} content — 原始文本(\f 分页)
110
+ * @returns {{ content: string, stats: object }}
111
+ */
112
+ export function mergePages(content) {
113
+ const stats = { mergedParagraphs: 0, mergedHyphens: 0, removedHeadings: 0, pages: 0 };
114
+
115
+ let pages = content.split('\f');
116
+ stats.pages = pages.filter(p => p.trim()).length;
117
+
118
+ // 1) 页眉页脚清理
119
+ const { headers, footers } = detectRunningHeads(pages);
120
+ pages = pages.map(page => {
121
+ let lines = page.split('\n');
122
+ const before = lines.length;
123
+ // 从页首剥除命中页眉的行
124
+ while (lines.length && headers.has(lines[0].trim())) { lines.shift(); stats.removedHeadings++; }
125
+ // 从页尾剥除命中页脚的行
126
+ while (lines.length && footers.has(lines[lines.length - 1].trim())) { lines.pop(); stats.removedHeadings++; }
127
+ return lines.join('\n');
128
+ });
129
+
130
+ // 2) 跨页段落/断词合并(含链式:同段连续跨多页时沿链合并到底)
131
+ for (let i = 0; i < pages.length - 1; i++) {
132
+ // 内层循环:页 i 末段与页 i+1 首段合并后,合并段成为页 i+1 新首段,
133
+ // 需继续与页 i+2 检查,直到段尾完整或不再续接
134
+ let guard = 0;
135
+ while (guard++ < 100) {
136
+ const pageN = pages[i];
137
+ const pageN1 = pages[i + 1];
138
+ if (!pageN || !pageN1 || !pageN.trim() || !pageN1.trim()) break;
139
+
140
+ const parasN = pageN.split(/\n\s*\n/);
141
+ // 找页 N 最后一个非空段
142
+ let lastIdx = -1;
143
+ for (let k = parasN.length - 1; k >= 0; k--) {
144
+ if (parasN[k].trim()) { lastIdx = k; break; }
145
+ }
146
+ if (lastIdx < 0) break;
147
+ const lastPara = parasN[lastIdx];
148
+
149
+ const parasN1 = pageN1.split(/\n\s*\n/, 2);
150
+ const firstPara = (parasN1[0] || '').trimStart();
151
+ if (!firstPara) break;
152
+
153
+ const incomplete = !isParagraphComplete(lastPara);
154
+ const continuation = looksLikeContinuation(firstPara);
155
+ const hyphenBreak = endsWithHyphenBreak(lastPara) && /^[a-zà-ÿ]/.test(firstPara);
156
+
157
+ if (incomplete && (continuation || hyphenBreak)) {
158
+ let joined;
159
+ if (hyphenBreak) {
160
+ // 断词合并:去掉页尾连字符,直接连接
161
+ joined = lastPara.trimEnd().replace(/-$/, '') + firstPara;
162
+ stats.mergedHyphens++;
163
+ } else {
164
+ joined = lastPara.trimEnd() + ' ' + firstPara;
165
+ }
166
+ stats.mergedParagraphs++;
167
+ // 页 N:去掉末段
168
+ pages[i] = parasN.slice(0, lastIdx).join('\n\n').trimEnd();
169
+ // 页 N+1:首段替换为合并段(成为新页首段,供下一轮链式检查)
170
+ const rest = pageN1.trimStart().slice(firstPara.length);
171
+ pages[i + 1] = joined + rest;
172
+ // 段尾仍不完整 → 继续与下一页合并(链式);否则结束本接缝
173
+ if (isParagraphComplete(joined)) break;
174
+ } else {
175
+ break;
176
+ }
177
+ }
178
+ }
179
+
180
+ // 3) 重组:页间以 \n\n 相连(保留段落边界语义,页分隔符使命完成)
181
+ const cleaned = pages.map(p => p.trim()).filter(Boolean).join('\n\n') + '\n';
182
+ return { content: cleaned, stats };
183
+ }
184
+
185
+ // --- CLI ---
186
+
187
+ const isMain = !process.env.JEST_WORKER_ID && import.meta.url === `file://${process.argv[1]}`;
188
+
189
+ if (isMain) {
190
+ const sourcePath = process.argv[2];
191
+ if (!sourcePath) {
192
+ console.error('usage: node merge-pages.js <source.txt>');
193
+ process.exit(1);
194
+ }
195
+ const content = readFileSync(sourcePath, 'utf-8');
196
+ const { content: cleaned, stats } = mergePages(content);
197
+ writeFileSync(sourcePath, cleaned, 'utf-8');
198
+ console.log(
199
+ `pages: ${stats.pages}, merged-paragraphs: ${stats.mergedParagraphs}, ` +
200
+ `merged-hyphens: ${stats.mergedHyphens}, removed-heading-lines: ${stats.removedHeadings}`
201
+ );
202
+ }
@@ -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
+ }
@@ -0,0 +1,200 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * verify-chunk.js — 随块自检脚本(ESM)
4
+ *
5
+ * 输入:stdin JSON { "original": "<原文>", "translated": "<译文>" }
6
+ * 可选:stdin JSON 增加字段 "glossary": "<术语表内容>" 启用术语检查
7
+ * 也可用参数传入输入文件:node verify-chunk.js <input.json>(兼容 stdin)
8
+ * 输出:stdout "VALID" 或 "INVALID: <原因>"
9
+ *
10
+ * 校验项(全部通过 = VALID,任一不过 = INVALID):
11
+ * 1. 段落数一致:原文段落数 = 译文段落数 / 2(双语交替格式)
12
+ * 2. 脚注 ID 一致:原文脚注 ID 集合 = 译文脚注 ID 集合
13
+ * 3. [CONT] 标记配对:每个 [CONT] 在原文段 + 译文段各出现一次(偶数配对)
14
+ * 4. 术语一致性:术语表中的术语在译文中使用正确(需传入 glossary 字段)
15
+ */
16
+
17
+ import { readFileSync, existsSync } from 'fs';
18
+
19
+ function readStdin() {
20
+ return new Promise((resolve) => {
21
+ let data = '';
22
+ process.stdin.setEncoding('utf-8');
23
+ process.stdin.on('data', (chunk) => { data += chunk; });
24
+ process.stdin.on('end', () => resolve(data));
25
+ });
26
+ }
27
+
28
+ // Count paragraphs (non-empty lines separated by empty lines)
29
+ function countParagraphs(text) {
30
+ const lines = text.split(/\n/);
31
+ let count = 0;
32
+ let inPara = false;
33
+ for (const line of lines) {
34
+ if (line.trim().length > 0) {
35
+ if (!inPara) {
36
+ count++;
37
+ inPara = true;
38
+ }
39
+ } else {
40
+ inPara = false;
41
+ }
42
+ }
43
+ return count;
44
+ }
45
+
46
+ // Extract unique footnote IDs ([^N] patterns)
47
+ function getFootnoteIds(text) {
48
+ const matches = text.match(/\[\^(\d+)\]/g);
49
+ if (!matches) return new Set();
50
+ const ids = new Set();
51
+ for (const m of matches) {
52
+ const num = m.match(/\[\^(\d+)\]/);
53
+ if (num) ids.add(num[1]);
54
+ }
55
+ return ids;
56
+ }
57
+
58
+ // Count [CONT] markers
59
+ function countCont(text) {
60
+ const matches = text.match(/\[CONT\]/g);
61
+ return matches ? matches.length : 0;
62
+ }
63
+
64
+ // Parse glossary and check terminology consistency
65
+ // glossary format: markdown table with | 原文 | 译文 | ... rows
66
+ function checkGlossary(translated, glossary) {
67
+ const errors = [];
68
+ const lines = glossary.split('\n').filter(l => l.trim().startsWith('|') && !l.includes('---') && !l.includes('原文'));
69
+
70
+ for (const line of lines) {
71
+ const cells = line.split('|').map(c => c.trim()).filter(c => c.length > 0);
72
+ if (cells.length >= 2) {
73
+ const original = cells[0];
74
+ const translation = cells[1];
75
+ // Check if the original term appears in the translated text
76
+ // (the translated text includes both original and translation paragraphs)
77
+ if (translated.includes(original)) {
78
+ // Term found in text — check if the translation is used
79
+ if (!translated.includes(translation)) {
80
+ errors.push(`术语不一致: "${original}" 应译为 "${translation}" 但译文中未找到该译法`);
81
+ }
82
+ }
83
+ }
84
+ }
85
+ return errors;
86
+ }
87
+
88
+ async function main() {
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
+
102
+ let data;
103
+
104
+ try {
105
+ data = JSON.parse(input);
106
+ } catch (e) {
107
+ console.log('INVALID: stdin is not valid JSON');
108
+ return;
109
+ }
110
+
111
+ if (!data.original || !data.translated) {
112
+ console.log('INVALID: missing "original" or "translated" field');
113
+ return;
114
+ }
115
+
116
+ const original = data.original;
117
+ const translated = data.translated;
118
+
119
+ const origParas = countParagraphs(original);
120
+ const transParas = countParagraphs(translated);
121
+
122
+ // In bilingual format, translated should have ~2x paragraphs (original + translation alternating)
123
+ const expectedTransParas = origParas * 2;
124
+ const paraTolerance = Math.max(2, Math.ceil(origParas * 0.1));
125
+
126
+ // Compare unique footnote ID sets
127
+ const origFnIds = getFootnoteIds(original);
128
+ const transFnIds = getFootnoteIds(translated);
129
+
130
+ // [CONT] check: in bilingual output, [CONT] appears in original para + translation para = even count
131
+ // Original chunk (from chunk-text.js) may have [CONT] at the end (added by chunk-text.js)
132
+ // Translated (bilingual) should have 2x the original's [CONT] count
133
+ const origCont = countCont(original);
134
+ const transCont = countCont(translated);
135
+
136
+ const errors = [];
137
+
138
+ // 1. Check paragraph count (bilingual should have ~2x)
139
+ if (Math.abs(transParas - expectedTransParas) > paraTolerance) {
140
+ errors.push(`段落数不匹配: 原文 ${origParas} 段, 译文 ${transParas} 段 (期望 ~${expectedTransParas} 段, 容差 ${paraTolerance})`);
141
+ }
142
+
143
+ // 1a. Check the chunk does not END with an unpaired original paragraph
144
+ // (bilingual flow must end with a translation paragraph; an original-only
145
+ // trailing paragraph becomes an orphan in the aggregated output)
146
+ {
147
+ const transLines = translated.trimEnd().split('\n');
148
+ let lastNonEmpty = '';
149
+ for (let i = transLines.length - 1; i >= 0; i--) {
150
+ if (transLines[i].trim().length > 0) { lastNonEmpty = transLines[i].trim(); break; }
151
+ }
152
+ const lastIsZh = /[\u4e00-\u9fff]/.test(lastNonEmpty);
153
+ if (!lastIsZh) {
154
+ errors.push(`块尾为未配对的原文段: "${lastNonEmpty.slice(0, 40)}"(每个原文段必须有对应译文段)`);
155
+ }
156
+ }
157
+
158
+ // 2. Check footnote IDs match (unique set comparison)
159
+ if (origFnIds.size > 0) {
160
+ const missingInTrans = [...origFnIds].filter(id => !transFnIds.has(id));
161
+ const extraInTrans = [...transFnIds].filter(id => !origFnIds.has(id));
162
+ if (missingInTrans.length > 0) {
163
+ errors.push(`脚注缺失: 原文有 [^${missingInTrans.join('], [^')}] 但译文中未找到`);
164
+ }
165
+ if (extraInTrans.length > 0) {
166
+ errors.push(`脚注多余: 译文有 [^${extraInTrans.join('], [^')}] 但原文中未找到`);
167
+ }
168
+ }
169
+
170
+ // 3. [CONT] check (fixed):
171
+ // If original chunk has [CONT] markers (added by chunk-text.js), bilingual should have 2x
172
+ // If original has no [CONT], bilingual should also have 0 (LLM shouldn't add [CONT] on its own)
173
+ if (origCont > 0) {
174
+ // Original has [CONT] → bilingual should have 2x (original para + translation para)
175
+ if (transCont !== origCont * 2) {
176
+ errors.push(`[CONT] 标记不配对: 原文 ${origCont} 个, 译文 ${transCont} 个 (期望 ${origCont * 2} 个)`);
177
+ }
178
+ } else {
179
+ // Original has no [CONT] → bilingual should have 0
180
+ if (transCont > 0) {
181
+ errors.push(`[CONT] 标记多余: 原文无 [CONT] 但译文有 ${transCont} 个 (LLM 不应自行添加 [CONT])`);
182
+ }
183
+ }
184
+
185
+ // 4. Terminology check (optional, only if glossary provided)
186
+ if (data.glossary) {
187
+ const glossaryErrors = checkGlossary(translated, data.glossary);
188
+ errors.push(...glossaryErrors);
189
+ }
190
+
191
+ if (errors.length > 0) {
192
+ console.log('INVALID: ' + errors.join('; '));
193
+ } else {
194
+ console.log('VALID');
195
+ }
196
+ }
197
+
198
+ main().catch((e) => {
199
+ console.log('INVALID: ' + e.message);
200
+ });