dsh-rp-card 1.6.2 → 1.6.3
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.
- package/CHANGELOG.md +8 -0
- package/lib/library/budget.js +127 -0
- package/lib/library/index.js +7 -0
- package/lib/library/mapping.js +103 -0
- package/lib/library/records.js +180 -0
- package/lib/library/sources.js +245 -0
- package/lib/library/state.js +151 -0
- package/lib/library/tool.js +367 -0
- package/lib/library/validate.js +169 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# 更新记录
|
|
2
2
|
|
|
3
|
+
## 1.6.3
|
|
4
|
+
|
|
5
|
+
修复 1.6.0–1.6.2 的打包缺陷:`files` 只写了 `lib/*.js`,导致 `lib/library/` 没有进包。
|
|
6
|
+
|
|
7
|
+
- 现象:从 npm 安装 1.6.0/1.6.1/1.6.2 后插件加载失败(index.js 引用 ./lib/library/tool.js 找不到),DSH 里表现为「更新失败」,用户停留在 1.5.4。
|
|
8
|
+
- 本地用 link 安装的开发环境不受影响(直接读源码目录),所以本地看起来正常。
|
|
9
|
+
- 修复:`files` 改为 `lib/**`;新增 tests/package-files.test.mjs 防止回归。
|
|
10
|
+
|
|
3
11
|
## 1.6.2
|
|
4
12
|
|
|
5
13
|
资料库流程的闸门与入口修正(基于 1.6.1 的真实剧本测试)。
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// 预算与两套取舍方案:复杂度判定、常驻/触发/背景分流、降级顺序。
|
|
2
|
+
export const PROFILES = {
|
|
3
|
+
simple: { id: 'simple', label: '简单卡', total: 800, entry: 600 },
|
|
4
|
+
complex: { id: 'complex', label: '复杂卡', total: 1600, entry: 900 },
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
export const SCHEMES = {
|
|
8
|
+
A: { id: 'A', name: '沉浸优先', residentShare: 0.7, note: '常驻占约 70% 预算,世界感强,触发条目少而精' },
|
|
9
|
+
B: { id: 'B', name: '轻量优先', residentShare: 0.4, note: '常驻占约 40% 预算,保留更多触发条目,token 更省' },
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
// 常驻优先顺序:规则 → 人物 → 势力 → 地点 → 事件 → 关系 → 物品
|
|
13
|
+
const PRIORITY = { rule: 0, character: 1, faction: 2, place: 3, event: 4, relationship: 5, item: 6, question: 9, visual: 99 };
|
|
14
|
+
|
|
15
|
+
// 超预算时的降级顺序:事件 → 地点 → 人物细节 → 规则细化(核心规则与主要人物不降级)
|
|
16
|
+
const DOWNGRADE_ORDER = ['event', 'item', 'place', 'relationship', 'faction', 'character', 'rule'];
|
|
17
|
+
|
|
18
|
+
export function detectComplexity(records = [], opts = {}) {
|
|
19
|
+
if (opts.complexity === true || opts.complexity === 'complex') return PROFILES.complex;
|
|
20
|
+
if (opts.complexity === false || opts.complexity === 'simple') return PROFILES.simple;
|
|
21
|
+
return records.length >= 24 ? PROFILES.complex : PROFILES.simple;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function recordChars(record) {
|
|
25
|
+
const head = record.name ? `【${record.name}】\n` : '';
|
|
26
|
+
return (head + String(record.body || '')).length;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function phaseAllowed(record, startPhase = 0) {
|
|
30
|
+
const kf = record.known_from;
|
|
31
|
+
if (kf === null || kf === undefined) return true;
|
|
32
|
+
return Number(kf) <= Number(startPhase);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function sortByPriority(a, b) {
|
|
36
|
+
const pa = PRIORITY[a.kind] ?? 50;
|
|
37
|
+
const pb = PRIORITY[b.kind] ?? 50;
|
|
38
|
+
if (pa !== pb) return pa - pb;
|
|
39
|
+
return String(a.id).localeCompare(String(b.id));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 按方案分配:常驻 / 条件触发 / 只做背景 / 视觉参考
|
|
44
|
+
* - uncertain 条目一律不进世界书(进背景,避免把存疑内容当设定)
|
|
45
|
+
* - 未解决冲突条目进背景并在 notes 里点名
|
|
46
|
+
* - visual 条目进视觉清单
|
|
47
|
+
* - 阶段晚于开局的条目只能条件触发
|
|
48
|
+
*/
|
|
49
|
+
export function allocate(records = [], { scheme = 'A', profile, startPhase = 0 } = {}) {
|
|
50
|
+
const sch = SCHEMES[scheme] || SCHEMES.A;
|
|
51
|
+
const prof = profile || detectComplexity(records);
|
|
52
|
+
const residentBudget = Math.floor(prof.total * sch.residentShare);
|
|
53
|
+
|
|
54
|
+
const resident = [];
|
|
55
|
+
const conditional = [];
|
|
56
|
+
const background = [];
|
|
57
|
+
const visual = [];
|
|
58
|
+
const notes = [];
|
|
59
|
+
let used = 0;
|
|
60
|
+
|
|
61
|
+
const sorted = [...records].sort(sortByPriority);
|
|
62
|
+
|
|
63
|
+
for (const rec of sorted) {
|
|
64
|
+
const chars = recordChars(rec);
|
|
65
|
+
if (rec.kind === 'visual') { visual.push({ id: rec.id, name: rec.name, chars }); continue; }
|
|
66
|
+
if (rec.conflict) {
|
|
67
|
+
background.push({ id: rec.id, name: rec.name, chars, reason: '未解决冲突' });
|
|
68
|
+
notes.push(`条目 ${rec.id} 存在未解决冲突,未进入世界书`);
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (rec.status === 'uncertain') {
|
|
72
|
+
background.push({ id: rec.id, name: rec.name, chars, reason: '确定性存疑' });
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
const gated = !phaseAllowed(rec, startPhase);
|
|
76
|
+
if (gated) {
|
|
77
|
+
conditional.push({ id: rec.id, name: rec.name, chars, reason: '阶段晚于开局,只能条件触发' });
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (chars > prof.entry) {
|
|
81
|
+
conditional.push({ id: rec.id, name: rec.name, chars, reason: `单条超过 ${prof.entry} 字上限` });
|
|
82
|
+
notes.push(`条目 ${rec.id} 单条 ${chars} 字超过上限 ${prof.entry},已降为条件触发并需拆分`);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (used + chars <= residentBudget) {
|
|
86
|
+
resident.push({ id: rec.id, name: rec.name, chars, kind: rec.kind });
|
|
87
|
+
used += chars;
|
|
88
|
+
} else {
|
|
89
|
+
conditional.push({ id: rec.id, name: rec.name, chars, reason: '常驻预算已满' });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return {
|
|
94
|
+
scheme: sch.id,
|
|
95
|
+
schemeName: sch.name,
|
|
96
|
+
profile: prof.id,
|
|
97
|
+
profileLabel: prof.label,
|
|
98
|
+
residentBudget,
|
|
99
|
+
entriesCap: prof.entry,
|
|
100
|
+
resident,
|
|
101
|
+
conditional,
|
|
102
|
+
background,
|
|
103
|
+
visual,
|
|
104
|
+
usage: {
|
|
105
|
+
residentChars: used,
|
|
106
|
+
residentBudget,
|
|
107
|
+
residentCount: resident.length,
|
|
108
|
+
conditionalCount: conditional.length,
|
|
109
|
+
backgroundCount: background.length,
|
|
110
|
+
visualCount: visual.length,
|
|
111
|
+
overBudget: used > residentBudget,
|
|
112
|
+
},
|
|
113
|
+
notes,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 超预算时的建议降级顺序(给方案文档用) */
|
|
118
|
+
export function downgradePlan(plan) {
|
|
119
|
+
const movable = plan.resident
|
|
120
|
+
.filter((r) => DOWNGRADE_ORDER.includes(r.kind))
|
|
121
|
+
.sort((a, b) => DOWNGRADE_ORDER.indexOf(b.kind) - DOWNGRADE_ORDER.indexOf(a.kind));
|
|
122
|
+
return {
|
|
123
|
+
order: DOWNGRADE_ORDER,
|
|
124
|
+
first: movable.slice(0, 3).map((r) => r.id),
|
|
125
|
+
text: '超预算时按「事件 → 物品 → 地点 → 关系 → 势力 → 人物 → 规则」降级;核心规则与主要人物不降级',
|
|
126
|
+
};
|
|
127
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// 资料条目 → 世界书条目:内容拼装、锚点生成、阶段前缀、平台字段默认值。
|
|
2
|
+
const TRIGGER_BY_KIND = {
|
|
3
|
+
character: '内容锚',
|
|
4
|
+
place: '内容锚',
|
|
5
|
+
faction: '内容锚',
|
|
6
|
+
event: '内容锚',
|
|
7
|
+
item: '内容锚',
|
|
8
|
+
relationship: '内容锚',
|
|
9
|
+
rule: '常驻或格式字段锚',
|
|
10
|
+
question: '条件触发',
|
|
11
|
+
visual: '不进世界书',
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export const PLATFORM_DEFAULTS = {
|
|
15
|
+
sort: 0,
|
|
16
|
+
depth: 0,
|
|
17
|
+
probability: 100,
|
|
18
|
+
value_region: 1,
|
|
19
|
+
key_region: 6,
|
|
20
|
+
value_type: 0,
|
|
21
|
+
match_type: 2,
|
|
22
|
+
enable: true,
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export function entryContent(record) {
|
|
26
|
+
const head = record.name ? `【${record.name}】\n` : '';
|
|
27
|
+
return head + String(record.body || '').trim();
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function anchorsOf(record, limit = 8) {
|
|
31
|
+
const raw = [record.name, ...(record.aliases || [])].filter(Boolean).map((s) => String(s).trim());
|
|
32
|
+
const seen = new Set();
|
|
33
|
+
const out = [];
|
|
34
|
+
for (const a of raw) {
|
|
35
|
+
if (seen.has(a)) continue;
|
|
36
|
+
seen.add(a);
|
|
37
|
+
out.push(a);
|
|
38
|
+
if (out.length >= limit) break;
|
|
39
|
+
}
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function triggerOf(record) {
|
|
44
|
+
return TRIGGER_BY_KIND[record.kind] || '内容锚';
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function toPlatformEntry(record, { key, content } = {}) {
|
|
48
|
+
return {
|
|
49
|
+
content: content ?? entryContent(record),
|
|
50
|
+
key: key ?? anchorsOf(record),
|
|
51
|
+
...PLATFORM_DEFAULTS,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const LATE_PREFIX = '(此信息此刻尚不可知;仅当剧情推进到相应阶段后再使用)\n';
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 按方案生成世界书条目。
|
|
59
|
+
* 只有 resident 与 conditional 进世界书;background / visual 不进。
|
|
60
|
+
* 阶段晚于开局的条目补一句「尚不可知」前缀。
|
|
61
|
+
*/
|
|
62
|
+
export function buildEntries(plan, records = [], { startPhase = 0 } = {}) {
|
|
63
|
+
const byId = new Map(records.map((r) => [r.id, r]));
|
|
64
|
+
const entries = [];
|
|
65
|
+
const meta = [];
|
|
66
|
+
const skipped = [];
|
|
67
|
+
|
|
68
|
+
const push = (item, bucket) => {
|
|
69
|
+
const rec = byId.get(item.id);
|
|
70
|
+
if (!rec) { skipped.push({ id: item.id, reason: '条目已删除' }); return; }
|
|
71
|
+
const gated = !(rec.known_from === null || rec.known_from === undefined || Number(rec.known_from) <= Number(startPhase));
|
|
72
|
+
const content = (gated ? LATE_PREFIX : '') + entryContent(rec);
|
|
73
|
+
const key = anchorsOf(rec);
|
|
74
|
+
if (!key.length) { skipped.push({ id: rec.id, reason: '没有可用锚点' }); return; }
|
|
75
|
+
entries.push(toPlatformEntry(rec, { key, content }));
|
|
76
|
+
meta.push({
|
|
77
|
+
id: rec.id,
|
|
78
|
+
name: rec.name,
|
|
79
|
+
kind: rec.kind,
|
|
80
|
+
bucket,
|
|
81
|
+
trigger: triggerOf(rec),
|
|
82
|
+
gated,
|
|
83
|
+
chars: content.length,
|
|
84
|
+
key,
|
|
85
|
+
});
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
for (const item of plan.resident || []) push(item, 'resident');
|
|
89
|
+
for (const item of plan.conditional || []) push(item, 'conditional');
|
|
90
|
+
for (const item of plan.background || []) skipped.push({ id: item.id, reason: item.reason || '只做背景' });
|
|
91
|
+
for (const item of plan.visual || []) skipped.push({ id: item.id, reason: '视觉参考,不进世界书' });
|
|
92
|
+
|
|
93
|
+
return {
|
|
94
|
+
entries,
|
|
95
|
+
meta,
|
|
96
|
+
skipped,
|
|
97
|
+
usage: {
|
|
98
|
+
entryCount: entries.length,
|
|
99
|
+
residentChars: meta.filter((m) => m.bucket === 'resident').reduce((a, m) => a + m.chars, 0),
|
|
100
|
+
conditionalChars: meta.filter((m) => m.bucket === 'conditional').reduce((a, m) => a + m.chars, 0),
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// 资料条目:序列化、读写、哈希保护、索引重建、证据校验。
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import crypto from 'node:crypto';
|
|
5
|
+
import { readSource } from './sources.js';
|
|
6
|
+
|
|
7
|
+
export const RECORD_MARK = '<!-- library-record:v1 -->';
|
|
8
|
+
const FENCE = '`'.repeat(3);
|
|
9
|
+
export const RECORD_KINDS = ['character', 'place', 'faction', 'rule', 'event', 'relationship', 'item', 'visual', 'question'];
|
|
10
|
+
export const STATUSES = ['confirmed', 'inference', 'uncertain'];
|
|
11
|
+
export const REALMS = ['canon', 'reference', 'fanon', 'unknown'];
|
|
12
|
+
|
|
13
|
+
const META_KEYS = ['id', 'kind', 'name', 'aliases', 'realm', 'continuity', 'known_from', 'status', 'evidence', 'conflict', 'base_sha256'];
|
|
14
|
+
|
|
15
|
+
export function recordsDir(projectDir) {
|
|
16
|
+
return path.join(projectDir, '.card-build', 'library', 'records');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function sha256(input) {
|
|
20
|
+
return crypto.createHash('sha256').update(input).digest('hex');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function digestOfFileText(text) {
|
|
24
|
+
return sha256(text.replace(/"base_sha256":\s*"[^"]*"/, '"base_sha256":""'));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function serializeRecord(record) {
|
|
28
|
+
const meta = {};
|
|
29
|
+
for (const k of META_KEYS) {
|
|
30
|
+
if (record[k] !== undefined) meta[k] = record[k];
|
|
31
|
+
}
|
|
32
|
+
if (!meta.aliases) meta.aliases = [];
|
|
33
|
+
if (!meta.evidence) meta.evidence = [];
|
|
34
|
+
const body = String(record.body ?? '').replace(/\s+$/, '');
|
|
35
|
+
return [RECORD_MARK, FENCE + 'json', JSON.stringify(meta, null, 2), FENCE, '', body, ''].join('\n');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function parseRecord(text) {
|
|
39
|
+
const src = String(text ?? '');
|
|
40
|
+
if (!src.includes(RECORD_MARK)) throw new Error('不是合法的资料条目(缺少 library-record:v1 标记)');
|
|
41
|
+
const first = src.indexOf(FENCE + 'json');
|
|
42
|
+
if (first < 0) throw new Error('资料条目缺少 JSON 元数据块');
|
|
43
|
+
const jsonStart = src.indexOf('\n', first) + 1;
|
|
44
|
+
const jsonEnd = src.indexOf('\n' + FENCE, jsonStart);
|
|
45
|
+
if (jsonEnd < 0) throw new Error('资料条目 JSON 块未闭合');
|
|
46
|
+
const meta = JSON.parse(src.slice(jsonStart, jsonEnd));
|
|
47
|
+
const bodyStart = src.indexOf('\n', jsonEnd + FENCE.length + 1) + 1;
|
|
48
|
+
const body = bodyStart > 0 ? src.slice(bodyStart).replace(/^\n+/, '') : '';
|
|
49
|
+
return { ...meta, body: body.replace(/\s+$/, '') };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function recordPath(projectDir, id) {
|
|
53
|
+
return path.join(recordsDir(projectDir), `${id}.md`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function readRecord(projectDir, id) {
|
|
57
|
+
const p = recordPath(projectDir, id);
|
|
58
|
+
if (!fs.existsSync(p)) return null;
|
|
59
|
+
return parseRecord(fs.readFileSync(p, 'utf8'));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function listRecords(projectDir) {
|
|
63
|
+
const dir = recordsDir(projectDir);
|
|
64
|
+
if (!fs.existsSync(dir)) return [];
|
|
65
|
+
return fs
|
|
66
|
+
.readdirSync(dir)
|
|
67
|
+
.filter((f) => f.endsWith('.md'))
|
|
68
|
+
.map((f) => parseRecord(fs.readFileSync(path.join(dir, f), 'utf8')))
|
|
69
|
+
.sort((a, b) => String(a.id).localeCompare(String(b.id)));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function normalizeRecord(record) {
|
|
73
|
+
const out = { ...record };
|
|
74
|
+
if (!out.id || !/^[a-z0-9_-]+$/.test(out.id)) {
|
|
75
|
+
throw new Error(`条目 id 只能是小写字母/数字/短横线/下划线:${out.id}`);
|
|
76
|
+
}
|
|
77
|
+
if (!RECORD_KINDS.includes(out.kind)) throw new Error(`未知条目类型:${out.kind}`);
|
|
78
|
+
if (out.status && !STATUSES.includes(out.status)) throw new Error(`未知确定性:${out.status}`);
|
|
79
|
+
if (out.realm && !REALMS.includes(out.realm)) throw new Error(`未知来源身份:${out.realm}`);
|
|
80
|
+
if (!Array.isArray(out.aliases)) out.aliases = [];
|
|
81
|
+
if (!Array.isArray(out.evidence)) out.evidence = [];
|
|
82
|
+
if (out.known_from === undefined) out.known_from = null;
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function writeRecord(projectDir, record) {
|
|
87
|
+
const rec = normalizeRecord(record);
|
|
88
|
+
const p = recordPath(projectDir, rec.id);
|
|
89
|
+
const exists = fs.existsSync(p);
|
|
90
|
+
if (exists) {
|
|
91
|
+
const current = fs.readFileSync(p, 'utf8');
|
|
92
|
+
if (!rec.base_sha256) {
|
|
93
|
+
const err = new Error(`条目 ${rec.id} 已存在,修改时必须提供 base_sha256(当前 ${digestOfFileText(current).slice(0, 12)}…),避免覆盖人工修改`);
|
|
94
|
+
err.code = 'LIB011';
|
|
95
|
+
throw err;
|
|
96
|
+
}
|
|
97
|
+
if (rec.base_sha256 !== digestOfFileText(current)) {
|
|
98
|
+
const err = new Error(`条目 ${rec.id} 已被修改(base_sha256 不匹配),本次写入已停止;请先读回当前文件再合并`);
|
|
99
|
+
err.code = 'LIB012';
|
|
100
|
+
throw err;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const serialized = serializeRecord({ ...rec, base_sha256: '' });
|
|
104
|
+
const final = serializeRecord({ ...rec, base_sha256: digestOfFileText(serialized) });
|
|
105
|
+
fs.mkdirSync(recordsDir(projectDir), { recursive: true });
|
|
106
|
+
fs.writeFileSync(p, final, 'utf8');
|
|
107
|
+
return { id: rec.id, path: p, sha256: digestOfFileText(final) };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function rebuildIndex(projectDir) {
|
|
111
|
+
const records = listRecords(projectDir);
|
|
112
|
+
const dir = path.join(projectDir, '.card-build', 'library');
|
|
113
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
114
|
+
const lines = records.map((r) =>
|
|
115
|
+
JSON.stringify({
|
|
116
|
+
id: r.id,
|
|
117
|
+
kind: r.kind,
|
|
118
|
+
name: r.name,
|
|
119
|
+
aliases: r.aliases || [],
|
|
120
|
+
realm: r.realm || 'unknown',
|
|
121
|
+
continuity: r.continuity || '',
|
|
122
|
+
known_from: r.known_from ?? null,
|
|
123
|
+
status: r.status || 'inference',
|
|
124
|
+
chars: String(r.body || '').length,
|
|
125
|
+
conflict: Boolean(r.conflict),
|
|
126
|
+
}),
|
|
127
|
+
);
|
|
128
|
+
const file = path.join(dir, 'index.jsonl');
|
|
129
|
+
fs.writeFileSync(file, lines.join('\n') + (lines.length ? '\n' : ''), 'utf8');
|
|
130
|
+
return { file, count: lines.length };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* 证据校验:每条证据必须能在来源单元里逐字找到。
|
|
135
|
+
* 兼容两种定位:start 为全文位置,或仅给 quote。
|
|
136
|
+
*/
|
|
137
|
+
export function verifyEvidence(projectDir, record) {
|
|
138
|
+
const problems = [];
|
|
139
|
+
const evs = record.evidence || [];
|
|
140
|
+
if (!evs.length) return [{ code: 'LIB001', message: `条目 ${record.id} 没有任何原文证据` }];
|
|
141
|
+
|
|
142
|
+
for (const ev of evs) {
|
|
143
|
+
const { source_id: sourceId, unit_id: unitId, quote } = ev || {};
|
|
144
|
+
if (!sourceId || !unitId || !quote) {
|
|
145
|
+
problems.push({ code: 'LIB001', message: `条目 ${record.id} 的证据缺少 source_id / unit_id / quote` });
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
let src;
|
|
149
|
+
try {
|
|
150
|
+
src = readSource(projectDir, sourceId);
|
|
151
|
+
} catch {
|
|
152
|
+
problems.push({ code: 'LIB001', message: `条目 ${record.id} 引用了不存在的来源 ${sourceId}` });
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
const unit = (src.meta.units || []).find((u) => u.id === unitId);
|
|
156
|
+
if (!unit) {
|
|
157
|
+
problems.push({ code: 'LIB001', message: `条目 ${record.id} 引用了不存在的单元 ${sourceId}/${unitId}` });
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
const unitText = src.text.slice(unit.start, unit.end);
|
|
161
|
+
const at = unitText.indexOf(quote);
|
|
162
|
+
if (at < 0) {
|
|
163
|
+
problems.push({
|
|
164
|
+
code: 'LIB001',
|
|
165
|
+
message: `条目 ${record.id} 的引文在 ${sourceId}/${unitId} 中找不到:${String(quote).slice(0, 20)}…`,
|
|
166
|
+
});
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
if (typeof ev.start === 'number' && ev.start >= unit.start && ev.start < unit.end) {
|
|
170
|
+
if (!src.text.startsWith(quote, ev.start)) {
|
|
171
|
+
problems.push({ code: 'LIB001', message: `条目 ${record.id} 的引文位置与 start 不符(${sourceId}/${unitId})` });
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return problems;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function unresolvedConflicts(projectDir) {
|
|
179
|
+
return listRecords(projectDir).filter((r) => r.conflict);
|
|
180
|
+
}
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
// 材料导入与切分:编码判定、归一化、按类型切分、块大小校正。
|
|
2
|
+
// 纯逻辑为主,IO 只在 registerSource / readSource 中出现。
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import crypto from 'node:crypto';
|
|
6
|
+
|
|
7
|
+
export const SOURCE_KINDS = ['novel', 'screenplay', 'setting-book', 'game-script'];
|
|
8
|
+
|
|
9
|
+
export const PRESETS = {
|
|
10
|
+
novel: [/^第[零一二三四五六七八九十百千万0-9]{1,10}[章回卷节部篇][^\n]{0,40}$/m, /^Chapter\s+\d+[^\n]{0,40}$/m],
|
|
11
|
+
screenplay: [/^第[零一二三四五六七八九十百0-9]{1,6}集[^\n]{0,40}$/m, /^(?:Episode|EP)\s*\d+[^\n]{0,40}$/m],
|
|
12
|
+
scene: [/^第?[0-9一二三四五六七八九十]{1,4}场[^\n]{0,40}$/m, /^(?:INT|EXT)\.\s*[^\n]{0,60}$/m],
|
|
13
|
+
'setting-book': [/^#{1,3}\s+[^\n]{1,40}$/m, /^【[^】\n]{1,30}】/m],
|
|
14
|
+
'game-script': [/^第[零一二三四五六七八九十百0-9]{1,10}[章回节][^\n]{0,40}$/m, /^(?:任务|Quest)\s*[::]\s*[^\n]{1,30}$/m],
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export const DEFAULT_OPTIONS = { maxChars: 15000, minChars: 500, sceneFallback: true };
|
|
18
|
+
|
|
19
|
+
const CJK = /[\u3400-\u9fff\u3000-\u303f\uff00-\uffef]/;
|
|
20
|
+
|
|
21
|
+
function scoreText(text) {
|
|
22
|
+
if (!text) return -1;
|
|
23
|
+
const sample = text.slice(0, 4000);
|
|
24
|
+
let cjk = 0;
|
|
25
|
+
let bad = 0;
|
|
26
|
+
for (const ch of sample) {
|
|
27
|
+
if (CJK.test(ch)) cjk++;
|
|
28
|
+
if (ch === '\uFFFD') bad++;
|
|
29
|
+
}
|
|
30
|
+
return (cjk - bad * 5) / Math.max(1, sample.length);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function decodeText(buf) {
|
|
34
|
+
if (!Buffer.isBuffer(buf)) buf = Buffer.from(String(buf ?? ''), 'utf8');
|
|
35
|
+
if (buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf) {
|
|
36
|
+
return { encoding: 'utf-8', text: buf.toString('utf8').replace(/^\uFEFF/, '') };
|
|
37
|
+
}
|
|
38
|
+
if (buf[0] === 0xff && buf[1] === 0xfe) {
|
|
39
|
+
return { encoding: 'utf-16le', text: new TextDecoder('utf-16le').decode(buf) };
|
|
40
|
+
}
|
|
41
|
+
if (buf[0] === 0xfe && buf[1] === 0xff) {
|
|
42
|
+
return { encoding: 'utf-16be', text: new TextDecoder('utf-16be').decode(buf) };
|
|
43
|
+
}
|
|
44
|
+
let best = null;
|
|
45
|
+
for (const enc of ['utf-8', 'gb18030', 'big5']) {
|
|
46
|
+
try {
|
|
47
|
+
const text = new TextDecoder(enc, { fatal: true }).decode(buf);
|
|
48
|
+
const score = scoreText(text);
|
|
49
|
+
if (!best || score > best.score) best = { encoding: enc, text, score };
|
|
50
|
+
} catch {
|
|
51
|
+
// 该编码解不出,试下一个
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (best) return { encoding: best.encoding, text: best.text };
|
|
55
|
+
return { encoding: 'utf-8', text: new TextDecoder('utf-8').decode(buf) };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function normalizeText(text) {
|
|
59
|
+
return String(text ?? '')
|
|
60
|
+
.replace(/^\uFEFF/, '')
|
|
61
|
+
.replace(/\r\n?/g, '\n')
|
|
62
|
+
.replace(/\u00a0/g, ' ');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function findHeads(text, regexes) {
|
|
66
|
+
const hits = [];
|
|
67
|
+
for (const re of regexes) {
|
|
68
|
+
const g = new RegExp(re.source, re.flags.includes('g') ? re.flags : re.flags + 'g');
|
|
69
|
+
let m;
|
|
70
|
+
while ((m = g.exec(text))) {
|
|
71
|
+
hits.push({ index: m.index, title: m[0].trim().slice(0, 60) });
|
|
72
|
+
if (m.index === g.lastIndex) g.lastIndex++;
|
|
73
|
+
}
|
|
74
|
+
if (hits.length) break;
|
|
75
|
+
}
|
|
76
|
+
return hits.sort((a, b) => a.index - b.index);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function sliceByHeads(text, heads) {
|
|
80
|
+
if (!heads.length) return [{ title: '', text }];
|
|
81
|
+
const parts = [];
|
|
82
|
+
if (heads[0].index > 0) {
|
|
83
|
+
const lead = text.slice(0, heads[0].index);
|
|
84
|
+
if (lead.trim()) parts.push({ title: '(前言)', text: lead });
|
|
85
|
+
}
|
|
86
|
+
for (let i = 0; i < heads.length; i++) {
|
|
87
|
+
const start = heads[i].index;
|
|
88
|
+
const end = i + 1 < heads.length ? heads[i + 1].index : text.length;
|
|
89
|
+
parts.push({ title: heads[i].title, text: text.slice(start, end) });
|
|
90
|
+
}
|
|
91
|
+
return parts;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function hardSplit(text, maxChars) {
|
|
95
|
+
const out = [];
|
|
96
|
+
let rest = text;
|
|
97
|
+
while (rest.length > maxChars) {
|
|
98
|
+
let cut = rest.lastIndexOf('\n\n', maxChars);
|
|
99
|
+
if (cut < maxChars * 0.4) cut = rest.lastIndexOf('\n', maxChars);
|
|
100
|
+
if (cut < maxChars * 0.4) cut = rest.lastIndexOf('。', maxChars);
|
|
101
|
+
if (cut < maxChars * 0.4) cut = maxChars - 1;
|
|
102
|
+
if (cut > maxChars - 1) cut = maxChars - 1;
|
|
103
|
+
out.push(rest.slice(0, cut + 1));
|
|
104
|
+
rest = rest.slice(cut + 1);
|
|
105
|
+
}
|
|
106
|
+
if (rest) out.push(rest);
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function enforceMax(parts, maxChars) {
|
|
111
|
+
const out = [];
|
|
112
|
+
for (const p of parts) {
|
|
113
|
+
if (p.text.length <= maxChars) { out.push(p); continue; }
|
|
114
|
+
const pieces = hardSplit(p.text, maxChars);
|
|
115
|
+
pieces.forEach((t, i) => out.push({ title: pieces.length > 1 ? `${p.title}(${i + 1})` : p.title, text: t }));
|
|
116
|
+
}
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function mergeSmall(parts, minChars) {
|
|
121
|
+
const out = [];
|
|
122
|
+
for (const p of parts) {
|
|
123
|
+
const last = out[out.length - 1];
|
|
124
|
+
const titled = Boolean(p.title && p.title !== '(前言)');
|
|
125
|
+
if (!titled && last && p.text.length < minChars && last.text.length + p.text.length <= 15000) {
|
|
126
|
+
last.text += '\n' + p.text;
|
|
127
|
+
if (!last.title) last.title = p.title;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
out.push({ ...p });
|
|
131
|
+
}
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function splitText(text, kind = 'novel', opts = {}) {
|
|
136
|
+
const { maxChars, minChars, sceneFallback } = { ...DEFAULT_OPTIONS, ...opts };
|
|
137
|
+
const src = normalizeText(text);
|
|
138
|
+
if (!src.trim()) return { units: [], stats: { count: 0, chars: 0, kind } };
|
|
139
|
+
|
|
140
|
+
const preset = PRESETS[kind] || PRESETS.novel;
|
|
141
|
+
let parts = sliceByHeads(src, findHeads(src, preset));
|
|
142
|
+
|
|
143
|
+
// 剧本:单集超上限时按场再切
|
|
144
|
+
if (kind === 'screenplay' && sceneFallback) {
|
|
145
|
+
const next = [];
|
|
146
|
+
for (const p of parts) {
|
|
147
|
+
if (p.text.length <= maxChars) { next.push(p); continue; }
|
|
148
|
+
const scenes = sliceByHeads(p.text, findHeads(p.text, PRESETS.scene));
|
|
149
|
+
for (const s of scenes) next.push({ title: `${p.title} ${s.title}`.trim(), text: s.text });
|
|
150
|
+
}
|
|
151
|
+
parts = next;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
parts = mergeSmall(enforceMax(parts, maxChars), minChars);
|
|
155
|
+
|
|
156
|
+
const units = [];
|
|
157
|
+
let cursor = 0;
|
|
158
|
+
parts.forEach((p, i) => {
|
|
159
|
+
let start = src.indexOf(p.text, cursor);
|
|
160
|
+
if (start < 0) start = cursor;
|
|
161
|
+
cursor = start + p.text.length;
|
|
162
|
+
units.push({
|
|
163
|
+
id: `u${String(i + 1).padStart(6, '0')}`,
|
|
164
|
+
index: i,
|
|
165
|
+
title: p.title,
|
|
166
|
+
start,
|
|
167
|
+
end: start + p.text.length,
|
|
168
|
+
chars: p.text.length,
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
return {
|
|
173
|
+
units,
|
|
174
|
+
stats: {
|
|
175
|
+
count: units.length,
|
|
176
|
+
chars: src.length,
|
|
177
|
+
kind,
|
|
178
|
+
oversized: units.filter((u) => u.chars > maxChars).length,
|
|
179
|
+
smallest: units.reduce((a, u) => Math.min(a, u.chars), Number.MAX_SAFE_INTEGER) === Number.MAX_SAFE_INTEGER ? 0 : units.reduce((a, u) => Math.min(a, u.chars), 1e9),
|
|
180
|
+
},
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function sha256(input) {
|
|
185
|
+
return crypto.createHash('sha256').update(input).digest('hex');
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export function libraryDir(projectDir) {
|
|
189
|
+
return path.join(projectDir, '.card-build', 'library');
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export function sourcesDir(projectDir) {
|
|
193
|
+
return path.join(libraryDir(projectDir), 'sources');
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export function registerSource(projectDir, { id, kind = 'novel', title = '', realm = 'unknown', continuity = '', edition = '', phase = null, buffer, text, filePath }) {
|
|
197
|
+
if (!id) throw new Error('registerSource 需要 id');
|
|
198
|
+
if (!SOURCE_KINDS.includes(kind)) throw new Error(`未知材料类型:${kind}`);
|
|
199
|
+
const raw = buffer
|
|
200
|
+
? Buffer.from(buffer)
|
|
201
|
+
: filePath
|
|
202
|
+
? fs.readFileSync(filePath)
|
|
203
|
+
: Buffer.from(String(text ?? ''), 'utf8');
|
|
204
|
+
const decoded = decodeText(raw);
|
|
205
|
+
const normalized = normalizeText(text ?? decoded.text);
|
|
206
|
+
const dir = sourcesDir(projectDir);
|
|
207
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
208
|
+
|
|
209
|
+
const textFile = path.join(dir, `${id}.txt`);
|
|
210
|
+
fs.writeFileSync(textFile, normalized, 'utf8');
|
|
211
|
+
|
|
212
|
+
const split = splitText(normalized, kind);
|
|
213
|
+
const meta = {
|
|
214
|
+
id,
|
|
215
|
+
kind,
|
|
216
|
+
title: title || path.basename(filePath || id),
|
|
217
|
+
realm,
|
|
218
|
+
continuity,
|
|
219
|
+
edition,
|
|
220
|
+
phase,
|
|
221
|
+
encoding: decoded.encoding,
|
|
222
|
+
file: path.basename(textFile),
|
|
223
|
+
file_sha256: sha256(normalized),
|
|
224
|
+
chars: normalized.length,
|
|
225
|
+
units: split.units,
|
|
226
|
+
stats: split.stats,
|
|
227
|
+
registered_from: filePath || 'inline',
|
|
228
|
+
};
|
|
229
|
+
fs.writeFileSync(path.join(dir, `${id}.json`), JSON.stringify(meta, null, 2) + '\n', 'utf8');
|
|
230
|
+
return meta;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export function readSource(projectDir, id) {
|
|
234
|
+
const dir = sourcesDir(projectDir);
|
|
235
|
+
const meta = JSON.parse(fs.readFileSync(path.join(dir, `${id}.json`), 'utf8'));
|
|
236
|
+
const text = fs.readFileSync(path.join(dir, meta.file), 'utf8');
|
|
237
|
+
return { meta, text };
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export function readUnitText(projectDir, sourceId, unitId) {
|
|
241
|
+
const { meta, text } = readSource(projectDir, sourceId);
|
|
242
|
+
const unit = (meta.units || []).find((u) => u.id === unitId);
|
|
243
|
+
if (!unit) return null;
|
|
244
|
+
return text.slice(unit.start, unit.end);
|
|
245
|
+
}
|