@cloud411716/fancy-webnovel 4.28.0 → 4.29.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.
@@ -0,0 +1,602 @@
1
+ /**
2
+ * 世界母体与 facet 选择状态。
3
+ *
4
+ * 这一层只负责“用户选了什么、世界母体是什么、怎么把交集约束写进提示词”,
5
+ * 不负责素材生成、不碰 material 表。
6
+ *
7
+ * 关键语义:
8
+ * - 同一层多选 = AND(交集),不是 OR(并集);
9
+ * - 不同层之间也是 AND;
10
+ * - “无(不限)”表示这一层不限制;
11
+ * - 复合题材(都市异能 / 悬疑脑洞)会展开成原子题材,
12
+ * 例如 都市异能 → 都市 + 异能,两者都必须满足。
13
+ */
14
+
15
+ import { createHash } from 'node:crypto';
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+
20
+ import { atomicWriteJson } from '#workspace';
21
+ import { MATERIAL_FACET_CANDIDATES } from './facets.js';
22
+ import { KIND_GROUPS, KIND_LABELS, MATERIAL_KINDS } from './kinds.js';
23
+
24
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
25
+ const WORLD_PROMPT_FILE = path.join(__dirname, 'prompts', 'world-mother.md');
26
+
27
+ export const FLOW_VERSION = 1;
28
+ export const FLOW_RELATIVE_PATH = path.join('.fancy', 'material', 'flow.json');
29
+ export const EMPTY_FACET_LABEL = '无(不限)';
30
+ export const DEFAULT_TARGET_PER_KIND = 20;
31
+ export const DEFAULT_SCOPE_TITLES = ['命名', '世界与势力', '能力', '剧情与脑洞'];
32
+
33
+ /**
34
+ * 弹框顺序。只选 6 层,避免把用户拖进十几个框。
35
+ * 每一层都是多选,第一项统一是“无(不限)”。
36
+ */
37
+ export const FACET_STEPS = [
38
+ { id: 'genres', label: '题材 / 世界类型', header: '题材', limit: 18 },
39
+ { id: 'settings', label: '时代 / 场景 / 背景', header: '场景', limit: 15 },
40
+ { id: 'moods', label: '情绪 / 调性', header: '情绪', limit: 14 },
41
+ { id: 'tropes', label: '情节 / 流派 / 梗', header: '情节', limit: 16 },
42
+ { id: 'roles', label: '身份 / 职业', header: '身份', limit: 14 },
43
+ { id: 'relations', label: '关系 / 功能', header: '关系', limit: 14 },
44
+ ];
45
+
46
+ /**
47
+ * 平台复合题材 → 原子题材。
48
+ * 用户勾选复合题材时,生成结果必须同时满足展开后的全部原子题材。
49
+ */
50
+ export const GENRE_ALIASES = {
51
+ 西方奇幻: ['西幻', '奇幻'],
52
+ 东方仙侠: ['仙侠'],
53
+ 科幻末世: ['科幻', '末世'],
54
+ 都市日常: ['都市', '日常'],
55
+ 都市修真: ['都市', '修真'],
56
+ 都市高武: ['都市', '高武'],
57
+ 历史古代: ['历史', '古代'],
58
+ 战神赘婿: ['都市', '战神', '赘婿'],
59
+ 都市种田: ['都市', '种田'],
60
+ 传统玄幻: ['玄幻'],
61
+ 历史脑洞: ['历史', '脑洞'],
62
+ 悬疑脑洞: ['悬疑', '脑洞'],
63
+ 都市脑洞: ['都市', '脑洞'],
64
+ 玄幻脑洞: ['玄幻', '脑洞'],
65
+ 悬疑灵异: ['悬疑', '灵异'],
66
+ 抗战谍战: ['抗战', '谍战'],
67
+ 游戏体育: ['游戏', '体育'],
68
+ 动漫衍生: ['动漫', '衍生'],
69
+ 男频衍生: ['男频', '衍生'],
70
+ 古风世情: ['古风', '世情'],
71
+ 女频衍生: ['女频', '衍生'],
72
+ 玄幻言情: ['玄幻', '言情'],
73
+ 种田: ['种田'],
74
+ 年代: ['年代'],
75
+ 现言脑洞: ['现言', '脑洞'],
76
+ 宫斗宅斗: ['宫斗', '宅斗'],
77
+ 古言脑洞: ['古言', '脑洞'],
78
+ 快穿: ['快穿'],
79
+ 青春甜宠: ['青春', '甜宠'],
80
+ 星光璀璨: ['娱乐圈', '星光'],
81
+ 女频悬疑: ['女频', '悬疑'],
82
+ 职场婚恋: ['职场', '婚恋'],
83
+ 豪门总裁: ['豪门', '总裁'],
84
+ 民国言情: ['民国', '言情'],
85
+ 都市异能: ['都市', '异能'],
86
+ };
87
+
88
+ function asArray(value) {
89
+ return Array.isArray(value) ? value : [];
90
+ }
91
+
92
+ function clean(value) {
93
+ return String(value == null ? '' : value).trim();
94
+ }
95
+
96
+ function unique(values) {
97
+ const seen = new Set();
98
+ const out = [];
99
+ for (const value of values) {
100
+ const text = clean(value);
101
+ if (!text || seen.has(text)) continue;
102
+ seen.add(text);
103
+ out.push(text);
104
+ }
105
+ return out;
106
+ }
107
+
108
+ /** 复合题材展开成原子题材;普通题材原样返回。 */
109
+ export function expandGenre(value) {
110
+ const raw = clean(value);
111
+ if (!raw) return [];
112
+ return unique(GENRE_ALIASES[raw] || [raw]);
113
+ }
114
+
115
+ export function expandGenres(values) {
116
+ return unique(asArray(values).flatMap(expandGenre));
117
+ }
118
+
119
+ export function normalizeFacetSelection(values) {
120
+ const list = unique(asArray(values).map(clean).filter(Boolean));
121
+ if (!list.length) return [];
122
+ // “无”与其它选项同时出现时,按用户意图清空这一层:无 = 不限制。
123
+ if (list.some((item) => item === EMPTY_FACET_LABEL || item === '无' || item === '不限')) {
124
+ return [];
125
+ }
126
+ return list;
127
+ }
128
+
129
+ export function facetStep(field) {
130
+ return FACET_STEPS.find((step) => step.id === field) || null;
131
+ }
132
+
133
+ function recommendationLabels(field, suggestion) {
134
+ if (field !== 'genres' || !suggestion) return [];
135
+ const raw = clean(suggestion.genre);
136
+ if (!raw) return [];
137
+ return unique([raw, ...expandGenre(raw)]);
138
+ }
139
+
140
+ /**
141
+ * 为一层 facet 生成 DSH 合法的问题对象。
142
+ * 选项第一项固定是“无(不限)”。
143
+ */
144
+ export function facetQuestion(step, { suggestion = null, selected = [] } = {}) {
145
+ if (!step || !step.id) throw new Error('facetQuestion 缺少 step');
146
+ const recommended = recommendationLabels(step.id, suggestion);
147
+ const candidates = unique([
148
+ ...recommended,
149
+ ...asArray(MATERIAL_FACET_CANDIDATES[step.id]),
150
+ ...asArray(selected),
151
+ ]);
152
+ const limit = Math.max(1, Number(step.limit) || 18);
153
+ const options = [{
154
+ label: EMPTY_FACET_LABEL,
155
+ description: '这一层不限制;选中会清空同层的其它选项',
156
+ }];
157
+ const used = new Set([EMPTY_FACET_LABEL]);
158
+ for (const value of candidates) {
159
+ if (used.has(value)) continue;
160
+ used.add(value);
161
+ const isRecommended = recommended.includes(value);
162
+ options.push({
163
+ label: value,
164
+ description: isRecommended
165
+ ? '推荐:来自 _novel_topic_suggestion.json(可改)'
166
+ : (step.id === 'genres' ? '题材约束;复合题材会展开成原子题材' : '选中后必须同时满足'),
167
+ });
168
+ if (options.length >= limit + 1) break;
169
+ }
170
+ const hint = step.id === 'genres'
171
+ ? '交集规则:例如同时选 都市 + 异能 + 脑洞,生成素材必须同时满足这三种,不是任选其一。复合题材会展开成原子题材。'
172
+ : '交集规则:同一层多选是 AND,不是 OR;选中的每一项都必须同时成立。';
173
+ return {
174
+ id: 'material-facet-' + step.id,
175
+ header: '素材 · ' + step.header,
176
+ question: `请选择${step.label}(可多选;第一项「无」表示不限)`,
177
+ detail: hint,
178
+ options,
179
+ multiSelect: true,
180
+ };
181
+ }
182
+
183
+ /** 风格选择:无 = 自动,不使用 = 关闭,具体 key 可多选。 */
184
+ export function styleQuestion(styles = []) {
185
+ const available = asArray(styles)
186
+ .filter((style) => style && style.style_key)
187
+ .filter((style) => style.style_type === 'naming' || style.style_type === 'structure')
188
+ .slice(0, 12);
189
+ const options = [
190
+ { label: '无(自动选择)', description: '按题材自动选 2–3 个兼容风格' },
191
+ { label: '不使用账号风格', description: '关闭账号风格,按通用规则生成' },
192
+ ...available.map((style) => ({
193
+ label: `${style.style_key}(${style.style_name})`,
194
+ description: String(style.dna || '').slice(0, 100),
195
+ })),
196
+ ];
197
+ return {
198
+ id: 'material-style',
199
+ header: '素材 · 风格',
200
+ question: '请选择对标风格(可多选;第一项「无」表示自动)',
201
+ detail: '同一层多选=同时使用这些风格核心;无=按题材自动选;不使用账号风格=关闭风格锁定。',
202
+ options,
203
+ multiSelect: true,
204
+ };
205
+ }
206
+
207
+ function groupKindsByTitle(title) {
208
+ const group = KIND_GROUPS.find((item) => item.title === title);
209
+ return group ? group.kinds : [];
210
+ }
211
+
212
+ export function recommendedScopeKinds() {
213
+ return unique(DEFAULT_SCOPE_TITLES.flatMap(groupKindsByTitle));
214
+ }
215
+
216
+ export function allScopeKinds() {
217
+ return [...MATERIAL_KINDS];
218
+ }
219
+
220
+ function groupOption(title) {
221
+ const kinds = groupKindsByTitle(title);
222
+ return {
223
+ label: `${title}(${kinds.length})`,
224
+ description: kinds.map((kind) => KIND_LABELS[kind] || kind).slice(0, 8).join('、'),
225
+ };
226
+ }
227
+
228
+ export function scopeQuestion({ currentKinds = [] } = {}) {
229
+ const options = [];
230
+ if (Array.isArray(currentKinds) && currentKinds.length) {
231
+ options.push({
232
+ label: '沿用上次范围(推荐)',
233
+ description: `上次 ${currentKinds.length} 个 kind:` + currentKinds.slice(0, 8).map((kind) => KIND_LABELS[kind] || kind).join('、'),
234
+ });
235
+ }
236
+ options.push({
237
+ label: '推荐:命名 + 世界 + 能力 + 剧情',
238
+ description: `世界母体最相关的 ${recommendedScopeKinds().length} 个 kind`,
239
+ });
240
+ options.push({
241
+ label: `全部 ${MATERIAL_KINDS.length} 个 kind`,
242
+ description: '覆盖全部素材类型,耗时最长',
243
+ });
244
+ for (const group of KIND_GROUPS) options.push(groupOption(group.title));
245
+ return {
246
+ id: 'material-scope',
247
+ header: '素材 · 范围',
248
+ question: '本次生成哪些范围?(可多选;推荐先跑世界核心)',
249
+ detail: '只决定本次队列,不删除已有素材;之后可用 /fancy-material continue 追加。',
250
+ options,
251
+ multiSelect: true,
252
+ };
253
+ }
254
+
255
+ export function countQuestion() {
256
+ return {
257
+ id: 'material-count',
258
+ header: '素材 · 数量',
259
+ question: '每个 kind 本次追加多少条?',
260
+ detail: '只追加,不覆盖已有素材。默认 20 条;首次建议 20 条先看质量。',
261
+ options: [
262
+ { label: '20 条(推荐)', description: '质量与数量平衡,默认值' },
263
+ { label: '10 条', description: '先小批试跑' },
264
+ { label: '30 条', description: '需要更多备选' },
265
+ { label: '50 条', description: '批量生成,耗时较长' },
266
+ ],
267
+ };
268
+ }
269
+
270
+ export function parseCountAnswer(value) {
271
+ const match = String(value || '').match(/\d+/);
272
+ const n = match ? Number(match[0]) : DEFAULT_TARGET_PER_KIND;
273
+ return Math.max(1, Math.min(200, Number.isFinite(n) ? n : DEFAULT_TARGET_PER_KIND));
274
+ }
275
+
276
+ export function resolveScopeKinds(labels, { currentKinds = [] } = {}) {
277
+ const selected = unique(asArray(labels).map(clean).filter(Boolean));
278
+ const current = unique(asArray(currentKinds));
279
+ if (!selected.length) return current.length ? current : recommendedScopeKinds();
280
+ if (selected.some((label) => label.includes('沿用上次范围'))) {
281
+ return current.length ? current : recommendedScopeKinds();
282
+ }
283
+ if (selected.some((label) => label.includes(`全部 ${MATERIAL_KINDS.length}`) || label === `全部 ${MATERIAL_KINDS.length} 个 kind`)) {
284
+ return allScopeKinds();
285
+ }
286
+ const kinds = [];
287
+ if (selected.some((label) => label.includes('推荐:命名'))) {
288
+ kinds.push(...recommendedScopeKinds());
289
+ }
290
+ for (const group of KIND_GROUPS) {
291
+ if (selected.some((label) => label.startsWith(group.title + '(') || label === group.title)) {
292
+ kinds.push(...group.kinds);
293
+ }
294
+ }
295
+ return kinds.length ? unique(kinds) : (current.length ? current : recommendedScopeKinds());
296
+ }
297
+
298
+ export function worldCandidateQuestion(candidates, { allowReroll = true } = {}) {
299
+ const options = [];
300
+ const seen = new Set();
301
+ for (const candidate of asArray(candidates)) {
302
+ let label = clean(candidate.title) || '未命名世界';
303
+ if (seen.has(label)) label = `${label}(${seen.size + 1})`;
304
+ seen.add(label);
305
+ const bits = [];
306
+ if (candidate.core_conflict) bits.push('核心矛盾:' + candidate.core_conflict);
307
+ if (candidate.suggestion_fit) bits.push('与选题关系:' + candidate.suggestion_fit);
308
+ if (candidate.difference) bits.push('差异:' + candidate.difference);
309
+ options.push({
310
+ label,
311
+ description: bits.join(';').slice(0, 300) || '世界母体候选',
312
+ });
313
+ }
314
+ if (allowReroll) {
315
+ options.push({ label: '换一批(重新生成)', description: '同一组 facet 下重新生成 3 个候选' });
316
+ }
317
+ options.push({ label: '取消', description: '不生成素材' });
318
+ return {
319
+ id: 'material-world',
320
+ header: '素材 · 世界母体',
321
+ question: '请选择一个世界母体;后续素材都从这个母体里长出来',
322
+ detail: '推荐第一个:它优先兑现 _novel_topic_suggestion.json 的方向和定位。选定后可用 /fancy-material continue 沿用同一世界追加素材。',
323
+ options,
324
+ };
325
+ }
326
+
327
+ function stripJsonFence(text) {
328
+ return String(text || '')
329
+ .replace(/^\uFEFF/, '')
330
+ .trim()
331
+ .replace(/^```(?:json)?\s*/i, '')
332
+ .replace(/\s*```$/, '')
333
+ .trim();
334
+ }
335
+
336
+ function slugFromTitle(title) {
337
+ return createHash('sha1').update(String(title || '')).digest('hex').slice(0, 10);
338
+ }
339
+
340
+ function normalizeStringArray(value) {
341
+ return unique(asArray(value).map(clean));
342
+ }
343
+
344
+ function normalizeWorldCandidate(raw, index, { constraintGenres = [] } = {}) {
345
+ const source = raw && typeof raw === 'object' ? raw : {};
346
+ const title = clean(source.title || source.name) || `世界母体 ${index + 1}`;
347
+ const coreGenres = normalizeStringArray(source.core_genres || source.genres);
348
+ return {
349
+ world_id: clean(source.world_id || source.id) || `world_${slugFromTitle(title)}`,
350
+ candidate_type: clean(source.candidate_type) || ['suggestion_anchor', 'facet_driven', 'wildcard'][index] || 'candidate',
351
+ title,
352
+ logline: clean(source.logline || source.summary),
353
+ core_conflict: clean(source.core_conflict || source.conflict),
354
+ reader_promise: clean(source.reader_promise || source.promise),
355
+ power_source: clean(source.power_source),
356
+ cost: clean(source.cost || source.price),
357
+ world_rules: normalizeStringArray(source.world_rules || source.rules),
358
+ institutions: normalizeStringArray(source.institutions || source.organizations),
359
+ taboos: normalizeStringArray(source.taboos || source.forbidden),
360
+ visual_motifs: normalizeStringArray(source.visual_motifs || source.motifs),
361
+ naming_logic: clean(source.naming_logic || source.naming),
362
+ core_genres: coreGenres.length ? coreGenres : [...constraintGenres],
363
+ supported_kinds: normalizeStringArray(source.supported_kinds)
364
+ .filter((kind) => MATERIAL_KINDS.includes(kind)),
365
+ suggestion_fit: clean(source.suggestion_fit),
366
+ difference: clean(source.difference || source.why_different),
367
+ };
368
+ }
369
+
370
+ /**
371
+ * 解析 LLM 写出的世界母体 JSON。允许纯 JSON、```json 围栏和前后解释。
372
+ */
373
+ export function parseWorldCandidates(text, { constraintGenres = [] } = {}) {
374
+ const source = stripJsonFence(text);
375
+ let data;
376
+ try {
377
+ data = JSON.parse(source);
378
+ } catch {
379
+ const start = source.indexOf('{');
380
+ const end = source.lastIndexOf('}');
381
+ if (start < 0 || end <= start) throw new Error('世界母体结果不是 JSON 对象');
382
+ data = JSON.parse(source.slice(start, end + 1));
383
+ }
384
+ const list = Array.isArray(data) ? data : data.candidates;
385
+ if (!Array.isArray(list) || !list.length) throw new Error('世界母体结果缺少 candidates 数组');
386
+ return list.slice(0, 3).map((item, index) => normalizeWorldCandidate(item, index, { constraintGenres }));
387
+ }
388
+
389
+ export function flowPath(root) {
390
+ return path.join(root, FLOW_RELATIVE_PATH);
391
+ }
392
+
393
+ export function readMaterialFlow(root) {
394
+ try {
395
+ const data = JSON.parse(fs.readFileSync(flowPath(root), 'utf8'));
396
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return null;
397
+ return data;
398
+ } catch {
399
+ return null;
400
+ }
401
+ }
402
+
403
+ export function writeMaterialFlow(root, flow) {
404
+ const value = {
405
+ ...flow,
406
+ version: FLOW_VERSION,
407
+ updated_at: new Date().toISOString(),
408
+ };
409
+ atomicWriteJson(flowPath(root), value);
410
+ return value;
411
+ }
412
+
413
+ export function suggestionFingerprint(suggestion) {
414
+ if (!suggestion) return '';
415
+ return createHash('sha256')
416
+ .update(JSON.stringify({
417
+ genre: suggestion.genre || '',
418
+ direction_title: suggestion.direction_title || '',
419
+ positioning: suggestion.positioning || '',
420
+ }))
421
+ .digest('hex')
422
+ .slice(0, 16);
423
+ }
424
+
425
+ export function flowSummaryText(flow) {
426
+ if (!flow || !flow.world) return '(没有可沿用的世界母体)';
427
+ const facets = flow.facet_labels || flow.facets || {};
428
+ const lines = [
429
+ '世界母体:' + (flow.world.title || '未命名'),
430
+ flow.world.core_conflict ? '核心矛盾:' + flow.world.core_conflict : '',
431
+ '题材:' + ((facets.genres || []).join('、') || '无(不限)'),
432
+ '场景:' + ((facets.settings || []).join('、') || '无(不限)'),
433
+ '情绪:' + ((facets.moods || []).join('、') || '无(不限)'),
434
+ '情节:' + ((facets.tropes || []).join('、') || '无(不限)'),
435
+ '身份:' + ((facets.roles || []).join('、') || '无(不限)'),
436
+ '关系:' + ((facets.relations || []).join('、') || '无(不限)'),
437
+ '风格:' + ((flow.styles?.keys || []).join('、') || flow.styles?.mode || '自动'),
438
+ '上次范围:' + ((flow.scope?.kinds || []).length || 0) + ' 个 kind;每 kind ' + (flow.scope?.target_per_kind || DEFAULT_TARGET_PER_KIND) + ' 条',
439
+ ].filter(Boolean);
440
+ return lines.join('\n');
441
+ }
442
+
443
+ function renderFacetBlock({ facets = {}, facetLabels = {}, scopeKinds = [] } = {}) {
444
+ const lines = ['## 本次选择(同一层多选 = 交集,不是并集)', ''];
445
+ for (const step of FACET_STEPS) {
446
+ const raw = normalizeFacetSelection(facetLabels[step.id] || facets[step.id] || []);
447
+ lines.push(`- ${step.label}:${raw.length ? raw.join('、') : EMPTY_FACET_LABEL}`);
448
+ }
449
+ lines.push('');
450
+ lines.push('硬规则:上面每一层、每一个选中项都必须**同时成立**。');
451
+ lines.push('例如题材同时选 都市 + 异能 + 脑洞,世界和素材必须同时满足三种;不能只取其中一种。');
452
+ lines.push('复合题材会展开成原子题材;不要偷偷丢掉任何一个约束。');
453
+ if (scopeKinds.length) {
454
+ lines.push('本次生成范围:' + scopeKinds.map((kind) => `${kind}(${KIND_LABELS[kind] || kind})`).join('、'));
455
+ }
456
+ return lines.join('\n');
457
+ }
458
+
459
+ function renderSuggestionBlock(suggestion) {
460
+ if (!suggestion) {
461
+ return [
462
+ '## 选题建议锚点',
463
+ '',
464
+ '当前没有 _novel_topic_suggestion.json。按用户 facet 自由构建世界母体,但不要伪造选题建议。',
465
+ ].join('\n');
466
+ }
467
+ return [
468
+ '## 选题建议锚点(来自 _novel_topic_suggestion.json)',
469
+ '',
470
+ '- 方向:' + (suggestion.direction_title || '(无)'),
471
+ '- 题材:' + (suggestion.genre || '(无)'),
472
+ '- 定位:' + (suggestion.positioning || '(无)'),
473
+ '',
474
+ '使用规则:',
475
+ '- 方向是候选世界母体的锚点,不是最终世界名。',
476
+ '- 定位是读者承诺和核心矛盾,不是命名词表。',
477
+ '- 必须先把定位翻译成 3–5 条世界公理/代价/禁忌,再让名字从公理里长出来。',
478
+ '- 禁止把定位里的职业、机构、流程名词直接当 rank_name / skill_name / faction_name。',
479
+ '- 反例:试岗、替班、带班、值守、包月令、静音条。',
480
+ ].join('\n');
481
+ }
482
+
483
+ function renderStyleBlock(styleSummary = '') {
484
+ if (!styleSummary) {
485
+ return '## 风格锚点\n\n本次未选择账号风格;按通用创作标准,但世界母体仍要成立。';
486
+ }
487
+ return '## 风格锚点\n\n' + styleSummary;
488
+ }
489
+
490
+ export function buildWorldPrompt({
491
+ workspace,
492
+ resultPath,
493
+ facets = {},
494
+ facetLabels = {},
495
+ suggestion = null,
496
+ scopeKinds = [],
497
+ styleSummary = '',
498
+ previousTitles = [],
499
+ }) {
500
+ let template;
501
+ try {
502
+ template = fs.readFileSync(WORLD_PROMPT_FILE, 'utf8');
503
+ } catch (err) {
504
+ throw new Error('缺少世界母体提示词文件:' + WORLD_PROMPT_FILE + '(' + (err && err.message ? err.message : String(err)) + ')');
505
+ }
506
+ const previous = previousTitles.length
507
+ ? '## 上一批候选(不要重复)\n\n' + previousTitles.map((title) => '- ' + title).join('\n')
508
+ : '';
509
+ return template
510
+ .split('{{WORKSPACE}}').join(workspace || '')
511
+ .split('{{RESULT_PATH}}').join(resultPath || '')
512
+ .split('{{FACET_BLOCK}}').join(renderFacetBlock({ facets, facetLabels, scopeKinds }))
513
+ .split('{{SUGGESTION_BLOCK}}').join(renderSuggestionBlock(suggestion))
514
+ .split('{{STYLE_BLOCK}}').join(renderStyleBlock(styleSummary))
515
+ .split('{{PREVIOUS_BLOCK}}').join(previous)
516
+ .trim();
517
+ }
518
+
519
+ export function renderWorldBlock({
520
+ world,
521
+ facets = {},
522
+ facetLabels = {},
523
+ suggestion = null,
524
+ constraintGenres = [],
525
+ topicGenre = '',
526
+ }) {
527
+ if (!world) return '## 世界母体\n\n本次没有世界母体,按通用规则生成。';
528
+ const lines = [
529
+ '## 世界母体(最高优先级)',
530
+ '',
531
+ '- 世界母体:' + (world.title || '未命名'),
532
+ world.logline ? '- 一句话:' + world.logline : '',
533
+ world.core_conflict ? '- 核心矛盾:' + world.core_conflict : '',
534
+ world.reader_promise ? '- 读者承诺:' + world.reader_promise : '',
535
+ world.power_source ? '- 力量来源:' + world.power_source : '',
536
+ world.cost ? '- 核心代价:' + world.cost : '',
537
+ world.naming_logic ? '- 命名逻辑:' + world.naming_logic : '',
538
+ '',
539
+ '### 世界公理(必须遵守)',
540
+ ...(world.world_rules?.length ? world.world_rules.map((rule) => '- ' + rule) : ['- (未提供,按核心矛盾推导)']),
541
+ '',
542
+ '### 本次 facet(全部为 AND)',
543
+ ...FACET_STEPS.map((step) => {
544
+ const raw = normalizeFacetSelection(facetLabels[step.id] || facets[step.id] || []);
545
+ return `- ${step.label}:${raw.length ? raw.join('、') : EMPTY_FACET_LABEL}`;
546
+ }),
547
+ '',
548
+ '### 题材交集(必须全部满足)',
549
+ '- 核心题材:' + (constraintGenres.join('、') || '无(不限)'),
550
+ topicGenre ? '- 选题题材:' + topicGenre : '',
551
+ '',
552
+ '### 硬规则',
553
+ '- 同一层多选是交集,不是并集;选中的每一项都必须同时成立。',
554
+ '- 不同层之间也是交集;不能为了好写而丢掉题材、情绪、场景、情节、身份或关系。',
555
+ '- 素材的 genres 必须原样包含全部核心题材;缺任何一个都算废稿。',
556
+ '- 对应 facet 数组(tropes / moods / settings / roles / relations)必须包含本次选中的全部值;不能只写其中一个。',
557
+ '- 名字必须从世界母体的公理、代价、禁忌里长出来,不能是现实职业词或字面功能词。',
558
+ '- 禁止把 positioning 里的职业/机构/流程名词直接当 rank_name / skill_name / faction_name。',
559
+ '- 反例:试岗、替班、带班、值守、包月令、静音条。',
560
+ ].filter(Boolean);
561
+ if (world.institutions?.length) lines.push('', '### 机构/场所', ...world.institutions.map((item) => '- ' + item));
562
+ if (world.taboos?.length) lines.push('', '### 禁忌', ...world.taboos.map((item) => '- ' + item));
563
+ if (world.visual_motifs?.length) lines.push('', '### 视觉母题', ...world.visual_motifs.map((item) => '- ' + item));
564
+ if (suggestion?.positioning) {
565
+ lines.push('', '### 选题定位(原样保留,只作为承诺,不直接当词汇)', '- ' + suggestion.positioning);
566
+ }
567
+ return lines.join('\n');
568
+ }
569
+
570
+ export function renderWorldBatchSummary({
571
+ world,
572
+ facets = {},
573
+ facetLabels = {},
574
+ constraintGenres = [],
575
+ }) {
576
+ if (!world) return '';
577
+ const selected = FACET_STEPS
578
+ .map((step) => {
579
+ const raw = normalizeFacetSelection(facetLabels[step.id] || facets[step.id] || []);
580
+ return raw.length ? `${step.label}=${raw.join('+')}` : '';
581
+ })
582
+ .filter(Boolean)
583
+ .join(';');
584
+ return [
585
+ '- 世界母体:' + (world.title || '未命名'),
586
+ world.core_conflict ? '- 核心矛盾:' + world.core_conflict : '',
587
+ world.cost ? '- 核心代价:' + world.cost : '',
588
+ world.naming_logic ? '- 命名逻辑:' + world.naming_logic : '',
589
+ '- 题材交集(必须全部满足):' + (constraintGenres.join('、') || '无(不限)'),
590
+ selected ? '- facet 交集:' + selected : '',
591
+ '- 同一层多选是 AND;禁止只取其中一个约束。',
592
+ ].filter(Boolean).join('\n');
593
+ }
594
+
595
+ export function worldCandidateSummary(candidate) {
596
+ return [
597
+ candidate.title,
598
+ candidate.core_conflict ? '矛盾:' + candidate.core_conflict : '',
599
+ candidate.reader_promise ? '承诺:' + candidate.reader_promise : '',
600
+ candidate.cost ? '代价:' + candidate.cost : '',
601
+ ].filter(Boolean).join('\n');
602
+ }