@cloud411716/fancy-webnovel 4.29.1 → 4.30.1

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.
@@ -29,8 +29,9 @@ 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
+ import { renderGenreBlock } from './genre-playbooks.js';
32
33
  import { buildExistingIndex, countByKind, countKind } from './inventory.js';
33
- import { KIND_LABELS, MATERIAL_KINDS, focusBlock, renderKindTable } from './kinds.js';
34
+ import { KIND_LABELS, MATERIAL_KINDS, focusBlock, renderKindBlock, renderKindTable } from './kinds.js';
34
35
  import { loadStyleRegistry, selectStyles, styleBatchSummary, stylePromptBlock, styleSummaryText } from './styles.js';
35
36
  import {
36
37
  EMPTY_FACET_LABEL,
@@ -56,19 +57,22 @@ import {
56
57
  writeMaterialFlow,
57
58
  } from './world.js';
58
59
  import { exportMaterialDatabase, importMaterialDatabase } from './native-backup.js';
59
- import { nextBatchRequest, planMaterialQueue } from './queue.js';
60
+ import { nextBatchRequest } from './queue.js';
61
+ import { ABILITY_CORE_KINDS, buildGenerationItems, planGenerationQueue } from './plan.js';
60
62
  import { deployMaterialTools } from './tool-deploy.js';
61
63
  import {
62
64
  DEFAULT_BATCH_SIZE,
63
65
  DEFAULT_TARGET_PER_KIND,
64
66
  dumpResultText,
65
67
  generationPrompt,
68
+ abilityCorePrompt,
66
69
  generationRunText,
67
70
  helpText,
68
71
  loadResultText,
69
72
  nativeExportResultText,
70
73
  nativeImportResultText,
71
74
  promptDisplayText,
75
+ rankLadderPrompt,
72
76
  renderPrompt,
73
77
  validationFailedText,
74
78
  } from './templates.js';
@@ -147,6 +151,8 @@ function renderBasePrompt({
147
151
  styleBlock = '',
148
152
  styleRules = '',
149
153
  worldBlock = '',
154
+ kindBlock = '',
155
+ genreBlock = '',
150
156
  audience = '',
151
157
  }) {
152
158
  const sourceFixed = mode === 'other' ? 'other' : 'builtin';
@@ -161,6 +167,8 @@ function renderBasePrompt({
161
167
  GENRES: (genres || []).join('、') || '(未限制,按世界母体推导)',
162
168
  TOPIC_FILE: topicFile || '(无)',
163
169
  KIND_TABLE: renderKindTable(),
170
+ KIND_BLOCK: kindBlock || '(本批未指定 kind;按本次运行说明执行。)',
171
+ GENRE_BLOCK: genreBlock || '(本次未提供题材专属规则;按世界母体和 kind 要求执行。)',
164
172
  FOCUS_BLOCK: focusBlockText || focusBlock(focus),
165
173
  TARGET_PER_KIND: String(targetPerKind),
166
174
  BATCH_SIZE: String(batchSize),
@@ -352,6 +360,85 @@ function sourceCoverageProblem(file, expectedSource = 'builtin') {
352
360
  + '。请把 source 改成 builtin,或省略 source(数据库默认 builtin)。';
353
361
  }
354
362
 
363
+ function readJsonlRecords(file) {
364
+ let text;
365
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
366
+ const records = [];
367
+ for (const line of text.split(/\r?\n/)) {
368
+ const value = line.trim();
369
+ if (!value) continue;
370
+ try { records.push(JSON.parse(value)); } catch { /* validation reports it */ }
371
+ }
372
+ return records;
373
+ }
374
+
375
+ function metadataCoverageProblem(file, { worldId = '', subkind = '', groupId = '' } = {}) {
376
+ if (!worldId && !subkind && !groupId) return '';
377
+ const records = readJsonlRecords(file);
378
+ const bad = [];
379
+ for (let i = 0; i < records.length; i += 1) {
380
+ const record = records[i];
381
+ const missing = [];
382
+ if (worldId && String(record.world_id || '') !== worldId) missing.push('world_id');
383
+ if (subkind && String(record.subkind || '') !== subkind) missing.push('subkind');
384
+ if (groupId && String(record.group_id || '') !== groupId) missing.push('group_id');
385
+ if (missing.length) bad.push(`第 ${i + 1} 条「${record.name || record.id || '未命名'}」缺 ${missing.join('、')}`);
386
+ }
387
+ if (!bad.length) return '';
388
+ return '以下素材没有写本次要求的元数据:' + bad.slice(0, 8).join(';')
389
+ + (bad.length > 8 ? `等 ${bad.length} 条` : '')
390
+ + '。world_id/subkind/group_id 必须逐条原样写入。';
391
+ }
392
+
393
+ function groupCoverageProblem(file, item, groupId) {
394
+ const records = readJsonlRecords(file);
395
+ if (!records.length) return '文件里没有素材记录';
396
+ if (item.mode === 'ability_core') {
397
+ const expected = new Set(item.kinds || ABILITY_CORE_KINDS);
398
+ if (records.length !== expected.size) {
399
+ return `能力核心组必须恰好 ${expected.size} 条,当前 ${records.length} 条;机制/发动/代价/限制/反制/来源各一条。`;
400
+ }
401
+ const kinds = new Set();
402
+ const groups = new Set();
403
+ for (const record of records) {
404
+ const kind = String(record.kind || '');
405
+ if (!expected.has(kind)) return `能力核心组出现了不应有的 kind:${kind}`;
406
+ if (kinds.has(kind)) return `能力核心组重复了 kind:${kind}`;
407
+ kinds.add(kind);
408
+ groups.add(String(record.group_id || ''));
409
+ if (String(record.subkind || '') !== item.subkind) return `能力核心组的 subkind 必须是:${item.subkind}`;
410
+ if (groupId && String(record.group_id || '') !== groupId) return `能力核心组的 group_id 必须是:${groupId}`;
411
+ }
412
+ if (groups.size !== 1) return '能力核心组的所有记录必须共用同一个 group_id';
413
+ return '';
414
+ }
415
+ if (item.mode === 'rank_ladder') {
416
+ if (records.length < 8 || records.length > 12) {
417
+ return `等级阶梯需要 8–12 级,当前 ${records.length} 级。`;
418
+ }
419
+ if (item.kind && records.some((record) => String(record.kind || '') !== item.kind)) {
420
+ return `等级阶梯的所有记录 kind 必须是 ${item.kind}`;
421
+ }
422
+ const groups = new Set(records.map((record) => String(record.group_id || '')));
423
+ if (groups.size !== 1 || (groupId && !groups.has(groupId))) {
424
+ return `等级阶梯的所有记录必须共用 group_id:${groupId}`;
425
+ }
426
+ if (item.subkind && records.some((record) => String(record.subkind || '') !== item.subkind)) {
427
+ return `等级阶梯的所有记录 subkind 必须是:${item.subkind}`;
428
+ }
429
+ const orders = records.map((record) => Number(record.rank_order)).sort((a, b) => a - b);
430
+ if (orders.some((value) => !Number.isInteger(value) || value < 1)) {
431
+ return '等级阶梯的 rank_order 必须是正整数';
432
+ }
433
+ const expectedOrder = Array.from({ length: records.length }, (_, i) => i + 1);
434
+ if (orders.some((value, i) => value !== expectedOrder[i])) {
435
+ return '等级阶梯的 rank_order 必须从 1 开始连续递增,不能断号或重复';
436
+ }
437
+ return '';
438
+ }
439
+ return '';
440
+ }
441
+
355
442
  /**
356
443
  * 自定义素材第一轮没有预设 kind:由 LLM 自己选。
357
444
  * 这里检查同一批是否只出现一个 kind,并把该 kind 返回给插件,
@@ -1020,6 +1107,24 @@ async function runContinue(ctx, invocation, session, taskList, opts = {}) {
1020
1107
  });
1021
1108
  }
1022
1109
 
1110
+ function kindBlockForItem(item) {
1111
+ if (!item) return '';
1112
+ if (item.mode === 'ability_core') {
1113
+ const list = Array.isArray(item.kinds) && item.kinds.length ? item.kinds : [];
1114
+ return [
1115
+ '本批是能力核心组:六条记录必须指向同一个能力,且互相解释。',
1116
+ ...list.map((kind) => renderKindBlock(kind)),
1117
+ ].join('\n\n');
1118
+ }
1119
+ if (item.mode === 'rank_ladder') {
1120
+ return [
1121
+ renderKindBlock(item.kind),
1122
+ '本批是一套完整等级阶梯:每级一条,rank_order 从 1 开始连续递增。',
1123
+ ].join('\n\n');
1124
+ }
1125
+ return renderKindBlock(item.kind);
1126
+ }
1127
+
1023
1128
  export async function runGenerationWithPlan(ctx, invocation, session, taskList, opts = {}) {
1024
1129
  const root = opts.root || workspaceOf(session);
1025
1130
  const plan = opts.plan || {};
@@ -1030,6 +1135,8 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1030
1135
  const targetPerKind = Math.max(1, Number(opts.targetPerKind) || generationConfig().targetPerKind);
1031
1136
  const batchSize = Math.max(1, Number(opts.batchSize) || generationConfig().batchSize);
1032
1137
  const genres = [...new Set((plan.genres || []).filter(Boolean))];
1138
+ const worldId = String(world?.world_id || '');
1139
+ const selectedKinds = [...new Set((plan.kinds || []).filter((kind) => MATERIAL_KINDS.includes(kind)))];
1033
1140
 
1034
1141
  await ensureMaterialDatabase(root);
1035
1142
  const tools = deployMaterialTools(root);
@@ -1055,15 +1162,18 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1055
1162
  ? '本次使用账号风格:' + styleSummaryText(selectedStyles) + ';风格核心优先于题材命名体例。'
1056
1163
  : '未指定账号风格(执行通用创作标准)。';
1057
1164
  const styleSummary = styleBatchSummary(selectedStyles);
1058
- const counts = await countByKind(root, genres);
1059
- const kinds = [...new Set((plan.kinds || []).filter((kind) => MATERIAL_KINDS.includes(kind)))];
1060
- if (!kinds.length) {
1165
+
1166
+ if (!selectedKinds.length) {
1061
1167
  return notify(session, 'error', '❌ 本次没有可生成的 kind。');
1062
1168
  }
1063
- const planned = planMaterialQueue({ kinds, target: targetPerKind });
1064
- const scopeBlockText = '本次世界母体生成范围:'
1065
- + kinds.map((kind) => `\`${kind}\`(${KIND_LABELS[kind] || kind})`).join('、')
1066
- + '。插件只按这个范围排队;不要生成未选中的 kind。';
1169
+ const planned = planGenerationQueue(buildGenerationItems({
1170
+ kinds: selectedKinds,
1171
+ world,
1172
+ targetPerKind,
1173
+ }));
1174
+ if (!planned.all.length) {
1175
+ return notify(session, 'error', '❌ 本次没有可生成的项目。');
1176
+ }
1067
1177
 
1068
1178
  const startedAt = Date.now();
1069
1179
  const batchId = batchIdOfNow();
@@ -1087,7 +1197,10 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1087
1197
  facetLabels,
1088
1198
  constraintGenres: genres,
1089
1199
  });
1090
- const base = renderBasePrompt({
1200
+ const scopeBlockText = '本次世界母体生成范围:'
1201
+ + planned.all.map((item) => `\`${item.kind || item.mode}\`(${item.label})`).join('、')
1202
+ + '。插件只按这个范围排队;不要生成未选中的 kind。';
1203
+ const baseForItem = (item) => renderBasePrompt({
1091
1204
  mode: 'world',
1092
1205
  genres,
1093
1206
  topicFile: plan.topicFile || '(无)',
@@ -1104,12 +1217,29 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1104
1217
  styleBlock,
1105
1218
  styleRules,
1106
1219
  worldBlock,
1220
+ kindBlock: kindBlockForItem(item),
1221
+ genreBlock: renderGenreBlock(genres),
1107
1222
  });
1108
1223
 
1224
+ // 先统计已有数量,再进入队列。
1225
+ for (const item of planned.all) {
1226
+ if (item.mode === 'kind') {
1227
+ try { item.db_existing = await countKind(root, item.kind, genres, item.subkind || ''); } catch { item.db_existing = 0; }
1228
+ } else {
1229
+ item.db_existing = 0;
1230
+ }
1231
+ }
1232
+
1109
1233
  const queue = planned.all.map((item) => ({
1234
+ mode: item.mode,
1110
1235
  kind: item.kind,
1111
- label: KIND_LABELS[item.kind] || item.kind,
1112
- db_existing: Number(counts[item.kind]) || 0,
1236
+ kinds: item.kinds || [],
1237
+ subkind: item.subkind || '',
1238
+ group_id: item.group_id || '',
1239
+ groupPrefix: item.groupPrefix || '',
1240
+ levels: item.levels || 0,
1241
+ label: item.label,
1242
+ db_existing: item.db_existing,
1113
1243
  generated: item.generated,
1114
1244
  target: item.target,
1115
1245
  remaining: item.remaining,
@@ -1138,6 +1268,9 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1138
1268
  title: world.title,
1139
1269
  core_conflict: world.core_conflict,
1140
1270
  cost: world.cost,
1271
+ ability_categories: world.ability_categories,
1272
+ faction_types: world.faction_types,
1273
+ power_systems: world.power_systems,
1141
1274
  } : null,
1142
1275
  facets,
1143
1276
  facet_labels: facetLabels,
@@ -1163,14 +1296,25 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1163
1296
  flow.topic_genre = plan.topicGenre;
1164
1297
  flow.world = world;
1165
1298
  flow.styles = { mode: opts.styleMode || 'auto', keys: selectedStyles.map((style) => style.style_key) };
1166
- flow.scope = { kinds, target_per_kind: targetPerKind };
1299
+ flow.scope = {
1300
+ kinds: selectedKinds,
1301
+ target_per_kind: targetPerKind,
1302
+ items: planned.all.map((item) => ({
1303
+ mode: item.mode,
1304
+ kind: item.kind,
1305
+ kinds: item.kinds || [],
1306
+ subkind: item.subkind || '',
1307
+ target: item.target,
1308
+ label: item.label,
1309
+ })),
1310
+ };
1167
1311
  flow.last_run = {
1168
1312
  run_id: batchId,
1169
1313
  run_dir: runDir,
1170
1314
  started_at: new Date(startedAt).toISOString(),
1171
1315
  status: 'running',
1172
1316
  target_per_kind: targetPerKind,
1173
- kinds,
1317
+ kinds: selectedKinds,
1174
1318
  imported: 0,
1175
1319
  };
1176
1320
  writeMaterialFlow(root, flow);
@@ -1203,32 +1347,89 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1203
1347
  let aborted = false;
1204
1348
  let fatal = false;
1205
1349
  let kindFailureStreak = 0;
1206
- const maxBatchesPerKind = Math.max(1, Math.ceil(targetPerKind / batchSize) * 4);
1350
+
1351
+ const validateBatch = async (file, item, groupId) => {
1352
+ const checked = await checkFile(file);
1353
+ if (checked.code !== 0) return { ok: false, detail: scriptDetail(checked) };
1354
+ const genreProblem = genreCoverageProblem(file, genres);
1355
+ if (genreProblem) return { ok: false, detail: genreProblem };
1356
+ if (item.mode === 'ability_core' || item.mode === 'rank_ladder') {
1357
+ const groupProblem = groupCoverageProblem(file, item, groupId);
1358
+ if (groupProblem) return { ok: false, detail: groupProblem };
1359
+ } else {
1360
+ const kindProblem = kindCoverageProblem(file, item.kind);
1361
+ if (kindProblem) return { ok: false, detail: kindProblem };
1362
+ }
1363
+ const sourceProblem = sourceCoverageProblem(file, 'builtin');
1364
+ if (sourceProblem) return { ok: false, detail: sourceProblem };
1365
+ const metadataProblem = metadataCoverageProblem(file, {
1366
+ worldId,
1367
+ subkind: item.subkind || '',
1368
+ groupId: item.mode === 'kind' ? (item.group_id || '') : groupId,
1369
+ });
1370
+ if (metadataProblem) return { ok: false, detail: metadataProblem };
1371
+ return { ok: true, records: readJsonlRecords(file) };
1372
+ };
1373
+
1374
+ const acceptBatch = async (file, item, groupId) => {
1375
+ try {
1376
+ await importFile(root, file, { noPrefetch: true });
1377
+ } catch (err) {
1378
+ return { ok: false, fatal: true, detail: (err && err.message ? err.message : String(err)) };
1379
+ }
1380
+ if (item.mode === 'ability_core' || item.mode === 'rank_ladder') {
1381
+ const imported = readJsonlRecords(file).length;
1382
+ item.generated += 1;
1383
+ item.batches += 1;
1384
+ item.imported += imported;
1385
+ importedTotal += imported;
1386
+ batchCount += 1;
1387
+ item.remaining = Math.max(0, item.target - item.generated);
1388
+ return { ok: true, imported, generated: item.generated };
1389
+ }
1390
+ const beforeCount = item.db_existing;
1391
+ const afterCount = await countKind(root, item.kind, genres, item.subkind || '');
1392
+ const imported = Math.max(0, afterCount - beforeCount);
1393
+ item.db_existing = afterCount;
1394
+ item.generated += imported;
1395
+ item.batches += 1;
1396
+ importedTotal += imported;
1397
+ batchCount += 1;
1398
+ item.imported += imported;
1399
+ item.remaining = Math.max(0, item.target - item.generated);
1400
+ return { ok: true, imported, generated: item.generated };
1401
+ };
1207
1402
 
1208
1403
  for (let index = 0; index < pending.length; index += 1) {
1209
1404
  const item = pending[index];
1405
+ const base = baseForItem(item);
1210
1406
  taskList.progress(`分批生成并导入素材(${index + 1}/${pending.length}:${item.label})`);
1211
1407
  item.status = 'running';
1212
1408
  let stalled = 0;
1213
1409
  let lastReason = '';
1410
+ const maxBatches = item.mode === 'kind'
1411
+ ? Math.max(1, Math.ceil(item.target / batchSize) * 4)
1412
+ : Math.max(2, item.target * 3);
1214
1413
 
1215
- while (item.generated < targetPerKind && item.batches < maxBatchesPerKind) {
1414
+ while (item.generated < item.target && item.batches < maxBatches) {
1216
1415
  if (abortRequested(invocation)) {
1217
1416
  aborted = true;
1218
1417
  lastReason = '用户中断';
1219
1418
  break;
1220
1419
  }
1221
- const next = nextBatchRequest({
1222
- generated: item.generated,
1223
- target: targetPerKind,
1224
- batchSize,
1225
- });
1420
+ const isGroup = item.mode === 'ability_core' || item.mode === 'rank_ladder';
1421
+ const next = isGroup
1422
+ ? { requestCount: 1, remaining: item.target - item.generated }
1423
+ : nextBatchRequest({ generated: item.generated, target: item.target, batchSize });
1226
1424
  if (!next.requestCount) break;
1227
1425
 
1228
1426
  const batchNo = item.batches + 1;
1427
+ const groupId = isGroup
1428
+ ? `${item.groupPrefix}_${String(item.generated + 1).padStart(2, '0')}_v4`
1429
+ : '';
1229
1430
  const file = path.join(
1230
1431
  runDir,
1231
- String(index + 1).padStart(3, '0') + '_' + item.kind + '_' + String(batchNo).padStart(2, '0') + '.jsonl',
1432
+ String(index + 1).padStart(3, '0') + '_' + (item.kind || item.mode) + '_' + String(batchNo).padStart(2, '0') + '.jsonl',
1232
1433
  );
1233
1434
  const includeBase = batchNo === 1 || batchNo % FULL_PROMPT_EVERY === 1;
1234
1435
  let attemptDetail = '';
@@ -1242,37 +1443,95 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1242
1443
  let before = null;
1243
1444
  try { before = fs.readFileSync(file, 'utf8'); } catch { /* first attempt */ }
1244
1445
 
1245
- const prompt = generationPrompt({
1246
- base,
1247
- target: file,
1248
- workspace: root,
1249
- batchId,
1250
- attempt,
1251
- failures: attemptDetail ? [attemptDetail] : [],
1252
- mode: 'world',
1253
- genres,
1254
- focus: null,
1255
- targetPerKind,
1256
- batchSize,
1257
- kind: item.kind,
1258
- kindLabel: item.label,
1259
- kindIndex: index + 1,
1260
- kindTotal: pending.length,
1261
- generated: item.generated,
1262
- dbExisting: item.db_existing,
1263
- requestCount: next.requestCount,
1264
- includeBase,
1265
- validateScript: tools.validateScript,
1266
- queryScript: tools.queryScript,
1267
- existingIndex: existing.file,
1268
- existingTotal: existing.count,
1269
- custom: null,
1270
- customKindPending: false,
1271
- sourceFixed: 'builtin',
1272
- styleSummary,
1273
- worldBlock,
1274
- worldSummary,
1275
- });
1446
+ let prompt;
1447
+ if (item.mode === 'ability_core') {
1448
+ prompt = abilityCorePrompt({
1449
+ base,
1450
+ target: file,
1451
+ workspace: root,
1452
+ batchId,
1453
+ attempt,
1454
+ failures: attemptDetail ? [attemptDetail] : [],
1455
+ genres,
1456
+ category: item.subkind,
1457
+ groupId,
1458
+ worldId,
1459
+ targetSets: item.target,
1460
+ generatedSets: item.generated,
1461
+ requestSets: 1,
1462
+ includeBase,
1463
+ validateScript: tools.validateScript,
1464
+ queryScript: tools.queryScript,
1465
+ existingIndex: existing.file,
1466
+ existingTotal: existing.count,
1467
+ styleSummary,
1468
+ worldBlock,
1469
+ worldSummary,
1470
+ });
1471
+ } else if (item.mode === 'rank_ladder') {
1472
+ prompt = rankLadderPrompt({
1473
+ base,
1474
+ target: file,
1475
+ workspace: root,
1476
+ batchId,
1477
+ attempt,
1478
+ failures: attemptDetail ? [attemptDetail] : [],
1479
+ genres,
1480
+ kind: item.kind,
1481
+ kindLabel: KIND_LABELS[item.kind] || item.kind,
1482
+ subkind: item.subkind,
1483
+ groupId,
1484
+ worldId,
1485
+ targetSets: item.target,
1486
+ generatedSets: item.generated,
1487
+ requestSets: 1,
1488
+ levels: item.levels || 10,
1489
+ includeBase,
1490
+ validateScript: tools.validateScript,
1491
+ queryScript: tools.queryScript,
1492
+ existingIndex: existing.file,
1493
+ existingTotal: existing.count,
1494
+ styleSummary,
1495
+ worldBlock,
1496
+ worldSummary,
1497
+ });
1498
+ } else {
1499
+ prompt = generationPrompt({
1500
+ base,
1501
+ target: file,
1502
+ workspace: root,
1503
+ batchId,
1504
+ attempt,
1505
+ failures: attemptDetail ? [attemptDetail] : [],
1506
+ mode: 'world',
1507
+ genres,
1508
+ focus: null,
1509
+ targetPerKind: item.target,
1510
+ batchSize,
1511
+ kind: item.kind,
1512
+ kindLabel: item.label,
1513
+ kindIndex: index + 1,
1514
+ kindTotal: pending.length,
1515
+ generated: item.generated,
1516
+ dbExisting: item.db_existing,
1517
+ requestCount: next.requestCount,
1518
+ includeBase,
1519
+ validateScript: tools.validateScript,
1520
+ queryScript: tools.queryScript,
1521
+ existingIndex: existing.file,
1522
+ existingTotal: existing.count,
1523
+ custom: null,
1524
+ customKindPending: false,
1525
+ sourceFixed: 'builtin',
1526
+ styleSummary,
1527
+ worldBlock,
1528
+ worldSummary,
1529
+ subkind: item.subkind || '',
1530
+ groupId: item.group_id || '',
1531
+ worldId,
1532
+ });
1533
+ }
1534
+
1276
1535
  const sent = await llmFollowup(invocation, prompt, { appendTempRule: false });
1277
1536
  if (!sent || sent.ok !== true) {
1278
1537
  fatal = true;
@@ -1287,44 +1546,33 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1287
1546
  }
1288
1547
  if (!waited.ok && waited.code === 'TIMEOUT') {
1289
1548
  if (fs.existsSync(file)) {
1290
- const checked = await checkFile(file);
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') : '';
1294
- if (checked.code === 0 && !genreProblem && !kindProblem && !sourceProblem) {
1295
- try {
1296
- await importFile(root, file, { noPrefetch: true });
1297
- } catch (err) {
1549
+ const checked = await validateBatch(file, item, groupId);
1550
+ if (checked.ok) {
1551
+ const acceptedResult = await acceptBatch(file, item, groupId);
1552
+ if (acceptedResult.fatal) {
1298
1553
  fatal = true;
1299
- stopReason = '等待超时后导入数据库失败:' + (err && err.message ? err.message : String(err));
1554
+ stopReason = '等待超时后导入数据库失败:' + acceptedResult.detail;
1300
1555
  break;
1301
1556
  }
1302
- const beforeCount = item.db_existing;
1303
- const afterCount = await countKind(root, item.kind, genres);
1304
- const imported = Math.max(0, afterCount - beforeCount);
1305
- item.db_existing = afterCount;
1306
- item.generated += imported;
1307
- importedTotal += imported;
1308
- batchCount += 1;
1309
- item.batches = batchNo;
1310
- item.imported += imported;
1311
- item.remaining = Math.max(0, targetPerKind - item.generated);
1557
+ accepted = true;
1312
1558
  try {
1313
1559
  fs.appendFileSync(batchLog, JSON.stringify({
1314
1560
  at: new Date().toISOString(),
1561
+ mode: item.mode,
1315
1562
  kind: item.kind,
1563
+ kinds: item.kinds || [],
1564
+ subkind: item.subkind || '',
1565
+ group_id: groupId || item.group_id || '',
1316
1566
  batch: batchNo,
1317
1567
  file,
1318
1568
  request_count: next.requestCount,
1319
- db_before: beforeCount,
1320
- db_after: afterCount,
1321
- imported,
1569
+ imported: acceptedResult.imported,
1322
1570
  generated: item.generated,
1571
+ target: item.target,
1323
1572
  attempts: attempt,
1324
1573
  timeout_salvage: true,
1325
1574
  }) + '\n');
1326
1575
  } catch { /* best effort */ }
1327
- accepted = true;
1328
1576
  }
1329
1577
  }
1330
1578
  fatal = true;
@@ -1340,60 +1588,36 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1340
1588
  continue;
1341
1589
  }
1342
1590
 
1343
- const checked = await checkFile(file);
1344
- if (checked.code !== 0) {
1345
- attemptDetail = scriptDetail(checked);
1346
- continue;
1347
- }
1348
- const genreProblem = genreCoverageProblem(file, genres);
1349
- if (genreProblem) {
1350
- attemptDetail = genreProblem;
1351
- continue;
1352
- }
1353
- const kindProblem = kindCoverageProblem(file, item.kind);
1354
- if (kindProblem) {
1355
- attemptDetail = kindProblem;
1356
- continue;
1357
- }
1358
- const sourceProblem = sourceCoverageProblem(file, 'builtin');
1359
- if (sourceProblem) {
1360
- attemptDetail = sourceProblem;
1591
+ const checked = await validateBatch(file, item, groupId);
1592
+ if (!checked.ok) {
1593
+ attemptDetail = checked.detail;
1361
1594
  continue;
1362
1595
  }
1363
-
1364
- try {
1365
- await importFile(root, file, { noPrefetch: true });
1366
- } catch (err) {
1596
+ const acceptedResult = await acceptBatch(file, item, groupId);
1597
+ if (acceptedResult.fatal) {
1367
1598
  fatal = true;
1368
- stopReason = '导入数据库失败:' + (err && err.message ? err.message : String(err));
1599
+ stopReason = '导入数据库失败:' + acceptedResult.detail;
1369
1600
  break;
1370
1601
  }
1371
- const beforeCount = item.db_existing;
1372
- const afterCount = await countKind(root, item.kind, genres);
1373
- const imported = Math.max(0, afterCount - beforeCount);
1374
- item.db_existing = afterCount;
1375
- item.generated += imported;
1376
- importedTotal += imported;
1377
- batchCount += 1;
1378
- item.batches = batchNo;
1379
- item.imported += imported;
1380
- item.remaining = Math.max(0, targetPerKind - item.generated);
1602
+ accepted = true;
1381
1603
  try {
1382
1604
  fs.appendFileSync(batchLog, JSON.stringify({
1383
1605
  at: new Date().toISOString(),
1606
+ mode: item.mode,
1384
1607
  kind: item.kind,
1608
+ kinds: item.kinds || [],
1609
+ subkind: item.subkind || '',
1610
+ group_id: groupId || item.group_id || '',
1385
1611
  batch: batchNo,
1386
1612
  file,
1387
1613
  request_count: next.requestCount,
1388
- db_before: beforeCount,
1389
- db_after: afterCount,
1390
- imported,
1614
+ imported: acceptedResult.imported,
1391
1615
  generated: item.generated,
1616
+ target: item.target,
1392
1617
  attempts: attempt,
1393
1618
  }) + '\n');
1394
1619
  } catch { /* best effort */ }
1395
- accepted = true;
1396
- if (imported === 0) {
1620
+ if (acceptedResult.imported === 0) {
1397
1621
  stalled += 1;
1398
1622
  attemptDetail = '本批没有新增素材(可能全是重复),必须写库中不存在的新素材';
1399
1623
  } else {
@@ -1409,15 +1633,15 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1409
1633
  break;
1410
1634
  }
1411
1635
  saveProgress();
1412
- if (item.generated >= targetPerKind) break;
1636
+ if (item.generated >= item.target) break;
1413
1637
  if (stalled >= MAX_STALLED_BATCHES) {
1414
1638
  lastReason = '连续 ' + stalled + ' 批没有新增素材';
1415
1639
  break;
1416
1640
  }
1417
1641
  }
1418
1642
 
1419
- item.remaining = Math.max(0, targetPerKind - item.generated);
1420
- if (item.generated >= targetPerKind) {
1643
+ item.remaining = Math.max(0, item.target - item.generated);
1644
+ if (item.generated >= item.target) {
1421
1645
  item.status = 'done';
1422
1646
  completed.push({ ...item });
1423
1647
  kindFailureStreak = 0;
@@ -1430,7 +1654,7 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1430
1654
  saveProgress();
1431
1655
  if (aborted || fatal) break;
1432
1656
  if (kindFailureStreak >= KIND_FAILURE_STREAK_LIMIT) {
1433
- stopReason = '连续 ' + kindFailureStreak + ' 个 kind 未完成,已停止以免继续空转';
1657
+ stopReason = '连续 ' + kindFailureStreak + ' 个项目未完成,已停止以免继续空转';
1434
1658
  break;
1435
1659
  }
1436
1660
  }
@@ -1441,7 +1665,7 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1441
1665
  report.imported_total = importedTotal;
1442
1666
  report.batches = batchCount;
1443
1667
  const notStarted = queue.filter((item) => item.status === 'pending' || item.status === 'running');
1444
- report.not_started = notStarted.map((item) => item.kind || item.label);
1668
+ report.not_started = notStarted.map((item) => item.label || item.kind || item.mode);
1445
1669
  const finalStatus = aborted
1446
1670
  ? 'aborted'
1447
1671
  : ((incomplete.length || notStarted.length || fatal || stopReason) ? 'incomplete' : 'complete');
@@ -1460,7 +1684,7 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1460
1684
  finished_at: finishedAt,
1461
1685
  status: finalStatus,
1462
1686
  target_per_kind: targetPerKind,
1463
- kinds,
1687
+ kinds: selectedKinds,
1464
1688
  imported: importedTotal,
1465
1689
  batches: batchCount,
1466
1690
  };
@@ -1567,6 +1791,8 @@ export async function apply(ctx) {
1567
1791
  validateScript: VALIDATE_SCRIPT,
1568
1792
  styleBlock,
1569
1793
  styleRules,
1794
+ kindBlock: '(prompt 子命令未指定本批 kind;实际运行时会按当前 kind 注入专属要求。)',
1795
+ genreBlock: renderGenreBlock(genres),
1570
1796
  });
1571
1797
  return notify(session, 'success', promptDisplayText(rendered));
1572
1798
  } catch (err) {