inkbone 0.0.0-stage → 2.0.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 (139) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +318 -0
  3. package/README.md +333 -2
  4. package/bin/inkbone.mjs +941 -0
  5. package/configs/genres.json +570 -0
  6. package/configs/messages.json +302 -0
  7. package/configs/platforms.json +62 -0
  8. package/configs/presets.json +265 -0
  9. package/configs/severity.json +52 -0
  10. package/configs/zh-linguistics.json +986 -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 +61 -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 +60 -0
  18. package/prompts/03-targeted-rewriter.md +39 -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 +98 -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 +21 -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 +334 -0
  37. package/skills/inkbone/SKILL.md +155 -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 +941 -0
  42. package/skills/inkbone/configs/genres.json +570 -0
  43. package/skills/inkbone/configs/messages.json +302 -0
  44. package/skills/inkbone/configs/platforms.json +62 -0
  45. package/skills/inkbone/configs/presets.json +265 -0
  46. package/skills/inkbone/configs/severity.json +52 -0
  47. package/skills/inkbone/configs/zh-linguistics.json +986 -0
  48. package/skills/inkbone/configs/zh-traditional.json +97 -0
  49. package/skills/inkbone/package.json +63 -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 +60 -0
  53. package/skills/inkbone/prompts/03-targeted-rewriter.md +39 -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 +98 -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 +21 -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/auditor.mjs +24 -0
  71. package/skills/inkbone/src/benchmark-runner.mjs +71 -0
  72. package/skills/inkbone/src/boundary-compiler.mjs +54 -0
  73. package/skills/inkbone/src/browser-doctor.mjs +30 -0
  74. package/skills/inkbone/src/calibrator.mjs +175 -0
  75. package/skills/inkbone/src/config-loader.mjs +233 -0
  76. package/skills/inkbone/src/continuity.mjs +5 -0
  77. package/skills/inkbone/src/core/auditor.mjs +914 -0
  78. package/skills/inkbone/src/core/boundary-compiler.mjs +423 -0
  79. package/skills/inkbone/src/core/browser-doctor.mjs +318 -0
  80. package/skills/inkbone/src/core/config-compiler.mjs +434 -0
  81. package/skills/inkbone/src/core/continuity.mjs +158 -0
  82. package/skills/inkbone/src/core/evidence-validator.mjs +77 -0
  83. package/skills/inkbone/src/core/exporter.mjs +128 -0
  84. package/skills/inkbone/src/core/formatter.mjs +241 -0
  85. package/skills/inkbone/src/core/ledger-manager.mjs +576 -0
  86. package/skills/inkbone/src/core/normalizer.mjs +517 -0
  87. package/skills/inkbone/src/core/profiler.mjs +686 -0
  88. package/skills/inkbone/src/core/rule-engine.mjs +1536 -0
  89. package/skills/inkbone/src/core/style-profiler.mjs +229 -0
  90. package/skills/inkbone/src/detector.mjs +270 -0
  91. package/skills/inkbone/src/doctor.mjs +428 -0
  92. package/skills/inkbone/src/evaluation.mjs +311 -0
  93. package/skills/inkbone/src/evidence-validator.mjs +15 -0
  94. package/skills/inkbone/src/exporter.mjs +106 -0
  95. package/skills/inkbone/src/formatter.mjs +34 -0
  96. package/skills/inkbone/src/importer.mjs +230 -0
  97. package/skills/inkbone/src/index.mjs +116 -0
  98. package/skills/inkbone/src/ledger-manager.mjs +15 -0
  99. package/skills/inkbone/src/mcp-server.mjs +861 -0
  100. package/skills/inkbone/src/normalizer.mjs +73 -0
  101. package/skills/inkbone/src/profiler.mjs +17 -0
  102. package/skills/inkbone/src/rule-engine.mjs +73 -0
  103. package/skills/inkbone/src/rule-stats.mjs +142 -0
  104. package/skills/inkbone/src/style-profiler.mjs +25 -0
  105. package/src/auditor.mjs +24 -0
  106. package/src/benchmark-runner.mjs +71 -0
  107. package/src/boundary-compiler.mjs +54 -0
  108. package/src/browser-doctor.mjs +30 -0
  109. package/src/calibrator.mjs +175 -0
  110. package/src/config-loader.mjs +233 -0
  111. package/src/continuity.mjs +5 -0
  112. package/src/core/auditor.mjs +914 -0
  113. package/src/core/boundary-compiler.mjs +423 -0
  114. package/src/core/browser-doctor.mjs +318 -0
  115. package/src/core/config-compiler.mjs +434 -0
  116. package/src/core/continuity.mjs +158 -0
  117. package/src/core/evidence-validator.mjs +77 -0
  118. package/src/core/exporter.mjs +128 -0
  119. package/src/core/formatter.mjs +241 -0
  120. package/src/core/ledger-manager.mjs +576 -0
  121. package/src/core/normalizer.mjs +517 -0
  122. package/src/core/profiler.mjs +686 -0
  123. package/src/core/rule-engine.mjs +1536 -0
  124. package/src/core/style-profiler.mjs +229 -0
  125. package/src/detector.mjs +270 -0
  126. package/src/doctor.mjs +428 -0
  127. package/src/evaluation.mjs +311 -0
  128. package/src/evidence-validator.mjs +15 -0
  129. package/src/exporter.mjs +106 -0
  130. package/src/formatter.mjs +34 -0
  131. package/src/importer.mjs +230 -0
  132. package/src/index.mjs +116 -0
  133. package/src/ledger-manager.mjs +15 -0
  134. package/src/mcp-server.mjs +861 -0
  135. package/src/normalizer.mjs +73 -0
  136. package/src/profiler.mjs +17 -0
  137. package/src/rule-engine.mjs +73 -0
  138. package/src/rule-stats.mjs +142 -0
  139. package/src/style-profiler.mjs +25 -0
@@ -0,0 +1,941 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { execFileSync } from "node:child_process";
5
+ import { fileURLToPath } from "node:url";
6
+ import {
7
+ profileText,
8
+ auditChapterText,
9
+ compileBoundaryPacket,
10
+ validateEvidenceReview,
11
+ runCorpusBenchmark,
12
+ formatBenchmarkMarkdown,
13
+ calibrateReference,
14
+ mineOverusedPhrases,
15
+ collectTextFiles,
16
+ detectWithZhuque,
17
+ listGenres,
18
+ diagnoseProject,
19
+ formatDoctorMarkdown,
20
+ scaffoldProject,
21
+ findProjectConfig,
22
+ loadProjectConfig,
23
+ importLedgerFromChapters,
24
+ normalizeFiles,
25
+ checkOutlineContract,
26
+ computeRuleStats,
27
+ formatRuleStatsMarkdown,
28
+ buildBlindPack,
29
+ writeBlindPack,
30
+ scoreBallots,
31
+ loadPairTexts,
32
+ saveReview,
33
+ summarizeReviews,
34
+ validateLedger,
35
+ applyChapterSettlement,
36
+ formatAuditMarkdown,
37
+ buildTargetedRewritePrompt,
38
+ startMcpServer,
39
+ analyzeStyleProfile,
40
+ formatStyleProfileMarkdown,
41
+ exportChapters,
42
+ listPlatforms,
43
+ } from "../src/index.mjs";
44
+
45
+ const currentFile = fileURLToPath(import.meta.url);
46
+ const binDir = path.dirname(currentFile);
47
+ const rootDir = path.resolve(binDir, "..");
48
+ const CLI_VERSION =
49
+ JSON.parse(fs.readFileSync(path.resolve(rootDir, "package.json"), "utf8")).version ||
50
+ "1.3.0";
51
+
52
+ // 解析简单的命令行键值对标志参数
53
+ function parseFlags(args) {
54
+ const positional = [];
55
+ const flags = {};
56
+ const multiValueKeys = new Set(["ai", "human", "vocab", "outline", "a", "b"]);
57
+ const booleanKeys = new Set([
58
+ "check",
59
+ "strip-bold",
60
+ "fix-emdash",
61
+ "force",
62
+ "json",
63
+ "strict",
64
+ "full",
65
+ "skip-length",
66
+ "no-ledger",
67
+ "no-project",
68
+ "no-cache",
69
+ "all",
70
+ "auto-characters",
71
+ "dry-run",
72
+ "include-closed",
73
+ "help-all",
74
+ "indent",
75
+ "no-indent",
76
+ "platforms",
77
+ ]);
78
+ for (let i = 0; i < args.length; i += 1) {
79
+ const token = args[i];
80
+ if (token.startsWith("--")) {
81
+ const key = token.slice(2);
82
+ const next = args[i + 1];
83
+ if (booleanKeys.has(key) || !next || next.startsWith("--")) {
84
+ flags[key] = true;
85
+ } else if (multiValueKeys.has(key)) {
86
+ // 多值参数:一直读到下一个 -- 标志为止
87
+ const values = [];
88
+ while (i + 1 < args.length && !args[i + 1].startsWith("--")) {
89
+ values.push(args[i + 1]);
90
+ i += 1;
91
+ }
92
+ flags[key] = values;
93
+ } else {
94
+ flags[key] = next;
95
+ i += 1;
96
+ }
97
+ } else {
98
+ positional.push(token);
99
+ }
100
+ }
101
+ return { positional, flags };
102
+ }
103
+
104
+ // 定位并加载书目录的项目配置:--project 显式指定,否则从目标文件向上找 novel.json;--no-project 关闭
105
+ function resolveProject(flags, targetPath) {
106
+ if (flags["no-project"]) return null;
107
+ let configPath = null;
108
+ if (typeof flags.project === "string") {
109
+ const explicit = path.resolve(flags.project);
110
+ configPath =
111
+ fs.existsSync(explicit) && fs.statSync(explicit).isDirectory()
112
+ ? path.join(explicit, "novel.json")
113
+ : explicit;
114
+ if (!fs.existsSync(configPath)) {
115
+ throw new Error(`Project config not found: ${configPath}`);
116
+ }
117
+ } else if (targetPath) {
118
+ const abs = path.resolve(targetPath);
119
+ const startDir =
120
+ fs.existsSync(abs) && fs.statSync(abs).isDirectory() ? abs : path.dirname(abs);
121
+ configPath = findProjectConfig(startDir);
122
+ }
123
+ if (!configPath) return null;
124
+ const project = loadProjectConfig(configPath);
125
+ console.error(`[inkbone] project config: ${project.path}`);
126
+ return project;
127
+ }
128
+
129
+ // 动态发现 benchmarks 子目录下的 manifest.json 文件列表(去除单书硬编码)
130
+ function discoverBenchmarkEntries(explicitManifest = null) {
131
+ if (explicitManifest) {
132
+ const mPath = path.resolve(explicitManifest);
133
+ if (!fs.existsSync(mPath)) return [];
134
+ const parsed = JSON.parse(fs.readFileSync(mPath, "utf8"));
135
+ return (parsed.entries || []).map((e) => ({
136
+ ...e,
137
+ path: path.resolve(path.dirname(mPath), e.file),
138
+ }));
139
+ }
140
+ const benchRoot = path.resolve(rootDir, "benchmarks");
141
+ if (!fs.existsSync(benchRoot)) return [];
142
+ const results = [];
143
+ for (const sub of fs.readdirSync(benchRoot, { withFileTypes: true })) {
144
+ if (!sub.isDirectory()) continue;
145
+ const mPath = path.resolve(benchRoot, sub.name, "manifest.json");
146
+ if (!fs.existsSync(mPath)) continue;
147
+ const parsed = JSON.parse(fs.readFileSync(mPath, "utf8"));
148
+ for (const e of parsed.entries || []) {
149
+ results.push({
150
+ ...e,
151
+ path: path.resolve(path.dirname(mPath), e.file),
152
+ });
153
+ }
154
+ }
155
+ return results;
156
+ }
157
+
158
+ // 通过 git status / git diff 识别当前工作区改动过的章稿文件(用于 doctor --changed 增量体检)
159
+ function resolveGitChangedFiles(targetDir, gitRef) {
160
+ const cwd = fs.existsSync(targetDir) && fs.statSync(targetDir).isDirectory()
161
+ ? targetDir
162
+ : path.dirname(targetDir);
163
+ try {
164
+ const repoRoot = execFileSync("git", ["rev-parse", "--show-toplevel"], {
165
+ cwd,
166
+ encoding: "utf8",
167
+ stdio: ["ignore", "pipe", "ignore"],
168
+ }).trim();
169
+ const relSet = new Set();
170
+ if (typeof gitRef === "string" && gitRef.trim()) {
171
+ const diffOut = execFileSync("git", ["diff", "--name-only", gitRef.trim()], {
172
+ cwd: repoRoot,
173
+ encoding: "utf8",
174
+ stdio: ["ignore", "pipe", "ignore"],
175
+ });
176
+ for (const line of diffOut.split(/\r?\n/u)) {
177
+ if (line.trim()) relSet.add(line.trim());
178
+ }
179
+ }
180
+ const statusOut = execFileSync("git", ["status", "--porcelain"], {
181
+ cwd: repoRoot,
182
+ encoding: "utf8",
183
+ stdio: ["ignore", "pipe", "ignore"],
184
+ });
185
+ for (const line of statusOut.split(/\r?\n/u)) {
186
+ if (line.length >= 4) {
187
+ const filePart = line.slice(3).trim().replace(/^"(.*)"$/u, "$1");
188
+ const arrowIdx = filePart.indexOf(" -> ");
189
+ const cleanRel = arrowIdx >= 0 ? filePart.slice(arrowIdx + 4) : filePart;
190
+ if (cleanRel) relSet.add(cleanRel);
191
+ }
192
+ }
193
+ return Array.from(relSet)
194
+ .filter((f) => /\.(md|txt)$/iu.test(f))
195
+ .map((f) => path.resolve(repoRoot, f))
196
+ .filter((abs) => fs.existsSync(abs));
197
+ } catch {
198
+ return [];
199
+ }
200
+ }
201
+
202
+ // 打印 CLI 帮助指南(默认分层聚焦作者日常命令,--help-all 展示全部 25 条命令)
203
+ function printHelp(showAll = false) {
204
+ const daily = [
205
+ `InkBone CLI ${CLI_VERSION} - local checks, living ledger, style profiler, exporter & MCP server for Chinese long-form fiction`,
206
+ "",
207
+ "Rule layers: universal (configs/ + auto zh-hant) -> genre pack -> project (novel.json found upward from the chapter:",
208
+ " inline projectRules, rulesFile, customGates, variant, whitelistLiterals / .inkbone-whitelist, and ledgerFile).",
209
+ "",
210
+ "Daily Writing, Revision & Publishing Commands:",
211
+ " inkbone genres List built-in multi-genre register packs",
212
+ " inkbone init [dir] [--genre <id>] [--title <name>] [--force]",
213
+ " Scaffold universal novel.json & ledger.json",
214
+ " inkbone import-ledger <file|dir>... [--merge <ledger.json>] [--out <ledger.json>] [--title <name>] [--auto-characters]",
215
+ " Scan existing chapters, mine candidate characters & merge ledger",
216
+ " inkbone packet --ledger <ledger.json> --chapter <n> [--prev <prev.md>] [--active-characters <a,b>] [--include-closed]",
217
+ " Compile spoiler-safe boundary packet for drafting",
218
+ " inkbone normalize <file|dir>... [--check] [--strip-bold] [--fix-emdash] [--project <dir|novel.json>] [--no-project]",
219
+ " Deterministic formatting & pause-punctuation cleaner (zero tokens)",
220
+ " inkbone audit <file.md> [--genre <id>] [--preset <id>] [--variant auto|zh-hans|zh-hant] [--format json|md] [--lang zh|en]",
221
+ " [--ledger <ledger.json> --chapter <n> --prev <prev.md> --skip-length] [--outline-chapter <outline.md>] [--strict]",
222
+ " Run boundary, deceased-guard, register, rhetoric, density & continuity audit",
223
+ " inkbone doctor <file|dir>... [--genre <id>] [--variant auto|zh-hans|zh-hant] [--chapters <40-45>] [--changed [ref]]",
224
+ " [--outline <dir|file>...] [--ledger <ledger.json>] [--lang zh|en] [--json]",
225
+ " Full or incremental multi-chapter checkup (preserves cross-chapter echo)",
226
+ " inkbone rewrite-prompt <file.md> [--genre <id>] [--variant auto|zh-hans|zh-hant] [--lang zh|en] [--skip-length]",
227
+ " Audit chapter and output a copy-ready targeted rewrite prompt",
228
+ " inkbone check-ledger <ledger.json> [--current <n>] [--overdue <20>]",
229
+ " Check ledger health (duplicates, reveal order, overdue foreshadowing)",
230
+ " inkbone settle --ledger <ledger.json> --patch <patch.json> [--dry-run]",
231
+ " Merge post-chapter settlement updates non-destructively into ledger",
232
+ " inkbone style-profile <file|dir>... [--out <style.json>] [--label <name>] [--lang zh|en] [--json]",
233
+ " Copyright-safe statistical style profile & suggested customGates",
234
+ " inkbone export <file|dir>... --platform <qidian|fanqie|qimao|jjwxc> [--out <dir>] [--merge-out <book.txt>] [--indent] [--check]",
235
+ " Clean Markdown & format chapters for web-fiction publishing platforms",
236
+ " inkbone mcp Start zero-dependency stdio MCP server (9 tools, 8 prompts, 11 resources)",
237
+ ];
238
+
239
+ const advanced = [
240
+ "",
241
+ "Review, Blind Evaluation & Rule Calibration Commands:",
242
+ " inkbone check-outline <file|dir>... Check Stage 1 beat outlines for placeholders & required dramatic facets",
243
+ " inkbone verify-review <chapter.md> <review.json> Verify verbatim quotes in logic & cold-reader reviews",
244
+ " inkbone review-save <chapter.md> <review.json> --kind <logic|reader> [--model <reviewer>] [--writer-model <writer>] [--dir <dir>] [--force]",
245
+ " Verify then archive a review with the chapter hash",
246
+ " inkbone review-stats <dir|file>... [--json] Count archived review items by category and show latest trends",
247
+ " inkbone eval-pack --a <dir|file>... --b <dir|file>... --out <dir> [--label-a <name>] [--label-b <name>] [--seed <n>]",
248
+ " Build a blind A/B reading packet (packet/ for readers, key.json for you)",
249
+ " inkbone eval-score --key <key.json> <ballot.json>... [--json]",
250
+ " Tally blind ballots: wins, ties, sign-test p, skim marks",
251
+ " inkbone profile <file.md> [--full] Measure 20+ linguistic fingerprint metrics",
252
+ " inkbone calibrate <dir|file>... [--out <ref.json>] [--label <name>]",
253
+ " Build a human reference range (statistics only)",
254
+ " inkbone rule-stats --human <dir|file>... --ai <dir|file>... [--genre <id>] [--project <dir>] [--json] [--all]",
255
+ " Per-rule hits per 10k chars in human vs AI text (taste vs AI marker)",
256
+ " inkbone mine --ai <dir|file>... --human <dir|file>... [--vocab <dir|file>...] [--top <n>]",
257
+ " Mine phrases overused in AI drafts vs human prose",
258
+ " inkbone detect <chapter.md> [--lines <start-end>] [--threshold <0.5>] [--no-cache]",
259
+ " Single-call cached Zhuque scan (final step only)",
260
+ " inkbone benchmark [--json] [--corpus <corpus.json>] [--manifest <manifest.json>]",
261
+ ];
262
+
263
+ const footer = showAll
264
+ ? ["", "Options: --version / -v Print InkBone version"]
265
+ : [
266
+ "",
267
+ "Run `inkbone --help-all` to list 12 additional review, blind-eval & calibration commands.",
268
+ "Run `inkbone --version` to print the installed version.",
269
+ ];
270
+
271
+ console.log([...daily, ...(showAll ? advanced : []), ...footer].join("\n"));
272
+ }
273
+
274
+ // 主命令行调度逻辑
275
+ async function main() {
276
+ const rawArgs = process.argv.slice(2);
277
+ if (rawArgs.includes("--version") || rawArgs.includes("-v")) {
278
+ console.log(`inkbone ${CLI_VERSION}`);
279
+ process.exit(0);
280
+ }
281
+ if (rawArgs.includes("--help-all")) {
282
+ printHelp(true);
283
+ process.exit(0);
284
+ }
285
+ if (rawArgs.length === 0 || rawArgs.includes("--help") || rawArgs.includes("-h")) {
286
+ printHelp(false);
287
+ process.exit(0);
288
+ }
289
+
290
+ const [command, ...rest] = rawArgs;
291
+ const { positional, flags } = parseFlags(rest);
292
+
293
+ if (command === "genres") {
294
+ console.log(JSON.stringify(listGenres(), null, 2));
295
+ return;
296
+ }
297
+
298
+ if (command === "init") {
299
+ const targetDir = positional[0] || ".";
300
+ const res = scaffoldProject(targetDir, {
301
+ genre: typeof flags.genre === "string" ? flags.genre : undefined,
302
+ title: typeof flags.title === "string" ? flags.title : undefined,
303
+ presetName: typeof flags.preset === "string" ? flags.preset : undefined,
304
+ force: Boolean(flags.force),
305
+ });
306
+ console.log(JSON.stringify(res, null, 2));
307
+ return;
308
+ }
309
+
310
+ if (command === "doctor") {
311
+ if (positional.length === 0) {
312
+ console.error("Error: Provide at least one <file.md> or <directory> for doctor.");
313
+ process.exit(2);
314
+ }
315
+ const project = resolveProject(flags, positional[0]);
316
+ const ledgerPath = flags.ledger
317
+ ? path.resolve(flags.ledger)
318
+ : !flags["no-ledger"] && project?.ledgerFile && fs.existsSync(project.ledgerFile)
319
+ ? project.ledgerFile
320
+ : null;
321
+ const ledger = ledgerPath
322
+ ? JSON.parse(fs.readFileSync(ledgerPath, "utf8"))
323
+ : null;
324
+ const changedFiles = flags.changed
325
+ ? resolveGitChangedFiles(path.resolve(positional[0]), flags.changed === true ? null : flags.changed)
326
+ : null;
327
+ const diagnosis = diagnoseProject(positional, {
328
+ genre:
329
+ typeof flags.genre === "string" ? flags.genre : project?.genre || undefined,
330
+ presetName:
331
+ typeof flags.preset === "string" ? flags.preset : project?.preset || undefined,
332
+ customGates: project?.customGates || null,
333
+ variant:
334
+ typeof flags.variant === "string" ? flags.variant : project?.variant || "auto",
335
+ chapterFilter: typeof flags.chapters === "string" ? flags.chapters : undefined,
336
+ changedFiles: changedFiles && changedFiles.length > 0 ? changedFiles : undefined,
337
+ projectRules: project ? project.rules : null,
338
+ genreSource:
339
+ typeof flags.genre !== "string" && project?.genre ? "project" : undefined,
340
+ outlinePaths: flags.outline || [],
341
+ ledger,
342
+ chapterNumber: flags.chapter ? Number(flags.chapter) : null,
343
+ skipLengthGate: Boolean(flags["skip-length"]),
344
+ });
345
+ if (flags.json) {
346
+ console.log(JSON.stringify(diagnosis, null, 2));
347
+ } else {
348
+ console.log(
349
+ formatDoctorMarkdown(diagnosis, {
350
+ lang: typeof flags.lang === "string" ? flags.lang : "zh",
351
+ })
352
+ );
353
+ }
354
+ process.exitCode = diagnosis.pass ? 0 : 1;
355
+ return;
356
+ }
357
+
358
+ if (command === "profile") {
359
+ const filePath = positional[0];
360
+ if (!filePath) {
361
+ console.error("Error: Missing <file.md> argument for profile.");
362
+ process.exit(2);
363
+ }
364
+ const text = fs.readFileSync(path.resolve(filePath), "utf8");
365
+ const result = profileText(text);
366
+ console.log(
367
+ JSON.stringify(
368
+ flags.full ? result : { file: path.basename(filePath), ...result.metrics },
369
+ null,
370
+ 2
371
+ )
372
+ );
373
+ return;
374
+ }
375
+
376
+ if (command === "audit") {
377
+ const filePath = positional[0];
378
+ if (!filePath) {
379
+ console.error("Error: Missing <file.md> argument for audit.");
380
+ process.exit(2);
381
+ }
382
+ const text = fs.readFileSync(path.resolve(filePath), "utf8");
383
+ const project = resolveProject(flags, filePath);
384
+ const ledgerPath = flags.ledger
385
+ ? path.resolve(flags.ledger)
386
+ : !flags["no-ledger"] && project?.ledgerFile && fs.existsSync(project.ledgerFile)
387
+ ? project.ledgerFile
388
+ : null;
389
+ const ledger = ledgerPath
390
+ ? JSON.parse(fs.readFileSync(ledgerPath, "utf8"))
391
+ : null;
392
+ const prevText = flags.prev
393
+ ? fs.readFileSync(path.resolve(flags.prev), "utf8")
394
+ : "";
395
+ let outlineText = "";
396
+ if (typeof flags["outline-chapter"] === "string") {
397
+ const outlinePath = path.resolve(flags["outline-chapter"]);
398
+ if (!fs.existsSync(outlinePath)) {
399
+ console.error(`Error: Outline file not found: ${outlinePath}`);
400
+ process.exit(2);
401
+ }
402
+ outlineText = fs.readFileSync(outlinePath, "utf8");
403
+ }
404
+ const report = auditChapterText(text, {
405
+ genre: typeof flags.genre === "string" ? flags.genre : project?.genre || null,
406
+ presetName:
407
+ typeof flags.preset === "string" ? flags.preset : project?.preset || null,
408
+ customGates: project?.customGates || null,
409
+ variant:
410
+ typeof flags.variant === "string" ? flags.variant : project?.variant || "auto",
411
+ projectRules: project ? project.rules : null,
412
+ ledger,
413
+ chapterNumber: flags.chapter ? Number(flags.chapter) : null,
414
+ previousChapterText: prevText,
415
+ outlineText,
416
+ skipLengthGate: Boolean(flags["skip-length"]),
417
+ strict: Boolean(flags.strict),
418
+ reference: flags.reference
419
+ ? JSON.parse(fs.readFileSync(path.resolve(flags.reference), "utf8"))
420
+ : null,
421
+ });
422
+
423
+ if (flags.format === "md") {
424
+ console.log(
425
+ formatAuditMarkdown(report, {
426
+ lang: typeof flags.lang === "string" ? flags.lang : "zh",
427
+ fileName: path.basename(filePath),
428
+ })
429
+ );
430
+ } else {
431
+ console.log(JSON.stringify(report, null, 2));
432
+ }
433
+ process.exitCode = report.pass ? 0 : 1;
434
+ return;
435
+ }
436
+
437
+ if (command === "packet") {
438
+ if (!flags.ledger || !flags.chapter) {
439
+ console.error("Error: --ledger and --chapter are required for packet.");
440
+ process.exit(2);
441
+ }
442
+ const ledger = JSON.parse(
443
+ fs.readFileSync(path.resolve(flags.ledger), "utf8")
444
+ );
445
+ const prevText = flags.prev
446
+ ? fs.readFileSync(path.resolve(flags.prev), "utf8")
447
+ : "";
448
+ const activeCharacters =
449
+ typeof flags["active-characters"] === "string"
450
+ ? flags["active-characters"]
451
+ .split(/[,;\s]+/u)
452
+ .map((s) => s.trim())
453
+ .filter(Boolean)
454
+ : undefined;
455
+ const packet = compileBoundaryPacket(ledger, Number(flags.chapter), prevText, {
456
+ activeCharacters,
457
+ includeClosedForeshadowing: Boolean(flags["include-closed"]),
458
+ });
459
+ console.log(JSON.stringify(packet, null, 2));
460
+ return;
461
+ }
462
+
463
+ if (command === "verify-review") {
464
+ const [chapterPath, reviewPath] = positional;
465
+ if (!chapterPath || !reviewPath) {
466
+ console.error("Error: Provide both <chapter.md> and <review.json>.");
467
+ process.exit(2);
468
+ }
469
+ const chapterText = fs.readFileSync(path.resolve(chapterPath), "utf8");
470
+ const reviewJson = JSON.parse(
471
+ fs.readFileSync(path.resolve(reviewPath), "utf8")
472
+ );
473
+ const validation = validateEvidenceReview(chapterText, reviewJson);
474
+ console.log(JSON.stringify(validation, null, 2));
475
+ process.exitCode = validation.valid ? 0 : 1;
476
+ return;
477
+ }
478
+
479
+ if (command === "calibrate") {
480
+ const files = collectTextFiles(positional);
481
+ if (files.length === 0) {
482
+ console.error("Error: No .md/.txt files found for calibrate.");
483
+ process.exit(2);
484
+ }
485
+ const texts = files.map((f) => fs.readFileSync(f, "utf8"));
486
+ const reference = calibrateReference(texts, { label: flags.label || "" });
487
+ const output = JSON.stringify(reference, null, 2);
488
+ if (flags.out) {
489
+ fs.writeFileSync(path.resolve(flags.out), output + "\n");
490
+ console.error(`Wrote ${reference.sampleCount} samples to ${flags.out} (reliable: ${reference.reliable})`);
491
+ } else {
492
+ console.log(output);
493
+ }
494
+ return;
495
+ }
496
+
497
+ if (command === "review-save") {
498
+ const [chapterPath, reviewPath] = positional;
499
+ if (!chapterPath || !reviewPath) {
500
+ console.error("Error: Provide both <chapter.md> and <review.json>.");
501
+ process.exit(2);
502
+ }
503
+ const payload = JSON.parse(fs.readFileSync(path.resolve(reviewPath), "utf8"));
504
+ const result = saveReview(path.resolve(chapterPath), payload, {
505
+ kind: typeof flags.kind === "string" ? flags.kind : "review",
506
+ dir: typeof flags.dir === "string" ? path.resolve(flags.dir) : undefined,
507
+ force: Boolean(flags.force),
508
+ reviewerModel: typeof flags.model === "string" ? flags.model : null,
509
+ writerModel: typeof flags["writer-model"] === "string" ? flags["writer-model"] : null,
510
+ });
511
+ console.log(JSON.stringify(result, null, 2));
512
+ process.exitCode = result.saved ? 0 : 1;
513
+ return;
514
+ }
515
+
516
+ if (command === "review-stats") {
517
+ const inputs = positional.length > 0 ? positional : ["."];
518
+ const files = [];
519
+ const walk = (p) => {
520
+ const abs = path.resolve(p);
521
+ if (!fs.existsSync(abs)) return;
522
+ if (fs.statSync(abs).isDirectory()) {
523
+ for (const entry of fs.readdirSync(abs)) walk(path.join(abs, entry));
524
+ } else if (abs.endsWith(".json")) {
525
+ files.push(abs);
526
+ }
527
+ };
528
+ inputs.forEach(walk);
529
+ const stats = summarizeReviews(files);
530
+ if (flags.json) {
531
+ console.log(JSON.stringify(stats, null, 2));
532
+ } else {
533
+ for (const r of stats.records) {
534
+ const models = `reviewer=${r.reviewerModel || "?"} writer=${r.writerModel || "?"}`;
535
+ console.log(`${r.savedAt} ${r.chapter} ${r.kind} ${models} ${JSON.stringify(r.counts)}`);
536
+ }
537
+ for (const t of stats.trends) {
538
+ const notes = [t.textChanged ? "" : "text unchanged", t.reviewerChanged ? "reviewer model changed" : ""].filter(Boolean).join(", ");
539
+ console.log(`trend ${t.chapter} ${t.kind}: ${JSON.stringify(t.delta)}${notes ? ` (${notes})` : ""}`);
540
+ }
541
+ }
542
+ return;
543
+ }
544
+
545
+ if (command === "eval-pack") {
546
+ const aFiles = collectTextFiles([].concat(flags.a || []));
547
+ const bFiles = collectTextFiles([].concat(flags.b || []));
548
+ if (aFiles.length === 0 || bFiles.length === 0 || typeof flags.out !== "string") {
549
+ console.error("Error: eval-pack needs --a, --b and --out.");
550
+ process.exit(2);
551
+ }
552
+ const pack = buildBlindPack(aFiles, bFiles, {
553
+ seed: flags.seed ? Number(flags.seed) : undefined,
554
+ labelA: typeof flags["label-a"] === "string" ? flags["label-a"] : "A",
555
+ labelB: typeof flags["label-b"] === "string" ? flags["label-b"] : "B",
556
+ modelA: typeof flags["model-a"] === "string" ? flags["model-a"] : null,
557
+ modelB: typeof flags["model-b"] === "string" ? flags["model-b"] : null,
558
+ });
559
+ if (pack.pairs.length === 0) {
560
+ console.error("Error: No chapter pairs matched between --a and --b (match by the first number in file names).");
561
+ process.exit(2);
562
+ }
563
+ const instructionsPath = path.resolve(rootDir, "resources/eval/blind-read-instructions.md");
564
+ const written = writeBlindPack(pack, path.resolve(flags.out), {
565
+ instructions: fs.existsSync(instructionsPath) ? fs.readFileSync(instructionsPath, "utf8") : "",
566
+ });
567
+ console.log(JSON.stringify({ ...written, seed: pack.seed, unpaired: pack.unpaired }, null, 2));
568
+ return;
569
+ }
570
+
571
+ if (command === "eval-score") {
572
+ if (typeof flags.key !== "string" || positional.length === 0) {
573
+ console.error("Error: eval-score needs --key <key.json> and at least one ballot.json.");
574
+ process.exit(2);
575
+ }
576
+ const key = JSON.parse(fs.readFileSync(path.resolve(flags.key), "utf8"));
577
+ const ballots = positional.map((f) => JSON.parse(fs.readFileSync(path.resolve(f), "utf8")));
578
+ const score = scoreBallots(key, ballots, { texts: loadPairTexts(key) });
579
+ console.log(JSON.stringify(score, null, 2));
580
+ return;
581
+ }
582
+
583
+ if (command === "rule-stats") {
584
+ const humanFiles = collectTextFiles([].concat(flags.human || []));
585
+ const aiFiles = collectTextFiles([].concat(flags.ai || []));
586
+ if (humanFiles.length === 0 || aiFiles.length === 0) {
587
+ console.error("Error: rule-stats needs both --human and --ai inputs.");
588
+ process.exit(2);
589
+ }
590
+ const project = resolveProject(flags, aiFiles[0]);
591
+ const read = (f) => fs.readFileSync(f, "utf8");
592
+ const stats = computeRuleStats(humanFiles.map(read), aiFiles.map(read), {
593
+ genre: typeof flags.genre === "string" ? flags.genre : project?.genre || null,
594
+ projectRules: project ? project.rules : null,
595
+ });
596
+ if (flags.json) {
597
+ console.log(JSON.stringify(stats, null, 2));
598
+ } else {
599
+ console.log(formatRuleStatsMarkdown(stats, { all: Boolean(flags.all) }));
600
+ }
601
+ return;
602
+ }
603
+
604
+ if (command === "mine") {
605
+ const aiFiles = collectTextFiles([].concat(flags.ai || []));
606
+ const humanFiles = collectTextFiles([].concat(flags.human || []));
607
+ if (aiFiles.length === 0 || humanFiles.length === 0) {
608
+ console.error("Error: mine needs both --ai and --human inputs.");
609
+ process.exit(2);
610
+ }
611
+ const read = (f) => fs.readFileSync(f, "utf8");
612
+ const vocabFiles = collectTextFiles([].concat(flags.vocab || []));
613
+ const result = mineOverusedPhrases(aiFiles.map(read), humanFiles.map(read), {
614
+ vocabTexts: vocabFiles.map(read),
615
+ top: flags.top ? Number(flags.top) : undefined,
616
+ minRatio: flags["min-ratio"] ? Number(flags["min-ratio"]) : undefined,
617
+ });
618
+ console.log(JSON.stringify(result, null, 2));
619
+ return;
620
+ }
621
+
622
+ if (command === "detect") {
623
+ const filePath = positional[0];
624
+ if (!filePath) {
625
+ console.error("Error: Missing <file.md> argument for detect.");
626
+ process.exit(2);
627
+ }
628
+ const absPath = path.resolve(filePath);
629
+ const text = fs.readFileSync(absPath, "utf8");
630
+ let lineRange = null;
631
+ if (typeof flags.lines === "string" && flags.lines.includes("-")) {
632
+ const [s, e] = flags.lines.split("-").map((n) => Number(n.trim()));
633
+ if (Number.isFinite(s) && Number.isFinite(e) && s >= 1 && e >= s) {
634
+ lineRange = [s, e];
635
+ }
636
+ }
637
+ const report = await detectWithZhuque(text, {
638
+ startDir: path.dirname(absPath),
639
+ lineRange,
640
+ noCache: Boolean(flags["no-cache"]),
641
+ threshold: flags.threshold ? Number(flags.threshold) : 0.5,
642
+ });
643
+ const output = flags.full
644
+ ? report
645
+ : {
646
+ file: path.basename(absPath),
647
+ pass: report.pass,
648
+ cached: report.cached,
649
+ lineSpan: report.lineSpan,
650
+ inputChars: report.inputChars,
651
+ tokenUsage: report.tokenUsage,
652
+ humanPct: report.humanPct,
653
+ suspectedPct: report.suspectedPct,
654
+ aiPct: report.aiPct,
655
+ softmaxConfidence: report.softmaxConfidence,
656
+ segments: report.segments,
657
+ flaggedWindowCount: report.flaggedWindowCount,
658
+ flaggedWindows: report.flaggedWindows,
659
+ fineWindows: report.fineWindows.map((w) => ({
660
+ order: w.order,
661
+ lines: `${w.startLine}-${w.endLine}`,
662
+ aigc: w.aigc,
663
+ preview: w.preview,
664
+ })),
665
+ };
666
+ console.log(JSON.stringify(output, null, 2));
667
+ process.exit(report.pass ? 0 : 1);
668
+ }
669
+
670
+ if (command === "benchmark") {
671
+ const extraFiles = discoverBenchmarkEntries(
672
+ typeof flags.manifest === "string" ? flags.manifest : null
673
+ );
674
+ const rows = runCorpusBenchmark({ extraFiles, corpusPath: flags.corpus || null });
675
+ if (flags.json) {
676
+ console.log(JSON.stringify(rows, null, 2));
677
+ } else {
678
+ console.log(formatBenchmarkMarkdown(rows));
679
+ }
680
+ return;
681
+ }
682
+
683
+ if (command === "import-ledger") {
684
+ if (positional.length === 0) {
685
+ console.error(
686
+ "Error: Provide at least one <file.md> or <directory> for import-ledger."
687
+ );
688
+ process.exit(2);
689
+ }
690
+ const mergeFlag =
691
+ typeof flags.merge === "string"
692
+ ? flags.merge
693
+ : typeof flags.ledger === "string"
694
+ ? flags.ledger
695
+ : null;
696
+ let existingLedger = null;
697
+ if (mergeFlag) {
698
+ const mergePath = path.resolve(mergeFlag);
699
+ if (!fs.existsSync(mergePath)) {
700
+ console.error(`Error: Merge ledger file not found: ${mergePath}`);
701
+ process.exit(2);
702
+ }
703
+ existingLedger = JSON.parse(fs.readFileSync(mergePath, "utf8"));
704
+ }
705
+ const imported = importLedgerFromChapters(positional, {
706
+ existingLedger,
707
+ projectTitle: typeof flags.title === "string" ? flags.title : undefined,
708
+ autoPopulateCharacters: Boolean(flags["auto-characters"]),
709
+ });
710
+ if (typeof flags.out === "string") {
711
+ const outPath = path.resolve(flags.out);
712
+ fs.writeFileSync(outPath, JSON.stringify(imported.ledger, null, 2) + "\n");
713
+ console.log(
714
+ JSON.stringify({ out: outPath, stats: imported.stats }, null, 2)
715
+ );
716
+ } else {
717
+ console.log(JSON.stringify(imported, null, 2));
718
+ }
719
+ return;
720
+ }
721
+
722
+ if (command === "normalize") {
723
+ if (positional.length === 0) {
724
+ console.error(
725
+ "Error: Provide at least one <file.md> or <directory> for normalize."
726
+ );
727
+ process.exit(2);
728
+ }
729
+ const project = resolveProject(flags, positional[0]);
730
+ const report = normalizeFiles(positional, {
731
+ check: Boolean(flags.check),
732
+ stripMarkdownEmphasis: Boolean(flags["strip-bold"]),
733
+ fixNarrationEmDash: Boolean(flags["fix-emdash"]),
734
+ whitelistLiterals: project?.rules?.whitelistLiterals || [],
735
+ });
736
+ console.log(JSON.stringify(report, null, 2));
737
+ process.exitCode = report.pass ? 0 : 1;
738
+ return;
739
+ }
740
+
741
+ if (command === "check-outline") {
742
+ if (positional.length === 0) {
743
+ console.error(
744
+ "Error: Provide at least one <outline.md> or <directory> for check-outline."
745
+ );
746
+ process.exit(2);
747
+ }
748
+ const files = collectTextFiles(positional);
749
+ if (files.length === 0) {
750
+ console.error("Error: No .md or .txt outline files found.");
751
+ process.exit(2);
752
+ }
753
+ const results = files.map((absPath) => {
754
+ const text = fs.readFileSync(absPath, "utf8");
755
+ const check = checkOutlineContract(text);
756
+ return {
757
+ file: path.basename(absPath),
758
+ path: absPath,
759
+ ...check,
760
+ };
761
+ });
762
+ const allPass = results.every((r) => r.pass);
763
+ console.log(
764
+ JSON.stringify(
765
+ {
766
+ pass: allPass,
767
+ filesScanned: results.length,
768
+ failingCount: results.filter((r) => !r.pass).length,
769
+ files: results,
770
+ },
771
+ null,
772
+ 2
773
+ )
774
+ );
775
+ process.exitCode = allPass ? 0 : 1;
776
+ return;
777
+ }
778
+
779
+ if (command === "check-ledger") {
780
+ const ledgerArg = positional[0] || flags.ledger;
781
+ if (!ledgerArg || typeof ledgerArg !== "string") {
782
+ console.error("Error: Provide <ledger.json> path for check-ledger.");
783
+ process.exit(2);
784
+ }
785
+ const ledgerPath = path.resolve(ledgerArg);
786
+ if (!fs.existsSync(ledgerPath)) {
787
+ console.error(`Error: Ledger file not found: ${ledgerPath}`);
788
+ process.exit(2);
789
+ }
790
+ const ledger = JSON.parse(fs.readFileSync(ledgerPath, "utf8"));
791
+ const report = validateLedger(ledger, {
792
+ currentChapter: flags.current ? Number(flags.current) : undefined,
793
+ overdueThreshold: flags.overdue ? Number(flags.overdue) : undefined,
794
+ });
795
+ console.log(JSON.stringify(report, null, 2));
796
+ process.exitCode = report.pass ? 0 : 1;
797
+ return;
798
+ }
799
+
800
+ if (command === "settle") {
801
+ const ledgerArg = typeof flags.ledger === "string" ? flags.ledger : positional[0];
802
+ const patchArg = typeof flags.patch === "string" ? flags.patch : positional[1];
803
+ if (!ledgerArg || !patchArg) {
804
+ console.error("Error: Provide --ledger <ledger.json> and --patch <settlement.json> for settle.");
805
+ process.exit(2);
806
+ }
807
+ const ledgerPath = path.resolve(ledgerArg);
808
+ const patchPath = path.resolve(patchArg);
809
+ if (!fs.existsSync(ledgerPath)) {
810
+ console.error(`Error: Ledger file not found: ${ledgerPath}`);
811
+ process.exit(2);
812
+ }
813
+ if (!fs.existsSync(patchPath)) {
814
+ console.error(`Error: Settlement patch file not found: ${patchPath}`);
815
+ process.exit(2);
816
+ }
817
+ const ledger = JSON.parse(fs.readFileSync(ledgerPath, "utf8"));
818
+ const patch = JSON.parse(fs.readFileSync(patchPath, "utf8"));
819
+ const settled = applyChapterSettlement(ledger, patch);
820
+ const dryRun = Boolean(flags["dry-run"]);
821
+ if (!dryRun) {
822
+ fs.writeFileSync(ledgerPath, JSON.stringify(settled.ledger, null, 2) + "\n");
823
+ }
824
+ const health = validateLedger(settled.ledger, {
825
+ currentChapter: settled.diff.chapterNumber,
826
+ });
827
+ console.log(
828
+ JSON.stringify(
829
+ {
830
+ ledgerPath,
831
+ wroteFile: !dryRun,
832
+ diff: settled.diff,
833
+ health,
834
+ },
835
+ null,
836
+ 2
837
+ )
838
+ );
839
+ process.exitCode = health.pass ? 0 : 1;
840
+ return;
841
+ }
842
+
843
+ if (command === "rewrite-prompt") {
844
+ const filePath = positional[0];
845
+ if (!filePath) {
846
+ console.error("Error: Missing <file.md> argument for rewrite-prompt.");
847
+ process.exit(2);
848
+ }
849
+ const text = fs.readFileSync(path.resolve(filePath), "utf8");
850
+ const project = resolveProject(flags, filePath);
851
+ const ledgerPath = flags.ledger
852
+ ? path.resolve(flags.ledger)
853
+ : !flags["no-ledger"] && project?.ledgerFile && fs.existsSync(project.ledgerFile)
854
+ ? project.ledgerFile
855
+ : null;
856
+ const ledger = ledgerPath ? JSON.parse(fs.readFileSync(ledgerPath, "utf8")) : null;
857
+ const report = auditChapterText(text, {
858
+ genre: typeof flags.genre === "string" ? flags.genre : project?.genre || null,
859
+ presetName: typeof flags.preset === "string" ? flags.preset : project?.preset || null,
860
+ customGates: project?.customGates || null,
861
+ variant: typeof flags.variant === "string" ? flags.variant : project?.variant || "auto",
862
+ projectRules: project ? project.rules : null,
863
+ ledger,
864
+ chapterNumber: flags.chapter ? Number(flags.chapter) : null,
865
+ skipLengthGate: Boolean(flags["skip-length"]),
866
+ strict: Boolean(flags.strict),
867
+ });
868
+ const built = buildTargetedRewritePrompt(text, report, {
869
+ lang: typeof flags.lang === "string" ? flags.lang : "zh",
870
+ });
871
+ if (flags.json) {
872
+ console.log(JSON.stringify(built, null, 2));
873
+ } else {
874
+ console.log(built.prompt);
875
+ }
876
+ return;
877
+ }
878
+
879
+ if (command === "style-profile") {
880
+ const files = collectTextFiles(positional);
881
+ if (files.length === 0) {
882
+ console.error("Error: Provide at least one <file.md> or <directory> for style-profile.");
883
+ process.exit(2);
884
+ }
885
+ const texts = files.map((f) => fs.readFileSync(f, "utf8"));
886
+ const profile = analyzeStyleProfile(texts, {
887
+ label: typeof flags.label === "string" ? flags.label : "",
888
+ });
889
+ if (typeof flags.out === "string") {
890
+ fs.writeFileSync(path.resolve(flags.out), JSON.stringify(profile, null, 2) + "\n");
891
+ console.error(`Wrote style profile (${profile.sampleCount} samples) to ${flags.out}`);
892
+ }
893
+ if (flags.json) {
894
+ console.log(JSON.stringify(profile, null, 2));
895
+ } else {
896
+ console.log(
897
+ formatStyleProfileMarkdown(profile, {
898
+ lang: typeof flags.lang === "string" ? flags.lang : "zh",
899
+ })
900
+ );
901
+ }
902
+ return;
903
+ }
904
+
905
+ if (command === "export") {
906
+ if (flags.platforms) {
907
+ console.log(JSON.stringify(listPlatforms(), null, 2));
908
+ return;
909
+ }
910
+ if (positional.length === 0) {
911
+ console.error("Error: Provide at least one <file.md> or <directory> for export.");
912
+ process.exit(2);
913
+ }
914
+ const project = resolveProject(flags, positional[0]);
915
+ const indentOpt = flags.indent ? true : flags["no-indent"] ? false : undefined;
916
+ const report = exportChapters(positional, {
917
+ platform: typeof flags.platform === "string" ? flags.platform : "qidian",
918
+ outDir: typeof flags.out === "string" ? flags.out : undefined,
919
+ mergeOut: typeof flags["merge-out"] === "string" ? flags["merge-out"] : undefined,
920
+ indent: indentOpt,
921
+ check: Boolean(flags.check),
922
+ whitelistLiterals: project?.rules?.whitelistLiterals || [],
923
+ });
924
+ console.log(JSON.stringify(report, null, 2));
925
+ return;
926
+ }
927
+
928
+ if (command === "mcp") {
929
+ startMcpServer();
930
+ return;
931
+ }
932
+
933
+ console.error(`Unknown command: "${command}"`);
934
+ printHelp();
935
+ process.exit(2);
936
+ }
937
+
938
+ main().catch((err) => {
939
+ console.error(`Error: ${err.message}`);
940
+ process.exit(1);
941
+ });