@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.
@@ -25,13 +25,36 @@ import {
25
25
  workspacePaths,
26
26
  } from '#workspace';
27
27
  import { connectMaterial, ensureMaterialDatabase, materialDatabaseName, removeMaterialDatabase } from '#material-db';
28
- import { BUILTIN_GENRES, resolveMaterialTopic } from '#material-topic';
28
+ import { readMinimalTopic, readSuggestion } from '#material-topic';
29
29
  import { makeWaitForTurn } from '../fancy-story-builder/writing-driver.js';
30
30
  import { exportMaterials } from './exporter.js';
31
31
  import { allKnownGenres } from './genres.js';
32
32
  import { buildExistingIndex, countByKind, countKind } from './inventory.js';
33
- import { KIND_LABELS, MATERIAL_KINDS, customFocusBlock, focusBlock, renderKindTable, resolveCustomKinds, resolveFocus } from './kinds.js';
33
+ import { KIND_LABELS, MATERIAL_KINDS, focusBlock, renderKindTable } from './kinds.js';
34
34
  import { loadStyleRegistry, selectStyles, styleBatchSummary, stylePromptBlock, styleSummaryText } from './styles.js';
35
+ import {
36
+ EMPTY_FACET_LABEL,
37
+ FACET_STEPS,
38
+ buildWorldPrompt,
39
+ countQuestion,
40
+ expandGenre,
41
+ expandGenres,
42
+ facetQuestion,
43
+ flowPath,
44
+ flowSummaryText,
45
+ normalizeFacetSelection,
46
+ parseCountAnswer,
47
+ parseWorldCandidates,
48
+ readMaterialFlow,
49
+ renderWorldBatchSummary,
50
+ renderWorldBlock,
51
+ resolveScopeKinds,
52
+ scopeQuestion,
53
+ suggestionFingerprint,
54
+ styleQuestion,
55
+ worldCandidateQuestion,
56
+ writeMaterialFlow,
57
+ } from './world.js';
35
58
  import { exportMaterialDatabase, importMaterialDatabase } from './native-backup.js';
36
59
  import { nextBatchRequest, planMaterialQueue } from './queue.js';
37
60
  import { deployMaterialTools } from './tool-deploy.js';
@@ -123,6 +146,7 @@ function renderBasePrompt({
123
146
  custom = null,
124
147
  styleBlock = '',
125
148
  styleRules = '',
149
+ worldBlock = '',
126
150
  audience = '',
127
151
  }) {
128
152
  const sourceFixed = mode === 'other' ? 'other' : 'builtin';
@@ -134,7 +158,7 @@ function renderBasePrompt({
134
158
  : '下面素材类型总表之一;builtin 素材必须在表内';
135
159
  return renderPrompt(readPrompt(), {
136
160
  MATERIAL_MODE: mode,
137
- GENRES: (genres || []).join('、'),
161
+ GENRES: (genres || []).join('、') || '(未限制,按世界母体推导)',
138
162
  TOPIC_FILE: topicFile || '(无)',
139
163
  KIND_TABLE: renderKindTable(),
140
164
  FOCUS_BLOCK: focusBlockText || focusBlock(focus),
@@ -143,6 +167,7 @@ function renderBasePrompt({
143
167
  AUDIENCE: audience || '男频 / 女频 / 通用',
144
168
  STYLE_RULES: styleRules || '未指定(执行通用创作标准)',
145
169
  STYLE_BLOCK: styleBlock || '(本次未选择账号风格,按通用规则生成。)',
170
+ WORLD_BLOCK: worldBlock || '(本次未指定世界母体,按通用规则生成。)',
146
171
  BATCH_ID: batchId || 'material-YYYYMMDD-01',
147
172
  SEED: batchId || 'material-v4',
148
173
  EXISTING_INDEX: existingIndex || '(运行 /fancy-material 时由插件提供)',
@@ -237,13 +262,12 @@ async function checkFile(file) {
237
262
  }
238
263
 
239
264
  /**
240
- * Every generated card must keep at least one exact selected genre in `genres`.
241
- * The model may add subgenres, but replacing the selected label with a synonym
242
- * breaks genre filtering and the existing-library index.
265
+ * 本版 facet 是交集语义:每条记录的 genres 必须原样包含本次选中的**全部**
266
+ * 题材。只要缺一个,就不能算满足本次世界母体。
243
267
  */
244
268
  function genreCoverageProblem(file, genres) {
245
- const selected = new Set((genres || []).filter(Boolean));
246
- if (!selected.size) return '';
269
+ const selected = [...new Set((genres || []).filter(Boolean))];
270
+ if (!selected.length) return '';
247
271
  let text;
248
272
  try { text = fs.readFileSync(file, 'utf8'); } catch { return ''; }
249
273
  const lines = text.split(/\r?\n/);
@@ -253,15 +277,17 @@ function genreCoverageProblem(file, genres) {
253
277
  if (!line) continue;
254
278
  let record;
255
279
  try { record = JSON.parse(line); } catch { continue; }
256
- const values = Array.isArray(record.genres) ? record.genres.map(String) : [];
257
- if (!values.some((genre) => selected.has(genre))) {
258
- bad.push(`第 ${i + 1} 条「${record.name || record.id || '未命名'}」`);
280
+ const values = new Set(Array.isArray(record.genres) ? record.genres.map(String) : []);
281
+ const missing = selected.filter((genre) => !values.has(genre));
282
+ if (missing.length) {
283
+ bad.push(`第 ${i + 1} 条「${record.name || record.id || '未命名'}」缺 ${missing.join('、')}`);
259
284
  }
260
285
  }
261
286
  if (!bad.length) return '';
262
- return '以下素材的 genres 没有原样包含本次主题材:' + bad.slice(0, 8).join('、')
287
+ return '以下素材没有同时满足本次题材交集:' + bad.slice(0, 8).join(';')
263
288
  + (bad.length > 8 ? `等 ${bad.length} 条` : '')
264
- + '。请把本次题材列表中的主题材名原样写进 genres,可再附加子题材。';
289
+ + '。每条素材的 genres 必须原样包含全部选中题材:' + selected.join('、')
290
+ + '。缺任何一个都算废稿。';
265
291
  }
266
292
 
267
293
  /**
@@ -543,59 +569,468 @@ async function runNativeImport(ctx, invocation, session, rawPath, taskList) {
543
569
  }
544
570
  }
545
571
 
546
- async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, opts = {}) {
572
+ async function askOne(ctx, invocation, question) {
573
+ const asked = await askUserQuestion(ctx, invocation, [question]);
574
+ if (!asked.ok) {
575
+ const type = asked.failure?.type;
576
+ if (type === 'cancelled') return { ok: false, message: '🚫 操作已取消。' };
577
+ if (type === 'no_provider') {
578
+ return { ok: false, message: '⚠️ 当前运行环境不支持交互式提问。请在 dsh-tui 中运行,或确认 Web UI 已加载交互组件。' };
579
+ }
580
+ return { ok: false, message: asked.failure?.message || '❌ 提问失败' };
581
+ }
582
+ const answers = asked.answer?.answers;
583
+ return { ok: true, answer: Array.isArray(answers) ? answers[0] : null };
584
+ }
585
+
586
+ function answerList(answer) {
587
+ if (!answer || typeof answer !== 'object') return [];
588
+ const selected = Array.isArray(answer.selected)
589
+ ? answer.selected.map((value) => String(value || '').trim()).filter(Boolean)
590
+ : [];
591
+ const custom = typeof answer.custom === 'string' ? answer.custom.trim() : '';
592
+ if (custom) {
593
+ for (const part of custom.split(/[,,、]/).map((value) => value.trim()).filter(Boolean)) {
594
+ selected.push(part);
595
+ }
596
+ }
597
+ return [...new Set(selected)];
598
+ }
599
+
600
+ function answerSingle(answer) {
601
+ if (!answer || typeof answer !== 'object') return '';
602
+ const custom = typeof answer.custom === 'string' ? answer.custom.trim() : '';
603
+ if (custom) return custom;
604
+ return Array.isArray(answer.selected) ? String(answer.selected[0] || '').trim() : '';
605
+ }
606
+
607
+ function facetStateFromLabels(facetLabels) {
608
+ const facets = {};
609
+ for (const step of FACET_STEPS) {
610
+ const values = normalizeFacetSelection(facetLabels[step.id] || []);
611
+ facets[step.id] = step.id === 'genres' ? expandGenres(values) : values;
612
+ }
613
+ return facets;
614
+ }
615
+
616
+ function chooseTopicGenre(facetGenres, suggestion) {
617
+ const raw = String(suggestion?.genre || '').trim();
618
+ if (raw) {
619
+ const expanded = expandGenre(raw);
620
+ if (!facetGenres.length || expanded.every((genre) => facetGenres.includes(genre))) return raw;
621
+ }
622
+ return facetGenres[0] || raw || '通用';
623
+ }
624
+
625
+ function styleSelectionFromRaw(raw) {
626
+ const value = String(raw || '').trim();
627
+ if (!value || value.toLowerCase() === 'auto') return { mode: 'auto', keys: [] };
628
+ if (value.toLowerCase() === 'none') return { mode: 'none', keys: [] };
629
+ return {
630
+ mode: 'manual',
631
+ keys: value.split(/[,,、]/).map((item) => item.trim()).filter(Boolean),
632
+ };
633
+ }
634
+
635
+ function styleSelectionFromLabels(labels, styles) {
636
+ const values = Array.isArray(labels) ? labels : [];
637
+ if (values.includes('不使用账号风格')) return { mode: 'none', keys: [] };
638
+ const keys = [];
639
+ for (const label of values) {
640
+ if (!label || label === EMPTY_FACET_LABEL || label === '无(自动选择)') continue;
641
+ const exact = styles.find((style) => style.style_key === label);
642
+ if (exact) {
643
+ keys.push(exact.style_key);
644
+ continue;
645
+ }
646
+ const labelled = styles.find((style) => label === `${style.style_key}(${style.style_name})`);
647
+ if (labelled) keys.push(labelled.style_key);
648
+ }
649
+ return keys.length ? { mode: 'manual', keys } : { mode: 'auto', keys: [] };
650
+ }
651
+
652
+ function resolveStyleObjects(registry, { genres = [], selection = { mode: 'auto', keys: [] } } = {}) {
653
+ const explicit = selection.mode === 'none'
654
+ ? 'none'
655
+ : (selection.keys?.length ? selection.keys.join(',') : 'auto');
656
+ return selectStyles(registry.styles, {
657
+ genres,
658
+ explicit,
659
+ limit: 3,
660
+ });
661
+ }
662
+
663
+ async function askFacetSelections(ctx, invocation, suggestion, taskList) {
664
+ const facetLabels = {};
665
+ for (const step of FACET_STEPS) {
666
+ if (taskList && typeof taskList.progress === 'function') {
667
+ taskList.progress(`选择${step.label}(同一层多选=交集)`);
668
+ }
669
+ const asked = await askOne(ctx, invocation, facetQuestion(step, { suggestion }));
670
+ if (!asked.ok) return { ok: false, message: asked.message };
671
+ facetLabels[step.id] = normalizeFacetSelection(answerList(asked.answer));
672
+ }
673
+ return { ok: true, facetLabels };
674
+ }
675
+
676
+ async function generateWorldCandidates({
677
+ root,
678
+ invocation,
679
+ taskList,
680
+ facets,
681
+ facetLabels,
682
+ suggestion,
683
+ scopeKinds,
684
+ styleSummary,
685
+ previousTitles = [],
686
+ }) {
687
+ const stamp = localIsoString().replace(/[-:T+.]/g, '').slice(0, 14) || String(Date.now());
688
+ const file = path.join(workspacePaths(root).tmp, 'fancy_material_world_' + stamp + '.json');
689
+ let failure = '';
690
+ for (let attempt = 1; attempt <= 2; attempt += 1) {
691
+ if (abortRequested(invocation)) return { ok: false, aborted: true, message: '用户中断' };
692
+ if (taskList && typeof taskList.progress === 'function') {
693
+ taskList.progress('生成世界母体候选(第 ' + attempt + ' 次)');
694
+ }
695
+ let before = null;
696
+ try { before = fs.readFileSync(file, 'utf8'); } catch { /* first attempt */ }
697
+ let prompt;
698
+ try {
699
+ prompt = buildWorldPrompt({
700
+ workspace: root,
701
+ resultPath: file,
702
+ facets,
703
+ facetLabels,
704
+ suggestion,
705
+ scopeKinds,
706
+ styleSummary,
707
+ previousTitles,
708
+ });
709
+ } catch (err) {
710
+ return { ok: false, message: err && err.message ? err.message : String(err) };
711
+ }
712
+ if (failure) {
713
+ prompt += '\n\n## 上次输出不可用\n\n' + failure + '\n\n请重新生成完整 JSON,并写入同一个目标文件。';
714
+ }
715
+ const sent = await llmFollowup(invocation, prompt, { appendTempRule: false });
716
+ if (!sent || sent.ok !== true) {
717
+ return { ok: false, message: '向 LLM 发送世界母体提示词失败:' + ((sent && sent.error) || '未知错误') };
718
+ }
719
+ taskList.watchTurns(invocation);
720
+ const waitForTurn = makeWaitForTurn(invocation, {
721
+ timeoutMs: 10 * 60 * 1000,
722
+ idleGraceMs: 60 * 1000,
723
+ signal: invocation.signal,
724
+ changed: (files, previous) => {
725
+ try {
726
+ return fs.readFileSync(files[0], 'utf8') !== previous;
727
+ } catch {
728
+ return true;
729
+ }
730
+ },
731
+ });
732
+ const waited = await waitForTurn([file], before);
733
+ if (!waited.ok) {
734
+ failure = waited.reason || waited.code || '等待世界母体结果失败';
735
+ continue;
736
+ }
737
+ try {
738
+ const candidates = parseWorldCandidates(fs.readFileSync(file, 'utf8'), {
739
+ constraintGenres: facets.genres || [],
740
+ });
741
+ return { ok: true, candidates, file };
742
+ } catch (err) {
743
+ failure = err && err.message ? err.message : String(err);
744
+ }
745
+ }
746
+ return { ok: false, message: '世界母体生成失败:' + (failure || '未知错误') };
747
+ }
748
+
749
+ async function chooseWorldCandidate(ctx, invocation, candidates, { allowReroll = true } = {}) {
750
+ const asked = await askOne(ctx, invocation, worldCandidateQuestion(candidates, { allowReroll }));
751
+ if (!asked.ok) return { ok: false, message: asked.message };
752
+ const selected = answerSingle(asked.answer);
753
+ if (!selected || selected === '取消') return { ok: true, cancelled: true };
754
+ if (selected.startsWith('换一批')) return { ok: true, reroll: true };
755
+ const exact = candidates.find((candidate) => candidate.title === selected);
756
+ if (exact) return { ok: true, candidate: exact };
757
+ const prefixed = candidates.find((candidate) => selected.startsWith(candidate.title + '('));
758
+ if (prefixed) return { ok: true, candidate: prefixed };
759
+ return { ok: false, message: '未识别世界母体选择:' + selected };
760
+ }
761
+
762
+ function makeFlow({
763
+ previous = null,
764
+ suggestion = null,
765
+ topic = null,
766
+ facetLabels,
767
+ facets,
768
+ styleSelection,
769
+ world,
770
+ scopeKinds,
771
+ targetPerKind,
772
+ }) {
773
+ return {
774
+ ...(previous && typeof previous === 'object' ? previous : {}),
775
+ status: 'world_selected',
776
+ source: {
777
+ suggestion_file: suggestion ? '_novel_topic_suggestion.json' : '',
778
+ suggestion_snapshot: suggestion || null,
779
+ suggestion_fingerprint: suggestionFingerprint(suggestion),
780
+ topic_file: topic ? '_novel_topic.json' : '',
781
+ topic_genre: topic?.genre || '',
782
+ },
783
+ facets,
784
+ facet_labels: facetLabels,
785
+ topic_genre: chooseTopicGenre(facets.genres || [], suggestion),
786
+ styles: {
787
+ mode: styleSelection.mode,
788
+ keys: [...(styleSelection.keys || [])],
789
+ },
790
+ world,
791
+ scope: {
792
+ kinds: scopeKinds,
793
+ target_per_kind: targetPerKind,
794
+ },
795
+ runs: Array.isArray(previous?.runs) ? previous.runs : [],
796
+ };
797
+ }
798
+
799
+ async function runInteractive(ctx, invocation, session, taskList, opts = {}) {
547
800
  const root = workspaceOf(session);
548
- // 两参数形式:/fancy-material <题材> <素材类型>。
549
- // 题材和素材类型都允许用户随便写:题材直接进提示词,素材类型由 LLM
550
- // 判断对应哪个 kind(不在 58 个内置 kind 里时自拟 kind)。
551
- const custom = opts.custom || null;
552
- const isCustom = Boolean(custom && custom.genre && custom.materialType);
553
- const customAllKinds = Boolean(custom && custom.allKinds);
554
- if (isCustom && !customAllKinds) focusRaw = custom.materialType;
555
- const focus = customAllKinds
556
- ? { query: '全部素材类型(all)', kinds: [] }
557
- : resolveFocus(focusRaw);
558
- if (!isCustom && focusRaw && !focus.kinds.length) {
559
- return notify(session, 'error', '❌ 未识别素材类型:' + focusRaw
560
- + '\n可用示例:地名、人名、姓氏、门派、技能、超能力、武器、颜色、特效、脑洞、人物性格、关系、场景。'
561
- + '\n如果素材类型是自定义的,请用两参数形式:/fancy-material <题材> <素材类型>');
801
+ const suggestion = readSuggestion(root);
802
+ const topic = readMinimalTopic(root);
803
+ const facetHint = suggestion || (topic ? { genre: topic.genre } : null);
804
+ if (abortRequested(invocation)) return notify(session, 'error', '🚫 操作已取消。');
805
+
806
+ const previousFlow = readMaterialFlow(root);
807
+ if (!opts.fresh && previousFlow && previousFlow.world) {
808
+ const asked = await askOne(ctx, invocation, {
809
+ id: 'material-existing-flow',
810
+ header: '素材 · 上次世界',
811
+ question: '检测到上次生成过素材。本次要沿用上次的世界母体,还是重新构建?',
812
+ detail: flowSummaryText(previousFlow),
813
+ options: [
814
+ { label: '沿用上次世界母体(推荐)', description: '只确认追加范围和数量,不重问 facet' },
815
+ { label: '重新构建世界母体', description: '重新选择 facet 和世界母体;旧素材保留' },
816
+ { label: '取消', description: '不生成素材' },
817
+ ],
818
+ });
819
+ if (!asked.ok) return notify(session, 'error', asked.message);
820
+ const choice = answerSingle(asked.answer);
821
+ if (!choice || choice === '取消') return notify(session, 'success', '操作已取消。');
822
+ if (choice.startsWith('沿用上次')) {
823
+ return runContinue(ctx, invocation, session, taskList, { styleRaw: opts.styleRaw });
824
+ }
825
+ }
826
+
827
+ taskList.progress('读取选题建议与 facet 选择');
828
+ await ensureMaterialDatabase(root);
829
+ const tools = deployMaterialTools(root);
830
+ if (!tools.ok) {
831
+ return notify(session, 'error', '❌ 部署素材查询脚本失败:\n' + (tools.problems.join('\n') || '未知错误'));
832
+ }
833
+ const registry = await loadStyleRegistry(root);
834
+
835
+ const facetResult = await askFacetSelections(ctx, invocation, facetHint, taskList);
836
+ if (!facetResult.ok) {
837
+ return notify(session, 'error', facetResult.message);
562
838
  }
563
- // 素材题材只认用户选题链路:
564
- // _novel_topic.json > _novel_topic_suggestion.json > 内置全题材。
565
- // 自定义两参数形式直接用用户给的题材,不走选题链路,也不弹框。
566
- let plan;
567
- if (isCustom) {
568
- plan = {
569
- mode: 'other',
570
- genres: [String(custom.genre).trim()],
571
- topicFile: null,
572
- customGenre: String(custom.genre).trim(),
573
- customMaterialType: String(custom.materialType).trim(),
574
- };
839
+ const { facetLabels } = facetResult;
840
+ const facets = facetStateFromLabels(facetLabels);
841
+ taskList.advance(1);
842
+
843
+ let styleSelection;
844
+ if (opts.styleRaw) {
845
+ styleSelection = styleSelectionFromRaw(opts.styleRaw);
575
846
  } else {
576
- plan = resolveMaterialTopic(root);
577
- if (!plan.mode) {
578
- const asked = await askUserQuestion(ctx, invocation, [{
579
- id: 'material-builtin-confirm',
580
- header: '没有选题记录',
581
- question: '当前没有执行过扫榜和 /fancy-topic,将使用内置全题材生成素材(男频 + 女频)。是否继续?',
582
- detail: '内置题材共 ' + BUILTIN_GENRES.length + ' 类;确认后所有 kind 都会按全题材生成。',
583
- options: [
584
- { label: '确认', description: '使用内置全题材生成素材' },
585
- { label: '取消', description: '不生成任何素材' },
586
- ],
587
- }]);
588
- if (!asked.ok) {
589
- return notify(session, 'error', asked.failure?.message || '❌ 提问失败');
590
- }
591
- const selected = asked.answer?.answers?.[0]?.selected?.[0];
592
- if (selected !== '确认') return notify(session, 'success', '操作已取消。');
593
- plan = { mode: 'builtin', genres: [...BUILTIN_GENRES], topicFile: null };
847
+ const asked = await askOne(ctx, invocation, styleQuestion(registry.styles));
848
+ if (!asked.ok) return notify(session, 'error', asked.message);
849
+ styleSelection = styleSelectionFromLabels(answerList(asked.answer), registry.styles);
850
+ }
851
+ const styleGenres = facets.genres.length ? facets.genres : expandGenre(suggestion?.genre || topic?.genre);
852
+ let selectedStyles = [];
853
+ try {
854
+ selectedStyles = resolveStyleObjects(registry, { genres: styleGenres, selection: styleSelection });
855
+ } catch (err) {
856
+ return notify(session, 'error', '❌ ' + (err && err.message ? err.message : String(err)));
857
+ }
858
+
859
+ const scopeAsked = await askOne(ctx, invocation, scopeQuestion());
860
+ if (!scopeAsked.ok) return notify(session, 'error', scopeAsked.message);
861
+ const scopeLabels = answerList(scopeAsked.answer);
862
+ const scopeKinds = resolveScopeKinds(scopeLabels);
863
+ if (!scopeKinds.length) return notify(session, 'error', '❌ 本次没有选择任何 kind。');
864
+
865
+ const countAsked = await askOne(ctx, invocation, countQuestion());
866
+ if (!countAsked.ok) return notify(session, 'error', countAsked.message);
867
+ const targetPerKind = parseCountAnswer(answerSingle(countAsked.answer));
868
+
869
+ const worldResult = await generateWorldCandidates({
870
+ root,
871
+ invocation,
872
+ taskList,
873
+ facets,
874
+ facetLabels,
875
+ suggestion,
876
+ scopeKinds,
877
+ styleSummary: styleBatchSummary(selectedStyles),
878
+ });
879
+ if (!worldResult.ok) {
880
+ return notify(session, 'error', (worldResult.aborted ? '🚫 ' : '❌ ') + worldResult.message);
881
+ }
882
+
883
+ let candidates = worldResult.candidates;
884
+ let selectedWorld = null;
885
+ let rerolls = 0;
886
+ while (!selectedWorld) {
887
+ if (abortRequested(invocation)) return notify(session, 'error', '🚫 操作已取消。');
888
+ const picked = await chooseWorldCandidate(ctx, invocation, candidates, { allowReroll: rerolls < 1 });
889
+ if (!picked.ok) return notify(session, 'error', picked.message);
890
+ if (picked.cancelled) return notify(session, 'success', '操作已取消。');
891
+ if (picked.reroll) {
892
+ rerolls += 1;
893
+ const again = await generateWorldCandidates({
894
+ root,
895
+ invocation,
896
+ taskList,
897
+ facets,
898
+ facetLabels,
899
+ suggestion,
900
+ scopeKinds,
901
+ styleSummary: styleBatchSummary(selectedStyles),
902
+ previousTitles: candidates.map((candidate) => candidate.title),
903
+ });
904
+ if (!again.ok) return notify(session, 'error', '❌ ' + again.message);
905
+ candidates = again.candidates;
906
+ continue;
594
907
  }
908
+ selectedWorld = picked.candidate;
595
909
  }
596
910
 
597
- const config = generationConfig();
911
+ const flow = makeFlow({
912
+ suggestion,
913
+ topic,
914
+ facetLabels,
915
+ facets,
916
+ styleSelection,
917
+ world: selectedWorld,
918
+ scopeKinds,
919
+ targetPerKind,
920
+ });
921
+ flow.styles.keys = selectedStyles.map((style) => style.style_key);
922
+ try {
923
+ writeMaterialFlow(root, flow);
924
+ } catch (err) {
925
+ return notify(session, 'error', '❌ 写入世界母体状态失败:' + (err && err.message ? err.message : String(err)));
926
+ }
927
+
928
+ return runGenerationWithPlan(ctx, invocation, session, taskList, {
929
+ root,
930
+ plan: {
931
+ mode: 'world',
932
+ genres: facets.genres,
933
+ topicGenre: flow.topic_genre,
934
+ topicFile: suggestion ? '_novel_topic_suggestion.json' : null,
935
+ suggestion,
936
+ kinds: scopeKinds,
937
+ },
938
+ world: selectedWorld,
939
+ facets,
940
+ facetLabels,
941
+ flow,
942
+ styleMode: styleSelection.mode,
943
+ styleKeys: selectedStyles.map((style) => style.style_key),
944
+ targetPerKind,
945
+ batchSize: generationConfig().batchSize,
946
+ });
947
+ }
948
+
949
+ async function runContinue(ctx, invocation, session, taskList, opts = {}) {
950
+ const root = workspaceOf(session);
951
+ const flow = readMaterialFlow(root);
952
+ if (!flow || !flow.world) {
953
+ return notify(session, 'error', [
954
+ '⚠️ 没有可沿用的上次选择。',
955
+ '先运行 /fancy-material 选择 facet 和世界母体;之后再用 /fancy-material continue 追加。',
956
+ ].join('\n'));
957
+ }
958
+ if (opts.fresh) {
959
+ return runInteractive(ctx, invocation, session, taskList, opts);
960
+ }
961
+ taskList.progress('读取上次世界母体选择');
598
962
  taskList.advance(1);
963
+ const scope = scopeQuestion({ currentKinds: flow.scope?.kinds || [] });
964
+ scope.detail = flowSummaryText(flow) + '\n\n' + scope.detail;
965
+ const scopeAsked = await askOne(ctx, invocation, scope);
966
+ if (!scopeAsked.ok) return notify(session, 'error', scopeAsked.message);
967
+ const scopeKinds = resolveScopeKinds(answerList(scopeAsked.answer), {
968
+ currentKinds: flow.scope?.kinds || [],
969
+ });
970
+ if (!scopeKinds.length) return notify(session, 'error', '❌ 本次没有选择任何 kind。');
971
+
972
+ const countAsked = await askOne(ctx, invocation, countQuestion());
973
+ if (!countAsked.ok) return notify(session, 'error', countAsked.message);
974
+ const targetPerKind = parseCountAnswer(answerSingle(countAsked.answer));
975
+
976
+ let styleMode = flow.styles?.mode || 'auto';
977
+ let styleKeys = Array.isArray(flow.styles?.keys) ? flow.styles.keys : [];
978
+ if (opts.styleRaw) {
979
+ const override = styleSelectionFromRaw(opts.styleRaw);
980
+ styleMode = override.mode;
981
+ styleKeys = override.keys;
982
+ }
983
+
984
+ const suggestion = flow.source?.suggestion_snapshot || readSuggestion(root);
985
+ const facets = flow.facets || {};
986
+ const facetLabels = flow.facet_labels || facets;
987
+ const nextFlow = {
988
+ ...flow,
989
+ status: 'world_selected',
990
+ facets,
991
+ facet_labels: facetLabels,
992
+ topic_genre: flow.topic_genre || chooseTopicGenre(facets.genres || [], suggestion),
993
+ styles: { mode: styleMode, keys: styleKeys },
994
+ scope: { kinds: scopeKinds, target_per_kind: targetPerKind },
995
+ };
996
+ try {
997
+ writeMaterialFlow(root, nextFlow);
998
+ } catch (err) {
999
+ return notify(session, 'error', '❌ 更新世界母体状态失败:' + (err && err.message ? err.message : String(err)));
1000
+ }
1001
+ taskList.advance(2);
1002
+ return runGenerationWithPlan(ctx, invocation, session, taskList, {
1003
+ root,
1004
+ plan: {
1005
+ mode: 'world',
1006
+ genres: facets.genres || [],
1007
+ topicGenre: nextFlow.topic_genre,
1008
+ topicFile: flow.source?.suggestion_file || (suggestion ? '_novel_topic_suggestion.json' : null),
1009
+ suggestion,
1010
+ kinds: scopeKinds,
1011
+ },
1012
+ world: flow.world,
1013
+ facets,
1014
+ facetLabels,
1015
+ flow: nextFlow,
1016
+ styleMode,
1017
+ styleKeys,
1018
+ targetPerKind,
1019
+ batchSize: generationConfig().batchSize,
1020
+ });
1021
+ }
1022
+
1023
+ export async function runGenerationWithPlan(ctx, invocation, session, taskList, opts = {}) {
1024
+ const root = opts.root || workspaceOf(session);
1025
+ const plan = opts.plan || {};
1026
+ const world = opts.world || null;
1027
+ const facets = opts.facets || {};
1028
+ const facetLabels = opts.facetLabels || facets;
1029
+ const flow = opts.flow || null;
1030
+ const targetPerKind = Math.max(1, Number(opts.targetPerKind) || generationConfig().targetPerKind);
1031
+ const batchSize = Math.max(1, Number(opts.batchSize) || generationConfig().batchSize);
1032
+ const genres = [...new Set((plan.genres || []).filter(Boolean))];
1033
+
599
1034
  await ensureMaterialDatabase(root);
600
1035
  const tools = deployMaterialTools(root);
601
1036
  if (!tools.ok) {
@@ -605,25 +1040,30 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
605
1040
  const styleRegistry = await loadStyleRegistry(root);
606
1041
  let selectedStyles = [];
607
1042
  try {
608
- selectedStyles = selectStyles(styleRegistry.styles, {
609
- genres: plan.genres,
610
- explicit: opts.styleRaw || 'auto',
611
- limit: 3,
1043
+ selectedStyles = resolveStyleObjects(styleRegistry, {
1044
+ genres: genres.length ? genres : expandGenre(plan.topicGenre),
1045
+ selection: {
1046
+ mode: opts.styleMode || 'auto',
1047
+ keys: Array.isArray(opts.styleKeys) ? opts.styleKeys : [],
1048
+ },
612
1049
  });
613
1050
  } catch (err) {
614
1051
  return notify(session, 'error', '❌ ' + (err && err.message ? err.message : String(err)));
615
1052
  }
616
- const styleBlock = stylePromptBlock(styleRegistry.styles, selectedStyles, { genres: plan.genres });
1053
+ const styleBlock = stylePromptBlock(styleRegistry.styles, selectedStyles, { genres });
617
1054
  const styleRules = selectedStyles.length
618
1055
  ? '本次使用账号风格:' + styleSummaryText(selectedStyles) + ';风格核心优先于题材命名体例。'
619
1056
  : '未指定账号风格(执行通用创作标准)。';
620
1057
  const styleSummary = styleBatchSummary(selectedStyles);
621
- const counts = await countByKind(root, plan.genres);
622
- // 自定义素材第一轮 kind 由 LLM 决定,这里先用一个占位项跑一条队列。
623
- const kinds = isCustom
624
- ? resolveCustomKinds({ materialType: custom.materialType, kinds: focus.kinds })
625
- : [...new Set(focus.kinds.length ? focus.kinds : MATERIAL_KINDS)];
626
- const planned = planMaterialQueue({ kinds, target: config.targetPerKind });
1058
+ const counts = await countByKind(root, genres);
1059
+ const kinds = [...new Set((plan.kinds || []).filter((kind) => MATERIAL_KINDS.includes(kind)))];
1060
+ if (!kinds.length) {
1061
+ return notify(session, 'error', '❌ 本次没有可生成的 kind。');
1062
+ }
1063
+ const planned = planMaterialQueue({ kinds, target: targetPerKind });
1064
+ const scopeBlockText = '本次世界母体生成范围:'
1065
+ + kinds.map((kind) => `\`${kind}\`(${KIND_LABELS[kind] || kind})`).join('、')
1066
+ + '。插件只按这个范围排队;不要生成未选中的 kind。';
627
1067
 
628
1068
  const startedAt = Date.now();
629
1069
  const batchId = batchIdOfNow();
@@ -632,39 +1072,43 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
632
1072
  fs.mkdirSync(runDir, { recursive: true });
633
1073
  const progressFile = path.join(runDir, 'progress.json');
634
1074
  const batchLog = path.join(runDir, 'batches.jsonl');
635
- const existing = await buildExistingIndex(root, plan.genres, stamp);
636
- const focusBlockText = isCustom
637
- ? customFocusBlock({
638
- genre: plan.customGenre,
639
- materialType: plan.customMaterialType,
640
- kinds: focus.kinds,
641
- allKinds: customAllKinds,
642
- })
643
- : '';
1075
+ const existing = await buildExistingIndex(root, genres, stamp);
1076
+ const worldBlock = renderWorldBlock({
1077
+ world,
1078
+ facets,
1079
+ facetLabels,
1080
+ suggestion: plan.suggestion,
1081
+ constraintGenres: genres,
1082
+ topicGenre: plan.topicGenre,
1083
+ });
1084
+ const worldSummary = renderWorldBatchSummary({
1085
+ world,
1086
+ facets,
1087
+ facetLabels,
1088
+ constraintGenres: genres,
1089
+ });
644
1090
  const base = renderBasePrompt({
645
- mode: plan.mode,
646
- genres: plan.genres,
647
- topicFile: plan.topicFile,
1091
+ mode: 'world',
1092
+ genres,
1093
+ topicFile: plan.topicFile || '(无)',
648
1094
  existingIndex: existing.file,
649
1095
  existingTotal: existing.count,
650
1096
  batchId,
651
1097
  workspace: root,
652
- focus,
1098
+ focus: null,
653
1099
  queryScript: tools.queryScript,
654
1100
  validateScript: tools.validateScript,
655
- targetPerKind: config.targetPerKind,
656
- batchSize: config.batchSize,
657
- focusBlockText,
658
- custom: isCustom ? { genre: plan.customGenre, materialType: plan.customMaterialType } : null,
1101
+ targetPerKind,
1102
+ batchSize,
1103
+ focusBlockText: scopeBlockText,
659
1104
  styleBlock,
660
1105
  styleRules,
1106
+ worldBlock,
661
1107
  });
662
1108
 
663
1109
  const queue = planned.all.map((item) => ({
664
- kind: item.kind === '__custom__' ? '' : item.kind,
665
- label: isCustom && !customAllKinds
666
- ? plan.customMaterialType
667
- : (KIND_LABELS[item.kind] || item.kind),
1110
+ kind: item.kind,
1111
+ label: KIND_LABELS[item.kind] || item.kind,
668
1112
  db_existing: Number(counts[item.kind]) || 0,
669
1113
  generated: item.generated,
670
1114
  target: item.target,
@@ -675,31 +1119,34 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
675
1119
  reason: '',
676
1120
  }));
677
1121
  const pending = queue.filter((item) => item.remaining > 0);
678
-
679
1122
  const report = {
680
1123
  status: 'running',
681
- mode: 'per_run_quota',
1124
+ mode: 'world',
682
1125
  started_at: new Date(startedAt).toISOString(),
683
1126
  updated_at: new Date(startedAt).toISOString(),
684
1127
  batch_id: batchId,
685
1128
  database,
686
1129
  workspace: root,
687
- target_per_kind: config.targetPerKind,
688
- batch_size: config.batchSize,
689
- genre_mode: plan.mode,
690
- genres: plan.genres,
691
- source: plan.mode === 'other' ? 'other' : 'builtin',
1130
+ target_per_kind: targetPerKind,
1131
+ batch_size: batchSize,
1132
+ genre_mode: 'world',
1133
+ genres,
1134
+ topic_genre: plan.topicGenre,
1135
+ source: 'builtin',
1136
+ world: world ? {
1137
+ world_id: world.world_id,
1138
+ title: world.title,
1139
+ core_conflict: world.core_conflict,
1140
+ cost: world.cost,
1141
+ } : null,
1142
+ facets,
1143
+ facet_labels: facetLabels,
692
1144
  styles: selectedStyles.map((style) => ({
693
1145
  style_key: style.style_key,
694
1146
  style_name: style.style_name,
695
1147
  style_type: style.style_type,
696
1148
  genre_tags: style.genre_tags,
697
1149
  })),
698
- ...(isCustom ? {
699
- custom_genre: plan.customGenre,
700
- custom_material_type: plan.customMaterialType,
701
- custom_all_kinds: customAllKinds,
702
- } : {}),
703
1150
  kinds: queue,
704
1151
  };
705
1152
  const saveProgress = () => {
@@ -708,6 +1155,30 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
708
1155
  };
709
1156
  saveProgress();
710
1157
 
1158
+ if (flow) {
1159
+ try {
1160
+ flow.status = 'generating';
1161
+ flow.facets = facets;
1162
+ flow.facet_labels = facetLabels;
1163
+ flow.topic_genre = plan.topicGenre;
1164
+ flow.world = world;
1165
+ flow.styles = { mode: opts.styleMode || 'auto', keys: selectedStyles.map((style) => style.style_key) };
1166
+ flow.scope = { kinds, target_per_kind: targetPerKind };
1167
+ flow.last_run = {
1168
+ run_id: batchId,
1169
+ run_dir: runDir,
1170
+ started_at: new Date(startedAt).toISOString(),
1171
+ status: 'running',
1172
+ target_per_kind: targetPerKind,
1173
+ kinds,
1174
+ imported: 0,
1175
+ };
1176
+ writeMaterialFlow(root, flow);
1177
+ } catch (err) {
1178
+ console.error('[fancy-material] 写入 flow 失败:' + (err && err.message ? err.message : String(err)));
1179
+ }
1180
+ }
1181
+
711
1182
  const waitForTurn = makeWaitForTurn(invocation, {
712
1183
  timeoutMs: GENERATION_TIMEOUT_MS,
713
1184
  idleGraceMs: GENERATION_IDLE_GRACE_MS,
@@ -732,7 +1203,7 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
732
1203
  let aborted = false;
733
1204
  let fatal = false;
734
1205
  let kindFailureStreak = 0;
735
- const maxBatchesPerKind = Math.max(1, Math.ceil(config.targetPerKind / config.batchSize) * 4);
1206
+ const maxBatchesPerKind = Math.max(1, Math.ceil(targetPerKind / batchSize) * 4);
736
1207
 
737
1208
  for (let index = 0; index < pending.length; index += 1) {
738
1209
  const item = pending[index];
@@ -741,7 +1212,7 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
741
1212
  let stalled = 0;
742
1213
  let lastReason = '';
743
1214
 
744
- while (item.generated < config.targetPerKind && item.batches < maxBatchesPerKind) {
1215
+ while (item.generated < targetPerKind && item.batches < maxBatchesPerKind) {
745
1216
  if (abortRequested(invocation)) {
746
1217
  aborted = true;
747
1218
  lastReason = '用户中断';
@@ -749,15 +1220,15 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
749
1220
  }
750
1221
  const next = nextBatchRequest({
751
1222
  generated: item.generated,
752
- target: config.targetPerKind,
753
- batchSize: config.batchSize,
1223
+ target: targetPerKind,
1224
+ batchSize,
754
1225
  });
755
1226
  if (!next.requestCount) break;
756
1227
 
757
1228
  const batchNo = item.batches + 1;
758
1229
  const file = path.join(
759
1230
  runDir,
760
- String(index + 1).padStart(3, '0') + '_' + (item.kind || 'custom') + '_' + String(batchNo).padStart(2, '0') + '.jsonl',
1231
+ String(index + 1).padStart(3, '0') + '_' + item.kind + '_' + String(batchNo).padStart(2, '0') + '.jsonl',
761
1232
  );
762
1233
  const includeBase = batchNo === 1 || batchNo % FULL_PROMPT_EVERY === 1;
763
1234
  let attemptDetail = '';
@@ -778,11 +1249,11 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
778
1249
  batchId,
779
1250
  attempt,
780
1251
  failures: attemptDetail ? [attemptDetail] : [],
781
- mode: plan.mode,
782
- genres: plan.genres,
783
- focus,
784
- targetPerKind: config.targetPerKind,
785
- batchSize: config.batchSize,
1252
+ mode: 'world',
1253
+ genres,
1254
+ focus: null,
1255
+ targetPerKind,
1256
+ batchSize,
786
1257
  kind: item.kind,
787
1258
  kindLabel: item.label,
788
1259
  kindIndex: index + 1,
@@ -795,12 +1266,12 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
795
1266
  queryScript: tools.queryScript,
796
1267
  existingIndex: existing.file,
797
1268
  existingTotal: existing.count,
798
- custom: isCustom
799
- ? { genre: plan.customGenre, materialType: plan.customMaterialType, allKinds: customAllKinds }
800
- : null,
801
- customKindPending: isCustom && !item.kind,
802
- sourceFixed: plan.mode === 'other' ? 'other' : 'builtin',
1269
+ custom: null,
1270
+ customKindPending: false,
1271
+ sourceFixed: 'builtin',
803
1272
  styleSummary,
1273
+ worldBlock,
1274
+ worldSummary,
804
1275
  });
805
1276
  const sent = await llmFollowup(invocation, prompt, { appendTempRule: false });
806
1277
  if (!sent || sent.ok !== true) {
@@ -817,27 +1288,9 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
817
1288
  if (!waited.ok && waited.code === 'TIMEOUT') {
818
1289
  if (fs.existsSync(file)) {
819
1290
  const checked = await checkFile(file);
820
- const genreProblem = checked.code === 0 ? genreCoverageProblem(file, plan.genres) : '';
821
- let kindProblem = '';
822
- if (checked.code === 0) {
823
- if (isCustom && !item.kind) {
824
- const detected = detectSingleKind(file);
825
- if (detected.problem) {
826
- kindProblem = detected.problem;
827
- } else {
828
- item.kind = detected.kind;
829
- // 首次知道 kind,先把“导入前的库内数量”记下来,
830
- // 否则 beforeCount=0 会把同 kind 的历史素材也算成本次新增。
831
- item.db_existing = await countKind(root, item.kind, plan.genres);
832
- kindProblem = kindCoverageProblem(file, item.kind);
833
- }
834
- } else {
835
- kindProblem = kindCoverageProblem(file, item.kind);
836
- }
837
- }
838
- const sourceProblem = checked.code === 0
839
- ? sourceCoverageProblem(file, plan.mode === 'other' ? 'other' : 'builtin')
840
- : '';
1291
+ const genreProblem = checked.code === 0 ? genreCoverageProblem(file, genres) : '';
1292
+ const kindProblem = checked.code === 0 ? kindCoverageProblem(file, item.kind) : '';
1293
+ const sourceProblem = checked.code === 0 ? sourceCoverageProblem(file, 'builtin') : '';
841
1294
  if (checked.code === 0 && !genreProblem && !kindProblem && !sourceProblem) {
842
1295
  try {
843
1296
  await importFile(root, file, { noPrefetch: true });
@@ -847,7 +1300,7 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
847
1300
  break;
848
1301
  }
849
1302
  const beforeCount = item.db_existing;
850
- const afterCount = await countKind(root, item.kind, plan.genres);
1303
+ const afterCount = await countKind(root, item.kind, genres);
851
1304
  const imported = Math.max(0, afterCount - beforeCount);
852
1305
  item.db_existing = afterCount;
853
1306
  item.generated += imported;
@@ -855,7 +1308,7 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
855
1308
  batchCount += 1;
856
1309
  item.batches = batchNo;
857
1310
  item.imported += imported;
858
- item.remaining = Math.max(0, config.targetPerKind - item.generated);
1311
+ item.remaining = Math.max(0, targetPerKind - item.generated);
859
1312
  try {
860
1313
  fs.appendFileSync(batchLog, JSON.stringify({
861
1314
  at: new Date().toISOString(),
@@ -892,29 +1345,17 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
892
1345
  attemptDetail = scriptDetail(checked);
893
1346
  continue;
894
1347
  }
895
- const genreProblem = genreCoverageProblem(file, plan.genres);
1348
+ const genreProblem = genreCoverageProblem(file, genres);
896
1349
  if (genreProblem) {
897
1350
  attemptDetail = genreProblem;
898
1351
  continue;
899
1352
  }
900
- if (isCustom && !item.kind) {
901
- // 自定义素材第一轮:模型自己选 kind,插件记住它,
902
- // 后续批次和计数都沿用同一个 kind。
903
- const detected = detectSingleKind(file);
904
- if (detected.problem) {
905
- attemptDetail = detected.problem;
906
- continue;
907
- }
908
- item.kind = detected.kind;
909
- // 同上:第一次知道 kind 时先取库内基线。
910
- item.db_existing = await countKind(root, item.kind, plan.genres);
911
- }
912
1353
  const kindProblem = kindCoverageProblem(file, item.kind);
913
1354
  if (kindProblem) {
914
1355
  attemptDetail = kindProblem;
915
1356
  continue;
916
1357
  }
917
- const sourceProblem = sourceCoverageProblem(file, plan.mode === 'other' ? 'other' : 'builtin');
1358
+ const sourceProblem = sourceCoverageProblem(file, 'builtin');
918
1359
  if (sourceProblem) {
919
1360
  attemptDetail = sourceProblem;
920
1361
  continue;
@@ -928,7 +1369,7 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
928
1369
  break;
929
1370
  }
930
1371
  const beforeCount = item.db_existing;
931
- const afterCount = await countKind(root, item.kind, plan.genres);
1372
+ const afterCount = await countKind(root, item.kind, genres);
932
1373
  const imported = Math.max(0, afterCount - beforeCount);
933
1374
  item.db_existing = afterCount;
934
1375
  item.generated += imported;
@@ -936,7 +1377,7 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
936
1377
  batchCount += 1;
937
1378
  item.batches = batchNo;
938
1379
  item.imported += imported;
939
- item.remaining = Math.max(0, config.targetPerKind - item.generated);
1380
+ item.remaining = Math.max(0, targetPerKind - item.generated);
940
1381
  try {
941
1382
  fs.appendFileSync(batchLog, JSON.stringify({
942
1383
  at: new Date().toISOString(),
@@ -968,15 +1409,15 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
968
1409
  break;
969
1410
  }
970
1411
  saveProgress();
971
- if (item.generated >= config.targetPerKind) break;
1412
+ if (item.generated >= targetPerKind) break;
972
1413
  if (stalled >= MAX_STALLED_BATCHES) {
973
1414
  lastReason = '连续 ' + stalled + ' 批没有新增素材';
974
1415
  break;
975
1416
  }
976
1417
  }
977
1418
 
978
- item.remaining = Math.max(0, config.targetPerKind - item.generated);
979
- if (item.generated >= config.targetPerKind) {
1419
+ item.remaining = Math.max(0, targetPerKind - item.generated);
1420
+ if (item.generated >= targetPerKind) {
980
1421
  item.status = 'done';
981
1422
  completed.push({ ...item });
982
1423
  kindFailureStreak = 0;
@@ -1000,18 +1441,42 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
1000
1441
  report.imported_total = importedTotal;
1001
1442
  report.batches = batchCount;
1002
1443
  const notStarted = queue.filter((item) => item.status === 'pending' || item.status === 'running');
1003
- report.not_started = notStarted.map((item) => item.kind || item.label || '自定义素材');
1004
- report.status = aborted
1444
+ report.not_started = notStarted.map((item) => item.kind || item.label);
1445
+ const finalStatus = aborted
1005
1446
  ? 'aborted'
1006
1447
  : ((incomplete.length || notStarted.length || fatal || stopReason) ? 'incomplete' : 'complete');
1448
+ report.status = finalStatus;
1007
1449
  report.stop_reason = stopReason;
1008
1450
  saveProgress();
1009
1451
  taskList.advance(3);
1010
1452
 
1453
+ if (flow) {
1454
+ try {
1455
+ const finishedAt = new Date().toISOString();
1456
+ const summary = {
1457
+ run_id: batchId,
1458
+ run_dir: runDir,
1459
+ started_at: new Date(startedAt).toISOString(),
1460
+ finished_at: finishedAt,
1461
+ status: finalStatus,
1462
+ target_per_kind: targetPerKind,
1463
+ kinds,
1464
+ imported: importedTotal,
1465
+ batches: batchCount,
1466
+ };
1467
+ flow.status = finalStatus === 'complete' ? 'generated' : (finalStatus === 'aborted' ? 'aborted' : 'incomplete');
1468
+ flow.last_run = summary;
1469
+ flow.runs = [...(Array.isArray(flow.runs) ? flow.runs : []), summary].slice(-20);
1470
+ writeMaterialFlow(root, flow);
1471
+ } catch (err) {
1472
+ console.error('[fancy-material] 写入 flow 结果失败:' + (err && err.message ? err.message : String(err)));
1473
+ }
1474
+ }
1475
+
1011
1476
  return notify(session, (aborted || incomplete.length || notStarted.length || stopReason) ? 'error' : 'success', generationRunText({
1012
1477
  database,
1013
- targetPerKind: config.targetPerKind,
1014
- batchSize: config.batchSize,
1478
+ targetPerKind,
1479
+ batchSize,
1015
1480
  elapsedMs: Date.now() - startedAt,
1016
1481
  queue,
1017
1482
  completed,
@@ -1022,6 +1487,8 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
1022
1487
  total,
1023
1488
  progressFile,
1024
1489
  styles: selectedStyles.map((style) => ({ style_key: style.style_key, style_name: style.style_name })),
1490
+ worldTitle: world?.title || '',
1491
+ flowFile: flow ? flowPath(root) : '',
1025
1492
  aborted,
1026
1493
  stopReason,
1027
1494
  }));
@@ -1029,7 +1496,7 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
1029
1496
 
1030
1497
  function materialTaskTitles(invocation) {
1031
1498
  const parsed = splitStyleOption(String(invocation.rawInput || '').trim().split(/\s+/).filter(Boolean));
1032
- const tokens = parsed.tokens;
1499
+ const tokens = parsed.tokens.filter((token) => token !== '--fresh');
1033
1500
  const command = (tokens[0] || '').toLowerCase();
1034
1501
  if (command === 'help' || command === '?') return ['显示素材库帮助'];
1035
1502
  if (command === 'prompt') return ['读取题材列表', '渲染素材提示词'];
@@ -1039,18 +1506,17 @@ function materialTaskTitles(invocation) {
1039
1506
  if (command === 'import') return ['检查备份文件', '导入 SurrealQL'];
1040
1507
  if (command === 'init') return ['检查素材库', '初始化 schema 并部署查询脚本'];
1041
1508
  if (command === 'remove') return ['确认删除范围', '删除素材库数据'];
1042
- const special = new Set(['help', '?', 'load', 'dump', 'export', 'import', 'init', 'remove', 'prompt']);
1043
- if (!special.has(command) && tokens.length >= 2) {
1044
- return ['解析自定义题材与素材类型', '读取已有素材索引', '分批生成并导入素材', '汇总生成结果'];
1509
+ if (command === 'continue' || command === '继续') {
1510
+ return ['读取上次世界母体', '确认本次追加范围', '分批生成并导入素材', '汇总生成结果'];
1045
1511
  }
1046
- return ['解析素材类型与工作区', '读取题材与已有素材索引', '分批生成并导入素材', '汇总生成结果'];
1512
+ return ['读取选题建议与 facet', '选择世界母体', '分批生成并导入素材', '汇总生成结果'];
1047
1513
  }
1048
1514
 
1049
1515
  export async function apply(ctx) {
1050
1516
  registerCommandWithTasks(ctx, {
1051
1517
  name: 'fancy-material',
1052
- description: '🧩 素材库 ( usage: /fancy-material [--style <key>] [素材类型] | load <文件> | dump | export | import | init | remove | prompt | help )',
1053
- input: { hint: '[--style <key>] [素材类型] | load <文件.jsonl> | dump | export [文件.surql] | import [文件.surql]' },
1518
+ description: '🧩 素材库 ( usage: /fancy-material [--style <key>] [--fresh] | continue | load <文件> | dump | export | import | init | remove | prompt | help )',
1519
+ input: { hint: '[--style <key>] [--fresh] | continue | load <文件.jsonl> | dump | export [文件.surql] | import [文件.surql]' },
1054
1520
  handler: async (invocation, taskList) => {
1055
1521
  const session = invocation.agent.session;
1056
1522
  const raw = String(invocation.rawInput || '').trim();
@@ -1058,7 +1524,14 @@ export async function apply(ctx) {
1058
1524
  if (parsedStyle.missing) {
1059
1525
  return notify(session, 'error', '用法:--style <style_key>,多个用逗号分隔;可用 /fancy-douyin list 查看风格 key。');
1060
1526
  }
1061
- const tokens = parsedStyle.tokens;
1527
+ let fresh = false;
1528
+ const tokens = parsedStyle.tokens.filter((token) => {
1529
+ if (token === '--fresh' || token === 'fresh') {
1530
+ fresh = true;
1531
+ return false;
1532
+ }
1533
+ return true;
1534
+ });
1062
1535
  const styleRaw = parsedStyle.styleRaw;
1063
1536
  const command = (tokens[0] || '').toLowerCase();
1064
1537
 
@@ -1101,9 +1574,17 @@ export async function apply(ctx) {
1101
1574
  }
1102
1575
  }
1103
1576
 
1104
- const SPECIAL = new Set(['load', 'dump', 'export', 'import', 'init', 'remove', 'prompt']);
1105
1577
  try {
1106
- if (!command) return await runGenerate(ctx, invocation, session, '', taskList, { styleRaw });
1578
+ if (!command) {
1579
+ return await runInteractive(ctx, invocation, session, taskList, { styleRaw, fresh });
1580
+ }
1581
+ if (command === 'continue' || command === '继续') {
1582
+ if (tokens.length > 1) {
1583
+ return notify(session, 'error', '用法:/fancy-material continue(不接受额外参数)');
1584
+ }
1585
+ if (fresh) return await runInteractive(ctx, invocation, session, taskList, { styleRaw, fresh });
1586
+ return await runContinue(ctx, invocation, session, taskList, { styleRaw });
1587
+ }
1107
1588
  if (command === 'load') {
1108
1589
  if (tokens.length < 2) return notify(session, 'error', '用法:/fancy-material load <文件.jsonl>');
1109
1590
  return await runLoad(ctx, invocation, session, tokens.slice(1).join(' '), taskList);
@@ -1126,26 +1607,12 @@ export async function apply(ctx) {
1126
1607
  if (tokens.length > 1) return notify(session, 'error', '用法:/fancy-material remove(不接受额外参数)');
1127
1608
  return await runRemove(ctx, invocation, session, taskList);
1128
1609
  }
1129
- // 两参数形式:/fancy-material <题材> <素材类型>。
1130
- // 题材和素材类型都可以随便写;source 记 other,不占用内置目录。
1131
- if (!SPECIAL.has(command) && tokens.length >= 2) {
1132
- const genre = stripQuotes(tokens[0]);
1133
- const materialTypeRaw = stripQuotes(tokens.slice(1).join(' '));
1134
- if (!genre || !materialTypeRaw) {
1135
- return notify(session, 'error', '用法:/fancy-material <题材> <素材类型|all>(两个参数都不能为空)');
1136
- }
1137
- const allKinds = materialTypeRaw.toLowerCase() === 'all';
1138
- return await runGenerate(ctx, invocation, session, '', taskList, {
1139
- custom: {
1140
- genre,
1141
- materialType: allKinds ? 'all' : materialTypeRaw,
1142
- allKinds,
1143
- },
1144
- styleRaw,
1145
- });
1146
- }
1147
- // 其它单参数视为素材类型重点,例如 /fancy-material 地名
1148
- return await runGenerate(ctx, invocation, session, tokens.join(' '), taskList, { styleRaw });
1610
+ return notify(session, 'error', [
1611
+ '❌ 旧的素材类型/题材参数已移除:' + tokens.join(' '),
1612
+ '现在用交互式流程:/fancy-material',
1613
+ '继续上次世界:/fancy-material continue',
1614
+ '重新构建世界:/fancy-material --fresh',
1615
+ ].join('\n'));
1149
1616
  } catch (err) {
1150
1617
  return notify(session, 'error', '❌ ' + (err && err.message ? err.message : String(err)));
1151
1618
  }