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,843 @@
1
+ // 纯内存台账管理引擎(零文件系统依赖,供 Node CLI、MCP Server 与浏览器静态试跑台共用)
2
+ import { stripSpokenDialogue } from "./rule-engine.mjs";
3
+
4
+ const CLOSED_FORESHADOW_STATUSES = new Set(["paid_off", "abandoned"]);
5
+
6
+ // 深度克隆普通 JSON 数据对象,避免就地修改调用方传入的台账
7
+ function cloneJson(value) {
8
+ return JSON.parse(JSON.stringify(value));
9
+ }
10
+
11
+ // 从主角对象或字符串提取主角名称与别名集合
12
+ function extractProtagonistNames(ledger) {
13
+ const names = [];
14
+ const p = ledger?.protagonist;
15
+ if (typeof p === "string" && p.trim()) {
16
+ names.push(p.trim());
17
+ } else if (p && typeof p === "object") {
18
+ for (const [key, val] of Object.entries(p)) {
19
+ if (typeof val === "string" && val.trim() && (key === "name" || /alias/iu.test(key))) {
20
+ names.push(val.trim());
21
+ }
22
+ }
23
+ }
24
+ return names;
25
+ }
26
+
27
+ // 检查台账整体健康度:结构合法性、章号重复/断档、揭露章矛盾、空摘要、角色名单缺失与逾期伏笔
28
+ export function validateLedger(ledger, options = {}) {
29
+ const overdueThreshold =
30
+ Number.isFinite(Number(options.overdueThreshold)) && Number(options.overdueThreshold) > 0
31
+ ? Number(options.overdueThreshold)
32
+ : 20;
33
+ const issues = [];
34
+
35
+ if (!ledger || typeof ledger !== "object" || Array.isArray(ledger)) {
36
+ return {
37
+ pass: false,
38
+ summary: { error: 1, warning: 0 },
39
+ stats: {
40
+ chapterCount: 0,
41
+ latestChapter: 0,
42
+ characterCount: 0,
43
+ activeForeshadowingCount: 0,
44
+ overdueForeshadowingCount: 0,
45
+ knowledgeCount: 0,
46
+ },
47
+ issues: [
48
+ {
49
+ code: "INVALID_LEDGER_ROOT",
50
+ severity: "error",
51
+ detail: "Ledger must be a JSON object.",
52
+ },
53
+ ],
54
+ };
55
+ }
56
+
57
+ const chapters = Array.isArray(ledger.chapters) ? ledger.chapters : [];
58
+ const knowledgeLedger = Array.isArray(ledger.knowledgeLedger)
59
+ ? ledger.knowledgeLedger
60
+ : [];
61
+ const foreshadowing = Array.isArray(ledger.foreshadowing)
62
+ ? ledger.foreshadowing
63
+ : [];
64
+ const protagonistNames = extractProtagonistNames(ledger);
65
+ const allNames = Array.from(
66
+ new Set([...(Array.isArray(ledger.characterNames) ? ledger.characterNames : []), ...protagonistNames].filter(Boolean))
67
+ );
68
+
69
+ // 1. 核查章节号重复、断档与缺失核心摘要
70
+ const seenChapters = new Map();
71
+ const duplicateNumbers = [];
72
+ const emptySummaryChapters = [];
73
+ const numericChapters = [];
74
+
75
+ for (const ch of chapters) {
76
+ if (!ch || ch.chapterNumber == null || !Number.isFinite(Number(ch.chapterNumber))) {
77
+ continue;
78
+ }
79
+ const num = Number(ch.chapterNumber);
80
+ numericChapters.push(num);
81
+ seenChapters.set(num, (seenChapters.get(num) || 0) + 1);
82
+ if (seenChapters.get(num) === 2) {
83
+ duplicateNumbers.push(num);
84
+ }
85
+ if (!ch.coreSummary || !String(ch.coreSummary).trim()) {
86
+ emptySummaryChapters.push(num);
87
+ }
88
+ }
89
+
90
+ if (duplicateNumbers.length > 0) {
91
+ issues.push({
92
+ code: "DUPLICATE_CHAPTER_NUMBER",
93
+ severity: "error",
94
+ chapters: duplicateNumbers.sort((a, b) => a - b),
95
+ detail: `Duplicate chapterNumber(s): ${duplicateNumbers.join(", ")}`,
96
+ });
97
+ }
98
+
99
+ const sortedUnique = Array.from(new Set(numericChapters)).sort((a, b) => a - b);
100
+ const latestChapter =
101
+ options.currentChapter != null && Number.isFinite(Number(options.currentChapter))
102
+ ? Number(options.currentChapter)
103
+ : sortedUnique.length > 0
104
+ ? sortedUnique[sortedUnique.length - 1]
105
+ : 0;
106
+
107
+ const gaps = [];
108
+ for (let i = 1; i < sortedUnique.length; i += 1) {
109
+ const prev = sortedUnique[i - 1];
110
+ const curr = sortedUnique[i];
111
+ if (curr - prev > 1) {
112
+ gaps.push([prev + 1, curr - 1]);
113
+ }
114
+ }
115
+ if (gaps.length > 0) {
116
+ issues.push({
117
+ code: "CHAPTER_NUMBER_GAP",
118
+ severity: "warning",
119
+ gaps,
120
+ detail: `Missing chapter range(s): ${gaps.map(([s, e]) => (s === e ? String(s) : `${s}-${e}`)).join(", ")}`,
121
+ });
122
+ }
123
+
124
+ if (emptySummaryChapters.length > 0) {
125
+ issues.push({
126
+ code: "EMPTY_CHAPTER_SUMMARY",
127
+ severity: "warning",
128
+ chapters: emptySummaryChapters.sort((a, b) => a - b),
129
+ detail: `${emptySummaryChapters.length} chapter(s) have empty coreSummary: ${emptySummaryChapters.slice(0, 12).join(", ")}`,
130
+ });
131
+ }
132
+
133
+ // 2. 核查双栏知识台账揭露章先后逻辑矛盾
134
+ const invalidRevealEntries = [];
135
+ for (const entry of knowledgeLedger) {
136
+ if (!entry) continue;
137
+ const first = entry.firstChapter != null ? Number(entry.firstChapter) : null;
138
+ const reveal = entry.revealChapter != null ? Number(entry.revealChapter) : null;
139
+ if (first !== null && reveal !== null && reveal < first) {
140
+ invalidRevealEntries.push({
141
+ entity: entry.entity || "",
142
+ firstChapter: first,
143
+ revealChapter: reveal,
144
+ });
145
+ }
146
+ }
147
+ if (invalidRevealEntries.length > 0) {
148
+ issues.push({
149
+ code: "INVALID_REVEAL_CHAPTER",
150
+ severity: "error",
151
+ entries: invalidRevealEntries,
152
+ detail: invalidRevealEntries
153
+ .map((e) => `${e.entity || "unnamed"} (reveal ${e.revealChapter} < first ${e.firstChapter})`)
154
+ .join("; "),
155
+ });
156
+ }
157
+
158
+ // 3. 核查角色名单是否为空(为空时主语歧义检测默认静默跳过)
159
+ if (protagonistNames.length === 0) {
160
+ issues.push({
161
+ code: "MISSING_PROTAGONIST",
162
+ severity: "warning",
163
+ detail: "protagonist.name is empty.",
164
+ });
165
+ }
166
+ if (allNames.length === 0) {
167
+ issues.push({
168
+ code: "EMPTY_CHARACTER_NAMES",
169
+ severity: "warning",
170
+ detail: "characterNames is empty; SUBJECT_AMBIGUITY checks will be skipped until populated.",
171
+ });
172
+ }
173
+
174
+ // 4. 核查长期未回收或已过 targetChapter 的活跃伏笔
175
+ const activeForeshadowing = foreshadowing.filter(
176
+ (item) => item && !CLOSED_FORESHADOW_STATUSES.has(item.status)
177
+ );
178
+ const overdueForeshadowing = [];
179
+ for (const item of activeForeshadowing) {
180
+ const planted = item.plantedChapter != null ? Number(item.plantedChapter) : null;
181
+ const target = item.targetChapter != null ? Number(item.targetChapter) : null;
182
+ const pastTarget = target !== null && latestChapter > 0 && latestChapter > target;
183
+ const age = planted !== null && latestChapter > 0 ? latestChapter - planted : 0;
184
+ const pastAge = planted !== null && age >= overdueThreshold;
185
+ if (pastTarget || pastAge) {
186
+ overdueForeshadowing.push({
187
+ id: item.id || "",
188
+ clue: item.clue || "",
189
+ plantedChapter: planted,
190
+ targetChapter: target,
191
+ chaptersOpen: age,
192
+ reason: pastTarget ? "past_target_chapter" : "open_too_long",
193
+ });
194
+ }
195
+ }
196
+ if (overdueForeshadowing.length > 0) {
197
+ issues.push({
198
+ code: "OVERDUE_FORESHADOWING",
199
+ severity: "warning",
200
+ items: overdueForeshadowing,
201
+ detail: overdueForeshadowing
202
+ .map((f) => `${f.id || f.clue} (planted ch${f.plantedChapter ?? "?"}, target ch${f.targetChapter ?? "?"})`)
203
+ .join("; "),
204
+ });
205
+ }
206
+
207
+ // 5. 核查短线战术道具(mustResolveByChapter)是否已超过预定截止章仍未回收
208
+ const tacticalPool = [
209
+ ...activeForeshadowing,
210
+ ...(Array.isArray(ledger.tacticalProps)
211
+ ? ledger.tacticalProps.filter((p) => p && !CLOSED_FORESHADOW_STATUSES.has(p.status))
212
+ : []),
213
+ ];
214
+ const unresolvedProps = [];
215
+ for (const item of tacticalPool) {
216
+ const resolveBy =
217
+ item.mustResolveByChapter != null
218
+ ? Number(item.mustResolveByChapter)
219
+ : item.shortTerm && item.targetChapter != null
220
+ ? Number(item.targetChapter)
221
+ : null;
222
+ if (resolveBy !== null && Number.isFinite(resolveBy) && latestChapter >= resolveBy) {
223
+ unresolvedProps.push({
224
+ id: item.id || item.anchorTerm || item.clue || "",
225
+ anchorTerm: item.anchorTerm || item.clue || "",
226
+ plantedChapter: item.plantedChapter != null ? Number(item.plantedChapter) : null,
227
+ mustResolveByChapter: resolveBy,
228
+ });
229
+ }
230
+ }
231
+ if (unresolvedProps.length > 0) {
232
+ issues.push({
233
+ code: "UNRESOLVED_TACTICAL_PROP",
234
+ severity: "warning",
235
+ items: unresolvedProps,
236
+ detail: unresolvedProps
237
+ .map((p) => `${p.id} (mustResolveBy ch${p.mustResolveByChapter}, current ch${latestChapter})`)
238
+ .join("; "),
239
+ });
240
+ }
241
+
242
+ // 6. 核查跨章可量化资源流水(resourceDeltas)的单章加减算术与跨章期初/期末余额守恒
243
+ const sortedChObjs = [...chapters]
244
+ .filter((c) => c && Number.isFinite(Number(c.chapterNumber)))
245
+ .sort((a, b) => Number(a.chapterNumber) - Number(b.chapterNumber));
246
+ const lastResourceBalance = new Map();
247
+ const resourceMismatches = [];
248
+
249
+ for (const ch of sortedChObjs) {
250
+ const chNum = Number(ch.chapterNumber);
251
+ const deltas = ch.resourceDeltas;
252
+ if (!deltas || typeof deltas !== "object" || Array.isArray(deltas)) continue;
253
+
254
+ for (const [resName, rec] of Object.entries(deltas)) {
255
+ if (!rec || typeof rec !== "object") continue;
256
+ const before = rec.before != null ? Number(rec.before) : null;
257
+ const delta = rec.delta != null ? Number(rec.delta) : null;
258
+ const after = rec.after != null ? Number(rec.after) : null;
259
+
260
+ if (
261
+ before !== null &&
262
+ delta !== null &&
263
+ after !== null &&
264
+ Number.isFinite(before) &&
265
+ Number.isFinite(delta) &&
266
+ Number.isFinite(after)
267
+ ) {
268
+ const expectedAfter = Number((before + delta).toFixed(4));
269
+ if (Math.abs(expectedAfter - after) > 1e-4) {
270
+ resourceMismatches.push({
271
+ resource: resName,
272
+ chapterNumber: chNum,
273
+ kind: "arithmetic_error",
274
+ before,
275
+ delta,
276
+ after,
277
+ expectedAfter,
278
+ });
279
+ }
280
+ }
281
+
282
+ if (before !== null && Number.isFinite(before) && lastResourceBalance.has(resName)) {
283
+ const prev = lastResourceBalance.get(resName);
284
+ if (Math.abs(prev.after - before) > 1e-4) {
285
+ resourceMismatches.push({
286
+ resource: resName,
287
+ chapterNumber: chNum,
288
+ kind: "cross_chapter_discontinuity",
289
+ previousChapter: prev.chapterNumber,
290
+ previousAfter: prev.after,
291
+ currentBefore: before,
292
+ });
293
+ }
294
+ }
295
+
296
+ if (after !== null && Number.isFinite(after)) {
297
+ lastResourceBalance.set(resName, { chapterNumber: chNum, after });
298
+ }
299
+ }
300
+ }
301
+
302
+ if (resourceMismatches.length > 0) {
303
+ issues.push({
304
+ code: "RESOURCE_LEDGER_MISMATCH",
305
+ severity: "error",
306
+ mismatches: resourceMismatches,
307
+ detail: resourceMismatches
308
+ .map((m) =>
309
+ m.kind === "arithmetic_error"
310
+ ? `${m.resource}@ch${m.chapterNumber}: ${m.before} + (${m.delta}) != ${m.after}`
311
+ : `${m.resource}@ch${m.chapterNumber}: before=${m.currentBefore} != ch${m.previousChapter}.after=${m.previousAfter}`
312
+ )
313
+ .join("; "),
314
+ });
315
+ }
316
+
317
+ const errorCount = issues.filter((i) => i.severity === "error").length;
318
+ const warningCount = issues.filter((i) => i.severity === "warning").length;
319
+
320
+ return {
321
+ pass: errorCount === 0,
322
+ summary: { error: errorCount, warning: warningCount },
323
+ stats: {
324
+ chapterCount: chapters.length,
325
+ latestChapter,
326
+ characterCount: allNames.length,
327
+ activeForeshadowingCount: activeForeshadowing.length,
328
+ overdueForeshadowingCount: overdueForeshadowing.length,
329
+ knowledgeCount: knowledgeLedger.length,
330
+ },
331
+ issues,
332
+ };
333
+ }
334
+
335
+ // 无损合并单章写后结算 JSON 补丁到全书台账,并返回结构化变更 diff
336
+ export function applyChapterSettlement(ledger, patch) {
337
+ if (!patch || typeof patch !== "object" || Array.isArray(patch)) {
338
+ throw new Error("Settlement patch must be a JSON object.");
339
+ }
340
+ const chapNum = Number(patch.chapterNumber);
341
+ if (!Number.isFinite(chapNum) || chapNum <= 0) {
342
+ throw new Error("Settlement patch requires a positive numeric chapterNumber.");
343
+ }
344
+
345
+ const next = cloneJson(
346
+ ledger && typeof ledger === "object"
347
+ ? ledger
348
+ : {
349
+ projectTitle: "",
350
+ protagonist: "",
351
+ characterNames: [],
352
+ immutableWorldRules: [],
353
+ deprecatedTerms: [],
354
+ knowledgeLedger: [],
355
+ characterSnapshots: {},
356
+ foreshadowing: [],
357
+ chapters: [],
358
+ }
359
+ );
360
+
361
+ if (!Array.isArray(next.chapters)) next.chapters = [];
362
+ if (!Array.isArray(next.characterNames)) next.characterNames = [];
363
+ if (!Array.isArray(next.foreshadowing)) next.foreshadowing = [];
364
+ if (!Array.isArray(next.knowledgeLedger)) next.knowledgeLedger = [];
365
+ if (!next.characterSnapshots || typeof next.characterSnapshots !== "object") {
366
+ next.characterSnapshots = {};
367
+ }
368
+
369
+ const diff = {
370
+ chapterNumber: chapNum,
371
+ chapterAdded: false,
372
+ chapterUpdated: false,
373
+ updatedCharacters: [],
374
+ addedCharacters: [],
375
+ addedForeshadowing: [],
376
+ updatedForeshadowing: [],
377
+ resolvedForeshadowing: [],
378
+ updatedKnowledge: [],
379
+ updatedResources: [],
380
+ };
381
+
382
+ // 1. 合并或追加 chapters[] 条目
383
+ const existingIdx = next.chapters.findIndex(
384
+ (c) => Number(c.chapterNumber) === chapNum
385
+ );
386
+ if (existingIdx >= 0) {
387
+ const cur = next.chapters[existingIdx];
388
+ const merged = { ...cur };
389
+ if (patch.title !== undefined && String(patch.title).trim()) {
390
+ merged.title = String(patch.title).trim();
391
+ }
392
+ if (patch.coreSummary !== undefined && String(patch.coreSummary).trim()) {
393
+ merged.coreSummary = String(patch.coreSummary).trim();
394
+ }
395
+ if (Array.isArray(patch.requiredAnchors)) {
396
+ merged.requiredAnchors = Array.from(
397
+ new Set([...(cur.requiredAnchors || []), ...patch.requiredAnchors].filter(Boolean))
398
+ );
399
+ }
400
+ if (Array.isArray(patch.futureForbiddenTerms)) {
401
+ merged.futureForbiddenTerms = Array.from(
402
+ new Set([...(cur.futureForbiddenTerms || []), ...patch.futureForbiddenTerms].filter(Boolean))
403
+ );
404
+ }
405
+ if (Array.isArray(patch.activeCharacters)) {
406
+ merged.activeCharacters = Array.from(
407
+ new Set([...(cur.activeCharacters || []), ...patch.activeCharacters].filter(Boolean))
408
+ );
409
+ }
410
+ if (patch.hanCount != null && Number.isFinite(Number(patch.hanCount))) {
411
+ merged.hanCount = Number(patch.hanCount);
412
+ }
413
+ merged.settled = true;
414
+ next.chapters[existingIdx] = merged;
415
+ diff.chapterUpdated = true;
416
+ } else {
417
+ const entry = {
418
+ chapterNumber: chapNum,
419
+ title: String(patch.title || "").trim(),
420
+ coreSummary: String(patch.coreSummary || "").trim(),
421
+ requiredAnchors: Array.isArray(patch.requiredAnchors)
422
+ ? patch.requiredAnchors.filter(Boolean)
423
+ : [],
424
+ futureForbiddenTerms: Array.isArray(patch.futureForbiddenTerms)
425
+ ? patch.futureForbiddenTerms.filter(Boolean)
426
+ : [],
427
+ settled: true,
428
+ };
429
+ if (Array.isArray(patch.activeCharacters) && patch.activeCharacters.length > 0) {
430
+ entry.activeCharacters = Array.from(new Set(patch.activeCharacters.filter(Boolean)));
431
+ }
432
+ if (patch.hanCount != null && Number.isFinite(Number(patch.hanCount))) {
433
+ entry.hanCount = Number(patch.hanCount);
434
+ }
435
+ next.chapters.push(entry);
436
+ next.chapters.sort((a, b) => Number(a.chapterNumber) - Number(b.chapterNumber));
437
+ diff.chapterAdded = true;
438
+ }
439
+
440
+ // 2. 合并角色 8 字段快照增量
441
+ const charUpdates = patch.characterUpdates;
442
+ if (charUpdates && typeof charUpdates === "object" && !Array.isArray(charUpdates)) {
443
+ for (const [charName, delta] of Object.entries(charUpdates)) {
444
+ if (!charName || !delta || typeof delta !== "object") continue;
445
+ const prevSnap =
446
+ next.characterSnapshots[charName] && typeof next.characterSnapshots[charName] === "object"
447
+ ? next.characterSnapshots[charName]
448
+ : { name: charName };
449
+ const mergedSnap = {
450
+ ...prevSnap,
451
+ ...delta,
452
+ name: delta.name || prevSnap.name || charName,
453
+ lastUpdatedChapter: chapNum,
454
+ };
455
+ const statusLower = String(mergedSnap.status || "").toLowerCase();
456
+ if (
457
+ ["deceased", "dead", "exited", "killed"].includes(statusLower) &&
458
+ mergedSnap.deceasedChapter == null &&
459
+ mergedSnap.absentAfterChapter == null
460
+ ) {
461
+ mergedSnap.deceasedChapter = chapNum;
462
+ }
463
+ next.characterSnapshots[charName] = mergedSnap;
464
+ diff.updatedCharacters.push(charName);
465
+ }
466
+ }
467
+
468
+ // 3. 自动把新出场或更新过的角色同步写入 characterNames
469
+ const existingNameSet = new Set(next.characterNames);
470
+ const candidateNames = [
471
+ ...(Array.isArray(patch.newCharacters) ? patch.newCharacters : []),
472
+ ...(Array.isArray(patch.activeCharacters) ? patch.activeCharacters : []),
473
+ ...diff.updatedCharacters,
474
+ ];
475
+ for (const name of candidateNames) {
476
+ const clean = String(name || "").trim();
477
+ if (clean && !existingNameSet.has(clean)) {
478
+ next.characterNames.push(clean);
479
+ existingNameSet.add(clean);
480
+ diff.addedCharacters.push(clean);
481
+ }
482
+ }
483
+
484
+ // 4. 合并伏笔台账新增与状态跃迁(planted -> paid_off / abandoned)
485
+ if (Array.isArray(patch.foreshadowingUpdates)) {
486
+ for (const upd of patch.foreshadowingUpdates) {
487
+ if (!upd || typeof upd !== "object") continue;
488
+ const idx = next.foreshadowing.findIndex(
489
+ (item) =>
490
+ item &&
491
+ ((upd.id && item.id === upd.id) || (!upd.id && upd.clue && item.clue === upd.clue))
492
+ );
493
+ if (idx >= 0) {
494
+ const prev = next.foreshadowing[idx];
495
+ const merged = { ...prev, ...upd };
496
+ if (CLOSED_FORESHADOW_STATUSES.has(merged.status) && merged.paidOffChapter == null) {
497
+ merged.paidOffChapter = chapNum;
498
+ }
499
+ next.foreshadowing[idx] = merged;
500
+ if (
501
+ !CLOSED_FORESHADOW_STATUSES.has(prev.status) &&
502
+ CLOSED_FORESHADOW_STATUSES.has(merged.status)
503
+ ) {
504
+ diff.resolvedForeshadowing.push(merged.id || merged.clue);
505
+ } else {
506
+ diff.updatedForeshadowing.push(merged.id || merged.clue);
507
+ }
508
+ } else {
509
+ const added = {
510
+ id: upd.id || `fs_ch${chapNum}_${next.foreshadowing.length + 1}`,
511
+ clue: upd.clue || "",
512
+ plantedChapter: upd.plantedChapter ?? chapNum,
513
+ targetChapter: upd.targetChapter ?? null,
514
+ status: upd.status || "planted",
515
+ };
516
+ if (upd.mustResolveByChapter != null) {
517
+ added.mustResolveByChapter = Number(upd.mustResolveByChapter);
518
+ }
519
+ if (upd.anchorTerm) added.anchorTerm = String(upd.anchorTerm).trim();
520
+ if (upd.shortTerm != null) added.shortTerm = Boolean(upd.shortTerm);
521
+ if (upd.notes) added.notes = upd.notes;
522
+ next.foreshadowing.push(added);
523
+ diff.addedForeshadowing.push(added.id);
524
+ }
525
+ }
526
+ }
527
+
528
+ // 4b. 合并章节可量化资源流水(resourceDeltas / resourceUpdates)并更新总账余额
529
+ const resInput = patch.resourceDeltas || patch.resourceUpdates;
530
+ if (resInput && typeof resInput === "object" && !Array.isArray(resInput)) {
531
+ if (!next.resourceLedger || typeof next.resourceLedger !== "object") {
532
+ next.resourceLedger = {};
533
+ }
534
+ const chIdx = next.chapters.findIndex((c) => Number(c.chapterNumber) === chapNum);
535
+ const chObj = chIdx >= 0 ? next.chapters[chIdx] : null;
536
+ if (chObj && (!chObj.resourceDeltas || typeof chObj.resourceDeltas !== "object")) {
537
+ chObj.resourceDeltas = {};
538
+ }
539
+ for (const [resName, rec] of Object.entries(resInput)) {
540
+ if (!resName || !rec || typeof rec !== "object") continue;
541
+ const cleanRec = {};
542
+ if (rec.before != null && Number.isFinite(Number(rec.before))) {
543
+ cleanRec.before = Number(rec.before);
544
+ }
545
+ if (rec.delta != null && Number.isFinite(Number(rec.delta))) {
546
+ cleanRec.delta = Number(rec.delta);
547
+ }
548
+ if (rec.after != null && Number.isFinite(Number(rec.after))) {
549
+ cleanRec.after = Number(rec.after);
550
+ } else if (cleanRec.before !== undefined && cleanRec.delta !== undefined) {
551
+ cleanRec.after = Number((cleanRec.before + cleanRec.delta).toFixed(4));
552
+ }
553
+ if (rec.note) cleanRec.note = String(rec.note);
554
+ if (chObj) {
555
+ chObj.resourceDeltas[resName] = cleanRec;
556
+ }
557
+ if (cleanRec.after !== undefined) {
558
+ next.resourceLedger[resName] = {
559
+ balance: cleanRec.after,
560
+ lastUpdatedChapter: chapNum,
561
+ };
562
+ }
563
+ diff.updatedResources.push(resName);
564
+ }
565
+ }
566
+
567
+ // 5. 合并双栏知识台账增量更新
568
+ if (Array.isArray(patch.knowledgeUpdates)) {
569
+ for (const ku of patch.knowledgeUpdates) {
570
+ if (!ku || typeof ku !== "object" || !ku.entity) continue;
571
+ const idx = next.knowledgeLedger.findIndex((k) => k && k.entity === ku.entity);
572
+ if (idx >= 0) {
573
+ const prev = next.knowledgeLedger[idx];
574
+ next.knowledgeLedger[idx] = {
575
+ ...prev,
576
+ ...ku,
577
+ revealForbiddenTerms: Array.isArray(ku.revealForbiddenTerms)
578
+ ? Array.from(
579
+ new Set([...(prev.revealForbiddenTerms || []), ...ku.revealForbiddenTerms].filter(Boolean))
580
+ )
581
+ : prev.revealForbiddenTerms || [],
582
+ };
583
+ } else {
584
+ next.knowledgeLedger.push({
585
+ entity: ku.entity,
586
+ firstChapter: ku.firstChapter ?? chapNum,
587
+ readerKnown: ku.readerKnown || "",
588
+ fullTruth: ku.fullTruth || "",
589
+ revealChapter: ku.revealChapter ?? null,
590
+ revealForbiddenTerms: Array.isArray(ku.revealForbiddenTerms)
591
+ ? ku.revealForbiddenTerms.filter(Boolean)
592
+ : [],
593
+ });
594
+ }
595
+ diff.updatedKnowledge.push(ku.entity);
596
+ }
597
+ }
598
+
599
+ return { ledger: next, diff };
600
+ }
601
+
602
+ // 校验候选人名是否命中单姓、复姓或姓氏+称谓结构(完全由 JSON 配置驱动,零汉字字面量)
603
+ function classifyCandidateName(candidate, cfg) {
604
+ if (!candidate || candidate.length < 2 || candidate.length > 4) return null;
605
+ if (cfg.stopwordSet && cfg.stopwordSet.has(candidate)) return null;
606
+
607
+ for (const cs of cfg.compoundSurnames || []) {
608
+ if (candidate.startsWith(cs) && candidate.length >= cs.length + 1 && candidate.length <= cs.length + 2) {
609
+ return { kind: "compound_surname", bonus: 2.2 };
610
+ }
611
+ }
612
+ const firstChar = candidate[0];
613
+ const hasSurname = cfg.surnameSet ? cfg.surnameSet.has(firstChar) : false;
614
+ if (hasSurname) {
615
+ for (const suffix of cfg.titleSuffixes || []) {
616
+ if (candidate.endsWith(suffix) && candidate.length === 1 + suffix.length) {
617
+ return { kind: "surname_title", bonus: 2.0 };
618
+ }
619
+ }
620
+ if (candidate.length === 2 || candidate.length === 3) {
621
+ return { kind: "surname_name", bonus: 1.6 };
622
+ }
623
+ }
624
+ for (const suffix of cfg.titleSuffixes || []) {
625
+ if (suffix.length >= 2 && candidate.endsWith(suffix) && candidate.length >= suffix.length + 1 && candidate.length <= 4) {
626
+ return { kind: "title_name", bonus: 1.2 };
627
+ }
628
+ }
629
+ return null;
630
+ }
631
+
632
+ // 零依赖启发式挖掘存量章节中的高频角色名候选(用于初始化或补全 ledger.characterNames)
633
+ export function extractCandidateCharacters(texts, lingConfig, options = {}) {
634
+ const cfg = lingConfig?.compiledRegex?.characterExtraction;
635
+ if (!cfg || !cfg.speechActionRegex || !Array.isArray(texts) || texts.length === 0) {
636
+ return [];
637
+ }
638
+
639
+ const minTotalCount = options.minTotalCount ?? cfg.minTotalCount ?? 2;
640
+ const maxCandidates = options.maxCandidates ?? cfg.maxCandidates ?? 24;
641
+ const statsMap = new Map();
642
+
643
+ for (const rawText of texts) {
644
+ const lines = String(rawText || "").split(/\r?\n/u);
645
+ const seenInDoc = new Set();
646
+
647
+ for (const line of lines) {
648
+ const trimmed = line.trim();
649
+ if (!trimmed || trimmed.startsWith("#")) continue;
650
+ const { narration } = stripSpokenDialogue(trimmed, lingConfig, " ");
651
+ if (!narration) continue;
652
+
653
+ cfg.speechActionRegex.lastIndex = 0;
654
+ let match;
655
+ while ((match = cfg.speechActionRegex.exec(narration)) !== null) {
656
+ const rawCandidate = match[1];
657
+ if (!rawCandidate) continue;
658
+ // 尝试从最长到 2 字的后缀切片匹配,避免把前导介词/副词粘进人名
659
+ let matchedName = null;
660
+ let matchedMeta = null;
661
+ const maxLen = Math.min(rawCandidate.length, 4);
662
+ for (let len = maxLen; len >= 2; len -= 1) {
663
+ const slice = rawCandidate.slice(rawCandidate.length - len);
664
+ const meta = classifyCandidateName(slice, cfg);
665
+ if (meta) {
666
+ matchedName = slice;
667
+ matchedMeta = meta;
668
+ break;
669
+ }
670
+ }
671
+ if (!matchedName || !matchedMeta) continue;
672
+
673
+ const rec = statsMap.get(matchedName) || {
674
+ name: matchedName,
675
+ kind: matchedMeta.kind,
676
+ bonus: matchedMeta.bonus,
677
+ actionHits: 0,
678
+ totalCount: 0,
679
+ chapterCount: 0,
680
+ };
681
+ rec.actionHits += 1;
682
+ if (!seenInDoc.has(matchedName)) {
683
+ rec.chapterCount += 1;
684
+ seenInDoc.add(matchedName);
685
+ }
686
+ statsMap.set(matchedName, rec);
687
+ }
688
+ }
689
+ }
690
+
691
+ // 统计每个候选名在所有文本中的总出现频次,并按动作锚定次数 + 跨章覆盖综合排序
692
+ const allCombined = texts.join("\n");
693
+ const candidates = [];
694
+ for (const rec of statsMap.values()) {
695
+ const parts = allCombined.split(rec.name);
696
+ rec.totalCount = parts.length - 1;
697
+ if (rec.totalCount < minTotalCount) continue;
698
+ const score = Number(
699
+ (rec.actionHits * rec.bonus + Math.min(rec.totalCount, 40) * 0.4 + rec.chapterCount * 1.5).toFixed(2)
700
+ );
701
+ const confidence =
702
+ rec.actionHits >= 2 || (rec.chapterCount >= 2 && rec.totalCount >= 3)
703
+ ? "high"
704
+ : "medium";
705
+ candidates.push({
706
+ name: rec.name,
707
+ kind: rec.kind,
708
+ actionHits: rec.actionHits,
709
+ totalCount: rec.totalCount,
710
+ chapterCount: rec.chapterCount,
711
+ confidence,
712
+ score,
713
+ });
714
+ }
715
+
716
+ candidates.sort((a, b) => b.score - a.score || b.totalCount - a.totalCount);
717
+
718
+ // 去除被更长高频全名完全包含的低频截断片段
719
+ const filtered = candidates.filter((cand) => {
720
+ if (cand.name.length >= 3) return true;
721
+ const shadowedBy = candidates.find(
722
+ (other) =>
723
+ other.name.length > cand.name.length &&
724
+ other.name.includes(cand.name) &&
725
+ other.totalCount >= cand.totalCount * 0.7
726
+ );
727
+ return !shadowedBy;
728
+ });
729
+
730
+ return filtered.slice(0, maxCandidates);
731
+ }
732
+
733
+ // 批量无损合并多章写后结算补丁数组(供老书半途接管或批量回填 coreSummary 与状态使用)
734
+ export function applyBatchSettlement(ledger, patchesInput) {
735
+ const list = Array.isArray(patchesInput)
736
+ ? patchesInput
737
+ : Array.isArray(patchesInput?.patches)
738
+ ? patchesInput.patches
739
+ : null;
740
+ if (!list || list.length === 0) {
741
+ throw new Error("Batch settlement requires a non-empty array of chapter patches.");
742
+ }
743
+ const sorted = [...list].sort(
744
+ (a, b) => Number(a?.chapterNumber || 0) - Number(b?.chapterNumber || 0)
745
+ );
746
+ let curLedger = ledger;
747
+ const diffs = [];
748
+ for (const patch of sorted) {
749
+ const res = applyChapterSettlement(curLedger, patch);
750
+ curLedger = res.ledger;
751
+ diffs.push(res.diff);
752
+ }
753
+ return {
754
+ ledger: curLedger,
755
+ batchDiff: {
756
+ settledCount: diffs.length,
757
+ chapters: diffs.map((d) => d.chapterNumber),
758
+ diffs,
759
+ },
760
+ };
761
+ }
762
+
763
+ // 针对老书尚未填写 coreSummary 的存量章节,分批生成可直接输出 settle --batch JSON 的回填提示词
764
+ export function buildLedgerBackfillPrompts(chapterEntries, ledger = {}, options = {}) {
765
+ const batchSize =
766
+ Number.isFinite(Number(options.batchSize)) && Number(options.batchSize) > 0
767
+ ? Math.floor(Number(options.batchSize))
768
+ : 5;
769
+ const maxExcerptChars =
770
+ Number.isFinite(Number(options.maxExcerptChars)) && Number(options.maxExcerptChars) > 200
771
+ ? Math.floor(Number(options.maxExcerptChars))
772
+ : 3200;
773
+
774
+ const existingByNum = new Map();
775
+ for (const ch of ledger?.chapters || []) {
776
+ if (ch && Number.isFinite(Number(ch.chapterNumber))) {
777
+ existingByNum.set(Number(ch.chapterNumber), ch);
778
+ }
779
+ }
780
+
781
+ const missingEntries = (chapterEntries || [])
782
+ .filter((entry) => {
783
+ if (!entry || !Number.isFinite(Number(entry.chapterNumber))) return false;
784
+ const existing = existingByNum.get(Number(entry.chapterNumber));
785
+ if (options.includeAll) return true;
786
+ return !existing || !existing.coreSummary || !String(existing.coreSummary).trim();
787
+ })
788
+ .sort((a, b) => Number(a.chapterNumber) - Number(b.chapterNumber));
789
+
790
+ const batches = [];
791
+ for (let i = 0; i < missingEntries.length; i += batchSize) {
792
+ const slice = missingEntries.slice(i, i + batchSize);
793
+ const chNums = slice.map((s) => Number(s.chapterNumber));
794
+ const schemaExample = [
795
+ {
796
+ chapterNumber: chNums[0] || 1,
797
+ title: slice[0]?.title || "",
798
+ coreSummary: "One-sentence factual summary (<100 chars): who did what, key gain/cost, ending state.",
799
+ requiredAnchors: ["Anchor1", "Anchor2"],
800
+ activeCharacters: ["Protagonist"],
801
+ characterUpdates: {},
802
+ foreshadowingUpdates: [],
803
+ resourceDeltas: {},
804
+ },
805
+ ];
806
+
807
+ const bodyBlocks = slice.map((item) => {
808
+ const raw = String(item.text || "").trim();
809
+ const excerpt =
810
+ raw.length <= maxExcerptChars
811
+ ? raw
812
+ : `${raw.slice(0, Math.floor(maxExcerptChars * 0.65))}\n...\n${raw.slice(-Math.floor(maxExcerptChars * 0.35))}`;
813
+ return `=== CHAPTER ${item.chapterNumber}: ${item.title || item.name || ""} ===\n${excerpt}`;
814
+ });
815
+
816
+ const prompt = [
817
+ `# InkBone Batch Ledger Backfill (Chapters ${chNums[0]}-${chNums[chNums.length - 1]})`,
818
+ "Extract factual chapter summaries, key anchors, active characters, and resource/foreshadowing deltas from the chapters below.",
819
+ "Output ONLY a valid JSON array matching `inkbone settle --batch` format:",
820
+ "```json",
821
+ JSON.stringify(schemaExample, null, 2),
822
+ "```",
823
+ ...bodyBlocks,
824
+ ].join("\n\n");
825
+
826
+ batches.push({
827
+ batchIndex: batches.length + 1,
828
+ chapters: chNums,
829
+ chapterCount: slice.length,
830
+ prompt,
831
+ });
832
+ }
833
+
834
+ return {
835
+ totalMissingChapters: missingEntries.length,
836
+ batchSize,
837
+ batchCount: batches.length,
838
+ batches:
839
+ Number.isFinite(Number(options.limit)) && Number(options.limit) > 0
840
+ ? batches.slice(0, Number(options.limit))
841
+ : batches,
842
+ };
843
+ }