@cloud411716/fancy-webnovel 4.13.1 → 4.15.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.
@@ -144,7 +144,7 @@ FANCY_DOUYIN_SUBAGENTS=0 # 关闭子 Agent,回退单 Agent 串行
144
144
 
145
145
  子 Agent 不操作 Chrome,不修改 `crawled.json`,不运行 `import.js`,也不直接写素材数据库;数据库导入和采集状态只由父进程串行处理,避免并发覆盖。
146
146
 
147
- 采集和分析重叠时,任务列表会同时把“采集作品”和“分析素材”标为进行中:采集行显示已扫描账号数和已入队作品数,分析行显示已分析/已入队和当前并发数。所有账号采集完成后,“采集作品”才标记完成,“分析素材”继续转圈直到子 Agent 队列清空。
147
+ 采集、分析和入库重叠时,任务列表会同时把“采集作品”“分析素材”“写入素材库”标为进行中:采集行显示已扫描账号数和已入队作品数,分析行显示已分析/已入队和当前并发数,写入行显示已写入/已入队作品数。所有账号采集完成后,“采集作品”才标记完成;“分析素材”和“写入素材库”继续转圈,直到所有作品分析、校验和入库完成。
148
148
 
149
149
  子 Agent 是独立的新会话,不继承父 Agent 当前对话。因此 `.tmp` 临时文件规则、完整分析提示词和“不要删除测试文件/不要执行 rm”的约束都会直接写进子 Agent 任务提示,而不是依赖父对话。
150
150
 
@@ -26,6 +26,7 @@ plugins/fancy-material/
26
26
  ├── inventory.js # 已有素材索引、按 kind 计数
27
27
  ├── queue.js # 按 kind 排队、计算每批还差多少
28
28
  ├── exporter.js # 导出 Markdown
29
+ ├── native-backup.js # SurrealQL 原生导出 / 导入
29
30
  ├── scripts/query.js # 生成前查询数据库
30
31
  ├── validate.js # 生成后校验 JSONL 格式
31
32
  └── scripts/...
@@ -344,13 +345,17 @@ DEFINE ANALYZER material_zh
344
345
  /fancy-material 地名 只生成地名类,其它规则仍然有效
345
346
  /fancy-material 人物 生成人物相关 kind
346
347
  /fancy-material 颜色 只生成颜色词
347
- /fancy-material import <文件> 导入 JSONL
348
+ /fancy-material load <文件> 导入 JSONL
349
+ /fancy-material dump 导出 <工作区>/素材库.md
350
+ /fancy-material export [文件] 导出 SurrealDB 原生 SurrealQL 备份(默认 素材库.surql)
351
+ /fancy-material import [文件] 追加导入 SurrealQL 备份;已存在 ID 跳过
348
352
  /fancy-material init 创建/补齐 schema、索引和查询脚本
349
353
  /fancy-material remove 删除整个素材库(需确认)
350
354
  /fancy-material prompt 展示全类型提示词
351
- /fancy-material export 导出 <工作区>/素材库.md
352
355
  ```
353
356
 
357
+ `dump` / `load` 面向 Markdown 清单和 JSONL 素材;`export` / `import` 面向 SurrealDB 原生 SurrealQL 备份。原生备份包含表结构和记录;`import` 会补齐 schema、追加尚不存在的记录,并跳过已经存在的记录 ID,不会覆盖现有素材。
358
+
354
359
  素材题材只认用户选题链路:
355
360
 
356
361
  1. `_novel_topic.json`(最终选题)
@@ -98,11 +98,13 @@ namespace: fancy
98
98
  ```text
99
99
  /fancy-material # 生成全部原子素材类型,按 kind 顺序
100
100
  /fancy-material 地名 # 只生成指定类型(其他质量/题材/追加规则仍保留)
101
- /fancy-material import <文件> # 先校验 JSONL,再追加导入
101
+ /fancy-material load <文件> # 先校验 JSONL,再追加导入
102
+ /fancy-material dump # 导出 A/素材库.md
103
+ /fancy-material export [文件] # 导出 SurrealDB 原生 SurrealQL 备份(默认 素材库.surql)
104
+ /fancy-material import [文件] # 追加导入 SurrealQL 备份;已存在 ID 跳过
102
105
  /fancy-material init # 创建/补齐素材库 schema、索引、查询脚本
103
106
  /fancy-material remove # 删除整个素材库(二次确认)
104
107
  /fancy-material prompt # 展示全类型提示词,不发给 LLM
105
- /fancy-material export # 导出 A/素材库.md
106
108
  ```
107
109
 
108
110
  素材库是工作区级数据库 `material_library`,所有项目共享。每条素材只有
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloud411716/fancy-webnovel",
3
- "version": "4.13.1",
3
+ "version": "4.15.0",
4
4
  "type": "module",
5
5
  "main": "index.js",
6
6
  "exports": {
@@ -1052,14 +1052,20 @@ async function runCrawl(ctx, invocation, session, taskList) {
1052
1052
  let inserted = 0;
1053
1053
  let skippedMaterials = 0;
1054
1054
  let aborted = false;
1055
+ let writeActive = false;
1055
1056
 
1056
1057
  const collectText = () => `采集作品(已扫描 ${scannedAccounts}/${accounts.length},已入队 ${queueStats.queued})`;
1057
1058
  const analysisText = () => queue
1058
1059
  ? `分析素材(已分析 ${queueStats.finished}/${queueStats.queued},并发 ${subagentWorkers})`
1059
1060
  : `分析素材(${queueStats.finished}/${jobs.length})`;
1061
+ const writeText = () => {
1062
+ const total = queue ? queueStats.queued : jobs.length;
1063
+ return `写入素材库(已写入 ${queueStats.finished}/${total})`;
1064
+ };
1060
1065
  const refreshProgress = () => {
1061
1066
  if (taskList.index <= 3) taskList.progressAt(3, collectText());
1062
1067
  if (queue || taskList.index >= 4) taskList.progressAt(4, analysisText());
1068
+ if (writeActive) taskList.progressAt(5, writeText());
1063
1069
  };
1064
1070
 
1065
1071
  const jobRecord = (job, extra = {}) => ({
@@ -1080,6 +1086,10 @@ async function runCrawl(ctx, invocation, session, taskList) {
1080
1086
 
1081
1087
  const finalizeJob = async (job, analyzed) => {
1082
1088
  await withStateLock(async () => {
1089
+ if (!writeActive) {
1090
+ writeActive = true;
1091
+ taskList.activate(5);
1092
+ }
1083
1093
  if (analyzed && analyzed.needsFinalize) {
1084
1094
  analyzed = await finalizeMaterialFile({
1085
1095
  root,
@@ -1703,12 +1713,14 @@ async function runCrawl(ctx, invocation, session, taskList) {
1703
1713
  if (queue) {
1704
1714
  if (taskList.index < 4) {
1705
1715
  taskList.advance(4);
1716
+ if (writeActive) taskList.activate(5);
1706
1717
  refreshProgress();
1707
1718
  }
1708
1719
  queue.close();
1709
1720
  await Promise.all(workerPromises);
1710
1721
  } else if (jobs.length) {
1711
1722
  taskList.advance(4);
1723
+ if (writeActive) taskList.activate(5);
1712
1724
  refreshProgress();
1713
1725
  for (const job of jobs) {
1714
1726
  if (abortRequested(invocation)) { aborted = true; break; }
@@ -68,7 +68,7 @@ export function renderMaterialMarkdown(records, meta = {}) {
68
68
  lines.push('');
69
69
 
70
70
  if (!list.length) {
71
- lines.push('暂无素材。运行 `/fancy-material` 生成,或 `/fancy-material import <文件>` 导入。');
71
+ lines.push('暂无素材。运行 `/fancy-material` 生成,或 `/fancy-material load <文件.jsonl>` 导入。');
72
72
  lines.push('');
73
73
  return lines.join('\n');
74
74
  }
@@ -3,9 +3,11 @@
3
3
  *
4
4
  * Commands:
5
5
  * /fancy-material send the generation prompt, wait for JSONL, validate, import
6
- * /fancy-material import <file> validate then import an existing JSONL
6
+ * /fancy-material load <file> validate then import an existing JSONL
7
7
  * /fancy-material prompt print the prompt without sending it to the LLM
8
- * /fancy-material export export the library to <workspace>/素材库.md
8
+ * /fancy-material dump export the library to <workspace>/素材库.md
9
+ * /fancy-material export [file] export the library as SurrealQL
10
+ * /fancy-material import [file] restore a SurrealQL backup
9
11
  */
10
12
 
11
13
  import fs from 'fs';
@@ -29,16 +31,19 @@ import { exportMaterials } from './exporter.js';
29
31
  import { allKnownGenres } from './genres.js';
30
32
  import { buildExistingIndex, countByKind, countKind } from './inventory.js';
31
33
  import { KIND_LABELS, MATERIAL_KINDS, customFocusBlock, focusBlock, renderKindTable, resolveCustomKinds, resolveFocus } from './kinds.js';
34
+ import { exportMaterialDatabase, importMaterialDatabase } from './native-backup.js';
32
35
  import { nextBatchRequest, planMaterialQueue } from './queue.js';
33
36
  import { deployMaterialTools } from './tool-deploy.js';
34
37
  import {
35
38
  DEFAULT_BATCH_SIZE,
36
39
  DEFAULT_TARGET_PER_KIND,
37
- exportResultText,
40
+ dumpResultText,
38
41
  generationPrompt,
39
42
  generationRunText,
40
43
  helpText,
41
- importResultText,
44
+ loadResultText,
45
+ nativeExportResultText,
46
+ nativeImportResultText,
42
47
  promptDisplayText,
43
48
  renderPrompt,
44
49
  validationFailedText,
@@ -173,6 +178,17 @@ function resolveInputFile(raw, session, root) {
173
178
  return { input: value, file: first };
174
179
  }
175
180
 
181
+ /**
182
+ * Resolve an optional export target. Relative paths are resolved from the
183
+ * session cwd; no argument uses `<workspace>/<fallbackName>`.
184
+ */
185
+ function resolveOutputFile(raw, session, root, fallbackName) {
186
+ const value = stripQuotes(raw);
187
+ if (!value) return path.join(root, fallbackName);
188
+ const cwd = cwdOf(session) || root;
189
+ return resolvePath(value, cwd);
190
+ }
191
+
176
192
  function scriptDetail(result) {
177
193
  const stderr = String(result && result.stderr || '').trim();
178
194
  const stdout = String(result && result.output || '').trim();
@@ -348,11 +364,11 @@ function batchIdOfNow() {
348
364
  return 'material-' + (stamp || String(Date.now()));
349
365
  }
350
366
 
351
- async function runImport(ctx, invocation, session, rawPath, taskList) {
367
+ async function runLoad(ctx, invocation, session, rawPath, taskList) {
352
368
  const root = workspaceOf(session);
353
369
  const { input, file } = resolveInputFile(rawPath, session, root);
354
370
  if (!input || !file) {
355
- return notify(session, 'error', '用法:/fancy-material import <文件.jsonl>');
371
+ return notify(session, 'error', '用法:/fancy-material load <文件.jsonl>');
356
372
  }
357
373
 
358
374
  let stat = null;
@@ -379,7 +395,7 @@ async function runImport(ctx, invocation, session, rawPath, taskList) {
379
395
  }
380
396
  let total;
381
397
  try { total = await materialTotal(root); } catch { total = undefined; }
382
- return notify(session, 'success', importResultText({
398
+ return notify(session, 'success', loadResultText({
383
399
  file,
384
400
  importedText,
385
401
  total,
@@ -437,12 +453,57 @@ async function runRemove(ctx, invocation, session, taskList) {
437
453
  ].join('\n'));
438
454
  }
439
455
 
440
- async function runExport(ctx, invocation, session, taskList) {
456
+ async function runDump(ctx, invocation, session, taskList) {
441
457
  const root = workspaceOf(session);
442
458
  taskList.advance(1);
443
459
  await ensureMaterialDatabase(root);
444
460
  const result = await exportMaterials(root);
445
- return notify(session, 'success', exportResultText(result));
461
+ return notify(session, 'success', dumpResultText(result));
462
+ }
463
+
464
+ async function runNativeExport(ctx, invocation, session, rawPath, taskList) {
465
+ const root = workspaceOf(session);
466
+ const file = resolveOutputFile(rawPath, session, root, '素材库.surql');
467
+ try {
468
+ await ensureMaterialDatabase(root);
469
+ taskList.advance(1);
470
+ const result = await exportMaterialDatabase(root, { file });
471
+ return notify(session, 'success', nativeExportResultText(result));
472
+ } catch (err) {
473
+ return notify(session, 'error', '❌ SurrealDB 导出失败:'
474
+ + (err && err.message ? err.message : String(err))
475
+ + '\n文件:' + file);
476
+ }
477
+ }
478
+
479
+ async function runNativeImport(ctx, invocation, session, rawPath, taskList) {
480
+ const root = workspaceOf(session);
481
+ const resolved = rawPath
482
+ ? resolveInputFile(rawPath, session, root)
483
+ : { input: '素材库.surql', file: path.join(root, '素材库.surql') };
484
+ if (!resolved.input || !resolved.file) {
485
+ return notify(session, 'error', '用法:/fancy-material import [文件.surql]');
486
+ }
487
+ const file = resolved.file;
488
+ let stat = null;
489
+ try { stat = fs.statSync(file); } catch { /* reported below */ }
490
+ if (!stat || !stat.isFile()) {
491
+ return notify(session, 'error', '❌ 未找到 SurrealDB 备份文件,或目标不是普通文件:' + file);
492
+ }
493
+
494
+ taskList.advance(1);
495
+ try {
496
+ const result = await importMaterialDatabase(root, file);
497
+ // 旧备份可能没有最新的任务表或权限,导入后补一次 schema。
498
+ await ensureMaterialDatabase(root);
499
+ let total;
500
+ try { total = await materialTotal(root); } catch { total = undefined; }
501
+ return notify(session, 'success', nativeImportResultText({ ...result, total }));
502
+ } catch (err) {
503
+ return notify(session, 'error', '❌ SurrealDB 导入失败:'
504
+ + (err && err.message ? err.message : String(err))
505
+ + '\n文件:' + file);
506
+ }
446
507
  }
447
508
 
448
509
  async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, opts = {}) {
@@ -908,11 +969,13 @@ function materialTaskTitles(invocation) {
908
969
  const command = (tokens[0] || '').toLowerCase();
909
970
  if (command === 'help' || command === '?') return ['显示素材库帮助'];
910
971
  if (command === 'prompt') return ['读取题材列表', '渲染素材提示词'];
911
- if (command === 'import') return ['校验素材文件', '校验 JSONL 行', '写入素材库'];
912
- if (command === 'export') return ['读取素材库', '导出 JSONL'];
972
+ if (command === 'load') return ['校验素材文件', '校验 JSONL 行', '写入素材库'];
973
+ if (command === 'dump') return ['读取素材库', '导出 Markdown'];
974
+ if (command === 'export') return ['检查素材库', '导出 SurrealQL'];
975
+ if (command === 'import') return ['检查备份文件', '导入 SurrealQL'];
913
976
  if (command === 'init') return ['检查素材库', '初始化 schema 并部署查询脚本'];
914
977
  if (command === 'remove') return ['确认删除范围', '删除素材库数据'];
915
- const special = new Set(['help', '?', 'import', 'export', 'init', 'remove', 'prompt']);
978
+ const special = new Set(['help', '?', 'load', 'dump', 'export', 'import', 'init', 'remove', 'prompt']);
916
979
  if (!special.has(command) && tokens.length >= 2) {
917
980
  return ['解析自定义题材与素材类型', '读取已有素材索引', '分批生成并导入素材', '汇总生成结果'];
918
981
  }
@@ -922,8 +985,8 @@ function materialTaskTitles(invocation) {
922
985
  export async function apply(ctx) {
923
986
  registerCommandWithTasks(ctx, {
924
987
  name: 'fancy-material',
925
- description: '🧩 素材库 ( usage: /fancy-material [素材类型] | import <文件> | init | remove | prompt | export | help )',
926
- input: { hint: '[素材类型] | import <文件> | init | remove | prompt | export' },
988
+ description: '🧩 素材库 ( usage: /fancy-material [素材类型] | load <文件> | dump | export | import | init | remove | prompt | help )',
989
+ input: { hint: '[素材类型] | load <文件.jsonl> | dump | export [文件.surql] | import [文件.surql]' },
927
990
  handler: async (invocation, taskList) => {
928
991
  const session = invocation.agent.session;
929
992
  const raw = String(invocation.rawInput || '').trim();
@@ -955,16 +1018,22 @@ export async function apply(ctx) {
955
1018
  }
956
1019
  }
957
1020
 
958
- const SPECIAL = new Set(['import', 'export', 'init', 'remove', 'prompt']);
1021
+ const SPECIAL = new Set(['load', 'dump', 'export', 'import', 'init', 'remove', 'prompt']);
959
1022
  try {
960
1023
  if (!command) return await runGenerate(ctx, invocation, session, '', taskList);
961
- if (command === 'import') {
962
- if (tokens.length < 2) return notify(session, 'error', '用法:/fancy-material import <文件.jsonl>');
963
- return await runImport(ctx, invocation, session, tokens.slice(1).join(' '), taskList);
1024
+ if (command === 'load') {
1025
+ if (tokens.length < 2) return notify(session, 'error', '用法:/fancy-material load <文件.jsonl>');
1026
+ return await runLoad(ctx, invocation, session, tokens.slice(1).join(' '), taskList);
1027
+ }
1028
+ if (command === 'dump') {
1029
+ if (tokens.length > 1) return notify(session, 'error', '用法:/fancy-material dump(不接受额外参数)');
1030
+ return await runDump(ctx, invocation, session, taskList);
964
1031
  }
965
1032
  if (command === 'export') {
966
- if (tokens.length > 1) return notify(session, 'error', '用法:/fancy-material export(不接受额外参数)');
967
- return await runExport(ctx, invocation, session, taskList);
1033
+ return await runNativeExport(ctx, invocation, session, tokens.slice(1).join(' '), taskList);
1034
+ }
1035
+ if (command === 'import') {
1036
+ return await runNativeImport(ctx, invocation, session, tokens.slice(1).join(' '), taskList);
968
1037
  }
969
1038
  if (command === 'init') {
970
1039
  if (tokens.length > 1) return notify(session, 'error', '用法:/fancy-material init(不接受额外参数)');
@@ -0,0 +1,146 @@
1
+ /**
2
+ * SurrealDB native material-library backup / restore.
3
+ *
4
+ * `surreal export` writes a SurrealQL script containing table definitions,
5
+ * indexes and INSERT statements; `surreal import` replays it. This is the
6
+ * database-level counterpart to the Markdown dump and JSONL load commands.
7
+ */
8
+
9
+ import fs from 'fs';
10
+ import os from 'os';
11
+ import path from 'path';
12
+ import readline from 'readline';
13
+ import { finished } from 'stream/promises';
14
+
15
+ import { spawnScript } from '#infra';
16
+ import { materialDatabaseName } from '#material-db';
17
+ import { findSurrealBinary, rpcUrl, startServer } from '#surreal-server';
18
+ import { readSecrets, readWorkspace } from '#workspace';
19
+
20
+ const NATIVE_TIMEOUT_MS = 15 * 60 * 1000;
21
+
22
+ // SurrealDB 2.3 export emits both `DEFINE FIELD genres` and the auto-created
23
+ // `DEFINE FIELD genres[*]`. Replaying both into an empty database makes the
24
+ // second definition fail with "field already exists". Rewriting definitions to
25
+ // OVERWRITE avoids that conflict and lets a restore replace existing schema.
26
+ const DEFINITION_RE = /^(\s*)DEFINE\s+(TABLE|FIELD|INDEX|FUNCTION|ANALYZER|PARAM|EVENT)\s+(?!OVERWRITE\b|IF\s+NOT\s+EXISTS\b)(.*)$/i;
27
+ const INSERT_RE = /^(\s*)INSERT\s+(\[.*)$/i;
28
+
29
+ function rewriteDefinition(line) {
30
+ return line
31
+ .replace(DEFINITION_RE, (_match, indent, keyword, rest) =>
32
+ `${indent}DEFINE ${keyword.toUpperCase()} OVERWRITE ${rest}`)
33
+ // 原生备份默认用 INSERT,遇到已有记录 ID 会整批失败。IGNORE 让它
34
+ // 只追加缺失记录,已存在的记录原样保留。
35
+ .replace(INSERT_RE, (_match, indent, rest) => `${indent}INSERT IGNORE ${rest}`);
36
+ }
37
+
38
+ async function rewriteForImport(file) {
39
+ const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'fancy-material-import-'));
40
+ const target = path.join(dir, 'backup.surql');
41
+ const input = fs.createReadStream(file, { encoding: 'utf8' });
42
+ const output = fs.createWriteStream(target, { encoding: 'utf8' });
43
+ const lines = readline.createInterface({ input, crlfDelay: Infinity });
44
+ try {
45
+ for await (const line of lines) {
46
+ if (!output.write(rewriteDefinition(line) + '\n')) {
47
+ await new Promise((resolve) => output.once('drain', resolve));
48
+ }
49
+ }
50
+ output.end();
51
+ await finished(output);
52
+ return { dir, file: target };
53
+ } catch (err) {
54
+ output.destroy();
55
+ await fs.promises.rm(dir, { recursive: true, force: true });
56
+ throw err;
57
+ }
58
+ }
59
+
60
+ function controlEnv(root) {
61
+ const secrets = readSecrets(root);
62
+ return {
63
+ ...process.env,
64
+ SURREAL_USER: secrets.surreal?.username || 'root',
65
+ SURREAL_PASS: secrets.surreal?.password || '',
66
+ };
67
+ }
68
+
69
+ function controlDetail(result) {
70
+ const stderr = String(result && result.stderr || '').trim();
71
+ const stdout = String(result && result.output || '').trim();
72
+ return stderr || stdout || String(result && result.error || '').trim()
73
+ || ('退出码 ' + (result && result.code));
74
+ }
75
+
76
+ async function runSurreal(root, args, timeout = NATIVE_TIMEOUT_MS) {
77
+ const binary = findSurrealBinary(root);
78
+ if (!binary) {
79
+ throw new Error('未找到 surreal 可执行文件。请先运行 /fancy-db install,或将 SurrealDB 加入 PATH。');
80
+ }
81
+ await startServer(root);
82
+ const workspace = readWorkspace(root);
83
+ const database = materialDatabaseName(workspace);
84
+ const namespace = workspace.surreal?.namespace || 'fancy';
85
+ const result = await spawnScript(binary, [
86
+ args[0],
87
+ '--endpoint', rpcUrl(workspace),
88
+ '--namespace', namespace,
89
+ '--database', database,
90
+ ...args.slice(1),
91
+ ], {
92
+ timeout,
93
+ cwd: root,
94
+ env: controlEnv(root),
95
+ });
96
+ // `surreal export` writes to a file and prints only logs, so spawnScript's
97
+ // JSON-output heuristic marks it unsuccessful. The exit code is authoritative.
98
+ if (result.code !== 0) {
99
+ throw new Error(controlDetail(result));
100
+ }
101
+ return { result, workspace, namespace, database };
102
+ }
103
+
104
+ /**
105
+ * Export the material database as SurrealQL.
106
+ *
107
+ * @param {string} root workspace directory
108
+ * @param {{file?: string}} [options]
109
+ * @returns {Promise<{file: string, bytes: number, database: string}>}
110
+ */
111
+ export async function exportMaterialDatabase(root, options = {}) {
112
+ const file = path.resolve(options.file || path.join(root, '素材库.surql'));
113
+ fs.mkdirSync(path.dirname(file), { recursive: true });
114
+ const { database } = await runSurreal(root, ['export', file]);
115
+ const stat = fs.statSync(file);
116
+ if (!stat.isFile() || stat.size <= 0) {
117
+ throw new Error('SurrealDB 导出完成,但备份文件不存在或为空:' + file);
118
+ }
119
+ return { file, bytes: stat.size, database };
120
+ }
121
+
122
+ /**
123
+ * Import a SurrealQL backup into the material database.
124
+ *
125
+ * The backup contains its own `DEFINE TABLE` statements, so this command does
126
+ * not initialize the schema first. Existing schema definitions are overwritten,
127
+ * while records use INSERT IGNORE: missing records are appended and records
128
+ * whose IDs already exist are left untouched.
129
+ *
130
+ * @param {string} root workspace directory
131
+ * @param {string} file SurrealQL backup path
132
+ * @returns {Promise<{file: string, bytes: number, database: string}>}
133
+ */
134
+ export async function importMaterialDatabase(root, file) {
135
+ const resolved = path.resolve(file);
136
+ const stat = fs.statSync(resolved);
137
+ if (!stat.isFile()) throw new Error('备份路径不是普通文件:' + resolved);
138
+ if (stat.size <= 0) throw new Error('备份文件为空:' + resolved);
139
+ const rewritten = await rewriteForImport(resolved);
140
+ try {
141
+ const { database } = await runSurreal(root, ['import', rewritten.file]);
142
+ return { file: resolved, bytes: stat.size, database };
143
+ } finally {
144
+ await fs.promises.rm(rewritten.dir, { recursive: true, force: true });
145
+ }
146
+ }
@@ -25,11 +25,13 @@ export function helpText() {
25
25
  /fancy-material <素材类型> 只生成指定类型,例如:/fancy-material 地名
26
26
  /fancy-material <题材> <素材类型> 自定义题材+素材类型,source=other,例如:/fancy-material 都市高武 地名
27
27
  /fancy-material <题材> all 生成该题材下全部 58 个 kind,source=other,例如:/fancy-material 都市高武 all
28
- /fancy-material import <文件> 导入 JSONL;导入前先校验格式
28
+ /fancy-material load <文件.jsonl> 导入 JSONL;导入前先校验格式
29
29
  /fancy-material init 创建/补齐素材库 schema、索引和查询/校验脚本
30
30
  /fancy-material remove 删除整个素材库(会二次确认)
31
31
  /fancy-material prompt 展示全类型提示词,不发送给 LLM
32
- /fancy-material export 把素材库导出为 <工作区>/素材库.md
32
+ /fancy-material dump 把素材库导出为 <工作区>/素材库.md
33
+ /fancy-material export [文件.surql] 导出 SurrealDB 原生备份,默认 <工作区>/素材库.surql
34
+ /fancy-material import [文件.surql] 追加导入 SurrealDB 原生备份;已存在 ID 跳过
33
35
  /fancy-material help 显示本帮助
34
36
 
35
37
  说明:
@@ -47,6 +49,8 @@ export function helpText() {
47
49
  - 不设库内上限:运行两次就是每个 kind 累计 100 条;已有素材只用于去重。
48
50
  - 中断后重跑会开始新一轮 50 条配额,已经导入的素材不会撤销。
49
51
  - 只追加,不覆盖;同 kind 同 name 的素材会被跳过。
52
+ - dump / load 面向 Markdown 清单和 JSONL 素材;export / import 面向 SurrealDB 原生 SurrealQL 备份。
53
+ - 原生 import 会补齐 schema,并追加备份中尚不存在的记录;相同记录 ID 已存在时自动跳过,不会覆盖。
50
54
  - 全文索引:name(中文 ngram);tags / genres 精确过滤。
51
55
  - 查询脚本:<工作区>/.fancy-tools/fancy-material/query.js
52
56
  - 校验脚本:<工作区>/.fancy-tools/fancy-material/validate.js
@@ -290,13 +294,13 @@ export function validationFailedText({ file, detail }) {
290
294
  '',
291
295
  String(detail || '').trim(),
292
296
  '',
293
- '修正后请重新运行:/fancy-material import ' + file,
297
+ '修正后请重新运行:/fancy-material load ' + file,
294
298
  ].join('\n');
295
299
  }
296
300
 
297
- export function importResultText({ file, importedText, total, database }) {
301
+ export function loadResultText({ file, importedText, total, database }) {
298
302
  const lines = [
299
- '✅ 素材导入完成',
303
+ '✅ JSONL 素材导入完成',
300
304
  '文件:' + file,
301
305
  ];
302
306
  if (importedText) lines.push(importedText.trim());
@@ -305,17 +309,49 @@ export function importResultText({ file, importedText, total, database }) {
305
309
  return lines.join('\n');
306
310
  }
307
311
 
308
- export function exportResultText({ file, count, kinds }) {
312
+ export function dumpResultText({ file, count, kinds }) {
309
313
  if (!count) {
310
314
  return [
311
- '✅ 素材库已导出(当前素材库为空)',
315
+ '✅ 素材库已导出为 Markdown(当前素材库为空)',
312
316
  '文件:' + file,
313
- '可运行 /fancy-material 生成素材,或运行 /fancy-material import <文件> 导入。',
317
+ '可运行 /fancy-material 生成素材,或运行 /fancy-material load <文件.jsonl> 导入。',
314
318
  ].join('\n');
315
319
  }
316
320
  return [
317
- '✅ 素材库已导出',
321
+ '✅ 素材库已导出为 Markdown',
318
322
  '文件:' + file,
319
323
  '素材:' + count + ' 条 · 类型:' + kinds + ' 个',
320
324
  ].join('\n');
321
325
  }
326
+
327
+ function formatBytes(bytes) {
328
+ const value = Number(bytes);
329
+ if (!Number.isFinite(value) || value < 0) return '';
330
+ if (value < 1024) return value + ' B';
331
+ if (value < 1024 * 1024) return (value / 1024).toFixed(1) + ' KB';
332
+ return (value / 1024 / 1024).toFixed(1) + ' MB';
333
+ }
334
+
335
+ export function nativeExportResultText({ file, bytes, database }) {
336
+ const lines = [
337
+ '✅ 素材库已导出为 SurrealDB 原生备份',
338
+ '文件:' + file,
339
+ ];
340
+ if (database) lines.push('数据库:' + database);
341
+ const size = formatBytes(bytes);
342
+ if (size) lines.push('大小:' + size);
343
+ lines.push('恢复:/fancy-material import ' + file);
344
+ return lines.join('\n');
345
+ }
346
+
347
+ export function nativeImportResultText({ file, bytes, database, total }) {
348
+ const lines = [
349
+ '✅ 已从 SurrealDB 原生备份恢复',
350
+ '文件:' + file,
351
+ ];
352
+ if (database) lines.push('数据库:' + database);
353
+ const size = formatBytes(bytes);
354
+ if (size) lines.push('大小:' + size);
355
+ if (Number.isFinite(total)) lines.push('库中素材:' + total + ' 条');
356
+ return lines.join('\n');
357
+ }