Ame commited on
Commit
20cc92a
·
1 Parent(s): decded9

feat(tools): 翻译清单改为 v3 紧凑格式并增量校验

Browse files

history_language_manifest.json 从 v2 的 77MB 压到 v3 的 23MB:selector
按 blocks 分组共享,sourceSelector 利用 96% 与 selector 相同的事实改为
四态折叠,source 提升为文件级默认值,history/+common/ 全部 8722 个
文件入册并记录字节 sha256。加载改为展开回 v2 内存形状,下游消费方
(validate.mjs、build_history_english.mjs、dynasty_language_audit.mjs)
无需感知格式变化。

validate.mjs 的清单相位改为增量:hash 一致的文件跳过解析,稳态耗时
75s 降至约 1s;hash 失配报 manifest-stale 并提示 stamp。
build_history_english.mjs 在清单过期时拒绝构建,构建成功自动 stamp。

清单维护不再手改 JSON,新增 tools/history_language_manifest.mjs 的
migrate/stamp/add 命令;已用迁移前后英文 overlay 全量哈希比对验证
渲染等价(6386 文件 0 差异)。

AGENTS.md CHANGED
@@ -57,18 +57,21 @@ await eu4.save();
57
 
58
  ## 翻译清单(history_language_manifest.json)
59
 
60
- 这份文件( 189MB)记录了 `history/` 和 `common/` 里所有直写中文的英文翻译,供英文覆盖层使用。
61
 
62
- 每条记录用"在哪个键下面、第几次出现"来定位中文文本,不用行号(行号会随编辑漂移)。添加条目时用 `selectorForToken(tree, token)` 自动获取位置,不要手写。
 
 
 
 
63
 
64
  改了这个清单等于改了英文层。直接改英文层文件会绕过清单,下次校验会失败。
65
 
66
  需要同步更新清单的情况:
67
- - **删了文件** -> 删掉清单里对应的整个文件块
68
- - **了字段** -> 更新对应条目的键名
69
- - **删了字段** -> 删掉对应条目
70
- - **改了文件结构**(如省份从单个名称变成多个名称)-> 更新对应条目定位方式
71
- - **新增了含中文的字段** -> 添加新条目,填好中文、英文、来源
72
 
73
  ## 校验
74
 
 
57
 
58
  ## 翻译清单(history_language_manifest.json)
59
 
60
+ 这份文件(v3 紧凑格式,每个文件记录一行)记录了 `history/` 和 `common/` 里所有直写中文的英文翻译,供英文覆盖层使用。每个文件还存了字节的 sha256,校验时只重新解析变过的文件。
61
 
62
+ 每条记录用"在哪个键下面、第几次出现"来定位中文文本,不用行号(行号会随编辑漂移)。清单由工具维护,不要手改 JSON:
63
+
64
+ - 新增中文条目:`node tools/history_language_manifest.mjs add <file> <chinese> <english> [--occurrence N]`
65
+ - 改了 `history/` 或 `common/` 文件后若 `validate.mjs` 报 `manifest-stale`:`node tools/history_language_manifest.mjs stamp` 刷新哈希(会先全量校验,内容不合法会拒绝)
66
+ - `build_history_english.mjs build` 在清单过期时拒绝构建,构建成功后会自动 stamp
67
 
68
  改了这个清单等于改了英文层。直接改英文层文件会绕过清单,下次校验会失败。
69
 
70
  需要同步更新清单的情况:
71
+ - **删了文件** -> stamp 自动移除对应文件块
72
+ - **新增含中文的字段** -> 用 add 命令添加条目
73
+ - **改动不动中文 token**(改数值、日期、注释等)-> stamp 刷新哈希即可
74
+ - **改了字段名、删了字段、改了文件结构** -> 对应条目定位会失败(validate 报错),必须先手工修正清单条目再 stamp
 
75
 
76
  ## 校验
77
 
CHANGELOG.md CHANGED
@@ -63,6 +63,7 @@
63
 
64
  - 增加 Clausewitz 数据读写与完整性校验工具。
65
  - 本地化构建改为基于内容清单的增量流程。
 
66
  - 删除不适用于 EU4 1.37.5 的旧编码偏移兼容接口和依赖真实工作树状态的测试。
67
  - 在 `localisation_english_provenance.json` 登记新英文覆盖层 `loadingtips_l_english.yml`,并为该文件设置 `allowVanillaOverride`,允许其覆盖同名的原版 `LOADING_TIP_*` 键。
68
  - `tools/build_variants.mjs` 新增按文件粒度的 `allowVanillaOverride` 白名单校验,仅放过在 `localisation_english_provenance.json` 中显式标记的源文件。
 
63
 
64
  - 增加 Clausewitz 数据读写与完整性校验工具。
65
  - 本地化构建改为基于内容清单的增量流程。
66
+ - 翻译清单 `history_language_manifest.json` 改为 v3 紧凑格式(77MB → 23MB,每个文件记录一行),并为每个文件记录字节 sha256;`validate.mjs` 的清单相位改为增量校验(75s → 约 1s)。清单维护改用 `tools/history_language_manifest.mjs` 的 `add`/`stamp` 命令,不再手改 JSON。
67
  - 删除不适用于 EU4 1.37.5 的旧编码偏移兼容接口和依赖真实工作树状态的测试。
68
  - 在 `localisation_english_provenance.json` 登记新英文覆盖层 `loadingtips_l_english.yml`,并为该文件设置 `allowVanillaOverride`,允许其覆盖同名的原版 `LOADING_TIP_*` 键。
69
  - `tools/build_variants.mjs` 新增按文件粒度的 `allowVanillaOverride` 白名单校验,仅放过在 `localisation_english_provenance.json` 中显式标记的源文件。
history_language_manifest.json CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:34b3da615f7a0a7901d0885f8a6d80d97e2195dbdcaa0486eab797e90a8d1391
3
- size 78709081
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:02d29360e162100b3641eae7d0e3beb227362a8ea311e332e7fec484b74030a0
3
+ size 23233081
tools/build_history_english.mjs CHANGED
@@ -3,7 +3,7 @@ import { dirname, join, resolve } from 'node:path';
3
  import { fileURLToPath } from 'node:url';
4
  import { readGameText, writeGameText } from './eu4_clausewitz/src/codec.mjs';
5
  import { auditDynastyLanguage } from './dynasty_language_audit.mjs';
6
- import { loadManifest, renderText, validateManifestAgainstRoot } from './history_language_manifest.mjs';
7
 
8
  const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
9
  const manifestPath = join(root, 'history_language_manifest.json');
@@ -13,6 +13,9 @@ const stagingRoot = resolve(root, '..', 'Ab_Integro_English.history-staging');
13
  async function check() {
14
  const manifest = await loadManifest(manifestPath);
15
  const summary = await validateManifestAgainstRoot(manifest, root);
 
 
 
16
  const dynastyMap = JSON.parse(await readFile(join(root, 'tools', 'dynasty_translation_map.json'), 'utf8'));
17
  const dynastyFindings = await auditDynastyLanguage(root, manifest, dynastyMap.translations);
18
  if (dynastyFindings.length) throw new Error(`Dynasty language audit failed:\n${JSON.stringify(dynastyFindings, null, 2)}`);
@@ -23,7 +26,8 @@ async function check() {
23
  async function build() {
24
  const manifest = await check();
25
  await rm(stagingRoot, { recursive: true, force: true });
26
- const files = [...manifest.files];
 
27
  async function renderNext() {
28
  const file = files.pop();
29
  if (!file) return;
@@ -39,7 +43,9 @@ async function build() {
39
  for (const scope of ['history', 'common']) await rm(join(overlayRoot, scope), { recursive: true, force: true });
40
  for (const scope of ['history', 'common']) await rename(join(stagingRoot, scope), join(overlayRoot, scope));
41
  await rm(stagingRoot, { recursive: true, force: true });
42
- console.log(`English history overlay built: ${manifest.files.length} files.`);
 
 
43
  }
44
 
45
  const command = process.argv[2] ?? 'build';
 
3
  import { fileURLToPath } from 'node:url';
4
  import { readGameText, writeGameText } from './eu4_clausewitz/src/codec.mjs';
5
  import { auditDynastyLanguage } from './dynasty_language_audit.mjs';
6
+ import { loadManifest, renderText, saveManifest, stampManifest, validateManifestAgainstRoot } from './history_language_manifest.mjs';
7
 
8
  const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
9
  const manifestPath = join(root, 'history_language_manifest.json');
 
13
  async function check() {
14
  const manifest = await loadManifest(manifestPath);
15
  const summary = await validateManifestAgainstRoot(manifest, root);
16
+ if (summary.stale.length) {
17
+ throw new Error(`Manifest is out of date for ${summary.stale.length} file(s); run: node tools/history_language_manifest.mjs stamp`);
18
+ }
19
  const dynastyMap = JSON.parse(await readFile(join(root, 'tools', 'dynasty_translation_map.json'), 'utf8'));
20
  const dynastyFindings = await auditDynastyLanguage(root, manifest, dynastyMap.translations);
21
  if (dynastyFindings.length) throw new Error(`Dynasty language audit failed:\n${JSON.stringify(dynastyFindings, null, 2)}`);
 
26
  async function build() {
27
  const manifest = await check();
28
  await rm(stagingRoot, { recursive: true, force: true });
29
+ const files = [...manifest.files].filter((file) => file.entries.length);
30
+ const fileCount = files.length;
31
  async function renderNext() {
32
  const file = files.pop();
33
  if (!file) return;
 
43
  for (const scope of ['history', 'common']) await rm(join(overlayRoot, scope), { recursive: true, force: true });
44
  for (const scope of ['history', 'common']) await rename(join(stagingRoot, scope), join(overlayRoot, scope));
45
  await rm(stagingRoot, { recursive: true, force: true });
46
+ const stamped = await stampManifest(manifest, root);
47
+ await saveManifest(stamped, manifestPath);
48
+ console.log(`English history overlay built: ${fileCount} files.`);
49
  }
50
 
51
  const command = process.argv[2] ?? 'build';
tools/eu4_clausewitz/test/history_language_manifest.test.mjs CHANGED
@@ -1,9 +1,17 @@
1
  import assert from 'node:assert/strict';
 
 
 
2
  import { test } from 'node:test';
3
  import {
 
 
4
  parsedText,
5
  renderText,
 
6
  selectorForToken,
 
 
7
  valueTokens,
8
  } from '../../history_language_manifest.mjs';
9
 
@@ -52,3 +60,111 @@ test('a Chinese value drift fails at the selector location', () => {
52
  const changed = 'name = "乙"\n';
53
  assert.throws(() => renderText(changed, [entry(before, '甲', 'One')]), /expected Chinese/);
54
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import assert from 'node:assert/strict';
2
+ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
  import { test } from 'node:test';
6
  import {
7
+ addManifestEntry,
8
+ loadManifest,
9
  parsedText,
10
  renderText,
11
+ saveManifest,
12
  selectorForToken,
13
+ stampManifest,
14
+ validateManifestAgainstRoot,
15
  valueTokens,
16
  } from '../../history_language_manifest.mjs';
17
 
 
60
  const changed = 'name = "乙"\n';
61
  assert.throws(() => renderText(changed, [entry(before, '甲', 'One')]), /expected Chinese/);
62
  });
63
+
64
+ test('v3 manifest serializes and reloads to the same expanded form', async () => {
65
+ const blocksA = [{ key: 'monarch_names', occurrence: 0 }];
66
+ const sel = (blocks, target) => ({ blocks, target });
67
+ const expanded = {
68
+ version: 3,
69
+ sources: [
70
+ { id: 's0', upstream: 'vanilla', path: 'common/countries/X.txt' },
71
+ { id: 's1', upstream: 'vanilla', path: 'common/countries/Y.txt' },
72
+ ],
73
+ files: [
74
+ {
75
+ path: 'history/x.txt', sha256: 'a'.repeat(64),
76
+ entries: [
77
+ { selector: sel(blocksA, { kind: 'key', occurrence: 0 }), chinese: '甲 #0', english: 'A #0', source: 's0', sourceSelector: sel(blocksA, { kind: 'key', occurrence: 0 }) },
78
+ { selector: sel(blocksA, { kind: 'key', occurrence: 1 }), chinese: '乙 #1', english: 'B #1', source: 's0', sourceSelector: sel(blocksA, { kind: 'key', occurrence: 5 }) },
79
+ { selector: sel(blocksA, { kind: 'key', occurrence: 2 }), chinese: '丙 #2', english: 'C #2', source: 's1', sourceSelector: sel([{ key: 'other', occurrence: 1 }], { kind: 'bare', occurrence: 0 }) },
80
+ { selector: sel([{ key: 'dynasty_names', occurrence: 0 }], { kind: 'bare', occurrence: 0 }), chinese: '丁', english: 'D', source: 's0' },
81
+ ],
82
+ },
83
+ { path: 'history/clean.txt', sha256: 'b'.repeat(64), entries: [] },
84
+ ],
85
+ };
86
+ const dir = await mkdtemp(join(tmpdir(), 'hlm-'));
87
+ const file = join(dir, 'manifest.json');
88
+ await saveManifest(expanded, file);
89
+ const loaded = await loadManifest(file);
90
+ assert.deepEqual(loaded, expanded);
91
+ });
92
+
93
+ test('v3 compact entries render identically to the expanded form', async () => {
94
+ const text = 'name = "甲"\nmonarch_names = { "乙" "丙" }\n';
95
+ const entries = [entry(text, '甲', 'One'), entry(text, '乙', 'Two'), entry(text, '丙', 'Three')];
96
+ const manifest = {
97
+ version: 3,
98
+ sources: [{ id: 's0', upstream: 'vanilla', path: 'history/x.txt' }],
99
+ files: [{ path: 'history/x.txt', sha256: 'a'.repeat(64), entries: entries.map((item) => ({ ...item, source: 's0' })) }],
100
+ };
101
+ const dir = await mkdtemp(join(tmpdir(), 'hlm-'));
102
+ const file = join(dir, 'manifest.json');
103
+ await saveManifest(manifest, file);
104
+ const loaded = await loadManifest(file);
105
+ assert.equal(renderText(text, loaded.files[0].entries), 'name = "One"\nmonarch_names = { "Two" "Three" }\n');
106
+ });
107
+
108
+ test('incremental validation skips unchanged files and detects drift', async () => {
109
+ const dir = await mkdtemp(join(tmpdir(), 'hlm-root-'));
110
+ await mkdir(join(dir, 'history'), { recursive: true });
111
+ await mkdir(join(dir, 'common'), { recursive: true });
112
+ const chineseText = 'name = "甲" # comment\n';
113
+ await writeFile(join(dir, 'history', 'a.txt'), chineseText);
114
+ await writeFile(join(dir, 'common', 'b.txt'), 'name = "Vanilla"\n');
115
+ const parsed = parsedText(chineseText);
116
+ const token = valueTokens(parsed.tree).find((candidate) => candidate.value === '甲');
117
+ const manifest = {
118
+ version: 3,
119
+ sources: [{ id: 's0', upstream: 'vanilla', path: 'history/a.txt' }],
120
+ files: [{ path: 'history/a.txt', sha256: '', entries: [{ selector: selectorForToken(parsed.tree, token), chinese: '甲', english: 'A', source: 's0' }] }],
121
+ };
122
+ const stamped = await stampManifest(manifest, dir);
123
+ assert.equal(stamped.files.length, 2);
124
+ const clean = await validateManifestAgainstRoot(stamped, dir);
125
+ assert.deepEqual(clean.stale, []);
126
+
127
+ // Byte change that keeps the Chinese token: only that file is re-checked.
128
+ await writeFile(join(dir, 'history', 'a.txt'), 'name = "甲" # other comment\n');
129
+ const touched = await validateManifestAgainstRoot(stamped, dir);
130
+ assert.deepEqual(touched.stale, ['history/a.txt']);
131
+
132
+ // Chinese drift fails even though the selector still resolves.
133
+ await writeFile(join(dir, 'history', 'a.txt'), 'name = "乙"\n');
134
+ await assert.rejects(() => validateManifestAgainstRoot(stamped, dir), /expected Chinese/);
135
+
136
+ // A new clean file is stale; a new Chinese file without entries fails.
137
+ await writeFile(join(dir, 'history', 'a.txt'), chineseText);
138
+ await writeFile(join(dir, 'common', 'c.txt'), 'name = "New"\n');
139
+ const added = await validateManifestAgainstRoot(stamped, dir);
140
+ assert.deepEqual(added.stale, ['common/c.txt']);
141
+ await rm(join(dir, 'common', 'c.txt'));
142
+ await writeFile(join(dir, 'common', 'd.txt'), 'name = "新"\n');
143
+ await assert.rejects(() => validateManifestAgainstRoot(stamped, dir), /no manifest record/);
144
+
145
+ // A recorded file that disappears fails.
146
+ await rm(join(dir, 'common', 'd.txt'));
147
+ await rm(join(dir, 'common', 'b.txt'));
148
+ await assert.rejects(() => validateManifestAgainstRoot(stamped, dir), /missing file/);
149
+ });
150
+
151
+ test('addManifestEntry locates the token and refreshes the file hash', async () => {
152
+ const dir = await mkdtemp(join(tmpdir(), 'hlm-add-'));
153
+ await mkdir(join(dir, 'history'), { recursive: true });
154
+ const text = 'first = "同"\nsecond = "同"\n';
155
+ await writeFile(join(dir, 'history', 'a.txt'), text);
156
+ const parsed = parsedText(text);
157
+ const first = valueTokens(parsed.tree).find((candidate) => candidate.value === '同');
158
+ const manifest = {
159
+ version: 3,
160
+ sources: [{ id: 's0', upstream: 'vanilla', path: 'history/a.txt' }],
161
+ files: [{ path: 'history/a.txt', sha256: '', entries: [{ selector: selectorForToken(parsed.tree, first), chinese: '同', english: 'First', source: 's0' }] }],
162
+ };
163
+ await assert.rejects(() => addManifestEntry(manifest, dir, 'history/a.txt', '同', 'Second'), /--occurrence/);
164
+ await addManifestEntry(manifest, dir, 'history/a.txt', '同', 'Second', 1);
165
+ assert.equal(manifest.files[0].entries.length, 2);
166
+ assert.match(manifest.files[0].sha256, /^[0-9a-f]{64}$/);
167
+ assert.equal(renderText(text, manifest.files[0].entries), 'first = "First"\nsecond = "Second"\n');
168
+ await assert.rejects(() => addManifestEntry(manifest, dir, 'history/a.txt', '同', 'Third', 0), /already has an entry/);
169
+ await assert.rejects(() => addManifestEntry(manifest, dir, 'history/nope.txt', '同', 'X'), /no manifest entries/);
170
+ });
tools/history_language_manifest.mjs CHANGED
@@ -1,11 +1,31 @@
1
- import { readFile, readdir } from 'node:fs/promises';
2
- import { join, relative } from 'node:path';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import { parse } from './eu4_clausewitz/src/ast.mjs';
4
  import { countBraces } from './eu4_clausewitz/src/edit.mjs';
5
  import { tokenize } from './eu4_clausewitz/src/lexer.mjs';
6
  import { readGameText } from './eu4_clausewitz/src/codec.mjs';
7
 
8
- export const CJK = /[\u3400-\u9fff\uf900-\ufaff]/u;
 
 
9
 
10
  function scalarToken(item) {
11
  return item.kind === 'pair' && item.value.type === 'scalar' ? item.value.token : null;
@@ -124,26 +144,106 @@ export function renderText(text, entries, path = '<memory>') {
124
  return output;
125
  }
126
 
 
 
127
  export async function loadManifest(path) {
128
- const manifest = JSON.parse(await readFile(path, 'utf8'));
129
- if (manifest.version !== 2 || !Array.isArray(manifest.files) || !Array.isArray(manifest.sources)) {
130
- throw new Error(`${path}: expected history language manifest v2`);
131
  }
132
- const sourceIds = new Set(manifest.sources.map((source) => source.id));
 
 
 
133
  const paths = new Set();
134
- for (const file of manifest.files) {
135
  if (!file.path?.match(/^(history|common)\/.+\.txt$/)) throw new Error(`${path}: invalid target path ${file.path}`);
136
  if (paths.has(file.path)) throw new Error(`${path}: duplicate target file ${file.path}`);
137
  paths.add(file.path);
138
- if (!Array.isArray(file.entries) || file.entries.length === 0) throw new Error(`${path}: ${file.path} has no entries`);
139
- for (const entry of file.entries) {
140
- if (!entry.selector || typeof entry.chinese !== 'string' || typeof entry.english !== 'string') throw new Error(`${path}: malformed entry in ${file.path}`);
141
- if (!CJK.test(entry.chinese)) throw new Error(`${path}: non-Chinese source value in ${file.path}`);
142
- if (CJK.test(entry.english)) throw new Error(`${path}: CJK English value in ${file.path}`);
143
- if (!sourceIds.has(entry.source)) throw new Error(`${path}: unknown source ${entry.source} in ${file.path}`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  }
 
145
  }
146
- return manifest;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  }
148
 
149
  async function listTextFiles(root, current = root) {
@@ -156,21 +256,147 @@ async function listTextFiles(root, current = root) {
156
  return files;
157
  }
158
 
159
- export async function validateManifestAgainstRoot(manifest, root) {
160
- const byPath = new Map(manifest.files.map((file) => [file.path, file.entries]));
161
  const actual = [];
162
  for (const scope of ['history', 'common']) {
163
  for (const path of await listTextFiles(join(root, scope))) actual.push(`${scope}/${path}`);
164
  }
165
- for (const path of actual) {
166
- const { text } = await readGameText(join(root, path));
167
- const parsed = parsedText(text);
168
- const hasCjk = valueTokens(parsed.tree).some((token) => CJK.test(token.value));
169
- if (hasCjk && !byPath.has(path)) throw new Error(`${path}: contains Chinese direct text but has no manifest record`);
170
- if (byPath.has(path)) renderText(text, byPath.get(path), path);
 
171
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  for (const path of byPath.keys()) {
173
- if (!actual.includes(path)) throw new Error(`manifest references missing file ${path}`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  }
175
- return { files: manifest.files.length, entries: manifest.files.reduce((count, file) => count + file.entries.length, 0) };
 
 
176
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // History language manifest: records the English translation of every piece of
2
+ // Chinese direct text under history/ and common/, keyed by structural
3
+ // selectors (key path + occurrence) instead of line numbers.
4
+ //
5
+ // On-disk format v3: one JSON line per file record inside "files". Entries
6
+ // are grouped by shared selector blocks; per entry only the target ("t"),
7
+ // Chinese ("zh") and English ("en") are stored. "src" overrides the
8
+ // file-level default source. "ssel" encodes the upstream source selector:
9
+ // omitted -> identical to the entry selector
10
+ // { "t": ... } -> same blocks, different target
11
+ // { "blocks": ..., "target": ... } -> fully independent position
12
+ // null -> no recorded position in the source
13
+ // Every file under history/ and common/ is recorded, each with the sha256 of
14
+ // its current bytes; files without Chinese carry no "groups" and serve as a
15
+ // clean-file cache so validation only re-parses files whose bytes changed.
16
+
17
+ import { createHash } from 'node:crypto';
18
+ import { readFile, readdir, writeFile } from 'node:fs/promises';
19
+ import { dirname, join, relative, resolve } from 'node:path';
20
+ import { fileURLToPath } from 'node:url';
21
  import { parse } from './eu4_clausewitz/src/ast.mjs';
22
  import { countBraces } from './eu4_clausewitz/src/edit.mjs';
23
  import { tokenize } from './eu4_clausewitz/src/lexer.mjs';
24
  import { readGameText } from './eu4_clausewitz/src/codec.mjs';
25
 
26
+ export const CJK = /[-鿿豈-﫿]/u;
27
+
28
+ const CONCURRENCY = 16;
29
 
30
  function scalarToken(item) {
31
  return item.kind === 'pair' && item.value.type === 'scalar' ? item.value.token : null;
 
144
  return output;
145
  }
146
 
147
+ // --- v3 load / save ----------------------------------------------------------
148
+
149
  export async function loadManifest(path) {
150
+ const raw = JSON.parse(await readFile(path, 'utf8'));
151
+ if (raw.version === 2) {
152
+ throw new Error(`${path}: manifest is v2; run: node tools/history_language_manifest.mjs migrate`);
153
  }
154
+ if (raw.version !== 3 || !Array.isArray(raw.files) || !Array.isArray(raw.sources)) {
155
+ throw new Error(`${path}: expected history language manifest v3`);
156
+ }
157
+ const sourceIds = new Set(raw.sources.map((source) => source.id));
158
  const paths = new Set();
159
+ const files = raw.files.map((file) => {
160
  if (!file.path?.match(/^(history|common)\/.+\.txt$/)) throw new Error(`${path}: invalid target path ${file.path}`);
161
  if (paths.has(file.path)) throw new Error(`${path}: duplicate target file ${file.path}`);
162
  paths.add(file.path);
163
+ if (typeof file.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(file.sha256)) {
164
+ throw new Error(`${path}: ${file.path} has no sha256`);
165
+ }
166
+ const entries = [];
167
+ if (file.groups !== undefined) {
168
+ if (!sourceIds.has(file.source)) throw new Error(`${path}: ${file.path} has unknown default source ${file.source}`);
169
+ if (!Array.isArray(file.groups)) throw new Error(`${path}: ${file.path} has malformed groups`);
170
+ for (const group of file.groups) {
171
+ if (!Array.isArray(group.blocks) || !Array.isArray(group.entries) || group.entries.length === 0) {
172
+ throw new Error(`${path}: malformed group in ${file.path}`);
173
+ }
174
+ for (const item of group.entries) {
175
+ if (!item.t || typeof item.zh !== 'string' || typeof item.en !== 'string') {
176
+ throw new Error(`${path}: malformed entry in ${file.path}`);
177
+ }
178
+ if (!CJK.test(item.zh)) throw new Error(`${path}: non-Chinese source value in ${file.path}`);
179
+ if (CJK.test(item.en)) throw new Error(`${path}: CJK English value in ${file.path}`);
180
+ const source = item.src ?? file.source;
181
+ if (!sourceIds.has(source)) throw new Error(`${path}: unknown source ${source} in ${file.path}`);
182
+ const selector = { blocks: group.blocks, target: item.t };
183
+ const entry = { selector, chinese: item.zh, english: item.en, source };
184
+ if (item.ssel === undefined) {
185
+ entry.sourceSelector = { blocks: group.blocks, target: item.t };
186
+ } else if (item.ssel !== null) {
187
+ entry.sourceSelector = item.ssel.blocks
188
+ ? { blocks: item.ssel.blocks, target: item.ssel.target }
189
+ : { blocks: group.blocks, target: item.ssel.t };
190
+ }
191
+ entries.push(entry);
192
+ }
193
+ }
194
+ }
195
+ return { path: file.path, sha256: file.sha256, entries };
196
+ });
197
+ return { version: 3, sources: raw.sources, files };
198
+ }
199
+
200
+ function majoritySource(entries) {
201
+ const counts = new Map();
202
+ for (const entry of entries) counts.set(entry.source, (counts.get(entry.source) ?? 0) + 1);
203
+ return [...counts].sort((left, right) => right[1] - left[1])[0][0];
204
+ }
205
+
206
+ function compactFile(file) {
207
+ if (file.entries.length === 0) return { path: file.path, sha256: file.sha256 };
208
+ const source = majoritySource(file.entries);
209
+ const groups = [];
210
+ let current = null;
211
+ let lastBlocks = null;
212
+ for (const entry of file.entries) {
213
+ const blocksJson = JSON.stringify(entry.selector.blocks);
214
+ if (blocksJson !== lastBlocks) {
215
+ current = { blocks: entry.selector.blocks, entries: [] };
216
+ groups.push(current);
217
+ lastBlocks = blocksJson;
218
+ }
219
+ const item = { t: entry.selector.target, zh: entry.chinese, en: entry.english };
220
+ if (entry.source !== source) item.src = entry.source;
221
+ if (!entry.sourceSelector) {
222
+ item.ssel = null;
223
+ } else if (selectorKey(entry.sourceSelector) !== selectorKey(entry.selector)) {
224
+ item.ssel = JSON.stringify(entry.sourceSelector.blocks) === blocksJson
225
+ ? { t: entry.sourceSelector.target }
226
+ : { blocks: entry.sourceSelector.blocks, target: entry.sourceSelector.target };
227
  }
228
+ current.entries.push(item);
229
  }
230
+ return { path: file.path, sha256: file.sha256, source, groups };
231
+ }
232
+
233
+ export function serializeManifest(manifest) {
234
+ const sources = manifest.sources.map((source) => JSON.stringify(source)).join(',\n');
235
+ const files = manifest.files.map((file) => JSON.stringify(compactFile(file))).join(',\n');
236
+ return `{"version":3,"sources":[\n${sources}\n],"files":[\n${files}\n]}\n`;
237
+ }
238
+
239
+ export async function saveManifest(manifest, path) {
240
+ await writeFile(path, serializeManifest(manifest), 'utf8');
241
+ }
242
+
243
+ // --- validation / stamping ---------------------------------------------------
244
+
245
+ function sha256(buffer) {
246
+ return createHash('sha256').update(buffer).digest('hex');
247
  }
248
 
249
  async function listTextFiles(root, current = root) {
 
256
  return files;
257
  }
258
 
259
+ async function listScopedTextFiles(root) {
 
260
  const actual = [];
261
  for (const scope of ['history', 'common']) {
262
  for (const path of await listTextFiles(join(root, scope))) actual.push(`${scope}/${path}`);
263
  }
264
+ return actual.sort();
265
+ }
266
+
267
+ async function mapConcurrent(items, fn) {
268
+ const queue = [...items];
269
+ async function worker() {
270
+ for (let item; (item = queue.pop()) !== undefined;) await fn(item);
271
  }
272
+ await Promise.all(Array.from({ length: CONCURRENCY }, worker));
273
+ }
274
+
275
+ export async function validateManifestAgainstRoot(manifest, root) {
276
+ const byPath = new Map(manifest.files.map((file) => [file.path, file]));
277
+ const actual = await listScopedTextFiles(root);
278
+ const actualSet = new Set(actual);
279
+ const errors = [];
280
+ const stale = [];
281
+ await mapConcurrent(actual, async (path) => {
282
+ try {
283
+ const record = byPath.get(path);
284
+ const hash = sha256(await readFile(join(root, path)));
285
+ if (record && record.sha256 === hash) return;
286
+ const { text } = await readGameText(join(root, path));
287
+ if (record && record.entries.length) {
288
+ renderText(text, record.entries, path);
289
+ } else {
290
+ const parsed = parsedText(text);
291
+ if (valueTokens(parsed.tree).some((token) => CJK.test(token.value))) {
292
+ throw new Error(`${path}: contains Chinese direct text but has no manifest record`);
293
+ }
294
+ }
295
+ stale.push(path);
296
+ } catch (error) {
297
+ errors.push(error.message);
298
+ }
299
+ });
300
  for (const path of byPath.keys()) {
301
+ if (!actualSet.has(path)) errors.push(`manifest references missing file ${path}`);
302
+ }
303
+ if (errors.length) {
304
+ const shown = errors.slice(0, 10).join('\n');
305
+ throw new Error(errors.length > 10 ? `${shown}\n... and ${errors.length - 10} more` : shown);
306
+ }
307
+ return {
308
+ files: manifest.files.length,
309
+ entries: manifest.files.reduce((count, file) => count + file.entries.length, 0),
310
+ stale: stale.sort(),
311
+ };
312
+ }
313
+
314
+ export async function stampManifest(manifest, root) {
315
+ const actual = await listScopedTextFiles(root);
316
+ const byPath = new Map(manifest.files.map((file) => [file.path, file]));
317
+ const records = new Map();
318
+ await mapConcurrent(actual, async (path) => {
319
+ const hash = sha256(await readFile(join(root, path)));
320
+ const record = byPath.get(path);
321
+ records.set(path, record && record.entries.length
322
+ ? { path, sha256: hash, entries: record.entries }
323
+ : { path, sha256: hash, entries: [] });
324
+ });
325
+ return { version: 3, sources: manifest.sources, files: actual.map((path) => records.get(path)) };
326
+ }
327
+
328
+ export async function addManifestEntry(manifest, root, path, chinese, english, occurrence = null) {
329
+ const record = manifest.files.find((file) => file.path === path);
330
+ if (!record || record.entries.length === 0) {
331
+ throw new Error(`${path}: no manifest entries yet; provenance cannot be guessed, add the first entry manually`);
332
+ }
333
+ if (!CJK.test(chinese)) throw new Error(`not Chinese: ${JSON.stringify(chinese)}`);
334
+ if (CJK.test(english)) throw new Error(`English value contains CJK: ${JSON.stringify(english)}`);
335
+ const absolute = join(root, path);
336
+ const { text } = await readGameText(absolute);
337
+ const parsed = parsedText(text);
338
+ const matches = valueTokens(parsed.tree).filter((token) => token.value === chinese);
339
+ if (matches.length === 0) throw new Error(`${path}: no token with value ${JSON.stringify(chinese)}`);
340
+ let token = matches[0];
341
+ if (matches.length > 1) {
342
+ if (occurrence === null) {
343
+ throw new Error(`${path}: ${matches.length} tokens with value ${JSON.stringify(chinese)}; pass --occurrence 0-${matches.length - 1}`);
344
+ }
345
+ token = matches[occurrence];
346
+ if (!token) throw new Error(`${path}: occurrence ${occurrence} out of range (${matches.length} matches)`);
347
+ }
348
+ const selector = selectorForToken(parsed.tree, token);
349
+ if (record.entries.some((entry) => selectorKey(entry.selector) === selectorKey(selector))) {
350
+ throw new Error(`${path}: manifest already has an entry at ${selectorKey(selector)}`);
351
  }
352
+ record.entries.push({ selector, chinese, english, source: majoritySource(record.entries) });
353
+ record.sha256 = sha256(await readFile(absolute));
354
+ return record;
355
  }
356
+
357
+ // --- CLI ---------------------------------------------------------------------
358
+
359
+ async function main() {
360
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
361
+ const manifestPath = join(root, 'history_language_manifest.json');
362
+ const [command, ...args] = process.argv.slice(2);
363
+ if (command === 'migrate') {
364
+ const raw = JSON.parse(await readFile(manifestPath, 'utf8'));
365
+ if (raw.version !== 2) throw new Error(`${manifestPath}: migrate expects a v2 manifest`);
366
+ const manifest = {
367
+ version: 3,
368
+ sources: raw.sources,
369
+ files: raw.files.map((file) => ({ path: file.path, sha256: '', entries: file.entries })),
370
+ };
371
+ const summary = await validateManifestAgainstRoot(manifest, root);
372
+ const stamped = await stampManifest(manifest, root);
373
+ await saveManifest(stamped, manifestPath);
374
+ console.log(`Migrated manifest to v3: ${stamped.files.length} files, ${summary.entries} entries.`);
375
+ return;
376
+ }
377
+ if (command === 'stamp') {
378
+ const manifest = await loadManifest(manifestPath);
379
+ await validateManifestAgainstRoot(manifest, root);
380
+ const stamped = await stampManifest(manifest, root);
381
+ await saveManifest(stamped, manifestPath);
382
+ console.log(`Manifest stamped: ${stamped.files.length} files.`);
383
+ return;
384
+ }
385
+ if (command === 'add') {
386
+ const occurrenceIndex = args.indexOf('--occurrence');
387
+ const occurrence = occurrenceIndex === -1 ? null : Number(args[occurrenceIndex + 1]);
388
+ const positional = occurrenceIndex === -1 ? args : args.slice(0, occurrenceIndex);
389
+ const [path, chinese, english] = positional;
390
+ if (!path || !chinese || !english) {
391
+ throw new Error('Usage: node tools/history_language_manifest.mjs add <file> <chinese> <english> [--occurrence N]');
392
+ }
393
+ const manifest = await loadManifest(manifestPath);
394
+ addManifestEntry(manifest, root, path, chinese, english, occurrence);
395
+ await saveManifest(manifest, manifestPath);
396
+ console.log(`Added manifest entry: ${path}: ${chinese} -> ${english}`);
397
+ return;
398
+ }
399
+ throw new Error('Usage: node tools/history_language_manifest.mjs <migrate|stamp|add>');
400
+ }
401
+
402
+ if (process.argv[1] === fileURLToPath(import.meta.url)) await main();
tools/validate.mjs CHANGED
@@ -499,15 +499,24 @@ async function runScopeRefs(mapSets) {
499
 
500
  async function runManifestCheck() {
501
  const findings = [];
 
502
  try {
503
  const manifest = await loadManifest(MANIFEST_PATH);
504
- await validateManifestAgainstRoot(manifest, root);
 
 
 
 
 
 
 
505
  } catch (error) {
506
  findings.push({
507
  id: 'manifest-consistency', level: 'error',
508
  message: error.message,
509
  });
510
  }
 
511
  return findings;
512
  }
513
 
 
499
 
500
  async function runManifestCheck() {
501
  const findings = [];
502
+ const started = Date.now();
503
  try {
504
  const manifest = await loadManifest(MANIFEST_PATH);
505
+ const summary = await validateManifestAgainstRoot(manifest, root);
506
+ if (summary.stale.length) {
507
+ const sample = summary.stale.slice(0, 5).join(', ');
508
+ findings.push({
509
+ id: 'manifest-stale', level: 'error',
510
+ message: `${summary.stale.length} file(s) changed since last manifest stamp (e.g. ${sample}${summary.stale.length > 5 ? ', ...' : ''}); run: node tools/history_language_manifest.mjs stamp`,
511
+ });
512
+ }
513
  } catch (error) {
514
  findings.push({
515
  id: 'manifest-consistency', level: 'error',
516
  message: error.message,
517
  });
518
  }
519
+ console.log(`Manifest check took ${((Date.now() - started) / 1000).toFixed(1)}s`);
520
  return findings;
521
  }
522