inkbone 0.0.0-stage → 2.1.0

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 (143) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +380 -0
  3. package/README.md +384 -2
  4. package/bin/inkbone.mjs +1049 -0
  5. package/configs/genres.json +591 -0
  6. package/configs/messages.json +336 -0
  7. package/configs/platforms.json +66 -0
  8. package/configs/presets.json +265 -0
  9. package/configs/severity.json +59 -0
  10. package/configs/zh-linguistics.json +1040 -0
  11. package/configs/zh-traditional.json +97 -0
  12. package/examples/claude-code-hooks.json +15 -0
  13. package/examples/mcp-config.json +12 -0
  14. package/package.json +62 -4
  15. package/prompts/00-style-architect.md +42 -0
  16. package/prompts/01-beat-planner.md +54 -0
  17. package/prompts/02-paratactic-renderer.md +63 -0
  18. package/prompts/03-targeted-rewriter.md +44 -0
  19. package/prompts/04-evidence-reviewer.md +39 -0
  20. package/prompts/05-reader-simulator.md +54 -0
  21. package/prompts/06-ledger-importer.md +41 -0
  22. package/prompts/07-chapter-settler.md +66 -0
  23. package/resources/bad_vs_good_cases.md +132 -0
  24. package/resources/eval/blind-read-instructions.md +18 -0
  25. package/resources/genre_playbooks/classical-xianxia.md +22 -0
  26. package/resources/genre_playbooks/general-clean.md +19 -0
  27. package/resources/genre_playbooks/historical-court.md +21 -0
  28. package/resources/genre_playbooks/light-fantasy.md +22 -0
  29. package/resources/genre_playbooks/mystery-thriller.md +22 -0
  30. package/resources/genre_playbooks/romance-emotional.md +20 -0
  31. package/resources/genre_playbooks/scifi-wasteland.md +21 -0
  32. package/resources/genre_playbooks/urban-realism.md +22 -0
  33. package/resources/genre_playbooks/wuxia-jianghu.md +21 -0
  34. package/resources/micro_techniques.md +77 -0
  35. package/skills/inkbone/LICENSE +21 -0
  36. package/skills/inkbone/README.md +385 -0
  37. package/skills/inkbone/SKILL.md +162 -0
  38. package/skills/inkbone/benchmarks/eval-set/README.md +49 -0
  39. package/skills/inkbone/benchmarks/eval-set/public-pairs.json +42 -0
  40. package/skills/inkbone/benchmarks/eval-set/seeds.json +42 -0
  41. package/skills/inkbone/bin/inkbone.mjs +1049 -0
  42. package/skills/inkbone/configs/genres.json +591 -0
  43. package/skills/inkbone/configs/messages.json +336 -0
  44. package/skills/inkbone/configs/platforms.json +66 -0
  45. package/skills/inkbone/configs/presets.json +265 -0
  46. package/skills/inkbone/configs/severity.json +59 -0
  47. package/skills/inkbone/configs/zh-linguistics.json +1040 -0
  48. package/skills/inkbone/configs/zh-traditional.json +97 -0
  49. package/skills/inkbone/package.json +64 -0
  50. package/skills/inkbone/prompts/00-style-architect.md +42 -0
  51. package/skills/inkbone/prompts/01-beat-planner.md +54 -0
  52. package/skills/inkbone/prompts/02-paratactic-renderer.md +63 -0
  53. package/skills/inkbone/prompts/03-targeted-rewriter.md +44 -0
  54. package/skills/inkbone/prompts/04-evidence-reviewer.md +39 -0
  55. package/skills/inkbone/prompts/05-reader-simulator.md +54 -0
  56. package/skills/inkbone/prompts/06-ledger-importer.md +41 -0
  57. package/skills/inkbone/prompts/07-chapter-settler.md +66 -0
  58. package/skills/inkbone/resources/bad_vs_good_cases.md +132 -0
  59. package/skills/inkbone/resources/eval/blind-read-instructions.md +18 -0
  60. package/skills/inkbone/resources/genre_playbooks/classical-xianxia.md +22 -0
  61. package/skills/inkbone/resources/genre_playbooks/general-clean.md +19 -0
  62. package/skills/inkbone/resources/genre_playbooks/historical-court.md +21 -0
  63. package/skills/inkbone/resources/genre_playbooks/light-fantasy.md +22 -0
  64. package/skills/inkbone/resources/genre_playbooks/mystery-thriller.md +22 -0
  65. package/skills/inkbone/resources/genre_playbooks/romance-emotional.md +20 -0
  66. package/skills/inkbone/resources/genre_playbooks/scifi-wasteland.md +21 -0
  67. package/skills/inkbone/resources/genre_playbooks/urban-realism.md +22 -0
  68. package/skills/inkbone/resources/genre_playbooks/wuxia-jianghu.md +21 -0
  69. package/skills/inkbone/resources/micro_techniques.md +77 -0
  70. package/skills/inkbone/src/aigc-guard.mjs +83 -0
  71. package/skills/inkbone/src/auditor.mjs +24 -0
  72. package/skills/inkbone/src/benchmark-runner.mjs +71 -0
  73. package/skills/inkbone/src/boundary-compiler.mjs +60 -0
  74. package/skills/inkbone/src/browser-doctor.mjs +30 -0
  75. package/skills/inkbone/src/calibrator.mjs +175 -0
  76. package/skills/inkbone/src/config-loader.mjs +233 -0
  77. package/skills/inkbone/src/continuity.mjs +5 -0
  78. package/skills/inkbone/src/core/aigc-guard.mjs +387 -0
  79. package/skills/inkbone/src/core/auditor.mjs +1074 -0
  80. package/skills/inkbone/src/core/boundary-compiler.mjs +526 -0
  81. package/skills/inkbone/src/core/browser-doctor.mjs +320 -0
  82. package/skills/inkbone/src/core/config-compiler.mjs +434 -0
  83. package/skills/inkbone/src/core/continuity.mjs +158 -0
  84. package/skills/inkbone/src/core/evidence-validator.mjs +77 -0
  85. package/skills/inkbone/src/core/exporter.mjs +423 -0
  86. package/skills/inkbone/src/core/formatter.mjs +241 -0
  87. package/skills/inkbone/src/core/ledger-manager.mjs +843 -0
  88. package/skills/inkbone/src/core/normalizer.mjs +517 -0
  89. package/skills/inkbone/src/core/profiler.mjs +686 -0
  90. package/skills/inkbone/src/core/rule-engine.mjs +1710 -0
  91. package/skills/inkbone/src/core/style-profiler.mjs +229 -0
  92. package/skills/inkbone/src/detector.mjs +270 -0
  93. package/skills/inkbone/src/doctor.mjs +430 -0
  94. package/skills/inkbone/src/evaluation.mjs +311 -0
  95. package/skills/inkbone/src/evidence-validator.mjs +15 -0
  96. package/skills/inkbone/src/exporter.mjs +142 -0
  97. package/skills/inkbone/src/formatter.mjs +34 -0
  98. package/skills/inkbone/src/importer.mjs +230 -0
  99. package/skills/inkbone/src/index.mjs +134 -0
  100. package/skills/inkbone/src/ledger-manager.mjs +22 -0
  101. package/skills/inkbone/src/mcp-server.mjs +950 -0
  102. package/skills/inkbone/src/normalizer.mjs +73 -0
  103. package/skills/inkbone/src/profiler.mjs +17 -0
  104. package/skills/inkbone/src/rule-engine.mjs +91 -0
  105. package/skills/inkbone/src/rule-stats.mjs +142 -0
  106. package/skills/inkbone/src/style-profiler.mjs +25 -0
  107. package/src/aigc-guard.mjs +83 -0
  108. package/src/auditor.mjs +24 -0
  109. package/src/benchmark-runner.mjs +71 -0
  110. package/src/boundary-compiler.mjs +60 -0
  111. package/src/browser-doctor.mjs +30 -0
  112. package/src/calibrator.mjs +175 -0
  113. package/src/config-loader.mjs +233 -0
  114. package/src/continuity.mjs +5 -0
  115. package/src/core/aigc-guard.mjs +387 -0
  116. package/src/core/auditor.mjs +1074 -0
  117. package/src/core/boundary-compiler.mjs +526 -0
  118. package/src/core/browser-doctor.mjs +320 -0
  119. package/src/core/config-compiler.mjs +434 -0
  120. package/src/core/continuity.mjs +158 -0
  121. package/src/core/evidence-validator.mjs +77 -0
  122. package/src/core/exporter.mjs +423 -0
  123. package/src/core/formatter.mjs +241 -0
  124. package/src/core/ledger-manager.mjs +843 -0
  125. package/src/core/normalizer.mjs +517 -0
  126. package/src/core/profiler.mjs +686 -0
  127. package/src/core/rule-engine.mjs +1710 -0
  128. package/src/core/style-profiler.mjs +229 -0
  129. package/src/detector.mjs +270 -0
  130. package/src/doctor.mjs +430 -0
  131. package/src/evaluation.mjs +311 -0
  132. package/src/evidence-validator.mjs +15 -0
  133. package/src/exporter.mjs +142 -0
  134. package/src/formatter.mjs +34 -0
  135. package/src/importer.mjs +230 -0
  136. package/src/index.mjs +134 -0
  137. package/src/ledger-manager.mjs +22 -0
  138. package/src/mcp-server.mjs +950 -0
  139. package/src/normalizer.mjs +73 -0
  140. package/src/profiler.mjs +17 -0
  141. package/src/rule-engine.mjs +91 -0
  142. package/src/rule-stats.mjs +142 -0
  143. package/src/style-profiler.mjs +25 -0
@@ -0,0 +1,423 @@
1
+ // 纯内存网文平台投稿清洗与整卷导出模块(零文件系统依赖,供 Node CLI、MCP 与浏览器共用)
2
+ import { normalizeProseText } from "./normalizer.mjs";
3
+ import { countHan } from "./profiler.mjs";
4
+
5
+ // 解析目标平台预设对象
6
+ export function resolvePlatformConfig(platformsConfig, platformId) {
7
+ const key = platformId || platformsConfig?.defaultPlatform || "qidian";
8
+ const spec = platformsConfig?.platforms?.[key];
9
+ if (!spec) {
10
+ const valid = Object.keys(platformsConfig?.platforms || {}).join(", ");
11
+ throw new Error(`Unknown export platform "${key}". Available platforms: ${valid}`);
12
+ }
13
+ return spec;
14
+ }
15
+
16
+ // 剥离文首 YAML Frontmatter 与 HTML 注释,保留干净可发布正文
17
+ function stripNonPublishMetadata(rawText) {
18
+ let out = String(rawText || "").replace(/\r\n/gu, "\n");
19
+ out = out.replace(/^---\n[\s\S]*?\n---\n*/u, "");
20
+ out = out.replace(/<!--[\s\S]*?-->/gu, "");
21
+ return out;
22
+ }
23
+
24
+ // 将单章 Markdown 正文清洗为符合指定网文平台(起点/番茄/七猫/晋江)投稿习惯的纯文本
25
+ export function formatChapterForPlatform(rawText, platformSpec, lingConfig, options = {}) {
26
+ if (!platformSpec || !lingConfig) {
27
+ throw new Error("platformSpec and lingConfig are required for formatChapterForPlatform.");
28
+ }
29
+ const cleanedMeta = stripNonPublishMetadata(rawText);
30
+ const norm = normalizeProseText(cleanedMeta, {
31
+ lingConfig,
32
+ stripMarkdownEmphasis: platformSpec.stripMarkdownEmphasis !== false,
33
+ fixNarrationEmDash: Boolean(options.fixEmDash ?? platformSpec.fixNarrationEmDash),
34
+ whitelistLiterals: options.whitelistLiterals || [],
35
+ });
36
+
37
+ const useIndent =
38
+ options.indent !== undefined ? Boolean(options.indent) : Boolean(platformSpec.defaultIndent);
39
+ const indentStr = platformSpec.indentString || "\u3000\u3000";
40
+ const blankLines = Number.isFinite(platformSpec.blankLinesBetweenParagraphs)
41
+ ? platformSpec.blankLinesBetweenParagraphs
42
+ : 1;
43
+ const separator = "\n".repeat(blankLines + 1);
44
+ const hanRegex = lingConfig.compiledRegex.hanCharGlobal;
45
+ const headingRe = lingConfig.chineseNumerals?.chapterHeadingParseRegex
46
+ ? new RegExp(lingConfig.chineseNumerals.chapterHeadingParseRegex, "u")
47
+ : null;
48
+
49
+ const rawLines = norm.output.split("\n");
50
+ const outParagraphs = [];
51
+ let extractedTitle = "";
52
+
53
+ for (const rawLine of rawLines) {
54
+ let line = rawLine.trim();
55
+ if (!line) continue;
56
+ // 跳过纯 Markdown 分隔线与围栏代码块标记
57
+ if (/^[-*_]{3,}$/u.test(line) || /^```/u.test(line)) continue;
58
+ // 剥离引用前缀符号
59
+ line = line.replace(/^>\s*/u, "").trim();
60
+ if (!line) continue;
61
+
62
+ const isMdHeading = /^#{1,6}\s+/u.test(line);
63
+ if (isMdHeading && platformSpec.stripMarkdownHeadings !== false) {
64
+ const stripped = line.replace(/^#{1,6}\s+/u, "").trim();
65
+ if (!extractedTitle && stripped) {
66
+ extractedTitle = stripped;
67
+ }
68
+ if (stripped) {
69
+ outParagraphs.push(stripped);
70
+ }
71
+ continue;
72
+ }
73
+
74
+ if (!extractedTitle && outParagraphs.length === 0 && headingRe && headingRe.test(line)) {
75
+ extractedTitle = line;
76
+ outParagraphs.push(line);
77
+ continue;
78
+ }
79
+
80
+ // 剥离原有全角/半角缩进后按平台配置重新规范段首缩进
81
+ const bodyText = line.replace(/^[\s\u3000]+/u, "");
82
+ outParagraphs.push(useIndent ? `${indentStr}${bodyText}` : bodyText);
83
+ }
84
+
85
+ const output = outParagraphs.join(separator) + (outParagraphs.length > 0 ? "\n" : "");
86
+ const hanCount = countHan(output, hanRegex);
87
+ const minHan = platformSpec.minHan ?? 2000;
88
+ const maxHan = platformSpec.maxHan ?? 5000;
89
+ const lengthStatus =
90
+ hanCount < minHan ? "too_short" : hanCount > maxHan ? "too_long" : "ok";
91
+
92
+ return {
93
+ platform: platformSpec.id,
94
+ title: extractedTitle,
95
+ hanCount,
96
+ paragraphCount: outParagraphs.length,
97
+ expectedRange: [minHan, maxHan],
98
+ lengthStatus,
99
+ normalizationFindings: norm.findingCount,
100
+ output,
101
+ };
102
+ }
103
+
104
+ // 批量导出多章稿件,输出逐章结果与整卷合并纯文本
105
+ export function exportChapterEntries(entries, platformSpec, lingConfig, options = {}) {
106
+ const chapters = (entries || []).map((entry) => {
107
+ const formatted = formatChapterForPlatform(entry.text, platformSpec, lingConfig, options);
108
+ return {
109
+ name: entry.name,
110
+ ...formatted,
111
+ };
112
+ });
113
+
114
+ const joiner = platformSpec.chapterSeparator || "\n\n\n";
115
+ const mergedText = chapters.map((c) => c.output.trimEnd()).join(joiner) + (chapters.length > 0 ? "\n" : "");
116
+ const totalHan = chapters.reduce((acc, c) => acc + c.hanCount, 0);
117
+ const outOfRangeCount = chapters.filter((c) => c.lengthStatus !== "ok").length;
118
+ const submissionMinHan = platformSpec.submissionMinHan ?? 20000;
119
+ const submissionReady = totalHan >= submissionMinHan;
120
+ const submissionShortfallHan = Math.max(0, submissionMinHan - totalHan);
121
+
122
+ return {
123
+ platform: platformSpec.id,
124
+ platformTitle: platformSpec.title,
125
+ chapterCount: chapters.length,
126
+ totalHan,
127
+ outOfRangeCount,
128
+ submissionMinHan,
129
+ submissionReady,
130
+ submissionShortfallHan,
131
+ chapters,
132
+ mergedText,
133
+ };
134
+ }
135
+
136
+ // 预计算标准 CRC32 查表数组(供零依赖纯内存 ZIP 与 DOCX 容器生成使用)
137
+ const CRC32_TABLE = (() => {
138
+ const table = new Uint32Array(256);
139
+ for (let i = 0; i < 256; i += 1) {
140
+ let c = i;
141
+ for (let k = 0; k < 8; k += 1) {
142
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
143
+ }
144
+ table[i] = c >>> 0;
145
+ }
146
+ return table;
147
+ })();
148
+
149
+ function computeCrc32(bytes) {
150
+ let crc = 0xffffffff;
151
+ for (let i = 0; i < bytes.length; i += 1) {
152
+ crc = CRC32_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
153
+ }
154
+ return (crc ^ 0xffffffff) >>> 0;
155
+ }
156
+
157
+ // 零依赖构建标准 STORE(无压缩)ZIP 二进制流,兼容 Node 与浏览器 Blob 下载及 OOXML .docx
158
+ export function buildStoreZipBuffer(fileEntries) {
159
+ const encoder = new TextEncoder();
160
+ const prepared = (fileEntries || []).map((entry) => {
161
+ const nameBytes = encoder.encode(String(entry.name || "file.txt"));
162
+ const dataBytes =
163
+ entry.data instanceof Uint8Array
164
+ ? entry.data
165
+ : encoder.encode(String(entry.data ?? ""));
166
+ const crc = computeCrc32(dataBytes);
167
+ return { nameBytes, dataBytes, crc };
168
+ });
169
+
170
+ let localTotalSize = 0;
171
+ let centralTotalSize = 0;
172
+ for (const item of prepared) {
173
+ localTotalSize += 30 + item.nameBytes.length + item.dataBytes.length;
174
+ centralTotalSize += 46 + item.nameBytes.length;
175
+ }
176
+ const totalSize = localTotalSize + centralTotalSize + 22;
177
+ const out = new Uint8Array(totalSize);
178
+ const view = new DataView(out.buffer);
179
+
180
+ let localOffset = 0;
181
+ const localOffsets = [];
182
+
183
+ for (const item of prepared) {
184
+ localOffsets.push(localOffset);
185
+ view.setUint32(localOffset, 0x04034b50, true);
186
+ view.setUint16(localOffset + 4, 20, true);
187
+ view.setUint16(localOffset + 6, 0x0800, true); // UTF-8 文件名标志位
188
+ view.setUint16(localOffset + 8, 0, true); // STORE 方式(0 = 不压缩)
189
+ view.setUint16(localOffset + 10, 0, true);
190
+ view.setUint16(localOffset + 12, 0x21, true);
191
+ view.setUint32(localOffset + 14, item.crc, true);
192
+ view.setUint32(localOffset + 18, item.dataBytes.length, true);
193
+ view.setUint32(localOffset + 22, item.dataBytes.length, true);
194
+ view.setUint16(localOffset + 26, item.nameBytes.length, true);
195
+ view.setUint16(localOffset + 28, 0, true);
196
+ out.set(item.nameBytes, localOffset + 30);
197
+ out.set(item.dataBytes, localOffset + 30 + item.nameBytes.length);
198
+ localOffset += 30 + item.nameBytes.length + item.dataBytes.length;
199
+ }
200
+
201
+ const centralStart = localOffset;
202
+ let centralOffset = centralStart;
203
+
204
+ for (let i = 0; i < prepared.length; i += 1) {
205
+ const item = prepared[i];
206
+ view.setUint32(centralOffset, 0x02014b50, true);
207
+ view.setUint16(centralOffset + 4, 20, true);
208
+ view.setUint16(centralOffset + 6, 20, true);
209
+ view.setUint16(centralOffset + 8, 0x0800, true);
210
+ view.setUint16(centralOffset + 10, 0, true);
211
+ view.setUint16(centralOffset + 12, 0, true);
212
+ view.setUint16(centralOffset + 14, 0x21, true);
213
+ view.setUint32(centralOffset + 16, item.crc, true);
214
+ view.setUint32(centralOffset + 20, item.dataBytes.length, true);
215
+ view.setUint32(centralOffset + 24, item.dataBytes.length, true);
216
+ view.setUint16(centralOffset + 28, item.nameBytes.length, true);
217
+ view.setUint16(centralOffset + 30, 0, true);
218
+ view.setUint16(centralOffset + 32, 0, true);
219
+ view.setUint16(centralOffset + 34, 0, true);
220
+ view.setUint16(centralOffset + 36, 0, true);
221
+ view.setUint32(centralOffset + 38, 0, true);
222
+ view.setUint32(centralOffset + 42, localOffsets[i], true);
223
+ out.set(item.nameBytes, centralOffset + 46);
224
+ centralOffset += 46 + item.nameBytes.length;
225
+ }
226
+
227
+ const eocdOffset = centralOffset;
228
+ view.setUint32(eocdOffset, 0x06054b50, true);
229
+ view.setUint16(eocdOffset + 4, 0, true);
230
+ view.setUint16(eocdOffset + 6, 0, true);
231
+ view.setUint16(eocdOffset + 8, prepared.length, true);
232
+ view.setUint16(eocdOffset + 10, prepared.length, true);
233
+ view.setUint32(eocdOffset + 12, centralOffset - centralStart, true);
234
+ view.setUint32(eocdOffset + 16, centralStart, true);
235
+ view.setUint16(eocdOffset + 20, 0, true);
236
+
237
+ return out;
238
+ }
239
+
240
+ function escapeXml(str) {
241
+ return String(str || "")
242
+ .replace(/&/gu, "&amp;")
243
+ .replace(/</gu, "&lt;")
244
+ .replace(/>/gu, "&gt;")
245
+ .replace(/"/gu, "&quot;")
246
+ .replace(/'/gu, "&apos;");
247
+ }
248
+
249
+ // 构造单个 OOXML 段落节点字符串(统一宋体五号、1.25 倍行距,正文首行缩进 2 字符,标题居中加粗)
250
+ function buildDocxParagraphXml(text, opts = {}) {
251
+ const fontSong = "\u5b8b\u4f53"; // 宋体
252
+ const align = opts.center ? "center" : "both";
253
+ const sz = opts.sizeHalfPt || 21; // 21 = 五号 (10.5pt), 24 = 小四 (12pt), 28 = 四号 (14pt)
254
+ const before = opts.spaceBefore ?? (opts.isHeading ? 160 : 0);
255
+ const after = opts.spaceAfter ?? (opts.isHeading ? 140 : 0);
256
+ const keepNext = opts.isHeading ? "<w:keepNext/>" : "";
257
+ const pageBreak = opts.pageBreakBefore ? "<w:pageBreakBefore/>" : "";
258
+ const indent = opts.indentFirstLine
259
+ ? '<w:ind w:firstLine="420" w:firstLineChars="200"/>'
260
+ : "";
261
+ const bold = opts.bold || opts.isHeading ? "<w:b/><w:bCs/>" : "";
262
+ const safeText = escapeXml(text);
263
+
264
+ return [
265
+ "<w:p>",
266
+ "<w:pPr>",
267
+ keepNext,
268
+ pageBreak,
269
+ `<w:spacing w:before="${before}" w:after="${after}" w:line="300" w:lineRule="auto"/>`,
270
+ indent,
271
+ `<w:jc w:val="${align}"/>`,
272
+ "</w:pPr>",
273
+ "<w:r>",
274
+ "<w:rPr>",
275
+ `<w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman" w:eastAsia="${fontSong}" w:cs="Times New Roman"/>`,
276
+ bold,
277
+ '<w:color w:val="000000"/>',
278
+ `<w:sz w:val="${sz}"/><w:szCs w:val="${sz}"/>`,
279
+ "</w:rPr>",
280
+ `<w:t xml:space="preserve">${safeText}</w:t>`,
281
+ "</w:r>",
282
+ "</w:p>",
283
+ ].join("");
284
+ }
285
+
286
+ // 零依赖生成网文内投标准 Word (.docx) 二进制字节流(纯黑宋体、五号字、首行缩进 2 字符、1.25 倍行距,支持拼入大纲)
287
+ export function buildSubmissionDocxBytes(exportResultOrChapters, options = {}) {
288
+ const chapters = Array.isArray(exportResultOrChapters)
289
+ ? exportResultOrChapters
290
+ : Array.isArray(exportResultOrChapters?.chapters)
291
+ ? exportResultOrChapters.chapters
292
+ : [];
293
+
294
+ const paragraphsXml = [];
295
+
296
+ if (options.bookTitle && String(options.bookTitle).trim()) {
297
+ paragraphsXml.push(
298
+ buildDocxParagraphXml(String(options.bookTitle).trim(), {
299
+ isHeading: true,
300
+ center: true,
301
+ sizeHalfPt: 28,
302
+ spaceBefore: 120,
303
+ spaceAfter: 200,
304
+ })
305
+ );
306
+ }
307
+
308
+ let hasOutline = false;
309
+ if (options.outlineText && String(options.outlineText).trim()) {
310
+ const outlineLines = String(options.outlineText)
311
+ .replace(/\r\n/gu, "\n")
312
+ .split("\n");
313
+ for (const rawLine of outlineLines) {
314
+ const trimmed = rawLine.trim();
315
+ if (!trimmed || /^[-*_]{3,}$/u.test(trimmed)) continue;
316
+ const isHeading = /^#{1,4}\s+/u.test(trimmed);
317
+ const cleanLine = trimmed
318
+ .replace(/^#{1,6}\s+/u, "")
319
+ .replace(/\*\*([^*]+)\*\*/gu, "$1");
320
+ paragraphsXml.push(
321
+ buildDocxParagraphXml(cleanLine, {
322
+ isHeading,
323
+ bold: isHeading,
324
+ sizeHalfPt: isHeading ? 24 : 21,
325
+ indentFirstLine: !isHeading && !/^[-*•0-9]/u.test(cleanLine),
326
+ spaceBefore: isHeading ? 140 : 20,
327
+ spaceAfter: isHeading ? 80 : 20,
328
+ })
329
+ );
330
+ hasOutline = true;
331
+ }
332
+ }
333
+
334
+ chapters.forEach((ch, idx) => {
335
+ const rawOutput = String(ch.output || ch.text || "");
336
+ const lines = rawOutput
337
+ .replace(/\r\n/gu, "\n")
338
+ .split("\n")
339
+ .map((l) => l.trim().replace(/^[\s\u3000]+/u, ""))
340
+ .filter(Boolean);
341
+ if (lines.length === 0) return;
342
+
343
+ const explicitTitle = String(ch.title || "").trim();
344
+ let headingText = explicitTitle;
345
+ let bodyLines = lines;
346
+ if (explicitTitle && lines[0] === explicitTitle) {
347
+ bodyLines = lines.slice(1);
348
+ } else if (!headingText) {
349
+ headingText = lines[0];
350
+ bodyLines = lines.slice(1);
351
+ }
352
+
353
+ paragraphsXml.push(
354
+ buildDocxParagraphXml(headingText, {
355
+ isHeading: true,
356
+ center: true,
357
+ sizeHalfPt: 24,
358
+ pageBreakBefore: idx > 0 || hasOutline,
359
+ })
360
+ );
361
+
362
+ for (const bLine of bodyLines) {
363
+ paragraphsXml.push(
364
+ buildDocxParagraphXml(bLine, {
365
+ indentFirstLine: true,
366
+ sizeHalfPt: 21,
367
+ })
368
+ );
369
+ }
370
+ });
371
+
372
+ const documentXml = [
373
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
374
+ '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">',
375
+ "<w:body>",
376
+ ...paragraphsXml,
377
+ '<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/></w:sectPr>',
378
+ "</w:body>",
379
+ "</w:document>",
380
+ ].join("");
381
+
382
+ const contentTypesXml = [
383
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
384
+ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">',
385
+ '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>',
386
+ '<Default Extension="xml" ContentType="application/xml"/>',
387
+ '<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>',
388
+ '<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>',
389
+ "</Types>",
390
+ ].join("");
391
+
392
+ const rootRelsXml = [
393
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
394
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">',
395
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>',
396
+ "</Relationships>",
397
+ ].join("");
398
+
399
+ const docRelsXml = [
400
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
401
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">',
402
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>',
403
+ "</Relationships>",
404
+ ].join("");
405
+
406
+ const fontSong = "\u5b8b\u4f53";
407
+ const stylesXml = [
408
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
409
+ '<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">',
410
+ "<w:docDefaults>",
411
+ `<w:rPrDefault><w:rPr><w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman" w:eastAsia="${fontSong}" w:cs="Times New Roman"/><w:sz w:val="21"/><w:szCs w:val="21"/></w:rPr></w:rPrDefault>`,
412
+ "</w:docDefaults>",
413
+ "</w:styles>",
414
+ ].join("");
415
+
416
+ return buildStoreZipBuffer([
417
+ { name: "[Content_Types].xml", data: contentTypesXml },
418
+ { name: "_rels/.rels", data: rootRelsXml },
419
+ { name: "word/_rels/document.xml.rels", data: docRelsXml },
420
+ { name: "word/styles.xml", data: stylesXml },
421
+ { name: "word/document.xml", data: documentXml },
422
+ ]);
423
+ }
@@ -0,0 +1,241 @@
1
+ // 纯内存报告格式化与精准改稿 Prompt 生成模块(零文件系统依赖,供 Node CLI、MCP 与浏览器共用)
2
+
3
+ // 解析指定语言的本地化词典(默认回退至配置 defaultLang 或 zh)
4
+ export function resolveLocaleBundle(messagesConfig, lang = null) {
5
+ const locales = messagesConfig?.locales || {};
6
+ const fallbackKey = messagesConfig?.defaultLang || "zh";
7
+ const key = lang && locales[lang] ? lang : locales[fallbackKey] ? fallbackKey : Object.keys(locales)[0];
8
+ return {
9
+ lang: key || "en",
10
+ bundle: locales[key] || {},
11
+ };
12
+ }
13
+
14
+ // 模板占位符简单替换(例如 {files}、{genre})
15
+ function interpolate(template, vars = {}) {
16
+ let out = String(template || "");
17
+ for (const [k, v] of Object.entries(vars)) {
18
+ out = out.split(`{${k}}`).join(String(v ?? ""));
19
+ }
20
+ return out;
21
+ }
22
+
23
+ // 格式化单章审计报告为人类可读 Markdown(支持中英双语)
24
+ export function formatAuditMarkdown(report, options = {}) {
25
+ const { bundle } = resolveLocaleBundle(options.messagesConfig, options.lang);
26
+ const s = bundle.reportStrings || {};
27
+ const vLabels = bundle.violationLabels || {};
28
+ const remedies = bundle.remedies || {};
29
+ const sevLabels = bundle.severityLabels || {};
30
+ const mLabels = bundle.metricLabels || {};
31
+
32
+ const statusText = report.pass ? s.statusPass || "PASS" : s.statusFail || "FAIL";
33
+ const sum = report.summary || { error: 0, warning: 0, info: 0 };
34
+ const m = report.metrics || {};
35
+
36
+ const lines = [
37
+ s.auditTitle || "# InkBone Audit Report",
38
+ "",
39
+ `- **${s.genreLabel || "Genre"}**: \`${report.genre || "general-clean"}\` | **${s.presetLabel || "Preset"}**: \`${report.preset || "default"}\` | **Status**: ${statusText} (${report.mode || "default"})`,
40
+ `- **${s.totalsLabel || "Summary"}**: ${s.hardErrors || "Errors"}: ${sum.error} | ${s.warnings || "Warnings"}: ${sum.warning} | ${s.infos || "Info"}: ${sum.info}`,
41
+ ];
42
+
43
+ if (options.fileName) {
44
+ lines.splice(2, 0, `- **${s.tableFile || "File"}**: \`${options.fileName}\``);
45
+ }
46
+
47
+ // 关键语言学指标概览
48
+ lines.push(
49
+ "",
50
+ s.sectionMetrics || "## Metrics",
51
+ `- ${mLabels.totalHan || "Han"}: ${m.totalHan ?? 0} | ${mLabels.paragraphCount || "Paragraphs"}: ${m.paragraphCount ?? 0} | ${mLabels.sentLenMean || "Mean Sent"}: ${m.sentLenMean ?? 0} | ${mLabels.sentLenCV || "CV"}: ${m.sentLenCV ?? 0} | ${mLabels.mattr50 || "MATTR-50"}: ${m.mattr50 ?? 0} | ${mLabels.dePer100Han || "De/100"}: ${m.dePer100Han ?? 0}`
52
+ );
53
+
54
+ const targets = report.surgeryTargets || [];
55
+ const actionableViolations = (report.violations || []).filter(
56
+ (v) => v.severity !== "info" || options.includeInfo
57
+ );
58
+
59
+ if (targets.length === 0 && actionableViolations.length === 0) {
60
+ lines.push("", s.noIssues || "No issues detected.");
61
+ return lines.join("\n");
62
+ }
63
+
64
+ if (targets.length > 0) {
65
+ lines.push("", s.sectionTargets || "## Line Targets");
66
+ for (const target of targets) {
67
+ const desc = target.issues
68
+ .map((i) => {
69
+ const badge = i.level === "blocking" ? `${s.blockTag || "[BLOCK]"} ` : "";
70
+ return `${badge}\`${i.tag}\` (${i.detail})`;
71
+ })
72
+ .join("; ");
73
+ lines.push(`- **${s.linePrefix || "L"}${target.line}${s.lineSuffix || ""}**: ${desc}`);
74
+ }
75
+ }
76
+
77
+ if (actionableViolations.length > 0) {
78
+ lines.push("", s.sectionViolations || "## Chapter Findings");
79
+ for (const v of actionableViolations) {
80
+ const sevTag = sevLabels[v.severity] || v.severity;
81
+ const title = vLabels[v.code] || v.code;
82
+ const remedy = remedies[v.code] || v.remedy || "";
83
+ const suffix = remedy ? ` — ${s.remedyPrefix || ""}${remedy}` : "";
84
+ lines.push(`- **[${sevTag}] ${title}** (\`${v.code}\`)${suffix}`);
85
+ }
86
+ }
87
+
88
+ return lines.join("\n");
89
+ }
90
+
91
+ // 格式化整书四维体检报告为 Markdown(支持中英双语与实用引导提示)
92
+ export function formatDoctorMarkdown(diagnosis, options = {}) {
93
+ const { bundle } = resolveLocaleBundle(options.messagesConfig, options.lang);
94
+ const s = bundle.reportStrings || {};
95
+ const vLabels = bundle.violationLabels || {};
96
+ const remedies = bundle.remedies || {};
97
+ const hintMap = bundle.hintMessages || {};
98
+
99
+ const lines = [
100
+ s.doctorTitle || "# InkBone Doctor Report",
101
+ "",
102
+ `- **${s.genreLabel || "Genre Pack"}**: \`${diagnosis.genre.id}\` (${diagnosis.genre.title}) [${diagnosis.genre.source}]`,
103
+ `- **${s.presetLabel || "Preset"}**: \`${diagnosis.genre.defaultPreset}\``,
104
+ `- **${s.formulaLabel || "Register Formula"}**: ${diagnosis.genre.registerFormula}`,
105
+ ];
106
+
107
+ if (diagnosis.genre.mixedGenreFiles && diagnosis.genre.mixedGenreFiles.length > 0) {
108
+ const filesStr = diagnosis.genre.mixedGenreFiles
109
+ .map((m) => `${m.file} -> ${m.inferredGenre}`)
110
+ .join(", ");
111
+ const mixedMsg = hintMap.MIXED_GENRE_DETECTED
112
+ ? interpolate(hintMap.MIXED_GENRE_DETECTED, { files: filesStr })
113
+ : `Warning: Mixed genres detected in unconfigured folder (${filesStr}); pass \`--genre\` or add \`novel.json\` per book.`;
114
+ lines.push(`- ${mixedMsg}`);
115
+ }
116
+
117
+ for (const hint of diagnosis.hints || []) {
118
+ const text = hintMap[hint.code] || hint.detail || hint.code;
119
+ lines.push(`- ${text}`);
120
+ }
121
+
122
+ if (diagnosis.incremental?.active) {
123
+ const incTpl =
124
+ bundle.incrementalNote ||
125
+ "Incremental mode ({mode}): scanned {scanned} of {total} chapter(s).";
126
+ lines.push(
127
+ `- ${interpolate(incTpl, {
128
+ mode: diagnosis.incremental.mode,
129
+ scanned: diagnosis.incremental.scannedCount,
130
+ total: diagnosis.incremental.totalDiscovered,
131
+ })}`
132
+ );
133
+ }
134
+
135
+ const t = diagnosis.totals;
136
+ lines.push(
137
+ `- **${s.totalsLabel || "Totals"}**: ${t.chaptersScanned} ${s.chaptersUnit || "chapter(s)"} | ${s.hardErrors || "Hard Errors"}: ${t.hardErrors} | ${s.regClash || "Register Clash"}: ${t.registerCollisions} | ${s.fillers || "Fillers"}: ${t.narrativeFillers} | ${s.cliches || "AI Cliches"}: ${t.aiCliches} | ${s.rhetTics || "Rhet/Tics"}: ${t.rhetoricalPatterns + t.densityTics} | ${s.degeneration || "Degeneration"}: ${t.degenerationErrors} | ${s.metaLeaks || "Meta Leaks"}: ${t.metaLeaks} | ${s.proStreaks || "Pronoun Streaks"}: ${t.pronounStreaks}`,
138
+ "",
139
+ `| ${s.tableFile || "File"} | ${s.tableHan || "Han"} | ${s.tableErrors || "Errors"} | ${s.tableReg || "RegClash"} | ${s.tableFillers || "Fillers"} | ${s.tableCliches || "Cliches"} | ${s.tableRhet || "Rhet/Tics"} | ${s.tablePro || "ProStreak"} |`,
140
+ `| :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |`
141
+ );
142
+
143
+ for (const ch of diagnosis.chapters) {
144
+ const rhetTics = ch.counts.rhetoricalPatterns + ch.counts.densityTics;
145
+ lines.push(
146
+ `| ${ch.file} | ${ch.totalHan} | ${ch.summary.error} | ${ch.counts.registerCollisions} | ${ch.counts.narrativeFillers} | ${ch.counts.aiCliches} | ${rhetTics} | ${ch.maxPronounHeadStreak} |`
147
+ );
148
+ }
149
+
150
+ for (const ch of diagnosis.chapters) {
151
+ if (ch.surgeryTargets.length === 0 && ch.summary.error === 0) continue;
152
+ lines.push("", `## ${ch.file}`);
153
+ for (const v of ch.violations) {
154
+ if (v.severity === "error") {
155
+ const label = vLabels[v.code] ? `${vLabels[v.code]} (${v.code})` : v.code;
156
+ const desc = v.details ? JSON.stringify(v.details) : remedies[v.code] || v.remedy || "";
157
+ lines.push(`- **${s.errorTag || "[ERROR]"} ${label}**: ${desc}`);
158
+ }
159
+ }
160
+ for (const target of ch.surgeryTargets.slice(0, 25)) {
161
+ const desc = target.issues
162
+ .map((i) => {
163
+ const badge = i.level === "blocking" ? `${s.blockTag || "[BLOCK]"} ` : "";
164
+ return `${badge}\`${i.tag}\` (${i.detail})`;
165
+ })
166
+ .join("; ");
167
+ lines.push(`- **${s.linePrefix || "L"}${target.line}${s.lineSuffix || ""}**: ${desc}`);
168
+ }
169
+ }
170
+
171
+ return lines.join("\n");
172
+ }
173
+
174
+ // 基于单章审计结果,确定性拼装可直接粘贴至任意大模型聊天框的“精准局部改稿 Prompt”
175
+ export function buildTargetedRewritePrompt(chapterText, auditReport, options = {}) {
176
+ const { bundle } = resolveLocaleBundle(options.messagesConfig, options.lang);
177
+ const rp = bundle.rewritePrompt || {};
178
+ const s = bundle.reportStrings || {};
179
+ const vLabels = bundle.violationLabels || {};
180
+ const remedies = bundle.remedies || {};
181
+ const sevLabels = bundle.severityLabels || {};
182
+
183
+ const targets = auditReport?.surgeryTargets || [];
184
+ const actionableViolations = (auditReport?.violations || []).filter(
185
+ (v) => v.severity === "error" || v.severity === "warning"
186
+ );
187
+
188
+ if (targets.length === 0 && actionableViolations.length === 0) {
189
+ return {
190
+ hasIssues: false,
191
+ issueCount: 0,
192
+ prompt: rp.emptyNotice || "No issues found.",
193
+ };
194
+ }
195
+
196
+ const rawLines = String(chapterText || "").split(/\r?\n/u);
197
+ const parts = [rp.header || "Revise only the flagged lines below."];
198
+
199
+ const genreLabel = options.genreTitle || auditReport?.genre || "general-clean";
200
+ parts.push("", interpolate(rp.genreLine || "Genre: {genre}", { genre: genreLabel }));
201
+ if (rp.rulesBlock) {
202
+ parts.push("", rp.rulesBlock);
203
+ }
204
+
205
+ parts.push("", rp.issuesHeading || "### Flagged Issues");
206
+
207
+ let issueCount = 0;
208
+ for (const target of targets) {
209
+ const lineText = (rawLines[target.line - 1] || "").trim();
210
+ const issueDesc = target.issues
211
+ .map((i) => {
212
+ const badge = i.level === "blocking" ? `${s.blockTag || "[BLOCK]"} ` : "";
213
+ return `${badge}${i.tag}: ${i.detail}`;
214
+ })
215
+ .join(" | ");
216
+ parts.push(
217
+ `- ${s.linePrefix || "L"}${target.line}${s.lineSuffix || ""}: ${issueDesc}${lineText ? ` => "${lineText.slice(0, 60)}"` : ""}`
218
+ );
219
+ issueCount += target.issues.length;
220
+ }
221
+
222
+ for (const v of actionableViolations) {
223
+ const sev = sevLabels[v.severity] || v.severity;
224
+ const label = vLabels[v.code] || v.code;
225
+ const rem = remedies[v.code] || v.remedy || "";
226
+ parts.push(`- [${sev}] ${label} (${v.code})${rem ? ` — ${rem}` : ""}`);
227
+ issueCount += 1;
228
+ }
229
+
230
+ parts.push("", rp.chapterHeading || "### Chapter Text", "```markdown");
231
+ rawLines.forEach((line, idx) => {
232
+ parts.push(`L${idx + 1}: ${line}`);
233
+ });
234
+ parts.push("```");
235
+
236
+ return {
237
+ hasIssues: true,
238
+ issueCount,
239
+ prompt: parts.join("\n"),
240
+ };
241
+ }