dsh-novel-game 0.2.0 → 0.3.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,47 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## 0.3.0 — 2026-11-29
4
+
5
+ 新增 Godot 与 Unity(文本文件层)两个 P1 引擎,以及摘录改绑。
6
+
7
+ ### 新增
8
+
9
+ - **Godot**:`.pck` 归档(format v1/v2 头、条目索引、加密包拒绝、64MB 条目上限)+ 散装 `.tscn/.tres/.csv/.json/.txt/.po`;`text = "..."` 文本按节点分场景,剥离 BBCode;其它文本文件走通用嗅探解析。Godot 场景文本标低置信(UI/对话混排)。
10
+ - **Unity(文本文件层)**:检测 `*_Data/globalgamemanagers`、`Managed`、`UnityPlayer.dll`、`GameAssembly.dll`;读取 `*_Data/StreamingAssets/` 下的 CSV/JSON/TXT/PO/XML 本地化与对话表。序列化资产(`.assets`)、IL2CPP、加密 AB 包明确不支持。
11
+ - **摘录改绑**:`addPick` 记录原文 `quote`;`picks` 对失效摘录按原文找唯一候选;`game_pick action=remap` 把摘录改绑到候选行,不再只能标 stale。
12
+
13
+ ### 测试
14
+
15
+ - 28 项全过(新增 Godot PCK/`.tscn`、Unity StreamingAssets、摘录改绑)。
16
+
17
+ ### 已知限制
18
+
19
+ - Godot 场景文本无法区分 UI 与剧情,默认低置信;`[link]`/对话插件(Dialogic 等)未专门解析。
20
+ - Unity 只覆盖文本文件层;`.assets` 里的 TextAsset 不解析。
21
+ - GameMaker(`data.win` STRG)排在 0.3.1。
22
+ - 搜索/导出仍是全量扫描;索引分片与流式导出排在 0.3.1。
23
+
24
+ ## 0.2.1 — 2026-11-29
25
+
26
+ 修复 Codex 对 0.1.0 代码审查发现的 P0/P1(记录:`docs/REVIEW-0.1.0.md`)。
27
+
28
+ ### 修复
29
+
30
+ - **任务 ID 路径穿越**:`jobs` 读写先校验 jobId 只允许 `[A-Za-z0-9_-]`,并走插件根路径守卫。
31
+ - **游戏/插件目录互相包含**:工作区在游戏目录内、或游戏目录在 `.dsh-novel-game/` 内,直接拒绝(防止写入落进游戏目录)。
32
+ - **同标题不同目录共用 gameId**:检测到冲突时把游戏根路径掺进 gameId,两个副本不再互相覆盖。
33
+ - **并发导入**:同一游戏根加文件锁(`locks/<hash>.lock`,10 分钟过期),冲突返回 `BUSY`。
34
+ - **manifest 损坏**:读 manifest 区分「不存在」与「损坏」;损坏时抛 `IO_ERROR`,不再当首次导入、不会 prune 掉旧代。
35
+ - **归档增量丢内容**:`.rpa`/`.xp3` 内文本统一用外层归档作为容器键(条目名进 `src.path`),增量重导不再丢归档内剧情。
36
+ - **删除来源残留**:合并旧聚合前先与当前容器集合求交,删掉的地图/脚本不再留下场景、选项、词条。
37
+ - **Ren'Py 菜单分支体**:选项块里的对白/跳转继续解析(只跳过选项标签行);label 边界重置菜单提示。
38
+ - **复用与计数**:分片复制失败回退重抽;行/资产/未解析/条件计数从新代分片重算,不再报 0;词条型文件无分片时不误判失败。
39
+ - **只读探测副作用**:`game_detect` 不再创建 `games/`、`jobs/`。
40
+
41
+ ### 测试
42
+
43
+ - 25 项全过(新增 7 项回归:归档增量、删除来源、manifest 损坏、jobId 越界、重复 gameId、目录边界、菜单分支体)。
44
+
3
45
  ## 0.2.0 — 2026-11-29
4
46
 
5
47
  新增 KiriKiri / NScripter 两个 Galgame 引擎、Wolf RPG 文本抢救、剧情路线图与摘录失效标记。
package/README.md CHANGED
@@ -53,7 +53,9 @@ npm i dsh-novel-game
53
53
  | KiriKiri / KAG | 0.2.0 | `.xp3` 归档 + 散装 `.ks`:label、对白、`@jump/@call`、标签剥离 |
54
54
  | NScripter / ONScripter | 0.2.0 | `nscript.dat`(XOR)/`0.txt`:对白、`select` 选项、`goto/jumpf`;`.nsa` 报不支持 |
55
55
  | Wolf RPG Editor | 0.2.0(文本抢救) | `Data/*.dat` 里可读文本段;低置信,默认不显示/不导出 |
56
- | Godot / Unity / GameMaker | 0.3.0 计划 | — |
56
+ | Godot | 0.3.0 | `.pck`(v1/v2)与散装 `.tscn/.tres/.csv/.json/.txt`;`text = "..."` 按节点分场景 |
57
+ | Unity | 0.3.0(文本文件层) | `*_Data/StreamingAssets` 下的 CSV/JSON/TXT/PO 本地化与对话表 |
58
+ | GameMaker | 0.3.1 计划 | — |
57
59
 
58
60
  `.rpyc` 编译脚本在 0.1.0 不解反编译:会出现在覆盖率报告里并提示用 `unrpyc` 或提供明文脚本。
59
61
 
@@ -85,7 +87,7 @@ npm i dsh-novel-game
85
87
  | `game_routes` | 剧情路线图(节点/边/候选结局) |
86
88
  | `game_search` | 台词与词条检索 |
87
89
  | `game_characters` / `game_glossary` | 人物卡草稿 / 词条 |
88
- | `game_pick` | 同人准备篮(add / list) |
90
+ | `game_pick` | 同人准备篮(add / list / remap 改绑失效摘录) |
89
91
  | `game_export` | 导出三件套 |
90
92
 
91
93
  ## 开发
@@ -97,13 +99,15 @@ npm run check
97
99
 
98
100
  零运行时依赖;纯 Node ESM。
99
101
 
100
- ## 已知限制(0.2.0)
102
+ ## 已知限制(0.3.0)
101
103
 
102
- - 大 JSON 目前整文件解析(有 32MB 上限),流式 tokenizer 排在 0.2.1。
104
+ - 大 JSON 目前整文件解析(有 32MB 上限),流式 tokenizer 排在 0.3.1。
103
105
  - `.rpyc` 不反编译;`.rpa` 只支持受限 pickle 子集(白名单外拒绝)。
104
106
  - 不模拟 RPG Maker 的开关/变量;条件页并列展示为候选剧情,不声称实际游玩顺序。
105
107
  - Wolf RPG 只做文本抢救(`Game.dat` 常见加密,不破解);NScripter 的 `.nsa` 不解包。
106
- - KiriKiri 的 `[link]` 选项没有单独建边;Unity / Godot / GameMaker 未支持。
108
+ - KiriKiri 的 `[link]` 选项没有单独建边。
109
+ - Godot 场景文本分不清 UI 与剧情(低置信);Unity 只覆盖 StreamingAssets 文本层;GameMaker 未支持。
110
+ - 搜索/导出仍是全量扫描(索引分片与流式导出排 0.3.1)。
107
111
 
108
112
  ## 共同作者
109
113
 
package/docs/ENGINES.md CHANGED
@@ -67,9 +67,24 @@
67
67
  - 参考:[Sinflower/UberWolf](https://github.com/Sinflower/UberWolf)(加密与归档的权威实现;本插件不集成)。
68
68
  - 0.2.1 计划:`.wolf` 归档读取与明文 `Game.dat` 的结构化抽取。
69
69
 
70
- ## 0.3.0 计划
70
+ ## Godot(0.3.0)
71
71
 
72
- - Godot:`.pck` + `.tscn/.tres` + 翻译表。
73
- - Unity:`StreamingAssets` 本地化表、`TextAsset` 内嵌对话。
74
- - GameMaker:`data.win` 的 `STRG` 字符串表。
75
- - 参考:[Not-Parker/godot-pck-reader](https://github.com/Not-Parker/godot-pck-reader)、[AssetRipper/AssetRipper](https://github.com/AssetRipper/AssetRipper)、[UnderminersTeam/UndertaleModTool](https://github.com/UnderminersTeam/UndertaleModTool)。
72
+ - `.pck`:magic `GDPC`;v1/v2 头(v2 多 `flags` 与 `file_base`);条目 `path_len + path + offset/size(u64) + md5[16] + flags(v2)`,路径 4 字节对齐;`flags & 1` 视为加密包,直接拒绝。
73
+ - 散装项目:`project.godot`、`*.tscn`、`*.tres`、`*.csv/.json/.txt/.po`。
74
+ - `.tscn/.tres`:按 `[node name=... type=...]` 分场景,取 `text = "..."`,剥离 BBCode;标低置信(UI 与剧情混排)。
75
+ - CSV/JSON/TXT/PO:走通用嗅探解析。
76
+ - 不做:`.gd` 脚本、`.translation` 二进制、Dialogic 等插件专用格式(0.3.1 评估)。
77
+
78
+ ## Unity(0.3.0,文本文件层)
79
+
80
+ - 检测:`*_Data/globalgamemanagers`、`*_Data/Managed`、`StreamingAssets`、`UnityPlayer.dll`、`GameAssembly.dll`。
81
+ - 抽取:`*_Data/StreamingAssets/` 下 CSV/TSV/JSON/TXT/PO/XML,按通用嗅探解析;文件名作场景名,标低置信。
82
+ - 不做:`.assets`/AssetBundle/IL2CPP、`TextAsset` 二进制、加密 AB。
83
+ - 参考:[AssetRipper/AssetRipper](https://github.com/AssetRipper/AssetRipper)、[K0lb3/UnityPy](https://github.com/K0lb3/UnityPy)(仅格式参考,不集成)。
84
+
85
+ ## 0.3.1 计划
86
+
87
+ - GameMaker:`data.win` 的 `STRG` 字符串表与 `CODE` 引用。
88
+ - Godot:Dialogic/自定义对话格式、`.translation`。
89
+ - 检索索引分片 + 流式导出;KiriKiri `[link]` 建边;Wolf 抢救噪声过滤。
90
+ - 参考:[UnderminersTeam/UndertaleModTool](https://github.com/UnderminersTeam/UndertaleModTool)。
@@ -0,0 +1,39 @@
1
+ # dsh-novel-game — Codex 0.1.0 代码审查与修复(2026-11-29)
2
+
3
+ > 审查:桌面端 Codex,只读,按 P0/P1/P2 带文件行号输出(`tmp/2026-11-29-game-0.1.0-Codex审查任务书.md`)。
4
+ > 修复版本:**0.2.1**。测试:25/25 通过。
5
+
6
+ ## 已修(P0/P1)
7
+
8
+ | Codex 结论 | 修复 |
9
+ |---|---|
10
+ | 任务 ID 路径越界 | `jobs` 读写前 `assertSafeId` + `pluginPath`,`../` 直接 `INVALID_INPUT` |
11
+ | 存储根/游戏目录边界未验证 | `assertSeparateRoots`:游戏目录在插件目录内、或工作区在游戏目录内,都拒绝 |
12
+ | 重复 gameId 冲突 | 同指纹不同 root 时把 root 掺进 `gameId`(`gameIdOf` 支持 salt) |
13
+ | 并发导入丢更新 | 按游戏根加文件锁,10 分钟过期,冲突 `BUSY` |
14
+ | 损坏 manifest 后旧代可能被 prune | `readManifest` 区分 ENOENT 与损坏;损坏抛 `IO_ERROR`,不进入 finalize |
15
+ | RPA 增量重导丢内容 | 归档内文本统一外层归档 relPath,条目名进 `src.path`;场景/分片/覆盖率同一容器键 |
16
+ | 删除来源残留 | 合并旧聚合前与当前容器集合求交 |
17
+ | Ren'Py 菜单分支体漏解析 | 只跳过选项标签行,分支体继续解析;label 边界重置 `lastText` |
18
+
19
+ ## 顺带修(P2)
20
+
21
+ - 复用分片复制失败 → 回退重抽,不再标 `reused`。
22
+ - 计数从新代分片重算(修复复用文件 `lines/assets/skipped/conditions` 报 0)。
23
+ - 词条型文件无分片时不再误判复制失败。
24
+ - `game_detect` 不再创建目录(只读探测真正只读)。
25
+ - generation 保留数改为「当前代 + 上一代」总 2 代,与注释一致。
26
+
27
+ ## 未修 / 排到 0.3.0
28
+
29
+ | 结论 | 原因 |
30
+ |---|---|
31
+ | 搜索/导出全量扫描、内存峰值 | 需要索引与流式导出,0.3.0 统一做 |
32
+ | 通用嗅探的 JSON/CSV 启发式误判 | 需要更强的置信度与人工确认流 |
33
+ | KiriKiri `[link]` 选项未建边 | 需要解析 link 块结构 |
34
+ | Wolf 文本抢救噪声 | 低置信已隔离,后续做白名单/词典过滤 |
35
+ | 游戏目录只读的 OS 级保证 | 目前是代码级只读;OS 级只读需要平台能力 |
36
+
37
+ ## 结论
38
+
39
+ P0 全部修复;P1 全部修复;P2 中影响正确性的部分已修,性能与启发式问题登记到 0.3.0。发布 0.2.1。
package/index.js CHANGED
@@ -41,9 +41,9 @@ async function requireDir(args, exec) {
41
41
  return dir;
42
42
  }
43
43
 
44
- async function serviceFor(dir) {
44
+ async function serviceFor(dir, { init = true } = {}) {
45
45
  const service = new GameService({ workspace: dir });
46
- await service.init();
46
+ if (init) await service.init();
47
47
  return service;
48
48
  }
49
49
 
@@ -89,7 +89,7 @@ const tools = [
89
89
  },
90
90
  output,
91
91
  execute: guarded(async (args, exec) => {
92
- const service = await serviceFor(await requireDir(args, exec));
92
+ const service = await serviceFor(await requireDir(args, exec), { init: false });
93
93
  return service.detect({ gameRoot: path.resolve(args.path) });
94
94
  }),
95
95
  },
@@ -248,7 +248,8 @@ const tools = [
248
248
  properties: {
249
249
  dir: dirParam,
250
250
  gameId: gameIdParam,
251
- action: { type: 'string', enum: ['add', 'list'] },
251
+ action: { type: 'string', enum: ['add', 'list', 'remap'] },
252
+ pickId: { type: 'string', description: 'action=remap 时要改绑的摘录 ID' },
252
253
  kind: { type: 'string', enum: ['line', 'scene', 'glossary', 'character'] },
253
254
  refId: { type: 'string' },
254
255
  note: { type: 'string' },
@@ -261,6 +262,7 @@ const tools = [
261
262
  execute: guarded(async (args, exec) => {
262
263
  const service = await serviceFor(await requireDir(args, exec));
263
264
  if (args.action === 'list') return service.picks(args.gameId);
265
+ if (args.action === 'remap') return service.remapPick(args.gameId, { pickId: args.pickId });
264
266
  return service.addPick(args.gameId, {
265
267
  kind: args.kind ?? 'line',
266
268
  refId: args.refId,
@@ -0,0 +1,234 @@
1
+ import path from 'node:path';
2
+ import { isPck, readPckEntry, readPckIndex } from '../archive/pck.mjs';
3
+ import { parseGenericFile } from './generic.mjs';
4
+
5
+ const TEXT_EXT = /\.(tscn|tres|csv|json|txt|po|md)$/i;
6
+ const BBCode = /\[\/?[a-zA-Z][^\]]*\]/g;
7
+
8
+ function unescapeTscn(value) {
9
+ return String(value)
10
+ .replace(/\\n/g, '\n')
11
+ .replace(/\\t/g, '\t')
12
+ .replace(/\\"/g, '"')
13
+ .replace(/\\\\/g, '\\');
14
+ }
15
+
16
+ /**
17
+ * Godot 场景/资源里的可见文本:`text = "..."`(Label/RichTextLabel 等)。
18
+ * 只做静态读取:不还原节点继承,不执行脚本。
19
+ */
20
+ export function* parseGodotText(text, { relPath, pathPrefix = '' }) {
21
+ const lines = String(text).split(/\r?\n/);
22
+ let node = null;
23
+ let nodeType = null;
24
+ let sceneKey = null;
25
+ let sceneOrder = 0;
26
+ let lineOrder = 0;
27
+
28
+ const ensureScene = function* () {
29
+ if (sceneKey) return;
30
+ sceneKey = `${relPath}#${pathPrefix}node:${node ?? 'root'}`;
31
+ yield {
32
+ type: 'scene',
33
+ key: sceneKey,
34
+ title: node ? `${node}${nodeType ? ` (${nodeType})` : ''}` : '场景文本',
35
+ container: relPath,
36
+ order: sceneOrder++,
37
+ conditions: null,
38
+ lowConfidence: true,
39
+ src: { relPath, path: `${pathPrefix}node:${node ?? 'root'}` },
40
+ };
41
+ };
42
+
43
+ for (let index = 0; index < lines.length; index += 1) {
44
+ const trimmed = lines[index].trim();
45
+ const nodeMatch = /^\[node\s+name="([^"]+)"(?:\s+type="([^"]+)")?/.exec(trimmed);
46
+ if (nodeMatch) {
47
+ node = nodeMatch[1];
48
+ nodeType = nodeMatch[2] ?? null;
49
+ sceneKey = null;
50
+ lineOrder = 0;
51
+ continue;
52
+ }
53
+ const textMatch = /^text\s*=\s*"((?:[^"\\]|\\.)*)"\s*$/.exec(trimmed);
54
+ if (!textMatch) continue;
55
+ const value = unescapeTscn(textMatch[1]).replace(BBCode, '').trim();
56
+ if (!value || /^(res:\/\/|uid:\/\/|0$)/.test(value)) continue;
57
+ yield* ensureScene();
58
+ yield {
59
+ type: 'line',
60
+ sceneKey,
61
+ order: lineOrder++,
62
+ kind: 'narration',
63
+ speakerId: null,
64
+ speakerName: null,
65
+ text: value,
66
+ refs: {},
67
+ src: { relPath, path: `${pathPrefix}line:${index + 1}`, index },
68
+ };
69
+ }
70
+ }
71
+
72
+ function* parseTextFile(text, relPath, pathPrefix = '') {
73
+ const ext = path.extname(relPath).toLowerCase();
74
+ if (ext === '.tscn' || ext === '.tres') {
75
+ yield* parseGodotText(text, { relPath, pathPrefix });
76
+ return;
77
+ }
78
+ const parsed = parseGenericFile(text, relPath, ext);
79
+ if (parsed.length === 0) return;
80
+ const sceneKey = `${relPath}#${pathPrefix}file`;
81
+ yield {
82
+ type: 'scene',
83
+ key: sceneKey,
84
+ title: path.basename(relPath),
85
+ container: relPath,
86
+ order: 0,
87
+ conditions: null,
88
+ lowConfidence: true,
89
+ src: { relPath, path: `${pathPrefix}file` },
90
+ };
91
+ for (let index = 0; index < parsed.length; index += 1) {
92
+ const item = parsed[index];
93
+ if (!item.text?.trim()) continue;
94
+ yield {
95
+ type: 'line',
96
+ sceneKey,
97
+ order: index,
98
+ kind: item.speaker ? 'dialogue' : 'narration',
99
+ speakerId: item.speaker ? `name:${item.speaker}` : null,
100
+ speakerName: item.speaker || null,
101
+ text: item.text.trim(),
102
+ refs: {},
103
+ src: { relPath, path: `${pathPrefix}${item.addr}`, index },
104
+ };
105
+ }
106
+ }
107
+
108
+ async function walk(ctx, dir, extensions, depth = 2, level = 0, out = []) {
109
+ if (level > depth) return out;
110
+ for (const entry of await ctx.list(dir)) {
111
+ if (entry.dir) await walk(ctx, entry.rel, extensions, depth, level + 1, out);
112
+ else if (extensions.some((ext) => entry.name.toLowerCase().endsWith(ext))) out.push(entry.rel);
113
+ }
114
+ return out;
115
+ }
116
+
117
+ export const godot = {
118
+ id: 'godot',
119
+ label: 'Godot',
120
+
121
+ async detect(ctx) {
122
+ const evidence = [];
123
+ let score = 0;
124
+ if (await ctx.exists('project.godot')) {
125
+ score = 0.92;
126
+ evidence.push('project.godot');
127
+ }
128
+ const pcks = await walk(ctx, '.', ['.pck'], 1);
129
+ if (pcks.length) {
130
+ score = Math.max(score, 0.86);
131
+ evidence.push(`${pcks.length} 个 .pck`);
132
+ }
133
+ const scenes = await walk(ctx, '.', ['.tscn'], 2);
134
+ if (scenes.length) {
135
+ score = Math.max(score, score ? score : 0.8);
136
+ evidence.push(`${scenes.length} 个 .tscn`);
137
+ }
138
+ if (await ctx.exists('godot.exe') || (await ctx.list('.')).some((entry) => /godot/i.test(entry.name))) {
139
+ score = Math.max(score, score ? score : 0.72);
140
+ evidence.push('Godot 可执行文件/名称');
141
+ }
142
+ if (score === 0) return null;
143
+ return {
144
+ engineId: 'godot',
145
+ label: 'Godot',
146
+ confidence: score,
147
+ variant: 'godot',
148
+ evidence: [...new Set(evidence)],
149
+ title: path.basename(ctx.root),
150
+ pcks,
151
+ scenes,
152
+ };
153
+ },
154
+
155
+ async open(ctx, detection) {
156
+ const pcks = detection.pcks ?? (await walk(ctx, '.', ['.pck'], 1));
157
+ const loose = await walk(ctx, '.', ['.tscn', '.tres', '.csv', '.json', '.txt', '.po'], 2);
158
+ const containers = [
159
+ ...pcks.map((rel) => ({ rel, kind: 'archive', textBearing: true, note: 'PCK' })),
160
+ ...loose.map((rel) => ({ rel, kind: 'text', textBearing: true, note: '' })),
161
+ ];
162
+
163
+ return {
164
+ id: 'godot',
165
+ meta() {
166
+ return {
167
+ title: detection.title || path.basename(ctx.root),
168
+ engine: 'Godot',
169
+ variant: 'godot',
170
+ encrypted: false,
171
+ dataDir: '.',
172
+ pckCount: pcks.length,
173
+ fileCount: loose.length,
174
+ };
175
+ },
176
+ containers() {
177
+ return containers;
178
+ },
179
+ fingerprintFiles() {
180
+ return [...(detection.scenes ?? []).slice(0, 2), ...pcks.slice(0, 1)];
181
+ },
182
+
183
+ async *extract(options = {}) {
184
+ const shouldRead = typeof options.shouldRead === 'function' ? options.shouldRead : () => true;
185
+
186
+ for (const rel of loose) {
187
+ if (!shouldRead(rel)) continue;
188
+ try {
189
+ const { text } = await ctx.readText(rel, 16 * 1024 * 1024);
190
+ yield* parseTextFile(text, rel);
191
+ } catch (error) {
192
+ yield { type: 'error', relPath: rel, message: error.message };
193
+ }
194
+ }
195
+
196
+ for (const rel of pcks) {
197
+ if (!shouldRead(rel)) continue;
198
+ let buffer;
199
+ try {
200
+ buffer = await ctx.readBuffer(rel, 1024 * 1024 * 1024);
201
+ } catch (error) {
202
+ yield { type: 'error', relPath: rel, message: error.message };
203
+ continue;
204
+ }
205
+ if (!isPck(buffer)) {
206
+ yield { type: 'error', relPath: rel, message: '不是 Godot PCK(可能嵌入可执行文件)' };
207
+ continue;
208
+ }
209
+ let info;
210
+ try {
211
+ info = readPckIndex(buffer);
212
+ } catch (error) {
213
+ yield { type: 'error', relPath: rel, message: error.message };
214
+ continue;
215
+ }
216
+ const encrypted = (info.flags & 1) === 1;
217
+ for (const entry of info.entries) {
218
+ if (!TEXT_EXT.test(entry.name)) continue;
219
+ let content;
220
+ try {
221
+ content = readPckEntry(buffer, entry, { encrypted });
222
+ } catch (error) {
223
+ yield { type: 'error', relPath: `${rel}!${entry.name}`, message: error.message };
224
+ continue;
225
+ }
226
+ yield* parseTextFile(content.toString('utf8'), entry.name, `${entry.name}:`);
227
+ }
228
+ }
229
+ },
230
+ };
231
+ },
232
+ };
233
+
234
+ export default godot;
@@ -5,7 +5,7 @@ import { isXp3, readXp3Entry, readXp3Index } from '../archive/xp3.mjs';
5
5
  * KAG 剧本解析(KiriKiri .ks)。
6
6
  * 只做静态解析:标签、文本行、跳转;不解释表达式、不执行。
7
7
  */
8
- export function* parseKagScript(text, { relPath }) {
8
+ export function* parseKagScript(text, { relPath, pathPrefix = '' }) {
9
9
  const lines = String(text).split(/\r?\n/);
10
10
  let sceneKey = null;
11
11
  let sceneOrder = 0;
@@ -14,8 +14,8 @@ export function* parseKagScript(text, { relPath }) {
14
14
 
15
15
  const ensureScene = function* () {
16
16
  if (sceneKey) return;
17
- sceneKey = `${relPath}#top`;
18
- yield { type: 'scene', key: sceneKey, title: '开场', container: relPath, order: sceneOrder++, conditions: null, src: { relPath, path: 'top' } };
17
+ sceneKey = `${relPath}#${pathPrefix}top`;
18
+ yield { type: 'scene', key: sceneKey, title: '开场', container: relPath, order: sceneOrder++, conditions: null, src: { relPath, path: `${pathPrefix}top` } };
19
19
  };
20
20
 
21
21
  for (let index = 0; index < lines.length; index += 1) {
@@ -23,12 +23,12 @@ export function* parseKagScript(text, { relPath }) {
23
23
  const trimmed = raw.trim();
24
24
  if (!trimmed) continue;
25
25
  if (trimmed.startsWith(';') || trimmed.startsWith('//')) continue;
26
- const src = { relPath, path: `line:${index + 1}`, index };
26
+ const src = { relPath, path: `${pathPrefix}line:${index + 1}`, index };
27
27
 
28
28
  const labelMatch = /^\*([A-Za-z_][\w.-]*)\s*$/.exec(trimmed);
29
29
  if (labelMatch) {
30
30
  label = labelMatch[1];
31
- sceneKey = `${relPath}#label:${label}`;
31
+ sceneKey = `${relPath}#${pathPrefix}label:${label}`;
32
32
  lineOrder = 0;
33
33
  yield { type: 'scene', key: sceneKey, title: label, container: relPath, order: sceneOrder++, conditions: null, src };
34
34
  continue;
@@ -185,8 +185,7 @@ export const kirikiri = {
185
185
  yield { type: 'error', relPath: `${rel}!${entry.name}`, message: error.message };
186
186
  continue;
187
187
  }
188
- const virtual = `${rel}!${entry.name}`;
189
- yield* parseKagScript(content.toString('utf8'), { relPath: virtual });
188
+ yield* parseKagScript(content.toString('utf8'), { relPath: rel, pathPrefix: `${entry.name}:` });
190
189
  }
191
190
  }
192
191
  },
@@ -4,8 +4,10 @@ import { generic } from './generic.mjs';
4
4
  import { kirikiri } from './kirikiri.mjs';
5
5
  import { nscripter } from './nscripter.mjs';
6
6
  import { wolf } from './wolf.mjs';
7
+ import { godot } from './godot.mjs';
8
+ import { unity } from './unity.mjs';
7
9
 
8
- export const ADAPTERS = [rpgmaker, renpy, kirikiri, nscripter, wolf, generic];
10
+ export const ADAPTERS = [rpgmaker, renpy, kirikiri, nscripter, wolf, godot, unity, generic];
9
11
 
10
12
  export function getAdapter(id) {
11
13
  return ADAPTERS.find((adapter) => adapter.id === id) ?? null;
@@ -71,14 +71,14 @@ function parseMenuBlock(lines, startIndex) {
71
71
  }
72
72
  options.push({ id: options.length, text, targetLabel });
73
73
  }
74
- return { end, options };
74
+ return { end, options, optionLines: optionLines.map((entry) => entry.index) };
75
75
  }
76
76
 
77
77
  /**
78
78
  * 解析一个 Ren'Py 脚本(明文 .rpy)。
79
79
  * 只做静态解析:不执行 $ / python: 块,不求值条件;screen 文本不混入剧情。
80
80
  */
81
- export function* parseRenpyScript(text, { relPath }) {
81
+ export function* parseRenpyScript(text, { relPath, pathPrefix = '' }) {
82
82
  const lines = String(text).split(/\r?\n/);
83
83
  const characters = new Map();
84
84
  let sceneKey = null;
@@ -88,10 +88,11 @@ export function* parseRenpyScript(text, { relPath }) {
88
88
  let lastText = '';
89
89
  let pendingVoice = null;
90
90
  let skipDeeperThan = null;
91
+ const skipLines = new Set();
91
92
 
92
93
  const ensureScene = function* () {
93
94
  if (sceneKey) return;
94
- sceneKey = `${relPath}#top`;
95
+ sceneKey = `${relPath}#${pathPrefix}top`;
95
96
  sceneTitle = '开场';
96
97
  yield {
97
98
  type: 'scene',
@@ -100,28 +101,30 @@ export function* parseRenpyScript(text, { relPath }) {
100
101
  container: relPath,
101
102
  order: sceneOrder++,
102
103
  conditions: null,
103
- src: { relPath, path: 'top' },
104
+ src: { relPath, path: `${pathPrefix}top` },
104
105
  };
105
106
  };
106
107
 
107
108
  for (let index = 0; index < lines.length; index += 1) {
108
109
  const raw = lines[index];
109
110
  const trimmed = raw.trim();
110
- if (!trimmed || trimmed.startsWith('#')) continue;
111
+ if (!trimmed || skipLines.has(index)) continue;
112
+ if (trimmed.startsWith('#')) continue;
111
113
  const indent = indentOf(raw);
112
114
 
113
115
  if (skipDeeperThan !== null) {
114
116
  if (indent > skipDeeperThan) continue;
115
117
  skipDeeperThan = null;
116
118
  }
117
- const src = { relPath, path: `line:${index + 1}`, index };
119
+ const src = { relPath, path: `${pathPrefix}line:${index + 1}`, index };
118
120
 
119
121
  // label → 新场景
120
122
  const labelMatch = /^label\s+([A-Za-z_][\w.]*)\s*(?:\([^)]*\))?\s*:/.exec(trimmed);
121
123
  if (labelMatch && indent === 0) {
122
- sceneKey = `${relPath}#label:${labelMatch[1]}`;
124
+ sceneKey = `${relPath}#${pathPrefix}label:${labelMatch[1]}`;
123
125
  sceneTitle = labelMatch[1];
124
126
  lineOrder = 0;
127
+ lastText = '';
125
128
  yield {
126
129
  type: 'scene',
127
130
  key: sceneKey,
@@ -144,7 +147,7 @@ export function* parseRenpyScript(text, { relPath }) {
144
147
 
145
148
  // 菜单
146
149
  if (/^menu\s*:/.test(trimmed)) {
147
- const { end, options } = parseMenuBlock(lines, index);
150
+ const { options, optionLines } = parseMenuBlock(lines, index);
148
151
  yield* ensureScene();
149
152
  if (options.length > 0) {
150
153
  yield {
@@ -157,7 +160,8 @@ export function* parseRenpyScript(text, { relPath }) {
157
160
  };
158
161
  lastText = '';
159
162
  }
160
- index = end - 1;
163
+ // 不跳过整个块:让选项分支体里的对白/跳转继续被主循环解析;只跳过选项标签行。
164
+ for (const lineIndex of optionLines) skipLines.add(lineIndex);
161
165
  continue;
162
166
  }
163
167
 
@@ -373,8 +377,7 @@ export const renpy = {
373
377
  continue;
374
378
  }
375
379
  const text = content.toString('utf8');
376
- const virtual = `${rel}!${entry.name}`;
377
- yield* parseRenpyScript(text, { relPath: virtual });
380
+ yield* parseRenpyScript(text, { relPath: rel, pathPrefix: `${entry.name}:` });
378
381
  }
379
382
  } catch (error) {
380
383
  yield { type: 'error', relPath: rel, message: error.message };
@@ -0,0 +1,146 @@
1
+ import path from 'node:path';
2
+ import { parseGenericFile } from './generic.mjs';
3
+
4
+ const TEXT_EXT = ['.csv', '.json', '.txt', '.xml', '.po', '.tsv'];
5
+
6
+ async function walk(ctx, dir, depth = 3, level = 0, out = []) {
7
+ if (level > depth) return out;
8
+ for (const entry of await ctx.list(dir)) {
9
+ if (entry.dir) await walk(ctx, entry.rel, depth, level + 1, out);
10
+ else if (TEXT_EXT.includes(path.extname(entry.name).toLowerCase())) out.push(entry.rel);
11
+ }
12
+ return out;
13
+ }
14
+
15
+ async function findDataDirs(ctx) {
16
+ const dirs = [];
17
+ for (const entry of await ctx.list('.')) {
18
+ if (!entry.dir) continue;
19
+ if (/_Data$/i.test(entry.name) || entry.name.toLowerCase() === 'streamingassets') dirs.push(entry.rel);
20
+ }
21
+ return dirs;
22
+ }
23
+
24
+ /**
25
+ * Unity:0.3.0 只做「文本文件层」——StreamingAssets / *_Data 下的 CSV/JSON/TXT/PO 本地化表与对话表。
26
+ * 序列化资产(.assets)、IL2CPP、加密 AB 包不做。
27
+ */
28
+ export const unity = {
29
+ id: 'unity',
30
+ label: 'Unity(文本文件层)',
31
+
32
+ async detect(ctx) {
33
+ const evidence = [];
34
+ let score = 0;
35
+ const dataDirs = await findDataDirs(ctx);
36
+ for (const dir of dataDirs) {
37
+ const name = path.basename(dir);
38
+ if (/_Data$/i.test(name)) {
39
+ const hasGameManager = await ctx.exists(`${dir}/globalgamemanagers`);
40
+ const hasManaged = await ctx.exists(`${dir}/Managed`);
41
+ if (hasGameManager || hasManaged) {
42
+ score = Math.max(score, 0.9);
43
+ evidence.push(`${dir}/globalgamemanagers`);
44
+ }
45
+ }
46
+ if (name.toLowerCase() === 'streamingassets') {
47
+ const files = await walk(ctx, dir, 3);
48
+ if (files.length) {
49
+ score = Math.max(score, 0.8);
50
+ evidence.push(`${dir}/ 下 ${files.length} 个文本文件`);
51
+ }
52
+ }
53
+ }
54
+ for (const name of ['UnityPlayer.dll', 'GameAssembly.dll', 'UnityCrashHandler64.exe']) {
55
+ if (await ctx.exists(name)) {
56
+ score = Math.max(score, score ? score : 0.76);
57
+ evidence.push(name);
58
+ }
59
+ }
60
+ if (score === 0) return null;
61
+ return {
62
+ engineId: 'unity',
63
+ label: 'Unity(文本文件层)',
64
+ confidence: score,
65
+ variant: 'unity-text',
66
+ evidence,
67
+ title: path.basename(ctx.root),
68
+ dataDirs,
69
+ };
70
+ },
71
+
72
+ async open(ctx, detection) {
73
+ const dataDirs = detection.dataDirs ?? (await findDataDirs(ctx));
74
+ const files = [];
75
+ for (const dir of dataDirs) {
76
+ if (!/_Data$|streamingassets/i.test(dir)) continue;
77
+ for (const rel of await walk(ctx, dir, 3)) files.push(rel);
78
+ }
79
+ const unique = [...new Set(files)].sort();
80
+
81
+ return {
82
+ id: 'unity',
83
+ meta() {
84
+ return {
85
+ title: detection.title || path.basename(ctx.root),
86
+ engine: 'Unity(文本文件层)',
87
+ variant: 'unity-text',
88
+ encrypted: false,
89
+ dataDir: dataDirs.join(', '),
90
+ fileCount: unique.length,
91
+ };
92
+ },
93
+ containers() {
94
+ return unique.map((rel) => ({ rel, kind: 'text', textBearing: true, note: 'StreamingAssets 文本' }));
95
+ },
96
+ fingerprintFiles() {
97
+ return unique.slice(0, 3);
98
+ },
99
+
100
+ async *extract(options = {}) {
101
+ const shouldRead = typeof options.shouldRead === 'function' ? options.shouldRead : () => true;
102
+ let sceneOrder = 0;
103
+ for (const rel of unique) {
104
+ if (!shouldRead(rel)) continue;
105
+ let parsed = [];
106
+ try {
107
+ const { text } = await ctx.readText(rel, 16 * 1024 * 1024);
108
+ parsed = parseGenericFile(text, rel);
109
+ } catch (error) {
110
+ yield { type: 'error', relPath: rel, message: error.message };
111
+ continue;
112
+ }
113
+ if (parsed.length === 0) continue;
114
+ const sceneKey = `${rel}#file`;
115
+ yield {
116
+ type: 'scene',
117
+ key: sceneKey,
118
+ title: path.basename(rel),
119
+ container: rel,
120
+ order: sceneOrder++,
121
+ conditions: null,
122
+ lowConfidence: true,
123
+ src: { relPath: rel, path: 'file' },
124
+ };
125
+ for (let index = 0; index < parsed.length; index += 1) {
126
+ const item = parsed[index];
127
+ if (!item.text?.trim()) continue;
128
+ yield {
129
+ type: 'line',
130
+ sceneKey,
131
+ order: index,
132
+ kind: item.speaker ? 'dialogue' : 'narration',
133
+ speakerId: item.speaker ? `name:${item.speaker}` : null,
134
+ speakerName: item.speaker || null,
135
+ text: item.text.trim(),
136
+ refs: {},
137
+ src: { relPath: rel, path: item.addr, index },
138
+ };
139
+ }
140
+ }
141
+ },
142
+ };
143
+ },
144
+ };
145
+
146
+ export default unity;
@@ -0,0 +1,67 @@
1
+ import { GameError, ErrorCode } from '../core/errors.mjs';
2
+
3
+ const MAGIC = Buffer.from('GDPC', 'ascii');
4
+ const MAX_ENTRIES = 200000;
5
+
6
+ export function isPck(buffer) {
7
+ return buffer.length > 24 && buffer.subarray(0, 4).equals(MAGIC);
8
+ }
9
+
10
+ function align4(value) {
11
+ return (value + 3) & ~3;
12
+ }
13
+
14
+ /**
15
+ * 读取 Godot .pck 索引(format v1/v2)。
16
+ * v2 头:magic + version + major/minor/patch + flags + file_base + 16*u32 reserved + count
17
+ * 条目:path_len + path(utf8, 4 字节对齐) + offset u64 + size u64 + md5[16] + flags(v2)
18
+ */
19
+ export function readPckIndex(buffer) {
20
+ if (!isPck(buffer)) throw new GameError(ErrorCode.PARSE_ERROR, '不是 Godot .pck 归档');
21
+ let pos = 4;
22
+ const version = buffer.readUInt32LE(pos);
23
+ pos += 4;
24
+ if (version !== 1 && version !== 2) {
25
+ throw new GameError(ErrorCode.PARSE_ERROR, `不支持的 PCK 版本:${version}`);
26
+ }
27
+ const engine = { major: buffer.readUInt32LE(pos), minor: buffer.readUInt32LE(pos + 4), patch: buffer.readUInt32LE(pos + 8) };
28
+ pos += 12;
29
+ let flags = 0;
30
+ let fileBase = 0;
31
+ if (version === 2) {
32
+ flags = buffer.readUInt32LE(pos);
33
+ pos += 4;
34
+ fileBase = Number(buffer.readBigUInt64LE(pos));
35
+ pos += 8;
36
+ }
37
+ pos += 16 * 4; // reserved
38
+ const count = buffer.readUInt32LE(pos);
39
+ pos += 4;
40
+ if (count > MAX_ENTRIES) throw new GameError(ErrorCode.PARSE_ERROR, `PCK 条目超过上限:${count}`);
41
+
42
+ const entries = [];
43
+ for (let i = 0; i < count; i += 1) {
44
+ if (pos + 4 > buffer.length) break;
45
+ const pathLen = buffer.readUInt32LE(pos);
46
+ pos += 4;
47
+ if (pos + pathLen > buffer.length) break;
48
+ const name = buffer.toString('utf8', pos, pos + pathLen);
49
+ pos = align4(pos + pathLen);
50
+ const offset = Number(buffer.readBigUInt64LE(pos));
51
+ const size = Number(buffer.readBigUInt64LE(pos + 8));
52
+ pos += 16 + 16;
53
+ if (version === 2) pos += 4;
54
+ entries.push({ name, offset: offset + (version === 2 ? fileBase : 0), size });
55
+ }
56
+ return { version, engine, flags, entries };
57
+ }
58
+
59
+ /** 读一个 PCK 条目;加密包直接拒绝。 */
60
+ export function readPckEntry(buffer, entry, { encrypted = false, maxBytes = 64 * 1024 * 1024 } = {}) {
61
+ if (encrypted) throw new GameError(ErrorCode.ENCRYPTED, 'PCK 加密(需要游戏自身的 key),本插件不解密');
62
+ if (entry.size > maxBytes) throw new GameError(ErrorCode.INVALID_INPUT, `PCK 条目超过上限:${entry.name}`);
63
+ if (entry.offset < 0 || entry.offset + entry.size > buffer.length) {
64
+ throw new GameError(ErrorCode.PARSE_ERROR, `PCK 条目越界:${entry.name}`);
65
+ }
66
+ return buffer.subarray(entry.offset, entry.offset + entry.size);
67
+ }
package/lib/core/ids.mjs CHANGED
@@ -9,8 +9,8 @@ export function makeId(prefix, ...parts) {
9
9
  return `${prefix}_${digestOf(...parts).slice(0, 10)}`;
10
10
  }
11
11
 
12
- export function gameIdOf(engineId, fingerprintDigest) {
13
- return makeId('g', engineId, fingerprintDigest);
12
+ export function gameIdOf(engineId, fingerprintDigest, salt = '') {
13
+ return makeId('g', engineId, fingerprintDigest, salt);
14
14
  }
15
15
 
16
16
  export function sceneIdOf(gameId, relPath, address) {
@@ -75,6 +75,19 @@ export function assertSafeId(id, name = 'id') {
75
75
  return id;
76
76
  }
77
77
 
78
+ /** 游戏目录不得与插件数据目录互相包含(否则只读承诺会被破坏)。 */
79
+ export function assertSeparateRoots(workspace, gameRoot) {
80
+ const plugin = path.resolve(workspace, PLUGIN_DIR);
81
+ const game = path.resolve(gameRoot);
82
+ if (game === plugin || game.startsWith(plugin + path.sep)) {
83
+ throw new GameError(ErrorCode.INVALID_INPUT, '游戏目录不能位于 .dsh-novel-game/ 内');
84
+ }
85
+ if (plugin === game || plugin.startsWith(game + path.sep)) {
86
+ throw new GameError(ErrorCode.INVALID_INPUT, '工作区位于游戏目录内:插件写入会落进游戏目录,请换一个工作区');
87
+ }
88
+ return true;
89
+ }
90
+
78
91
  /** 只允许写插件目录内的相对路径。 */
79
92
  export function pluginPath(workspace, ...segments) {
80
93
  const root = pluginRoot(workspace);
package/lib/ingest.mjs CHANGED
@@ -1,5 +1,8 @@
1
1
  import path from 'node:path';
2
+ import { open as openFile, rm, stat } from 'node:fs/promises';
2
3
  import { GameError, ErrorCode } from './core/errors.mjs';
4
+ import { assertSeparateRoots } from './core/paths.mjs';
5
+ import { ensureDir } from './core/jsonl.mjs';
3
6
  import { createCtx } from './ctx.mjs';
4
7
  import { detectEngines, pickEngine } from './detect.mjs';
5
8
  import { getAdapter } from './adapters/registry.mjs';
@@ -52,7 +55,47 @@ export async function planImport({ gameRoot }) {
52
55
  * - mode=full 全量;incremental 只重解哈希变化的文件,其余代分片复用
53
56
  * - 单文件失败隔离,不中断整体
54
57
  */
55
- export async function importGame({
58
+ export async function importGame(options) {
59
+ const { workspace, gameRoot } = options;
60
+ if (!options.consent) throw new GameError(ErrorCode.CONSENT_REQUIRED, '需要作者确认本地合法持有该游戏副本(consent=true)');
61
+ const gameRootAbs = path.resolve(gameRoot);
62
+ assertSeparateRoots(workspace, gameRootAbs);
63
+
64
+ const store = new GameStore(workspace);
65
+ await store.init();
66
+ const lockDir = path.join(store.root, 'locks');
67
+ await ensureDir(lockDir);
68
+ const lockFile = path.join(lockDir, `${digestOf('lock', gameRootAbs).slice(0, 16)}.lock`);
69
+ await acquireLock(lockFile);
70
+ try {
71
+ return await importGameUnlocked({ ...options, gameRoot: gameRootAbs });
72
+ } finally {
73
+ await rm(lockFile, { force: true }).catch(() => {});
74
+ }
75
+ }
76
+
77
+ async function acquireLock(file) {
78
+ for (let attempt = 0; attempt < 2; attempt += 1) {
79
+ try {
80
+ const handle = await openFile(file, 'wx');
81
+ await handle.writeFile(JSON.stringify({ pid: process.pid, at: Date.now() }));
82
+ await handle.close();
83
+ return;
84
+ } catch (error) {
85
+ if (error?.code !== 'EEXIST') throw error;
86
+ const info = await stat(file).catch(() => null);
87
+ const stale = !info || Date.now() - info.mtimeMs > 10 * 60 * 1000;
88
+ if (stale && attempt === 0) {
89
+ await rm(file, { force: true }).catch(() => {});
90
+ continue;
91
+ }
92
+ throw new GameError(ErrorCode.BUSY, '同一游戏已有导入任务在跑(稍后再试或取消旧任务)');
93
+ }
94
+ }
95
+ throw new GameError(ErrorCode.BUSY, '无法获取导入锁');
96
+ }
97
+
98
+ async function importGameUnlocked({
56
99
  workspace,
57
100
  gameRoot,
58
101
  consent,
@@ -80,7 +123,14 @@ export async function importGame({
80
123
  const byRoot = (library.games ?? []).find(
81
124
  (game) => game.root && path.resolve(game.root) === path.resolve(gameRoot),
82
125
  );
83
- const gameId = byRoot?.gameId ?? gameIdOf(adapter.id, fingerprintDigest);
126
+ let gameId = byRoot?.gameId ?? gameIdOf(adapter.id, fingerprintDigest);
127
+ if (!byRoot) {
128
+ // 同标题/同指纹但不同目录:不能共用 gameId,否则两个游戏的数据会互相覆盖。
129
+ const conflict = (library.games ?? []).find(
130
+ (game) => game.gameId === gameId && path.resolve(game.root ?? '') !== path.resolve(gameRoot),
131
+ );
132
+ if (conflict) gameId = gameIdOf(adapter.id, fingerprintDigest, path.resolve(gameRoot));
133
+ }
84
134
  const previous = await store.readManifest(gameId);
85
135
  const previousSources = new Map((previous?.sources ?? []).map((row) => [row.rel, row]));
86
136
 
@@ -100,8 +150,12 @@ export async function importGame({
100
150
  if (previous?.activeGeneration) {
101
151
  for (const container of textContainers) {
102
152
  if (shouldRead(container.rel)) continue;
153
+ const previousRow = previousSources.get(container.rel);
154
+ // 上一代没有分片(只产词条、没有台词的文件)时不需要复制,也不算失败。
155
+ if (previousRow && (previousRow.units ?? 0) === 0) continue;
103
156
  const ok = await store.copyShard(gameId, previous.activeGeneration, genId, container.rel);
104
157
  if (ok) reused.push(container.rel);
158
+ else changed.add(container.rel); // 旧分片缺失/损坏:回退重抽,不能标 reused
105
159
  }
106
160
  }
107
161
 
@@ -244,11 +298,15 @@ export async function importGame({
244
298
  }
245
299
  await flush();
246
300
 
247
- // 合并未变化文件的旧场景/选项/词条
301
+ // 合并未变化文件的旧场景/选项/词条;已删除的来源(不在当前容器里)一律不保留。
302
+ const currentRels = new Set(containers.map((container) => container.rel));
248
303
  const prevScenes = previous?.activeGeneration ? await store.readScenes(gameId, previous.activeGeneration) : [];
249
304
  const prevChoices = previous?.activeGeneration ? await store.readChoices(gameId, previous.activeGeneration) : [];
250
305
  const prevGlossary = previous?.activeGeneration ? await store.readGlossary(gameId, previous.activeGeneration) : [];
251
- const keepIfUnchanged = (row) => !shouldRead(row.src?.relPath ?? '');
306
+ const keepIfUnchanged = (row) => {
307
+ const rel = row.src?.relPath ?? '';
308
+ return !shouldRead(rel) && currentRels.has(rel);
309
+ };
252
310
 
253
311
  const sceneMap = new Map(prevScenes.filter(keepIfUnchanged).map((row) => [row.sceneId, row]));
254
312
  for (const row of scenes) sceneMap.set(row.sceneId, row);
@@ -275,13 +333,24 @@ export async function importGame({
275
333
  counts.choices = allChoices.length;
276
334
  counts.glossary = allGlossary.length;
277
335
 
336
+ // 计数从新代分片重算:复用文件的分片不经过本次抽取,不能只统计新单元。
337
+ const recount = { lines: 0, assets: 0, skipped: 0, conditions: 0 };
338
+ for await (const row of store.iterateShards(gameId, genId)) {
339
+ if (row.t === 'line') recount.lines += 1;
340
+ else if (row.t === 'asset') recount.assets += 1;
341
+ else if (row.t === 'skip') recount.skipped += 1;
342
+ else if (row.t === 'condition') recount.conditions += 1;
343
+ }
344
+ Object.assign(counts, recount);
345
+
278
346
  onProgress({ phase: 'finalize', done: 0, total: 1 });
279
347
  await store.writeAggregates(gameId, genId, { scenes: allScenes, choices: allChoices, glossary: allGlossary });
280
348
 
281
349
  const errorByRel = new Map(coverageErrors.map((row) => [row.rel, row.message]));
282
350
  const sources = containers.map((container) => {
283
351
  const rel = container.rel;
284
- const stats = perFile.get(rel) ?? {};
352
+ const previousRow = previousSources.get(rel);
353
+ const stats = perFile.get(rel) ?? (previousRow ? { lines: previousRow.units ?? 0, scenes: previousRow.scenes ?? 0 } : {});
285
354
  const read = shouldRead(rel);
286
355
  return {
287
356
  rel,
package/lib/jobs.mjs CHANGED
@@ -2,6 +2,7 @@ import path from 'node:path';
2
2
  import { readFile } from 'node:fs/promises';
3
3
  import { writeJsonAtomic } from './core/jsonl.mjs';
4
4
  import { GameError, ErrorCode } from './core/errors.mjs';
5
+ import { assertSafeId, pluginPath } from './core/paths.mjs';
5
6
  import { jobIdOf } from './core/ids.mjs';
6
7
 
7
8
  function nowIso() {
@@ -17,7 +18,8 @@ export class JobRunner {
17
18
  }
18
19
 
19
20
  pathOf(jobId) {
20
- return path.join(this.store.root, 'jobs', `${jobId}.json`);
21
+ assertSafeId(jobId, 'jobId');
22
+ return pluginPath(this.store.workspace, 'jobs', `${jobId}.json`);
21
23
  }
22
24
 
23
25
  async create({ kind, gameRoot, meta = {} }) {
@@ -52,11 +54,12 @@ export class JobRunner {
52
54
  }
53
55
 
54
56
  async get(jobId) {
57
+ const file = this.pathOf(jobId); // jobId 非法在这里就抛 INVALID_INPUT
55
58
  // Windows 上 rename 与读取可能撞车:短暂重试,避免把瞬时错误当成任务不存在。
56
59
  let lastError = null;
57
60
  for (let attempt = 0; attempt < 5; attempt += 1) {
58
61
  try {
59
- const job = JSON.parse(await readFile(this.pathOf(jobId), 'utf8'));
62
+ const job = JSON.parse(await readFile(file, 'utf8'));
60
63
  return job;
61
64
  } catch (error) {
62
65
  lastError = error;
package/lib/service.mjs CHANGED
@@ -335,10 +335,20 @@ export class GameService {
335
335
  async addPick(gameId, { kind = 'line', refId, note = '', tags = [] } = {}) {
336
336
  if (!refId) throw new GameError(ErrorCode.INVALID_INPUT, 'refId 不能为空');
337
337
  const manifest = await this.manifest(gameId);
338
+ let quote = '';
339
+ if (kind === 'line') {
340
+ for await (const row of this.store.iterateShards(gameId, manifest.activeGeneration)) {
341
+ if (row.t === 'line' && row.lineId === refId) {
342
+ quote = String(row.text ?? '').slice(0, MAX_QUOTE);
343
+ break;
344
+ }
345
+ }
346
+ }
338
347
  const pick = {
339
348
  pickId: pickIdOf(gameId, kind, refId),
340
349
  kind,
341
350
  refId,
351
+ quote,
342
352
  note: String(note ?? ''),
343
353
  tags: Array.isArray(tags) ? tags.map(String) : [],
344
354
  generation: manifest.activeGeneration,
@@ -352,14 +362,47 @@ export class GameService {
352
362
  const rows = await this.store.readPicks(gameId);
353
363
  const { genId } = await this.active(gameId);
354
364
  const lineIds = new Set();
365
+ const textIndex = new Map();
355
366
  for await (const row of this.store.iterateShards(gameId, genId)) {
356
- if (row.t === 'line') lineIds.add(row.lineId);
367
+ if (row.t !== 'line') continue;
368
+ lineIds.add(row.lineId);
369
+ const text = String(row.text ?? '');
370
+ if (text) {
371
+ const list = textIndex.get(text) ?? [];
372
+ list.push({ lineId: row.lineId, sceneId: row.sceneId });
373
+ textIndex.set(text, list);
374
+ }
357
375
  }
358
- const items = rows.map((row) => ({
359
- ...row,
360
- stale: row.kind === 'line' ? !lineIds.has(row.refId) : false,
361
- }));
362
- return { gameId, total: items.length, items, staleCount: items.filter((row) => row.stale).length };
376
+ const items = rows.map((row) => {
377
+ const stale = row.kind === 'line' ? !lineIds.has(row.refId) : false;
378
+ let candidate = null;
379
+ if (stale && row.quote) {
380
+ const found = (textIndex.get(row.quote) ?? []).filter((entry) => entry.lineId !== row.refId);
381
+ if (found.length === 1) candidate = found[0];
382
+ }
383
+ return { ...row, stale, candidate };
384
+ });
385
+ return {
386
+ gameId,
387
+ total: items.length,
388
+ items,
389
+ staleCount: items.filter((row) => row.stale).length,
390
+ remappable: items.filter((row) => row.candidate).length,
391
+ };
392
+ }
393
+
394
+ /** 把失效摘录改绑到候选行(只改插件自己的 picks)。 */
395
+ async remapPick(gameId, { pickId } = {}) {
396
+ if (!pickId) throw new GameError(ErrorCode.INVALID_INPUT, 'pickId 不能为空');
397
+ const current = await this.picks(gameId);
398
+ const target = current.items.find((row) => row.pickId === pickId);
399
+ if (!target) throw new GameError(ErrorCode.NOT_FOUND, `摘录不存在:${pickId}`);
400
+ if (!target.candidate) throw new GameError(ErrorCode.NOT_FOUND, '没有唯一候选可改绑(可能文本已变或有多处相同)');
401
+ const rows = (await this.store.readPicks(gameId)).map((row) => (row.pickId === pickId
402
+ ? { ...row, refId: target.candidate.lineId, remappedFrom: row.refId, remappedAt: nowIso() }
403
+ : row));
404
+ await this.store.writePicks(gameId, rows);
405
+ return { pickId, refId: target.candidate.lineId, remappedFrom: target.refId };
363
406
  }
364
407
 
365
408
  /**
package/lib/store.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import path from 'node:path';
2
- import { copyFile, readdir, rm } from 'node:fs/promises';
2
+ import { copyFile, readdir, readFile, rm } from 'node:fs/promises';
3
3
  import { pluginRoot } from './core/paths.mjs';
4
+ import { GameError, ErrorCode } from './core/errors.mjs';
4
5
  import {
5
6
  appendJsonl,
6
7
  ensureDir,
@@ -90,8 +91,17 @@ export class GameStore {
90
91
  return Array.isArray(library.games) ? library.games : [];
91
92
  }
92
93
 
94
+ /**
95
+ * 读 manifest:文件不存在返回 null;存在但损坏必须抛错。
96
+ * 否则损坏会被当成「首次导入」,随后的 prune 可能删掉仍可读的旧代。
97
+ */
93
98
  async readManifest(gameId) {
94
- return readJson(this.manifestPath(gameId));
99
+ try {
100
+ return JSON.parse(await readFile(this.manifestPath(gameId), 'utf8'));
101
+ } catch (error) {
102
+ if (error?.code === 'ENOENT') return null;
103
+ throw new GameError(ErrorCode.IO_ERROR, `manifest 损坏或不可读:${gameId}(${error.message})`, { gameId });
104
+ }
95
105
  }
96
106
 
97
107
  async readSettings() {
@@ -167,6 +177,11 @@ export class GameStore {
167
177
  return pick;
168
178
  }
169
179
 
180
+ async writePicks(gameId, rows) {
181
+ await writeJsonl(this.picksPath(gameId), rows);
182
+ return rows;
183
+ }
184
+
170
185
  async readNotes(gameId) {
171
186
  return (await readJson(this.notesPath(gameId))) ?? { schemaVersion: SCHEMA_VERSION, notes: [] };
172
187
  }
@@ -243,11 +258,13 @@ export class GameStore {
243
258
  return manifest;
244
259
  }
245
260
 
246
- /** 只保留当前代与上一代,避免 generations 无限增长。 */
261
+ /** 只保留当前代与上一代(keep = 总代数)。 */
247
262
  async pruneGenerations(gameId, keep = 2) {
248
263
  const manifest = await this.readManifest(gameId);
249
264
  if (!manifest?.generations?.length) return;
250
- const keepIds = new Set([manifest.activeGeneration, ...manifest.generations.slice(-keep).map((gen) => gen.id)]);
265
+ const history = manifest.generations.filter((gen) => gen.id !== manifest.activeGeneration);
266
+ const kept = history.slice(-Math.max(0, keep - 1)).map((gen) => gen.id);
267
+ const keepIds = new Set([manifest.activeGeneration, ...kept]);
251
268
  const dir = path.join(this.gameDir(gameId), 'generations');
252
269
  let entries = [];
253
270
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-novel-game",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "DSH 小说插件·游戏剧情:解包本地合法游戏副本中玩家可见的剧情/文本/设定,整理成可浏览、可检索、可摘录的 canon,供同人创作参考;只写 .dsh-novel-game/,游戏目录只读。",
5
5
  "type": "module",
6
6
  "main": "index.js",