@cloud411716/fancy-webnovel 4.29.0 → 4.30.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.
@@ -117,8 +117,10 @@ export function renderMaterialMarkdown(records, meta = {}) {
117
117
  lines.push('- **tags**:' + valueText(record.tags));
118
118
  lines.push('- **genres**:' + valueText(record.genres));
119
119
  pushFacetLines(lines, record);
120
+ if (record.world_id) lines.push('- **world_id**:' + text(record.world_id));
120
121
  if (record.group_id) lines.push('- **group_id**:' + text(record.group_id));
121
122
  if (record.subkind) lines.push('- **subkind**:' + text(record.subkind));
123
+ if (record.rank_order !== undefined) lines.push('- **rank_order**:' + text(record.rank_order));
122
124
  if (record.source) lines.push('- **source**:' + text(record.source));
123
125
  if (record.note) lines.push('- **note**:' + text(record.note));
124
126
  lines.push('');
@@ -140,8 +142,10 @@ export function renderMaterialMarkdown(records, meta = {}) {
140
142
  lines.push('- **tags**:' + valueText(record.tags));
141
143
  lines.push('- **genres**:' + valueText(record.genres));
142
144
  pushFacetLines(lines, record);
145
+ if (record.world_id) lines.push('- **world_id**:' + text(record.world_id));
143
146
  if (record.group_id) lines.push('- **group_id**:' + text(record.group_id));
144
147
  if (record.subkind) lines.push('- **subkind**:' + text(record.subkind));
148
+ if (record.rank_order !== undefined) lines.push('- **rank_order**:' + text(record.rank_order));
145
149
  if (record.source) lines.push('- **source**:' + text(record.source));
146
150
  if (record.note) lines.push('- **note**:' + text(record.note));
147
151
  lines.push('');
@@ -161,7 +165,7 @@ export function renderMaterialMarkdown(records, meta = {}) {
161
165
  export async function exportMaterials(root) {
162
166
  const { db, database } = await connectMaterial(root);
163
167
  try {
164
- const rows = await db.query('SELECT kind, subkind, name, subject, tags, genres, tropes, narrative, traits, roles, relations, moods, settings, group_id, note, source FROM material ORDER BY kind, subkind, name;');
168
+ const rows = await db.query('SELECT kind, subkind, name, subject, tags, genres, tropes, narrative, traits, roles, relations, moods, settings, world_id, group_id, rank_order, note, source FROM material ORDER BY kind, subkind, rank_order, name;');
165
169
  const records = Array.isArray(rows) && Array.isArray(rows[0]) ? rows[0] : [];
166
170
  const file = path.join(path.resolve(root), '素材库.md');
167
171
  const markdown = renderMaterialMarkdown(records, {
@@ -56,19 +56,22 @@ import {
56
56
  writeMaterialFlow,
57
57
  } from './world.js';
58
58
  import { exportMaterialDatabase, importMaterialDatabase } from './native-backup.js';
59
- import { nextBatchRequest, planMaterialQueue } from './queue.js';
59
+ import { nextBatchRequest } from './queue.js';
60
+ import { ABILITY_CORE_KINDS, buildGenerationItems, planGenerationQueue } from './plan.js';
60
61
  import { deployMaterialTools } from './tool-deploy.js';
61
62
  import {
62
63
  DEFAULT_BATCH_SIZE,
63
64
  DEFAULT_TARGET_PER_KIND,
64
65
  dumpResultText,
65
66
  generationPrompt,
67
+ abilityCorePrompt,
66
68
  generationRunText,
67
69
  helpText,
68
70
  loadResultText,
69
71
  nativeExportResultText,
70
72
  nativeImportResultText,
71
73
  promptDisplayText,
74
+ rankLadderPrompt,
72
75
  renderPrompt,
73
76
  validationFailedText,
74
77
  } from './templates.js';
@@ -352,6 +355,85 @@ function sourceCoverageProblem(file, expectedSource = 'builtin') {
352
355
  + '。请把 source 改成 builtin,或省略 source(数据库默认 builtin)。';
353
356
  }
354
357
 
358
+ function readJsonlRecords(file) {
359
+ let text;
360
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
361
+ const records = [];
362
+ for (const line of text.split(/\r?\n/)) {
363
+ const value = line.trim();
364
+ if (!value) continue;
365
+ try { records.push(JSON.parse(value)); } catch { /* validation reports it */ }
366
+ }
367
+ return records;
368
+ }
369
+
370
+ function metadataCoverageProblem(file, { worldId = '', subkind = '', groupId = '' } = {}) {
371
+ if (!worldId && !subkind && !groupId) return '';
372
+ const records = readJsonlRecords(file);
373
+ const bad = [];
374
+ for (let i = 0; i < records.length; i += 1) {
375
+ const record = records[i];
376
+ const missing = [];
377
+ if (worldId && String(record.world_id || '') !== worldId) missing.push('world_id');
378
+ if (subkind && String(record.subkind || '') !== subkind) missing.push('subkind');
379
+ if (groupId && String(record.group_id || '') !== groupId) missing.push('group_id');
380
+ if (missing.length) bad.push(`第 ${i + 1} 条「${record.name || record.id || '未命名'}」缺 ${missing.join('、')}`);
381
+ }
382
+ if (!bad.length) return '';
383
+ return '以下素材没有写本次要求的元数据:' + bad.slice(0, 8).join(';')
384
+ + (bad.length > 8 ? `等 ${bad.length} 条` : '')
385
+ + '。world_id/subkind/group_id 必须逐条原样写入。';
386
+ }
387
+
388
+ function groupCoverageProblem(file, item, groupId) {
389
+ const records = readJsonlRecords(file);
390
+ if (!records.length) return '文件里没有素材记录';
391
+ if (item.mode === 'ability_core') {
392
+ const expected = new Set(item.kinds || ABILITY_CORE_KINDS);
393
+ if (records.length !== expected.size) {
394
+ return `能力核心组必须恰好 ${expected.size} 条,当前 ${records.length} 条;机制/发动/代价/限制/反制/来源各一条。`;
395
+ }
396
+ const kinds = new Set();
397
+ const groups = new Set();
398
+ for (const record of records) {
399
+ const kind = String(record.kind || '');
400
+ if (!expected.has(kind)) return `能力核心组出现了不应有的 kind:${kind}`;
401
+ if (kinds.has(kind)) return `能力核心组重复了 kind:${kind}`;
402
+ kinds.add(kind);
403
+ groups.add(String(record.group_id || ''));
404
+ if (String(record.subkind || '') !== item.subkind) return `能力核心组的 subkind 必须是:${item.subkind}`;
405
+ if (groupId && String(record.group_id || '') !== groupId) return `能力核心组的 group_id 必须是:${groupId}`;
406
+ }
407
+ if (groups.size !== 1) return '能力核心组的所有记录必须共用同一个 group_id';
408
+ return '';
409
+ }
410
+ if (item.mode === 'rank_ladder') {
411
+ if (records.length < 8 || records.length > 12) {
412
+ return `等级阶梯需要 8–12 级,当前 ${records.length} 级。`;
413
+ }
414
+ if (item.kind && records.some((record) => String(record.kind || '') !== item.kind)) {
415
+ return `等级阶梯的所有记录 kind 必须是 ${item.kind}`;
416
+ }
417
+ const groups = new Set(records.map((record) => String(record.group_id || '')));
418
+ if (groups.size !== 1 || (groupId && !groups.has(groupId))) {
419
+ return `等级阶梯的所有记录必须共用 group_id:${groupId}`;
420
+ }
421
+ if (item.subkind && records.some((record) => String(record.subkind || '') !== item.subkind)) {
422
+ return `等级阶梯的所有记录 subkind 必须是:${item.subkind}`;
423
+ }
424
+ const orders = records.map((record) => Number(record.rank_order)).sort((a, b) => a - b);
425
+ if (orders.some((value) => !Number.isInteger(value) || value < 1)) {
426
+ return '等级阶梯的 rank_order 必须是正整数';
427
+ }
428
+ const expectedOrder = Array.from({ length: records.length }, (_, i) => i + 1);
429
+ if (orders.some((value, i) => value !== expectedOrder[i])) {
430
+ return '等级阶梯的 rank_order 必须从 1 开始连续递增,不能断号或重复';
431
+ }
432
+ return '';
433
+ }
434
+ return '';
435
+ }
436
+
355
437
  /**
356
438
  * 自定义素材第一轮没有预设 kind:由 LLM 自己选。
357
439
  * 这里检查同一批是否只出现一个 kind,并把该 kind 返回给插件,
@@ -1030,6 +1112,8 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1030
1112
  const targetPerKind = Math.max(1, Number(opts.targetPerKind) || generationConfig().targetPerKind);
1031
1113
  const batchSize = Math.max(1, Number(opts.batchSize) || generationConfig().batchSize);
1032
1114
  const genres = [...new Set((plan.genres || []).filter(Boolean))];
1115
+ const worldId = String(world?.world_id || '');
1116
+ const selectedKinds = [...new Set((plan.kinds || []).filter((kind) => MATERIAL_KINDS.includes(kind)))];
1033
1117
 
1034
1118
  await ensureMaterialDatabase(root);
1035
1119
  const tools = deployMaterialTools(root);
@@ -1055,15 +1139,18 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1055
1139
  ? '本次使用账号风格:' + styleSummaryText(selectedStyles) + ';风格核心优先于题材命名体例。'
1056
1140
  : '未指定账号风格(执行通用创作标准)。';
1057
1141
  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) {
1142
+
1143
+ if (!selectedKinds.length) {
1061
1144
  return notify(session, 'error', '❌ 本次没有可生成的 kind。');
1062
1145
  }
1063
- const planned = planMaterialQueue({ kinds, target: targetPerKind });
1064
- const scopeBlockText = '本次世界母体生成范围:'
1065
- + kinds.map((kind) => `\`${kind}\`(${KIND_LABELS[kind] || kind})`).join('、')
1066
- + '。插件只按这个范围排队;不要生成未选中的 kind。';
1146
+ const planned = planGenerationQueue(buildGenerationItems({
1147
+ kinds: selectedKinds,
1148
+ world,
1149
+ targetPerKind,
1150
+ }));
1151
+ if (!planned.all.length) {
1152
+ return notify(session, 'error', '❌ 本次没有可生成的项目。');
1153
+ }
1067
1154
 
1068
1155
  const startedAt = Date.now();
1069
1156
  const batchId = batchIdOfNow();
@@ -1087,6 +1174,9 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1087
1174
  facetLabels,
1088
1175
  constraintGenres: genres,
1089
1176
  });
1177
+ const scopeBlockText = '本次世界母体生成范围:'
1178
+ + planned.all.map((item) => `\`${item.kind || item.mode}\`(${item.label})`).join('、')
1179
+ + '。插件只按这个范围排队;不要生成未选中的 kind。';
1090
1180
  const base = renderBasePrompt({
1091
1181
  mode: 'world',
1092
1182
  genres,
@@ -1106,10 +1196,25 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1106
1196
  worldBlock,
1107
1197
  });
1108
1198
 
1199
+ // 先统计已有数量,再进入队列。
1200
+ for (const item of planned.all) {
1201
+ if (item.mode === 'kind') {
1202
+ try { item.db_existing = await countKind(root, item.kind, genres, item.subkind || ''); } catch { item.db_existing = 0; }
1203
+ } else {
1204
+ item.db_existing = 0;
1205
+ }
1206
+ }
1207
+
1109
1208
  const queue = planned.all.map((item) => ({
1209
+ mode: item.mode,
1110
1210
  kind: item.kind,
1111
- label: KIND_LABELS[item.kind] || item.kind,
1112
- db_existing: Number(counts[item.kind]) || 0,
1211
+ kinds: item.kinds || [],
1212
+ subkind: item.subkind || '',
1213
+ group_id: item.group_id || '',
1214
+ groupPrefix: item.groupPrefix || '',
1215
+ levels: item.levels || 0,
1216
+ label: item.label,
1217
+ db_existing: item.db_existing,
1113
1218
  generated: item.generated,
1114
1219
  target: item.target,
1115
1220
  remaining: item.remaining,
@@ -1138,6 +1243,9 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1138
1243
  title: world.title,
1139
1244
  core_conflict: world.core_conflict,
1140
1245
  cost: world.cost,
1246
+ ability_categories: world.ability_categories,
1247
+ faction_types: world.faction_types,
1248
+ power_systems: world.power_systems,
1141
1249
  } : null,
1142
1250
  facets,
1143
1251
  facet_labels: facetLabels,
@@ -1163,14 +1271,25 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1163
1271
  flow.topic_genre = plan.topicGenre;
1164
1272
  flow.world = world;
1165
1273
  flow.styles = { mode: opts.styleMode || 'auto', keys: selectedStyles.map((style) => style.style_key) };
1166
- flow.scope = { kinds, target_per_kind: targetPerKind };
1274
+ flow.scope = {
1275
+ kinds: selectedKinds,
1276
+ target_per_kind: targetPerKind,
1277
+ items: planned.all.map((item) => ({
1278
+ mode: item.mode,
1279
+ kind: item.kind,
1280
+ kinds: item.kinds || [],
1281
+ subkind: item.subkind || '',
1282
+ target: item.target,
1283
+ label: item.label,
1284
+ })),
1285
+ };
1167
1286
  flow.last_run = {
1168
1287
  run_id: batchId,
1169
1288
  run_dir: runDir,
1170
1289
  started_at: new Date(startedAt).toISOString(),
1171
1290
  status: 'running',
1172
1291
  target_per_kind: targetPerKind,
1173
- kinds,
1292
+ kinds: selectedKinds,
1174
1293
  imported: 0,
1175
1294
  };
1176
1295
  writeMaterialFlow(root, flow);
@@ -1203,7 +1322,58 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1203
1322
  let aborted = false;
1204
1323
  let fatal = false;
1205
1324
  let kindFailureStreak = 0;
1206
- const maxBatchesPerKind = Math.max(1, Math.ceil(targetPerKind / batchSize) * 4);
1325
+
1326
+ const validateBatch = async (file, item, groupId) => {
1327
+ const checked = await checkFile(file);
1328
+ if (checked.code !== 0) return { ok: false, detail: scriptDetail(checked) };
1329
+ const genreProblem = genreCoverageProblem(file, genres);
1330
+ if (genreProblem) return { ok: false, detail: genreProblem };
1331
+ if (item.mode === 'ability_core' || item.mode === 'rank_ladder') {
1332
+ const groupProblem = groupCoverageProblem(file, item, groupId);
1333
+ if (groupProblem) return { ok: false, detail: groupProblem };
1334
+ } else {
1335
+ const kindProblem = kindCoverageProblem(file, item.kind);
1336
+ if (kindProblem) return { ok: false, detail: kindProblem };
1337
+ }
1338
+ const sourceProblem = sourceCoverageProblem(file, 'builtin');
1339
+ if (sourceProblem) return { ok: false, detail: sourceProblem };
1340
+ const metadataProblem = metadataCoverageProblem(file, {
1341
+ worldId,
1342
+ subkind: item.subkind || '',
1343
+ groupId: item.mode === 'kind' ? (item.group_id || '') : groupId,
1344
+ });
1345
+ if (metadataProblem) return { ok: false, detail: metadataProblem };
1346
+ return { ok: true, records: readJsonlRecords(file) };
1347
+ };
1348
+
1349
+ const acceptBatch = async (file, item, groupId) => {
1350
+ try {
1351
+ await importFile(root, file, { noPrefetch: true });
1352
+ } catch (err) {
1353
+ return { ok: false, fatal: true, detail: (err && err.message ? err.message : String(err)) };
1354
+ }
1355
+ if (item.mode === 'ability_core' || item.mode === 'rank_ladder') {
1356
+ const imported = readJsonlRecords(file).length;
1357
+ item.generated += 1;
1358
+ item.batches += 1;
1359
+ item.imported += imported;
1360
+ importedTotal += imported;
1361
+ batchCount += 1;
1362
+ item.remaining = Math.max(0, item.target - item.generated);
1363
+ return { ok: true, imported, generated: item.generated };
1364
+ }
1365
+ const beforeCount = item.db_existing;
1366
+ const afterCount = await countKind(root, item.kind, genres, item.subkind || '');
1367
+ const imported = Math.max(0, afterCount - beforeCount);
1368
+ item.db_existing = afterCount;
1369
+ item.generated += imported;
1370
+ item.batches += 1;
1371
+ importedTotal += imported;
1372
+ batchCount += 1;
1373
+ item.imported += imported;
1374
+ item.remaining = Math.max(0, item.target - item.generated);
1375
+ return { ok: true, imported, generated: item.generated };
1376
+ };
1207
1377
 
1208
1378
  for (let index = 0; index < pending.length; index += 1) {
1209
1379
  const item = pending[index];
@@ -1211,24 +1381,29 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1211
1381
  item.status = 'running';
1212
1382
  let stalled = 0;
1213
1383
  let lastReason = '';
1384
+ const maxBatches = item.mode === 'kind'
1385
+ ? Math.max(1, Math.ceil(item.target / batchSize) * 4)
1386
+ : Math.max(2, item.target * 3);
1214
1387
 
1215
- while (item.generated < targetPerKind && item.batches < maxBatchesPerKind) {
1388
+ while (item.generated < item.target && item.batches < maxBatches) {
1216
1389
  if (abortRequested(invocation)) {
1217
1390
  aborted = true;
1218
1391
  lastReason = '用户中断';
1219
1392
  break;
1220
1393
  }
1221
- const next = nextBatchRequest({
1222
- generated: item.generated,
1223
- target: targetPerKind,
1224
- batchSize,
1225
- });
1394
+ const isGroup = item.mode === 'ability_core' || item.mode === 'rank_ladder';
1395
+ const next = isGroup
1396
+ ? { requestCount: 1, remaining: item.target - item.generated }
1397
+ : nextBatchRequest({ generated: item.generated, target: item.target, batchSize });
1226
1398
  if (!next.requestCount) break;
1227
1399
 
1228
1400
  const batchNo = item.batches + 1;
1401
+ const groupId = isGroup
1402
+ ? `${item.groupPrefix}_${String(item.generated + 1).padStart(2, '0')}_v4`
1403
+ : '';
1229
1404
  const file = path.join(
1230
1405
  runDir,
1231
- String(index + 1).padStart(3, '0') + '_' + item.kind + '_' + String(batchNo).padStart(2, '0') + '.jsonl',
1406
+ String(index + 1).padStart(3, '0') + '_' + (item.kind || item.mode) + '_' + String(batchNo).padStart(2, '0') + '.jsonl',
1232
1407
  );
1233
1408
  const includeBase = batchNo === 1 || batchNo % FULL_PROMPT_EVERY === 1;
1234
1409
  let attemptDetail = '';
@@ -1242,37 +1417,95 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1242
1417
  let before = null;
1243
1418
  try { before = fs.readFileSync(file, 'utf8'); } catch { /* first attempt */ }
1244
1419
 
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
- });
1420
+ let prompt;
1421
+ if (item.mode === 'ability_core') {
1422
+ prompt = abilityCorePrompt({
1423
+ base,
1424
+ target: file,
1425
+ workspace: root,
1426
+ batchId,
1427
+ attempt,
1428
+ failures: attemptDetail ? [attemptDetail] : [],
1429
+ genres,
1430
+ category: item.subkind,
1431
+ groupId,
1432
+ worldId,
1433
+ targetSets: item.target,
1434
+ generatedSets: item.generated,
1435
+ requestSets: 1,
1436
+ includeBase,
1437
+ validateScript: tools.validateScript,
1438
+ queryScript: tools.queryScript,
1439
+ existingIndex: existing.file,
1440
+ existingTotal: existing.count,
1441
+ styleSummary,
1442
+ worldBlock,
1443
+ worldSummary,
1444
+ });
1445
+ } else if (item.mode === 'rank_ladder') {
1446
+ prompt = rankLadderPrompt({
1447
+ base,
1448
+ target: file,
1449
+ workspace: root,
1450
+ batchId,
1451
+ attempt,
1452
+ failures: attemptDetail ? [attemptDetail] : [],
1453
+ genres,
1454
+ kind: item.kind,
1455
+ kindLabel: KIND_LABELS[item.kind] || item.kind,
1456
+ subkind: item.subkind,
1457
+ groupId,
1458
+ worldId,
1459
+ targetSets: item.target,
1460
+ generatedSets: item.generated,
1461
+ requestSets: 1,
1462
+ levels: item.levels || 10,
1463
+ includeBase,
1464
+ validateScript: tools.validateScript,
1465
+ queryScript: tools.queryScript,
1466
+ existingIndex: existing.file,
1467
+ existingTotal: existing.count,
1468
+ styleSummary,
1469
+ worldBlock,
1470
+ worldSummary,
1471
+ });
1472
+ } else {
1473
+ prompt = generationPrompt({
1474
+ base,
1475
+ target: file,
1476
+ workspace: root,
1477
+ batchId,
1478
+ attempt,
1479
+ failures: attemptDetail ? [attemptDetail] : [],
1480
+ mode: 'world',
1481
+ genres,
1482
+ focus: null,
1483
+ targetPerKind: item.target,
1484
+ batchSize,
1485
+ kind: item.kind,
1486
+ kindLabel: item.label,
1487
+ kindIndex: index + 1,
1488
+ kindTotal: pending.length,
1489
+ generated: item.generated,
1490
+ dbExisting: item.db_existing,
1491
+ requestCount: next.requestCount,
1492
+ includeBase,
1493
+ validateScript: tools.validateScript,
1494
+ queryScript: tools.queryScript,
1495
+ existingIndex: existing.file,
1496
+ existingTotal: existing.count,
1497
+ custom: null,
1498
+ customKindPending: false,
1499
+ sourceFixed: 'builtin',
1500
+ styleSummary,
1501
+ worldBlock,
1502
+ worldSummary,
1503
+ subkind: item.subkind || '',
1504
+ groupId: item.group_id || '',
1505
+ worldId,
1506
+ });
1507
+ }
1508
+
1276
1509
  const sent = await llmFollowup(invocation, prompt, { appendTempRule: false });
1277
1510
  if (!sent || sent.ok !== true) {
1278
1511
  fatal = true;
@@ -1287,44 +1520,33 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1287
1520
  }
1288
1521
  if (!waited.ok && waited.code === 'TIMEOUT') {
1289
1522
  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) {
1523
+ const checked = await validateBatch(file, item, groupId);
1524
+ if (checked.ok) {
1525
+ const acceptedResult = await acceptBatch(file, item, groupId);
1526
+ if (acceptedResult.fatal) {
1298
1527
  fatal = true;
1299
- stopReason = '等待超时后导入数据库失败:' + (err && err.message ? err.message : String(err));
1528
+ stopReason = '等待超时后导入数据库失败:' + acceptedResult.detail;
1300
1529
  break;
1301
1530
  }
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);
1531
+ accepted = true;
1312
1532
  try {
1313
1533
  fs.appendFileSync(batchLog, JSON.stringify({
1314
1534
  at: new Date().toISOString(),
1535
+ mode: item.mode,
1315
1536
  kind: item.kind,
1537
+ kinds: item.kinds || [],
1538
+ subkind: item.subkind || '',
1539
+ group_id: groupId || item.group_id || '',
1316
1540
  batch: batchNo,
1317
1541
  file,
1318
1542
  request_count: next.requestCount,
1319
- db_before: beforeCount,
1320
- db_after: afterCount,
1321
- imported,
1543
+ imported: acceptedResult.imported,
1322
1544
  generated: item.generated,
1545
+ target: item.target,
1323
1546
  attempts: attempt,
1324
1547
  timeout_salvage: true,
1325
1548
  }) + '\n');
1326
1549
  } catch { /* best effort */ }
1327
- accepted = true;
1328
1550
  }
1329
1551
  }
1330
1552
  fatal = true;
@@ -1340,60 +1562,36 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1340
1562
  continue;
1341
1563
  }
1342
1564
 
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;
1565
+ const checked = await validateBatch(file, item, groupId);
1566
+ if (!checked.ok) {
1567
+ attemptDetail = checked.detail;
1351
1568
  continue;
1352
1569
  }
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;
1361
- continue;
1362
- }
1363
-
1364
- try {
1365
- await importFile(root, file, { noPrefetch: true });
1366
- } catch (err) {
1570
+ const acceptedResult = await acceptBatch(file, item, groupId);
1571
+ if (acceptedResult.fatal) {
1367
1572
  fatal = true;
1368
- stopReason = '导入数据库失败:' + (err && err.message ? err.message : String(err));
1573
+ stopReason = '导入数据库失败:' + acceptedResult.detail;
1369
1574
  break;
1370
1575
  }
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);
1576
+ accepted = true;
1381
1577
  try {
1382
1578
  fs.appendFileSync(batchLog, JSON.stringify({
1383
1579
  at: new Date().toISOString(),
1580
+ mode: item.mode,
1384
1581
  kind: item.kind,
1582
+ kinds: item.kinds || [],
1583
+ subkind: item.subkind || '',
1584
+ group_id: groupId || item.group_id || '',
1385
1585
  batch: batchNo,
1386
1586
  file,
1387
1587
  request_count: next.requestCount,
1388
- db_before: beforeCount,
1389
- db_after: afterCount,
1390
- imported,
1588
+ imported: acceptedResult.imported,
1391
1589
  generated: item.generated,
1590
+ target: item.target,
1392
1591
  attempts: attempt,
1393
1592
  }) + '\n');
1394
1593
  } catch { /* best effort */ }
1395
- accepted = true;
1396
- if (imported === 0) {
1594
+ if (acceptedResult.imported === 0) {
1397
1595
  stalled += 1;
1398
1596
  attemptDetail = '本批没有新增素材(可能全是重复),必须写库中不存在的新素材';
1399
1597
  } else {
@@ -1409,15 +1607,15 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1409
1607
  break;
1410
1608
  }
1411
1609
  saveProgress();
1412
- if (item.generated >= targetPerKind) break;
1610
+ if (item.generated >= item.target) break;
1413
1611
  if (stalled >= MAX_STALLED_BATCHES) {
1414
1612
  lastReason = '连续 ' + stalled + ' 批没有新增素材';
1415
1613
  break;
1416
1614
  }
1417
1615
  }
1418
1616
 
1419
- item.remaining = Math.max(0, targetPerKind - item.generated);
1420
- if (item.generated >= targetPerKind) {
1617
+ item.remaining = Math.max(0, item.target - item.generated);
1618
+ if (item.generated >= item.target) {
1421
1619
  item.status = 'done';
1422
1620
  completed.push({ ...item });
1423
1621
  kindFailureStreak = 0;
@@ -1430,7 +1628,7 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1430
1628
  saveProgress();
1431
1629
  if (aborted || fatal) break;
1432
1630
  if (kindFailureStreak >= KIND_FAILURE_STREAK_LIMIT) {
1433
- stopReason = '连续 ' + kindFailureStreak + ' 个 kind 未完成,已停止以免继续空转';
1631
+ stopReason = '连续 ' + kindFailureStreak + ' 个项目未完成,已停止以免继续空转';
1434
1632
  break;
1435
1633
  }
1436
1634
  }
@@ -1441,7 +1639,7 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1441
1639
  report.imported_total = importedTotal;
1442
1640
  report.batches = batchCount;
1443
1641
  const notStarted = queue.filter((item) => item.status === 'pending' || item.status === 'running');
1444
- report.not_started = notStarted.map((item) => item.kind || item.label);
1642
+ report.not_started = notStarted.map((item) => item.label || item.kind || item.mode);
1445
1643
  const finalStatus = aborted
1446
1644
  ? 'aborted'
1447
1645
  : ((incomplete.length || notStarted.length || fatal || stopReason) ? 'incomplete' : 'complete');
@@ -1460,7 +1658,7 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1460
1658
  finished_at: finishedAt,
1461
1659
  status: finalStatus,
1462
1660
  target_per_kind: targetPerKind,
1463
- kinds,
1661
+ kinds: selectedKinds,
1464
1662
  imported: importedTotal,
1465
1663
  batches: batchCount,
1466
1664
  };
@@ -99,18 +99,20 @@ export async function countByKind(root, genres) {
99
99
  * @param {string[]} genres selected genres; empty means all
100
100
  * @returns {Promise<number>}
101
101
  */
102
- export async function countKind(root, kind, genres) {
102
+ export async function countKind(root, kind, genres, subkind = '') {
103
103
  const { db } = await connectMaterial(root);
104
104
  try {
105
105
  const list = (genres || []).filter(Boolean);
106
+ const extra = subkind ? ' AND subkind = $subkind' : '';
107
+ const params = subkind ? { kind, genres: list, subkind } : { kind, genres: list };
106
108
  const rows = list.length
107
109
  ? await db.query(
108
- 'SELECT count() AS n FROM (SELECT VALUE id FROM material WHERE kind = $kind AND genres CONTAINSALL $genres) GROUP ALL;',
109
- { kind, genres: list },
110
+ 'SELECT count() AS n FROM (SELECT VALUE id FROM material WHERE kind = $kind AND genres CONTAINSALL $genres' + extra + ') GROUP ALL;',
111
+ params,
110
112
  )
111
113
  : await db.query(
112
- 'SELECT count() AS n FROM material WHERE kind = $kind GROUP ALL;',
113
- { kind },
114
+ 'SELECT count() AS n FROM material WHERE kind = $kind' + extra + ' GROUP ALL;',
115
+ params,
114
116
  );
115
117
  const row = Array.isArray(rows) && Array.isArray(rows[0]) ? rows[0][0] : null;
116
118
  return row ? Number(row.n) || 0 : 0;