dsh-rp-card 1.6.1 → 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 CHANGED
@@ -1,5 +1,27 @@
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
+
11
+ ## 1.6.2
12
+
13
+ 资料库流程的闸门与入口修正(基于 1.6.1 的真实剧本测试)。
14
+
15
+ - 新增入口分支:只发材料、没有任何玩法要求时,先问「补充要求还是自由创作」。选补充要求→只做到资料库(停在 P2)等玩家补指令;选自由创作→按正常流程继续。
16
+ - write 闸门:必须已确认条目清单且取舍方案已批准,否则拒绝并给原因与两条路。
17
+ - propose 闸门:必须已确认条目清单。
18
+ - visual 闸门:必须已进入 P4(世界书已写入)。
19
+ - 新增工具动作 confirm(records / proposal / visual)与 read-unit(取单段全文)。
20
+ - commit 新增 dry_run;ingest 改为返回全部单元(超 20 条折叠),每段带前 120 字。
21
+ - write 输出补文件结构说明与前 3 条样例;state 摘要的「下一步」改为可执行动作。
22
+ - 规范新增第二十、二十一小节:只发材料的分支边界;核心规则双写 ppt、禁止 sleep 轮询。
23
+ - 新增 tests/library-sim.test.mjs(材料→资料库→世界书全链路模拟);工具与规范测试同步扩充。
24
+
3
25
  ## 1.6.1
4
26
 
5
27
  资料库 MVP 的正式发布(1.6.0 曾因先发布后测试被标记废弃,现以 1.6.1 重新发布,内容相同)。
@@ -457,12 +457,14 @@ library: {
457
457
  | 动作 | 用途 | 关键参数 |
458
458
  |---|---|---|
459
459
  | `status` | 看当前阶段、材料数、条目数、下一步 | — |
460
- | `ingest` | 导入材料并切分,返回切分预览 | `file` 或 `text`、`id`、`kind`、`realm`、`continuity`、`phase` |
461
- | `commit` | 写入带原文证据的条目,逐条校验引文 | `records`(数组) |
460
+ | `ingest` | 导入材料并切分,返回全部单元的标题、字数与前 120 字 | `file` 或 `text`、`id`、`kind`、`realm`、`continuity`、`phase` |
461
+ | `read-unit` | 取某一段的全文,抽取时按段读 | `source_id`、`unit_id` |
462
+ | `commit` | 写入带原文证据的条目,逐条校验引文;`dry_run` 只预检不写盘 | `records`(数组)、`dry_run` |
463
+ | `confirm` | 记录用户确认(`records` / `proposal` / `visual`),闸门依据它放行 | `key` |
462
464
  | `allocate` | 算两套取舍方案并落盘所选 | `scheme`、`startPhase`、`complexity` |
463
- | `propose` | 生成方案文档给人看 | `startPhase`、`complexity` |
465
+ | `propose` | 生成方案文档给人看(需先 `confirm records`) | `startPhase`、`complexity` |
464
466
  | `approve` | 记录用户选定的方案 | `scheme` = A 或 B |
465
- | `write` | 生成世界书条目并跑 LIB 校验 | `scheme`、`startPhase` |
467
+ | `write` | 生成世界书条目并跑 LIB 校验(需 `confirm records` + 方案已批准) | `scheme`、`startPhase` |
466
468
  | `visual` | 保存视觉参考交付文档 | `visual`(数组,需 `use` 与 `note`) |
467
469
  | `pause` / `resume` | 暂停与恢复 | — |
468
470
  | `next-batch` | 开下一批(受上限约束) | — |
@@ -500,6 +502,38 @@ library: {
500
502
 
501
503
  ---
502
504
 
505
+ ## 二十、只有材料、没有要求时
506
+
507
+ 用户只丢了一个文件或附件、没有说玩法时,**不要直接进入第一部分**。先问一句:
508
+
509
+ ```text
510
+ 我有材料了,但你还没说要做什么。两个选择:
511
+ ① 你补充要求(玩家演谁、想要什么玩法、类型、尺度),我先把材料整理成资料库,整理完停下等你说下一步;
512
+ ② 我自由创作,我按资料库 → 取舍方案 → 写卡一路做下去。
513
+ 你选哪个?
514
+ ```
515
+
516
+ 两个分支的边界(硬规则):
517
+
518
+ | 选择 | 做到哪里停 | 不许做什么 |
519
+ |---|---|---|
520
+ | 补充要求 | **只做资料库**:ingest → commit → 条目清单确认,停在 P2 | 不许 propose、不许 write、不许写第一部分、不许写卡名方案 |
521
+ | 自由创作 | 按正常流程继续:两套取舍方案 → 用户选定 → 世界书 → 第一部分 | — |
522
+
523
+ 判断依据是「有没有玩家意图」,不是「有没有说话」:
524
+
525
+ - 用户说「我想演那个被救的人」→ 算补充要求(有意图);
526
+ - 用户只说「做同人卡」→ 没有具体意图,按上面问一句;
527
+ - 用户说了要什么但没给材料 → 走第三节(材料缺失的三条路)。
528
+
529
+ 停在 P2 之后,等用户补一句初始化指令再继续;用户不补就一直停着,不要自己往下推。
530
+
531
+ ## 二十一、两个提高质量的写法
532
+
533
+ **核心规则双写进 ppt。** 当常驻预算紧张时,把最核心的 2–4 条世界规则(比如「这个世界是模拟」「死了就是真死」)同时写进主提示词的世界事实里。主提示词每轮都在,比占用世界书预算更稳;世界书里那一条可以降为条件触发。
534
+
535
+ **不要用 sleep 轮询子任务。** 抽取交给子任务时,不要 `Start-Sleep` 反复查文件;按子任务返回结果继续,或一次查完。sleep 只会在真实环境里白白浪费时间。
536
+
503
537
  ## 十八、分期
504
538
 
505
539
  | 阶段 | 内容 |
package/index.js CHANGED
@@ -1217,6 +1217,10 @@ export function apply(ctx) {
1217
1217
  '## 资料库流程(同人 / 改编 / 参考材料)',
1218
1218
  '触发:用户说明作品是既有作品的同人、改编、续写、二创,或已提供小说、剧本、设定集、游戏文本等材料(工作区目录或对话附件都算),或要求「按原作做」→ 启动资料库流程,先读 supplements/资料库.md。',
1219
1219
  '- 只出现「同人」二字但没有指向既有作品、也没有材料,或处于否定语境(不要同人、别用原作设定),不触发,按普通原创卡处理。',
1220
+ '- 只有材料、没有任何玩法要求时(只发了文件或附件):不要直接进入第一部分。先问一句「你有具体要求(玩家演谁、想要什么玩法/类型/尺度),还是让我自由创作?」',
1221
+ ' · 选「补充要求」→ 只把材料整理成资料库(ingest → commit → 条目清单确认),到此停下等玩家补充初始化指令;不要 propose、不要 write、不要转入第一部分。',
1222
+ ' · 选「自由创作」→ 按正常流程继续(两套取舍方案 → 世界书 → 第一部分)。',
1223
+ ' · 判断依据是「有没有玩家意图」,不是「有没有说话」:用户说了想看什么、想演谁,就算补充要求。',
1220
1224
  '- 用户说要同人但没给材料:问一句要不要上传;上传则继续;不传则取消该流程,按原创卡做,不再追问,也不留任何资料库文件。',
1221
1225
  '- 对话附件先落盘到工作区的 .card-build/library/sources/ 再读取。',
1222
1226
  '- 用户想做同人但没材料时,给三条路:① 自己上传(推荐,免费、来源清楚);② 我帮你找(调用搜索与网页抓取,按次计费);③ 直接做原创卡。不要只问「传不传」。',
@@ -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,7 @@
1
+ // 资料库模块统一出口
2
+ export * from './sources.js';
3
+ export * from './records.js';
4
+ export * from './budget.js';
5
+ export * from './mapping.js';
6
+ export * from './validate.js';
7
+ export * from './state.js';
@@ -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
+ }