@wwkit/harness 1.0.35 → 1.0.36

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 (52) hide show
  1. package/package.json +4 -2
  2. package/readme/testing.md +4 -4
  3. package/skills/better-agent/SKILL.md +280 -0
  4. package/skills/better-agent/references/new-mode.md +142 -0
  5. package/skills/{better-agents → better-agentsmd}/SKILL.md +16 -16
  6. package/skills/{better-agents → better-agentsmd}/references/evidence-map.md +2 -2
  7. package/skills/{better-agents → better-agentsmd}/references/format-spec.md +3 -3
  8. package/skills/{better-agents → better-agentsmd}/references/section-template.md +3 -3
  9. package/skills/better-skill/SKILL.md +1 -1
  10. package/skills/better-skill-test/SKILL.md +312 -0
  11. package/skills/better-skill-test/references/test-patterns.md +224 -0
  12. package/skills/better-tool/SKILL.md +321 -0
  13. package/skills/better-tool/references/new-mode.md +217 -0
  14. package/skills/better-tool-test/SKILL.md +310 -0
  15. package/skills/better-tool-test/references/test-patterns.md +278 -0
  16. package/skills/blame-agent/SKILL.md +197 -0
  17. package/skills/blame-agent/references/scoring-rules.md +258 -0
  18. package/skills/{blame-agents → blame-agentsmd}/SKILL.md +8 -8
  19. package/skills/{blame-agents → blame-agentsmd}/references/check-agents.js +1 -1
  20. package/skills/blame-skill/references/scoring-rules.md +3 -3
  21. package/skills/blame-skill-test/SKILL.md +179 -0
  22. package/skills/blame-skill-test/references/scoring-rules.md +112 -0
  23. package/skills/blame-tool/SKILL.md +144 -0
  24. package/skills/blame-tool/references/scoring-rules.md +112 -0
  25. package/skills/blame-tool-test/SKILL.md +165 -0
  26. package/skills/blame-tool-test/references/scoring-rules.md +85 -0
  27. package/skills/extract/SKILL.md +55 -7
  28. package/skills/extract/references/detail.md +1 -1
  29. package/skills/extract/references/list.md +2 -2
  30. package/skills/extract/references/navi.md +1 -1
  31. package/skills/extract/references/text.md +1 -1
  32. package/skills/revise/SKILL.md +85 -16
  33. package/skills/tsl/SKILL.md +130 -37
  34. package/skills/tsl/package.json +1 -0
  35. package/skills/{tsl-format → tsl}/references/format-prompt.md +3 -7
  36. package/skills/{tsl-format → tsl}/references/format-rules.md +5 -8
  37. package/skills/tsl/references/translation-prompt.md +1 -0
  38. package/skills/tsl/references/translation-rules.md +6 -8
  39. package/skills/tsl/scripts/check-paragraphs.js +71 -0
  40. package/skills/tsl/scripts/md-to-docx.js +310 -0
  41. package/skills/tsl-format/SKILL.md +50 -34
  42. /package/skills/{blame-agents → blame-agentsmd}/references/scoring-rules.md +0 -0
  43. /package/skills/extract/{references → scripts}/build-xpath.js +0 -0
  44. /package/skills/extract/{references → scripts}/clean-html.js +0 -0
  45. /package/skills/extract/{references → scripts}/extract-detail.js +0 -0
  46. /package/skills/extract/{references → scripts}/extract-regex.js +0 -0
  47. /package/skills/extract/{references → scripts}/extract-sample.js +0 -0
  48. /package/skills/extract/{references → scripts}/to-text.js +0 -0
  49. /package/skills/extract/{references → scripts}/validate-schema.js +0 -0
  50. /package/skills/revise/{references → scripts}/validate-schema.js +0 -0
  51. /package/skills/{tsl-format → tsl}/scripts/chunk-bilingual.js +0 -0
  52. /package/skills/{tsl-format → tsl}/scripts/merge-format.js +0 -0
@@ -0,0 +1,310 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * md-to-docx.js — Markdown 转 docx 脚本(ESM)
4
+ *
5
+ * 将 Markdown 内容/文件转换为 Microsoft Word (.docx)。
6
+ * 被 tsl(Item 5 docx 段)和 tsl-format(Item 6)共同引用。
7
+ *
8
+ * 三道转换前/后修正(缺一不可,都针对 Word 打开 docx 报错):
9
+ * 1. sanitizeMarkdownUrls(转换前):把"裸 URL + 全角标点/CJK 紧贴"的畸形转成
10
+ * 标准 Markdown 链接,防止 marked 的 GFM autolink 把全角标点/中文吞入 href
11
+ * 生成非法 URI(Word 打开报超链接错误)。
12
+ * 2. normalizeFootnoteLabels(转换前):tsl/tsl-format 产物中每章脚注重新编号
13
+ * ([^1]..[^N]),全书 label 大量复用。markdown-docx 用 label 作 key,后章
14
+ * 定义覆盖前章定义,生成大量"孤儿定义 + 重复引用",Word 报成百上千个脚注
15
+ * 错误。本函数按"正文引用 → 之后最近的同 label 定义"配对,把 label 重写为
16
+ * 全局唯一 [^f1]..[^fN];同时给紧贴正文段落的定义行前补空行(否则 marked
17
+ * 的 paragraph tokenizer 会吞掉定义行,footnote 扩展匹配不到)。
18
+ * 3. rebuildFootnotes(转换后兜底):把 document.xml 每个脚注/尾注引用按出现
19
+ * 顺序分配唯一 id(同一旧 id 的重复引用拆分为独立定义,内容复制),重建
20
+ * footnotes.xml/endnotes.xml(保留 Word 规范的 separator id=-1 与
21
+ * continuationSeparator id=0,并保留 XML 声明与完整 xmlns——两者缺失都会让
22
+ * Word 报 xml parsing error),删除无引用的孤儿定义。
23
+ *
24
+ * 用法:node md-to-docx.js <input.md> <output.docx> [--ignore-image]
25
+ * stdout: docx: <input> → <output> (bytes=N)
26
+ * 退出码:0 成功 / 2 参数或输入错误 / 1 转换或写入失败
27
+ */
28
+
29
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'fs';
30
+ import { dirname } from 'path';
31
+ import markdownDocx, { Packer } from 'markdown-docx';
32
+ import JSZip from 'jszip';
33
+
34
+ // markdown-docx 默认选项:启用 GFM(脚注/表格/删除线等扩展语法依赖)
35
+ const DEFAULTS = { gfm: true };
36
+
37
+ /**
38
+ * 将跨章节复用的脚注 label 归一化为全局唯一(转换前预处理)。
39
+ *
40
+ * 背景:tsl/tsl-format 产物中每章脚注重新编号([^1]..[^N]),全书 label 大量
41
+ * 复用(实测 141 个定义行只有 14 个唯一 label)。markdown-docx 的 label→id Map
42
+ * 被后章定义覆盖,导致前章脚注内容丢失、生成大量孤儿定义与重复引用,Word 打开
43
+ * 报"成百上千个脚注错误"。
44
+ *
45
+ * 配对规则:正文引用 [^x] 对应其"之后最近"的同 label 定义(tsl-format 产物中
46
+ * 脚注定义位于各章末尾,正文引用在前)。定义在前、引用在后的罕见场景回退到
47
+ * "之前最近"的同 label 定义。无法配对的引用保留原样(不报错,按普通文本处理)。
48
+ *
49
+ * @param {string} markdown - 原始 Markdown 文本
50
+ * @returns {string} 归一化后的 Markdown(label 全部形如 [^f1]..[^fN])
51
+ */
52
+ export function normalizeFootnoteLabels(markdown) {
53
+ const lines = markdown.split('\n');
54
+ const defs = new Map(); // label -> [行号]
55
+ const defLines = new Set(); // 定义行号
56
+ let inCode = false;
57
+ lines.forEach((l, i) => {
58
+ if (/^\s*```/.test(l)) {
59
+ inCode = !inCode;
60
+ return;
61
+ }
62
+ if (inCode) return;
63
+ const m = l.match(/^\[\^([^\]\n]+)\]:/);
64
+ if (m) {
65
+ const label = m[1];
66
+ if (!defs.has(label)) defs.set(label, []);
67
+ defs.get(label).push(i);
68
+ defLines.add(i);
69
+ }
70
+ });
71
+
72
+ // 引用位置(跳过定义行与 ``` 代码块)
73
+ const refs = new Map(); // label -> [行号]
74
+ inCode = false;
75
+ lines.forEach((l, i) => {
76
+ if (/^\s*```/.test(l)) {
77
+ inCode = !inCode;
78
+ return;
79
+ }
80
+ if (inCode || defLines.has(i)) return;
81
+ for (const m of l.matchAll(/\[\^([^\]\n]+)\]/g)) {
82
+ const label = m[1];
83
+ if (!refs.has(label)) refs.set(label, []);
84
+ refs.get(label).push(i);
85
+ }
86
+ });
87
+
88
+ // 定义按文档顺序编号(1..N)
89
+ const defOrder = [];
90
+ for (const [label, positions] of defs) for (const li of positions) defOrder.push({ label, li });
91
+ defOrder.sort((a, b) => a.li - b.li);
92
+ const idxOf = new Map(); // `${label}#${行号}` -> 全局序号
93
+ defOrder.forEach((d, i) => idxOf.set(`${d.label}#${d.li}`, i + 1));
94
+
95
+ // 引用 → 定义映射(之后最近优先,回退之前最近)
96
+ const refIdx = new Map(); // `${label}#${行号}` -> 定义序号 | -1(无法配对)
97
+ for (const [label, rlines] of refs) {
98
+ const dlines = defs.get(label) || [];
99
+ for (const li of rlines) {
100
+ const later = dlines.find((d) => d > li);
101
+ if (later !== undefined) {
102
+ refIdx.set(`${label}#${li}`, idxOf.get(`${label}#${later}`));
103
+ } else {
104
+ const earlier = [...dlines].reverse().find((d) => d < li);
105
+ refIdx.set(`${label}#${li}`, earlier !== undefined ? idxOf.get(`${label}#${earlier}`) : -1);
106
+ }
107
+ }
108
+ }
109
+
110
+ return lines
111
+ .map((l, i) => {
112
+ if (defLines.has(i)) {
113
+ const rewritten = l.replace(/^\[\^([^\]\n]+)\]:/, (m, label) => `[^f${idxOf.get(`${label}#${i}`)}]:`);
114
+ // 定义行前补空行(若前一行非空且非文档开头):marked 的 paragraph tokenizer
115
+ // 会把紧贴正文段落(无空行分隔)的定义行吞进段落,footnote 扩展永远匹配不到。
116
+ return (i > 0 && lines[i - 1].trim() !== '' ? '\n' : '') + rewritten;
117
+ }
118
+ return l.replace(/\[\^([^\]\n]+)\]/g, (m, label) => {
119
+ const idx = refIdx.get(`${label}#${i}`);
120
+ return idx && idx > 0 ? `[^f${idx}]` : m;
121
+ });
122
+ })
123
+ .join('\n');
124
+ }
125
+
126
+ /**
127
+ * 解析 footnotes.xml / endnotes.xml,供 rebuildFootnotes 重建时复用。
128
+ *
129
+ * 返回对象字段:
130
+ * - decl:XML 声明(`<?xml ...?>`),重建时必须原样保留
131
+ * - rootOpen:根开标签(含全部 xmlns 声明),重建时必须原样保留
132
+ * - sep / contSep:separator / continuationSeparator 定义(Word 规范 id=-1 / 0)
133
+ * - defs:普通脚注定义 id → 内部 XML 的映射
134
+ * - tag / plural:元素名('footnote'/'footnotes' 或 'endnote'/'endnotes')
135
+ *
136
+ * @param {string} xml - footnotes.xml 或 endnotes.xml 文本
137
+ * @param {string} tag - 'footnote' | 'endnote'
138
+ */
139
+ function parseNotesXml(xml, tag) {
140
+ const plural = `${tag}s`;
141
+ // 必须保留 XML 声明(<?xml ...?>)与根开标签的完整 xmlns 声明:
142
+ // 若丢失,w: 前缀未绑定命名空间,Word 报 "xml parsing error"(行0,列0)。
143
+ const decl = xml.match(/^<\?xml[^>]*\?>/)?.[0] || '';
144
+ const rootOpen = xml.match(new RegExp(`<w:${plural}[^>]*>`))?.[0] || `<w:${plural}>`;
145
+ const sep = xml.match(new RegExp(`<w:${tag} w:type="separator"[^>]*>.*?</w:${tag}>`, 's'))?.[0] || '';
146
+ const contSep = xml.match(
147
+ new RegExp(`<w:${tag} w:type="continuationSeparator"[^>]*>.*?</w:${tag}>`, 's')
148
+ )?.[0] || '';
149
+ const defs = new Map();
150
+ const re = new RegExp(`<w:${tag} w:id="(\\d+)">(.*?)</w:${tag}>`, 'gs');
151
+ let m;
152
+ while ((m = re.exec(xml))) defs.set(parseInt(m[1], 10), m[2]);
153
+ return { decl, rootOpen, sep, contSep, defs, tag, plural };
154
+ }
155
+
156
+ /**
157
+ * 重建 docx 中的脚注/尾注结构(转换后兜底)。
158
+ *
159
+ * 保证每个引用在 document.xml 中有唯一定义且定义全部被引用,彻底消除
160
+ * "重复引用 + 孤儿定义"(Word 严格校验的报错来源);保留 Word 规范的
161
+ * separator(id=-1) / continuationSeparator(id=0) 以及 XML 声明与完整 xmlns
162
+ * 命名空间(缺失则 Word 报 xml parsing error 行0列0);普通脚注按引用出现
163
+ * 顺序分配连续 id(1..M)。同一旧 id 的重复引用拆分为独立定义(内容复制)。
164
+ *
165
+ * @param {Buffer} docxBuffer - 原始 docx buffer
166
+ * @returns {Promise<Buffer>} 重建后的 docx buffer
167
+ */
168
+ export async function rebuildFootnotes(docxBuffer) {
169
+ const zip = await JSZip.loadAsync(docxBuffer);
170
+ const docXml = await zip.file('word/document.xml').async('string');
171
+
172
+ // 引用按在 document.xml 中的出现顺序重编号为 1..M(每个引用一个唯一 id)
173
+ let fnCounter = 0;
174
+ let enCounter = 0;
175
+ const fnUses = []; // { oldId, newId }:脚注引用记录
176
+ const enUses = []; // { oldId, newId }:尾注引用记录
177
+ const newDocXml = docXml
178
+ .replace(/w:footnoteReference w:id="(-?\d+)"/g, (m, id) => {
179
+ fnCounter += 1;
180
+ fnUses.push({ oldId: parseInt(id, 10), newId: fnCounter });
181
+ return `w:footnoteReference w:id="${fnCounter}"`;
182
+ })
183
+ .replace(/w:endnoteReference w:id="(-?\d+)"/g, (m, id) => {
184
+ enCounter += 1;
185
+ enUses.push({ oldId: parseInt(id, 10), newId: enCounter });
186
+ return `w:endnoteReference w:id="${enCounter}"`;
187
+ });
188
+
189
+ // 按引用记录重建 notes XML:声明 + 根开标签 + 两个特殊定义 + 普通定义
190
+ const buildNotes = (notes, uses) => {
191
+ const { decl, rootOpen, sep, contSep, defs, tag, plural } = notes;
192
+ let body = '';
193
+ for (const { oldId, newId } of uses) {
194
+ // 引用无对应定义时用空段落占位(正常流程不会发生,仅为结构兜底)
195
+ const inner = defs.get(oldId) || '<w:p><w:r><w:t xml:space="preserve"> </w:t></w:r></w:p>';
196
+ body += `<w:${tag} w:id="${newId}">${inner}</w:${tag}>`;
197
+ }
198
+ return `${decl}${rootOpen}${sep}${contSep}${body}</w:${plural}>`;
199
+ };
200
+
201
+ if (zip.file('word/footnotes.xml')) {
202
+ const fnXml = await zip.file('word/footnotes.xml').async('string');
203
+ zip.file('word/footnotes.xml', buildNotes(parseNotesXml(fnXml, 'footnote'), fnUses));
204
+ }
205
+ if (zip.file('word/endnotes.xml')) {
206
+ const enXml = await zip.file('word/endnotes.xml').async('string');
207
+ zip.file('word/endnotes.xml', buildNotes(parseNotesXml(enXml, 'endnote'), enUses));
208
+ }
209
+ zip.file('word/document.xml', newDocXml);
210
+ return zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });
211
+ }
212
+
213
+ /**
214
+ * 裸 URL 匹配:https?:// 或 www. 开头,到空白/尖括号/全角标点/CJK 为止。
215
+ * 前缀排除半角 ( 和 ] —— 已是标准链接目标 `[text](url)` 的 URL 不被处理。
216
+ */
217
+ const BARE_URL_RE = /(^|[^(\]])((?:https?:\/\/|www\.)[^\s<()《》“”‘’!?,。;:、\u4e00-\u9fff]+)/g;
218
+
219
+ /** URL 尾部回退的半角标点(与 marked _backpedal 一致)。 */
220
+ const TRAILING_ASCII_PUNCT = /[?!.,:;*_'"~)]+$/;
221
+
222
+ /**
223
+ * 清洗 Markdown 中的畸形裸 URL。
224
+ *
225
+ * 背景:marked 的 GFM autolink 对裸 URL 只回退半角尾部标点,
226
+ * 全角标点()、。,等)与 CJK 字符会被吞入 href,生成的 docx 超链接
227
+ * URI 非法,Word 打开时报错。本函数在转换前把畸形裸 URL 转为标准
228
+ * Markdown 链接 [url](url),URL 后的全角标点/中文保持在链接外。
229
+ *
230
+ * @param {string} markdown - 原始 Markdown 文本
231
+ * @returns {string} 清洗后的 Markdown 文本
232
+ */
233
+ export function sanitizeMarkdownUrls(markdown) {
234
+ return markdown.replace(BARE_URL_RE, (match, prefix, url) => {
235
+ // 回退 URL 尾部半角标点(如 `pdf.` → url=`pdf`,`.` 放回链接外)
236
+ const cleaned = url.replace(TRAILING_ASCII_PUNCT, '');
237
+ if (cleaned.length === 0) return match;
238
+ const rest = url.slice(cleaned.length);
239
+ return `${prefix}[${cleaned}](${cleaned})${rest}`;
240
+ });
241
+ }
242
+
243
+ /**
244
+ * 将 Markdown 内容转换为 docx Buffer。
245
+ * 流程:sanitizeMarkdownUrls(畸形 URL 清洗)→ normalizeFootnoteLabels(脚注
246
+ * label 全局唯一化)→ markdown-docx 转换 → rebuildFootnotes(脚注结构兜底重建)。
247
+ * @param {string} markdown - Markdown 文本内容
248
+ * @param {object} [options] - markdown-docx 转换选项
249
+ * @returns {Promise<Buffer>} docx 文件 buffer
250
+ */
251
+ export async function mdToDocxBuffer(markdown, options = {}) {
252
+ const cleaned = normalizeFootnoteLabels(sanitizeMarkdownUrls(markdown));
253
+ const doc = await markdownDocx(cleaned, { ...DEFAULTS, ...options });
254
+ const rawBuf = await Packer.toBuffer(doc);
255
+ return rebuildFootnotes(rawBuf);
256
+ }
257
+
258
+ /**
259
+ * 将 Markdown 文件转换为 docx 文件。
260
+ * @param {string} inputPath - 输入 .md 文件路径
261
+ * @param {string} outputPath - 输出 .docx 文件路径(父目录不存在时自动创建)
262
+ * @param {object} [options] - markdown-docx 转换选项
263
+ * @returns {Promise<{ inputPath: string, outputPath: string, bytes: number }>}
264
+ * @throws {Error} 参数缺失 / 输入文件不存在 / 转换或写入失败
265
+ */
266
+ export async function mdToDocx(inputPath, outputPath, options = {}) {
267
+ if (!inputPath || !outputPath) {
268
+ throw new Error('Usage: node md-to-docx.js <input.md> <output.docx>');
269
+ }
270
+ if (!existsSync(inputPath)) {
271
+ throw new Error(`ERROR: input file not found: ${inputPath}`);
272
+ }
273
+ const markdown = readFileSync(inputPath, 'utf-8');
274
+ const buf = await mdToDocxBuffer(markdown, options);
275
+ mkdirSync(dirname(outputPath), { recursive: true });
276
+ writeFileSync(outputPath, buf);
277
+ return { inputPath, outputPath, bytes: buf.length };
278
+ }
279
+
280
+ // --- CLI entry point (only when run directly, not when imported) ---
281
+
282
+ const isMain = import.meta.url === `file://${process.argv[1]}`;
283
+
284
+ if (isMain) {
285
+ const args = process.argv.slice(2);
286
+ const inputPath = args[0];
287
+ const outputPath = args[1];
288
+ const options = args.includes('--ignore-image') ? { ignoreImage: true } : {};
289
+
290
+ if (!inputPath || !outputPath) {
291
+ console.error('Usage: node md-to-docx.js <input.md> <output.docx> [--ignore-image]');
292
+ process.exit(2);
293
+ }
294
+ if (!inputPath.endsWith('.md')) {
295
+ console.error(`ERROR: input must be a .md file: ${inputPath}`);
296
+ process.exit(2);
297
+ }
298
+ if (!existsSync(inputPath)) {
299
+ console.error(`ERROR: input file not found: ${inputPath}`);
300
+ process.exit(2);
301
+ }
302
+
303
+ try {
304
+ const result = await mdToDocx(inputPath, outputPath, options);
305
+ console.log(`docx: ${result.inputPath} → ${result.outputPath} (bytes=${result.bytes})`);
306
+ } catch (e) {
307
+ console.error(e.message);
308
+ process.exit(1);
309
+ }
310
+ }
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: tsl-format
3
- description: Use when formatting already-translated bilingual documents that lack Markdown markup. Triggers on: format bilingual text, add Markdown headings/bold/italic to translated documents, post-translation formatting. Does NOT translate or clean text—only adds structural formatting to existing bilingual content. Supports large files via chunked pipeline with subagent parallel processing and resume from checkpoint.
3
+ description: Use when formatting already-translated bilingual documents that lack Markdown markup. Triggers on: format bilingual text, add Markdown headings/bold/italic to translated documents, post-translation formatting. Does NOT translate or clean text—only adds structural formatting to existing bilingual content. Supports large files via chunked pipeline with subagent parallel processing and resume from checkpoint. Optionally generates a same-name .docx via md-to-docx.js.
4
4
  license: MIT
5
5
  metadata:
6
6
  workflow: sequential
@@ -18,9 +18,9 @@ metadata:
18
18
  2. **Sprint Execution**:逐项执行(进入前 in_progress → 执行 → 验证 DoD → todowrite 勾单 completed),其中 Item 4 为核心格式化阶段(支持 subagent 并行)
19
19
  3. **Sprint Review**:对照 Sprint Goal 验证 Increment(格式化后的文档)
20
20
 
21
- **Sprint Goal** = `对已翻译的双语对照文档执行格式重建(标题/粗体/斜体),输出格式化后的 -fmt.md 文件`
21
+ **Sprint Goal** = `对已翻译的双语对照文档执行格式重建(标题/粗体/斜体),输出格式化后的 -fmt.md 文件及同名 .docx 文件`
22
22
 
23
- **Increment** = `<input_dir>/<文件名>-fmt.md`(原文件内容 + Markdown 格式标记)
23
+ **Increment** = `<input_dir>/<文件名>-fmt.md`(原文件内容 + Markdown 格式标记)+ `<input_dir>/<文件名>-fmt.docx`(Word 成品)
24
24
 
25
25
  ## When to Use
26
26
 
@@ -44,49 +44,52 @@ metadata:
44
44
 
45
45
  ## 输出
46
46
 
47
- `<文件名>-fmt.md` 创建在**输入文件同目录**下。原文件不修改。
47
+ `<文件名>-fmt.md` 创建在**输入文件同目录**下。原文件不修改。Item 6 生成同名 `<文件名>-fmt.docx`。
48
48
 
49
49
  ```
50
50
  <input_dir>/
51
51
  ├── <文件名>.md # 原文件(不修改)
52
- └── <文件名>-fmt.md # 格式化后的文件(新增)
52
+ ├── <文件名>-fmt.md # 格式化后的文件(新增)
53
+ └── <文件名>-fmt.docx # Word 成品(Item 6 新增)
53
54
  ```
54
55
 
55
- **增量输出**:每完成一批 chunk 的格式化+合并,立即追加到 `formatted.md`。即使中途崩溃,已完成的 chunk 不会丢失。重新执行时自动检测 `.tsl-format-tmp/` 已有产物,跳过已完成步骤,从断点继续。
56
+ **增量输出**:每完成一批 chunk 的格式化+合并,立即追加到 `formatted.md`。即使中途崩溃,已完成的 chunk 不会丢失。重新执行时自动检测 `.tsl/<文件名>/fmt/` 已有产物,跳过已完成步骤,从断点继续。
56
57
 
57
58
  ## 依赖
58
59
 
59
- 无外部依赖。`chunk-bilingual.js` 和 `merge-format.js` 是纯 Node.js ESM 脚本,无 npm 包依赖。
60
+ 无外部依赖。`chunk-bilingual.js` 和 `merge-format.js` 是纯 Node.js ESM 脚本(位于 `<tsl-dir>/scripts/`),无 npm 包依赖。格式规则和 dispatch prompt 位于 `<tsl-dir>/references/`。`md-to-docx.js`(Item 6)使用 `markdown-docx` npm 依赖(同 `<tsl-dir>/scripts/`)。
60
61
 
61
62
  ## 工作目录
62
63
 
63
- `.tsl-format-tmp/` 创建在**输入文件同目录**下。
64
+ `.tsl/<文件名>/fmt/` 创建在**输入文件同目录**下。
64
65
 
65
66
  ```
66
- <input_dir>/.tsl-format-tmp/
67
+ <input_dir>/.tsl/<文件名>/fmt/
67
68
  ├── p001.md ... pNNN.md # 分块文件(chunk-bilingual.js 产出)
68
69
  ├── result-p001.md ... # subagent 格式化结果(临时,合并后删除)
69
70
  ├── formatted.md # 累积格式化输出(chunk 追加)
70
71
  └── progress.md # 进度追踪(chunk 状态)
71
72
  ```
72
73
 
73
- ## 固定 Sprint Backlog(5 项,todowrite 落单,覆盖历史 todos)
74
+ ## 固定 Sprint Backlog(6 项,todowrite 落单,覆盖历史 todos)
74
75
 
75
76
  1. 解析入参 + 文件检查 | DoD: input 路径存在、是 .md 文件、词数已统计(或 stderr 结束)
76
77
  2. 分块 | DoD: 文件已按段落边界分块、每块 ≤ chunk_words 词数、chunk 数已知
77
78
  3. 进度初始化 | DoD: `progress.md` 已创建、所有 chunk 标记为 pending(短路:已存在 → **绝不覆盖,直接 skip**)
78
79
  4. 逐块格式重建(subagent 并行) | DoD: 所有 chunk 格式化完成、`progress.md` 全 done、`formatted.md` 已生成
79
80
  5. 合并 + 输出 | DoD: `<文件名>-fmt.md` 已写入、段落数与原文件一致(±5%)、临时文件已清理
81
+ 6. 生成同名 docx | DoD: `<文件名>-fmt.docx` 已生成、文件非空(短路:已存在且非空 → skip)
80
82
 
81
83
  ## Quick Reference
82
84
 
83
85
  | Item | 做什么 | 短路条件 | 关键命令/文件 |
84
86
  |---|---|---|---|
85
87
  | 1 | 解析入参 + 文件检查 | input 为空/路径不存在/非 .md → stderr 结束 | `bash wc -w <input>` |
86
- | 2 | 分块 | 文件词数 ≤ chunk_words → 单块,跳过分块 | `node '<技能目录>/scripts/chunk-bilingual.js'` |
88
+ | 2 | 分块 | 文件词数 ≤ chunk_words → 单块,跳过分块 | `node '<tsl-dir>/scripts/chunk-bilingual.js'` |
87
89
  | 3 | 进度初始化 | `progress.md` 已存在 → **绝不覆盖** | `write <tmp>/progress.md` |
88
90
  | 4 | 逐块格式重建 + 合并 | progress.md 全 done → skip | chunk ≤5 顺序 / >5 并行(≤5),批间滚动重试,merge-format.js 合并 |
89
91
  | 5 | 合并 + 输出 | — | `read formatted.md` → `write <文件名>-fmt.md` |
92
+ | 6 | 生成同名 docx | `<文件名>-fmt.docx` 已存在且非空 → skip | `node <tsl-dir>/scripts/md-to-docx.js` |
90
93
 
91
94
  ## Sprint Execution
92
95
 
@@ -96,7 +99,8 @@ metadata:
96
99
  - `<input_dir>` = input 文件所在目录
97
100
  - `<文件名>` = input 文件名去掉 .md 扩展名,原样使用
98
101
  - `<技能目录>` = skill 安装目录(skills/tsl-format/)
99
- - `<tmp>` = `<input_dir>/.tsl-format-tmp/`
102
+ - `<tsl-dir>` = `<技能目录>/../tsl`(格式规则和脚本的单源目录)
103
+ - `<tmp>` = `<input_dir>/.tsl/<文件名>/fmt/`
100
104
  - 临时分块文件在 `<tmp>` 下
101
105
 
102
106
  ### Item 1:解析入参 + 文件检查
@@ -118,7 +122,7 @@ metadata:
118
122
 
119
123
  `bash mkdir -p <tmp>`
120
124
 
121
- `node '<技能目录>/scripts/chunk-bilingual.js' '<input>' <chunk_words> '<tmp>'`
125
+ `node '<tsl-dir>/scripts/chunk-bilingual.js' '<input>' <chunk_words> '<tmp>'`
122
126
 
123
127
  脚本按段落边界(空行分隔)分块,每块 ≤ chunk_words 词数。stdout 打印总块数。
124
128
 
@@ -129,7 +133,7 @@ metadata:
129
133
  创建 `<tmp>/progress.md`:
130
134
 
131
135
  ```
132
- # tsl-format progress — file: <文件名>
136
+ # tsl format progress — book: <input_dir basename>, file: <文件名>
133
137
 
134
138
  | Chunk | 状态 | 重试 |
135
139
  |-------|------|------|
@@ -146,17 +150,17 @@ metadata:
146
150
 
147
151
  **顺序模式**(chunk 数 ≤ 5 时):
148
152
 
149
- 每个 chunk:`read` `<tmp>/pNNN.md` + `read` `<技能目录>/references/format-rules.md` → LLM 格式化 → `write` `<tmp>/result-pNNN.md`(格式同批量模式)→ 运行 `merge-format.js` 合并 → 输出 `[pNNN/总块数] done`。顺序模式与批量模式的区别仅在于无 subagent 并发,合并流程完全一致。
153
+ 每个 chunk:`read` `<tmp>/pNNN.md` + `read` `<tsl-dir>/references/format-rules.md` → LLM 格式化 → `write` `<tmp>/result-pNNN.md`(格式同批量模式)→ 运行 `merge-format.js` 合并 → 输出 `[pNNN/总块数] done`。顺序模式与批量模式的区别仅在于无 subagent 并发,合并流程完全一致。
150
154
 
151
155
  **批量并行模式**(chunk 数 > 5 时):
152
156
 
153
157
  每个 subagent 只处理 1 个 chunk。并发最多 5 个 subagent(即 5 个 chunk 同时格式化)。**并发数不可超过 5**——实测 10 并发导致高超时失败率(API 资源争用)。
154
158
 
155
- **dispatch prompt**:`read` `<技能目录>/references/format-prompt.md` → 替换 `{{变量}}`(`{{work_dir}}`、`{{chunk_file}}`、`{{chunk_id}}`、`{{format_rules_path}}`)→ 作为 task prompt 发送。不自行编写 prompt。
159
+ **dispatch prompt**:`read` `<tsl-dir>/references/format-prompt.md` → 替换 `{{变量}}`(`{{work_dir}}`、`{{chunk_file}}`、`{{chunk_id}}`、`{{format_rules_path}}`)→ 作为 task prompt 发送。不自行编写 prompt。
156
160
 
157
161
  **subagent 执行**:`read` 格式规则 + `read` chunk 文件 → LLM 格式化 → `write` `<tmp>/result-pNNN.md`。subagent 不直接写 `formatted.md`、`progress.md`。
158
162
 
159
- **result 文件格式**:详见 `references/format-prompt.md`。VALID 时含格式化内容 + `## status\n\nVALID`;INVALID 时仅含 `## status\n\nFAILED`,无内容。
163
+ **result 文件格式**:详见 `<tsl-dir>/references/format-prompt.md`。VALID 时含格式化内容 + `## status\n\nVALID`;INVALID 时仅含 `## status\n\nFAILED`,无内容。
160
164
 
161
165
  **批次循环(批间滚动重试)**:
162
166
  1. 从 `<tmp>/progress.md` 读取 chunk 状态,**收集所有待处理 chunk**:`pending` chunk + `failed` 且重试次数 < 3 的 chunk。**不可跳过任何编号。**
@@ -168,7 +172,7 @@ metadata:
168
172
 
169
173
  对每个 result 文件运行(`pNNN` = chunk 编号,如 `p001`):
170
174
  ```bash
171
- node '<技能目录>/scripts/merge-format.js' '<tmp>/result-pNNN.md' '<tmp>' 'pNNN'
175
+ node '<tsl-dir>/scripts/merge-format.js' '<tmp>/result-pNNN.md' '<tmp>' 'pNNN'
172
176
  ```
173
177
  脚本自动完成:追加格式化内容到 `formatted.md`(VALID)、更新 `progress.md`(VALID→done,FAILED→failed+retry+1)、删除 result 文件。stdout 仅输出 `pNNN VALID` 或 `pNNN FAILED`——**完整格式化内容不进入主 Agent 上下文**。
174
178
 
@@ -212,7 +216,7 @@ ORDER BY p.time_created;"
212
216
 
213
217
  4. **连续失败保护**:同一 chunk 重试 ≥ 2 次仍失败,**必须**更换策略(拆分 chunk / 主 Agent 直接处理 / 调整 prompt),不可第三次以相同方式重试
214
218
 
215
- **Rulings, not stalls**:格式化过程中遇到歧义(不确定是否为标题、术语是否标记),主 Agent 自行裁决并继续,不停下来问用户。裁决原则:不确定是否为标题 → 不标记(宁可不标记,不误标记);术语不确定 → 首次出现标记。唯一需要停下来问用户的是:源文件本身有损坏或缺失。
219
+ **Rulings, not stalls**:格式化过程中遇到歧义(不确定是否为标题、术语是否标记),主 Agent 自行裁决并继续,不停下来问用户。裁决原则:根据文档结构和语义判断是否为标题;术语不确定 → 首次出现标记。唯一需要停下来问用户的是:源文件本身有损坏或缺失。
216
220
 
217
221
  **连续执行**:批次间不暂停、不向用户汇报中间进度、不问"要继续吗"。每个 chunk 完成后输出一行状态(`[pNNN/总块数] done`)即可。只有全部 chunk 完成、遇到不可恢复错误时才停止。
218
222
 
@@ -221,38 +225,49 @@ ORDER BY p.time_created;"
221
225
  **关键约束**:`<tmp>/formatted.md` 只追加不重写。
222
226
 
223
227
  **格式化完成后**:
224
- 0. **FAILED chunk 补处理**:对重试次数 ≥ 3 仍标记为 failed 的 chunk,主 Agent 直接 `read` chunk 原文 + 格式规则 → LLM 格式化 → `write` result 文件 → 运行 `merge-format.js` 合并。**确保最终输出无缺失块。**
228
+ 0. **FAILED chunk 补处理**:对重试次数 ≥ 3 仍标记为 failed 的 chunk,主 Agent 直接 `read` chunk 原文 + `read` `<tsl-dir>/references/format-rules.md` → LLM 格式化 → `write` result 文件 → 运行 `merge-format.js` 合并。**确保最终输出无缺失块。**
225
229
  1. 确认 `<tmp>/progress.md` 全部 `done`。
226
230
 
227
231
  ### Item 5:合并 + 输出
228
232
 
229
233
  1. `read` `<tmp>/formatted.md` → `write` `<input_dir>/<文件名>-fmt.md`
230
234
  2. `bash rm -rf <tmp>`(清理临时文件)
231
- 3. `bash diff <input> <input_dir>/<文件名>-fmt.md | grep -c '^[<>]'` 统计差异行数。差异行数 / 原文件行数 > 10% → 报警(可能有内容丢失),但仍输出文件
235
+ 3. `node '<tsl-dir>/scripts/check-paragraphs.js' '<input>' '<input_dir>/<文件名>-fmt.md'` 统计段落数差异。段落数差异 > 5% → 报警(可能有内容丢失),但仍输出文件
236
+
237
+ ### Item 6:生成同名 docx
238
+
239
+ **短路**:`<input_dir>/<文件名>-fmt.docx` 已存在且非空 → skip(不覆盖已有产物,与 progress.md 铁律同精神)。
240
+
241
+ 1. `node '<tsl-dir>/scripts/md-to-docx.js' '<input_dir>/<文件名>-fmt.md' '<input_dir>/<文件名>-fmt.docx'`
242
+ - 脚本内部:读 `-fmt.md` → markdown-docx 转换 → 写 `-fmt.docx`(自动创建目录、幂等)
243
+ 2. 验证 DoD:`bash wc -c <input_dir>/<文件名>-fmt.docx` 确认存在且非空(合法 docx 即使空文档也有 ~10KB 结构)
244
+
245
+ **失败处理**:脚本 exit 1/2 → stderr 有错误信息 → 修正后重跑(脚本幂等,可安全重试)。
232
246
 
233
247
  ## Sprint Review
234
248
 
235
- 本 skill 每次调用 = 无状态独立 Sprint,无跨调用状态(进度持久化在 `.tsl-format-tmp/` 文件中,不在会话内存中),故不进行 Retrospective。
249
+ 本 skill 每次调用 = 无状态独立 Sprint,无跨调用状态(进度持久化在 `.tsl/<文件名>/fmt/` 文件中,不在会话内存中),故不进行 Retrospective。
236
250
 
237
251
  所有 Backlog Items 完成后:
238
252
 
239
253
  - **对照 Sprint Goal 验证**:双语对照文档是否已添加 Markdown 格式标记?输出文件是否已生成?
240
- - **验证 Increment**:`<文件名>-fmt.md` 存在且非空?段落数与原文件一致(±5%)?
254
+ - **验证 Increment**:`<文件名>-fmt.md` 存在且非空?段落数与原文件一致(±5%)?`<文件名>-fmt.docx` 存在且非空?
241
255
 
242
256
  ## Common Mistakes
243
257
 
244
258
  | 错误 | 原因 | 修复 |
245
259
  |---|---|---|
246
- | 格式化时修改了译文内容 | LLM 自作主张改翻译 | format-rules.md 明确禁止修改内容 |
260
+ | 格式化时修改了译文内容 | LLM 自作主张改翻译 | `<tsl-dir>/references/format-rules.md` 明确禁止修改内容 |
247
261
  | 合并时丢失块 | 未按序号读取 | merge-format.js 按批次合并,formatted.md 只追加 |
248
262
  | 原文件被覆盖 | 输出路径写错 | 输出到 `-fmt.md`,不碰原文件 |
249
263
  | 标题层级错误 | LLM 随意选层级 | 按格式规则:章节→##,小节→### |
250
- | 误标记普通段落为标题 | 短行被误判 | 裁决规则:有主谓宾→段落 |
264
+ | 误标记普通段落为标题 | 段落被误判为标题 | 根据文档结构和语义判断,非标题段落不加 `#` |
251
265
  | 逐个发起 task 调用 | 框架串行执行,非并行 | 必须在一条消息中发起全部 task 调用 |
252
266
  | subagent 直接写 formatted.md | subagent 无权写累积文件 | subagent 只写 result-pNNN.md,主 Agent 合并 |
253
267
  | progress.md 已存在但重新初始化 | 丢失所有 done 状态 | 铁律:绝不覆盖 progress.md |
254
268
  | 并发超过 5 个 subagent | API 资源争用高超时率 | 并发不超过 5 |
255
269
  | FAILED chunk 无脑重试 | 未诊断根因,相同原因反复失败 | **铁律:批间发现 FAILED 必须诊断**,按失败特征选择策略 |
270
+ | docx 输出路径写错 | 覆盖了原文件或 -fmt.md | docx 输出到 `-fmt.docx`,不碰原文件和 -fmt.md |
256
271
 
257
272
  ## Common Rationalizations
258
273
 
@@ -262,7 +277,7 @@ ORDER BY p.time_created;"
262
277
  | "标题层级我凭感觉选" | 按格式规则选层级,不凭感觉。 |
263
278
  | "这个术语不太重要,不标记粗体" | 关键术语首次出现都标记,不论"重要性"。 |
264
279
  | "原文件改一下也无所谓" | 原文件绝不修改。输出到 -fmt.md。 |
265
- | "合并后行数不一样,差不多就行" | 差异 > 10% 说明可能有内容丢失,必须排查。 |
280
+ | "合并后段落数不一样,差不多就行" | 段落数差异 > 5% 说明可能有内容丢失,必须排查。 |
266
281
  | "progress.md 已存在,重新初始化一下更干净" | **铁律:绝不覆盖 progress.md。** 重新初始化会丢失所有 done 状态,已完成的 chunk 全部重做。 |
267
282
  | "批量并行太复杂,顺序就行" | chunk 数 > 5 时必须并行,否则耗时数倍。 |
268
283
  | "一个一个分派 subagent 也算并行" | 必须在一条消息中同时发起多个 task 调用。逐个发起 = 串行。 |
@@ -281,18 +296,19 @@ ORDER BY p.time_created;"
281
296
  - 即将让 subagent 直接写 `formatted.md` 或 `progress.md`
282
297
  - 即将修改译文内容
283
298
  - 即将跳过批间失败诊断,无脑重试 FAILED chunk
299
+ - 即将跳过 Item 6 docx 生成或覆盖已有 `-fmt.docx`
284
300
 
285
- **停下来。回到流水线起点。先进度检查,再逐块格式化+合并,再输出。**
301
+ **停下来。回到流水线起点。先进度检查,再逐块格式化+合并,再输出,再生成 docx。**
286
302
 
287
303
  ## 目录结构(skill 本身)
288
304
 
289
305
  ```
290
306
  tsl-format/
291
- ├── SKILL.md
292
- ├── scripts/
293
- │ ├── chunk-bilingual.js # 分块(段落感知)
294
- │ └── merge-format.js # 合并 result 到主产物(不读入上下文)
295
- └── references/
296
- ├── format-rules.md # 格式重建规则(标题/粗体/斜体/保留/禁止)
297
- └── format-prompt.md # 格式化 subagent dispatch prompt 模板
307
+ └── SKILL.md # 格式规则和脚本单源于 tsl skill,通过 <tsl-dir> 引用:
308
+ # <tsl-dir>/references/format-rules.md — 格式重建规则
309
+ # <tsl-dir>/references/format-prompt.md — 格式化 subagent dispatch prompt
310
+ # <tsl-dir>/scripts/chunk-bilingual.js — 分块(段落感知)
311
+ # <tsl-dir>/scripts/merge-format.js — 合并 result 到主产物
312
+ # <tsl-dir>/scripts/check-paragraphs.js — 段落数对比检查
313
+ # <tsl-dir>/scripts/md-to-docx.js — md→docx 转换(Item 6)
298
314
  ```