dsh-zipfix 0.0.0-stage → 0.4.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.
@@ -0,0 +1,633 @@
1
+ /**
2
+ * dsh-zipfix:ZIP 中文文件名乱码修复器的 Host 插件入口。
3
+ *
4
+ * 在 tools 服务上注册 5 个 agent 可调用工具:
5
+ * - zipfix_scan 分类与体检(只读)
6
+ * - zipfix_fix_zip 按正确编码解压 + 生成置位 UTF-8 标志的修复版 ZIP
7
+ * - zipfix_rename_dir 已解压目录形态 A 批量改名(cp437/latin1 → GBK)
8
+ * - zipfix_match_source 形态 B(U+FFFD)按 (size, CRC32) 与源包精确配对
9
+ * - zipfix_verify_names 内容反推 + 编码指纹验证
10
+ *
11
+ * 设计约束:零第三方依赖(只用 Node 标准库),不删除/不覆盖任何源文件,
12
+ * 所有写操作默认 dry-run,需显式传 dryRun=false 才落盘。
13
+ */
14
+
15
+ import path from 'node:path';
16
+ import fsp from 'node:fs/promises';
17
+ import { REPORTS_DIR_NAME, fixZipArchive, matchSource, renameDirectory, verifyNames } from './lib/fix.js';
18
+ import { classifyName } from './lib/detect.js';
19
+ import { displayWidth } from './lib/encoding.js';
20
+
21
+ export const name = 'dsh-zipfix';
22
+ export const inject = ['tools'];
23
+
24
+ /* ------------------------------------------------------------------ *
25
+ * 工具输出辅助
26
+ * ------------------------------------------------------------------ */
27
+
28
+ const MAX_TEXT = 6000;
29
+
30
+ function truncate(text, width) {
31
+ const value = String(text ?? '');
32
+ if (displayWidth(value) <= width) return value;
33
+ let out = '';
34
+ let used = 0;
35
+ for (const ch of value) {
36
+ const w = displayWidth(ch);
37
+ if (used + w > width - 1) break;
38
+ out += ch;
39
+ used += w;
40
+ }
41
+ return `${out}…`;
42
+ }
43
+
44
+ function textContent(lines) {
45
+ let text = lines.filter((line) => line !== undefined && line !== null && line !== '').join('\n');
46
+ if (text.length > MAX_TEXT) text = `${text.slice(0, MAX_TEXT)}\n…(输出已截断)`;
47
+ return [{ type: 'text', text }];
48
+ }
49
+
50
+ function rowLines(rows, limit = 8) {
51
+ if (!Array.isArray(rows) || rows.length === 0) return [];
52
+ const lines = ['', '样例:'];
53
+ for (const row of rows.slice(0, limit)) {
54
+ const original = truncate(row.original ?? '', 44);
55
+ const fixed = truncate(row.fixed ?? '', 44);
56
+ const verify = row.verify ? `|${truncate(row.verify, 40)}` : '';
57
+ lines.push(` ${original} → ${fixed}${verify}`);
58
+ }
59
+ return lines;
60
+ }
61
+
62
+ function failureLines(failures, limit = 5) {
63
+ if (!Array.isArray(failures) || failures.length === 0) return [];
64
+ const lines = ['', '失败 / 待人工:'];
65
+ for (const failure of failures.slice(0, limit)) {
66
+ lines.push(` ${truncate(failure.original ?? failure.path ?? '', 44)}:${truncate(failure.reason ?? '', 80)}`);
67
+ }
68
+ if (failures.length > limit) lines.push(` …另有 ${failures.length - limit} 条,见报告`);
69
+ return lines;
70
+ }
71
+
72
+ /**
73
+ * 工具输出 schema:只强制校验 ok/summary 两个字段。
74
+ * 其余字段随工具语义自由扩展(additionalProperties: true),
75
+ * 避免为每个工具维护一份容易与实现漂移的完整 schema。
76
+ */
77
+ function outputSchema() {
78
+ return {
79
+ type: 'object',
80
+ additionalProperties: true,
81
+ properties: {
82
+ ok: { type: 'boolean' },
83
+ summary: { type: 'string' },
84
+ },
85
+ required: ['ok', 'summary'],
86
+ };
87
+ }
88
+
89
+ function defineTool({ name: toolName, description, parameters, schema, timeoutMs, execute, render }) {
90
+ return {
91
+ name: toolName,
92
+ description,
93
+ parameters,
94
+ output: { schema, render },
95
+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
96
+ execute,
97
+ };
98
+ }
99
+
100
+ /* ------------------------------------------------------------------ *
101
+ * 路径解析:相对路径按当前会话的工作目录展开
102
+ * ------------------------------------------------------------------ */
103
+
104
+ function createPathResolver(ctx) {
105
+ return async function resolvePath(input, exec) {
106
+ const raw = String(input ?? '').trim();
107
+ if (raw.length === 0) throw new Error('路径不能为空');
108
+ if (path.isAbsolute(raw)) return path.normalize(raw);
109
+ let base = process.cwd();
110
+ const directories = ctx.get('workingDirectory');
111
+ if (exec?.agent && directories !== undefined) {
112
+ try {
113
+ base = await directories.ensure(exec.agent, exec.signal);
114
+ } catch {
115
+ base = process.cwd();
116
+ }
117
+ }
118
+ return path.resolve(base, raw);
119
+ };
120
+ }
121
+
122
+ /* ------------------------------------------------------------------ *
123
+ * 只读扫描
124
+ * ------------------------------------------------------------------ */
125
+
126
+ async function scanDirectory(root, { limit = 30 } = {}) {
127
+ const forms = { ascii: 0, clean: 0, reversibleA: 0, reversibleA2: 0, irreversible: 0, double: 0, unknown: 0 };
128
+ const reversible = [];
129
+ const irreversible = [];
130
+ const unknown = [];
131
+ const doubleDamaged = [];
132
+ let scanned = 0;
133
+
134
+ async function walk(current) {
135
+ const children = await fsp.readdir(current, { withFileTypes: true });
136
+ for (const child of children) {
137
+ if (child.isDirectory() && child.name === REPORTS_DIR_NAME) continue; // 跳过本插件报告目录
138
+ if (child.isFile() && /^zipfix-(?:fix-zip|rename-dir|match-source)-/.test(child.name)) continue;
139
+ scanned++;
140
+ const classified = classifyName(child.name);
141
+ forms[classified.form === 'A' ? 'reversibleA' : classified.form === 'A2' ? 'reversibleA2' : classified.form]++;
142
+ const display = path.join(path.relative(root, current), child.name).replace(/\\/g, '/');
143
+ if (classified.form === 'A' || classified.form === 'A2') {
144
+ if (reversible.length < limit) {
145
+ reversible.push({ original: display, fixed: classified.fixed, basis: classified.chain });
146
+ }
147
+ } else if (classified.form === 'irreversible') {
148
+ if (irreversible.length < limit) {
149
+ irreversible.push({ original: display, fffd: classified.fffd ?? 0, fixed: null, basis: '含 U+FFFD,字节已销毁' });
150
+ }
151
+ } else if (classified.form === 'double') {
152
+ if (doubleDamaged.length < limit) {
153
+ doubleDamaged.push({ original: display, fffd: 0, fixed: null, basis: '二次损坏(锟斤拷型)' });
154
+ }
155
+ } else if (classified.form === 'unknown') {
156
+ if (unknown.length < limit) unknown.push({ original: display, fixed: null, basis: '无法自动识别编码' });
157
+ }
158
+ if (child.isDirectory()) await walk(path.join(current, child.name));
159
+ }
160
+ }
161
+
162
+ await walk(root);
163
+
164
+ const total = forms.ascii + forms.clean + forms.reversibleA + forms.reversibleA2 + forms.irreversible + forms.double + forms.unknown;
165
+ const verdict =
166
+ forms.irreversible + forms.double > 0
167
+ ? forms.reversibleA + forms.reversibleA2 > 0
168
+ ? 'mixed'
169
+ : 'irreversible'
170
+ : forms.reversibleA + forms.reversibleA2 > 0
171
+ ? 'reversible'
172
+ : forms.unknown > 0
173
+ ? 'unknown'
174
+ : 'no-fix-needed';
175
+
176
+ const nextSteps = [];
177
+ if (forms.reversibleA + forms.reversibleA2 > 0) {
178
+ nextSteps.push('可用 zipfix_rename_dir(先 dryRun=true 预览,再 dryRun=false 执行)无损批量改名。');
179
+ }
180
+ if (forms.irreversible + forms.double > 0) {
181
+ nextSteps.push('含 U+FFFD 的名字不可逆:若源 ZIP 还在,用 zipfix_match_source 按 (size, CRC32) 精确配对还原。');
182
+ nextSteps.push('无源包时用 zipfix_verify_names 从文档内部标题生成候选名并做编码指纹验证,只改「已验证」的名字。');
183
+ }
184
+ if (forms.unknown > 0) nextSteps.push('无法识别的名字请人工确认编码(可能为 Big5/Shift-JIS,可显式指定 encoding 重试)。');
185
+ if (nextSteps.length === 0) nextSteps.push('目录内文件名编码正常,无需处理。');
186
+
187
+ return {
188
+ ok: true,
189
+ kind: 'directory',
190
+ path: root,
191
+ verdict,
192
+ scanning: '仅读取文件名,未读取文件内容,也未改动任何文件',
193
+ forms,
194
+ total,
195
+ scanned,
196
+ samples: [...reversible, ...irreversible, ...doubleDamaged, ...unknown].slice(0, limit),
197
+ nextSteps,
198
+ warnings: [],
199
+ summary:
200
+ verdict === 'no-fix-needed'
201
+ ? `扫描 ${scanned} 项:文件名编码正常,无需修复`
202
+ : verdict === 'reversible'
203
+ ? `扫描 ${scanned} 项:${forms.reversibleA + forms.reversibleA2} 项可无损还原(形态 A)`
204
+ : verdict === 'irreversible'
205
+ ? `扫描 ${scanned} 项:${forms.irreversible + forms.double} 项字节已销毁(U+FFFD),需源包或内容反推`
206
+ : verdict === 'mixed'
207
+ ? `扫描 ${scanned} 项:${forms.reversibleA + forms.reversibleA2} 项可无损还原,${forms.irreversible + forms.double} 项不可逆`
208
+ : `扫描 ${scanned} 项:${forms.unknown} 项无法自动识别编码`,
209
+ };
210
+ }
211
+
212
+ /* ------------------------------------------------------------------ *
213
+ * 插件主体
214
+ * ------------------------------------------------------------------ */
215
+
216
+ /**
217
+ * @param {object} ctx Cordis 插件上下文(inject: tools)
218
+ */
219
+ export function apply(ctx) {
220
+ const resolvePath = createPathResolver(ctx);
221
+
222
+ /* ---------------- zipfix_scan ---------------- */
223
+ ctx.effect(() =>
224
+ ctx.tools.register(
225
+ defineTool({
226
+ name: 'zipfix_scan',
227
+ description:
228
+ '诊断 ZIP 压缩包或已解压目录的中文文件名乱码(只读,不改任何文件)。' +
229
+ '对 ZIP:读取中央目录原始文件名字节,按 utf-8/gbk/gb18030/big5 严格解码打分,给出编码判定、置信度、每个条目的修正后名字与「可逆/不可逆」结论。' +
230
+ '对目录:递归分类文件名形态(A=CP437/Latin-1 误解码可无损反解;B=含 U+FFFD 字节已销毁不可逆;二次损坏等)。' +
231
+ '修复任何文件前先调用本工具确认形态。',
232
+ parameters: {
233
+ type: 'object',
234
+ additionalProperties: false,
235
+ properties: {
236
+ path: {
237
+ type: 'string',
238
+ description: 'ZIP 文件或已解压目录的路径;相对路径按当前会话工作目录解析。',
239
+ },
240
+ encoding: {
241
+ type: 'string',
242
+ enum: ['auto', 'utf-8', 'gbk', 'gb18030', 'big5'],
243
+ description: '强制指定 ZIP 条目名编码,默认 auto(嗅探)。嗅探置信度低时用它覆盖。',
244
+ },
245
+ limit: {
246
+ type: 'integer',
247
+ description: '样例条目上限,默认 30。',
248
+ },
249
+ },
250
+ required: ['path'],
251
+ },
252
+ schema: outputSchema(),
253
+ timeoutMs: 300000,
254
+ async execute(args, exec) {
255
+ const target = await resolvePath(args.path, exec);
256
+ let stat;
257
+ try {
258
+ stat = await fsp.stat(target);
259
+ } catch (error) {
260
+ throw new Error(`路径不存在或无法访问:${target}(${error.message})`);
261
+ }
262
+ const limit = Number.isInteger(args.limit) && args.limit > 0 ? args.limit : 30;
263
+ if (stat.isDirectory()) {
264
+ const result = await scanDirectory(target, { limit });
265
+ return { ...result, nextSteps: result.nextSteps.slice(0, 10) };
266
+ }
267
+ const result = await fixZipArchive({
268
+ zipPath: target,
269
+ encoding: args.encoding,
270
+ extract: false,
271
+ buildFixedZip: false,
272
+ dryRun: true,
273
+ signal: exec.signal,
274
+ });
275
+ const nextSteps = [];
276
+ if (result.status === 'reversible' || result.status === 'mixed') {
277
+ nextSteps.push('可用 zipfix_fix_zip(先 dryRun=true 预览)按正确文件名解压,并生成置位 UTF-8 标志的修复版 ZIP。');
278
+ }
279
+ if (result.status === 'flag-missing-utf8') {
280
+ nextSteps.push('名字本身是 UTF-8,只是缺少 0x0800 标志位:用 zipfix_fix_zip 并设 buildFixedZip=true 重建即可。');
281
+ }
282
+ if (result.irreversible.length > 0) {
283
+ nextSteps.push('压缩包内有条目名含 U+FFFD(信息已丢失),无法从包内还原。');
284
+ }
285
+ if (result.status === 'unknown') {
286
+ nextSteps.push('编码无法识别:请显式指定 encoding(如 big5 / gb18030)后重试。');
287
+ }
288
+ if (nextSteps.length === 0) nextSteps.push('文件名编码已合规,无需修复。');
289
+ // ZIP 视角的形态统计:条目是否需要按选中编码重新解码
290
+ const reversible = result.encoding !== 'utf-8' && result.encoding !== 'ascii'
291
+ ? result.entries.nonAscii - result.irreversible.length
292
+ : 0;
293
+ return {
294
+ ok: true,
295
+ kind: 'zip',
296
+ path: target,
297
+ zipSize: result.zipSize,
298
+ verdict: result.status,
299
+ encoding: result.encoding,
300
+ method: result.method,
301
+ confidence: result.confidence,
302
+ scores: result.scores,
303
+ entries: result.entries,
304
+ forms: {
305
+ reversible: Math.max(0, reversible),
306
+ irreversible: result.irreversible.length,
307
+ ascii: result.entries.total - result.entries.nonAscii,
308
+ alreadyUtf8: result.entries.declaredUtf8,
309
+ },
310
+ stripRoot: result.stripRoot,
311
+ samples: result.rows.slice(0, limit),
312
+ irreversible: result.irreversible.slice(0, limit),
313
+ failures: result.failures.slice(0, limit),
314
+ nextSteps,
315
+ warnings: result.warnings,
316
+ summary: result.summary,
317
+ };
318
+ },
319
+ render(args, value) {
320
+ const lines = [`【ZIP 文件名体检】${value.summary}`, `路径:${value.path}`];
321
+ if (value.kind === 'zip') {
322
+ lines.push(
323
+ `编码:${value.encoding ?? '未知'}(${value.method},置信度 ${value.confidence})|条目 ${value.entries.total}(文件 ${value.entries.files} / 目录 ${value.entries.directories})`,
324
+ );
325
+ if (value.stripRoot) lines.push(`冗余顶层目录:${value.stripRoot}`);
326
+ lines.push(
327
+ `形态:可逆=${value.forms.reversible}|U+FFFD=${value.forms.irreversible}|ASCII=${value.forms.ascii}|已声明 UTF-8=${value.forms.alreadyUtf8}`,
328
+ );
329
+ } else {
330
+ lines.push(
331
+ `形态:可逆 A=${value.forms.reversibleA} A2=${value.forms.reversibleA2}|U+FFFD=${value.forms.irreversible}|二次损坏=${value.forms.double}|正常=${value.forms.clean + value.forms.ascii}|未知=${value.forms.unknown}`,
332
+ );
333
+ }
334
+ lines.push(...rowLines(value.samples));
335
+ lines.push(...failureLines(value.failures));
336
+ if (value.nextSteps?.length) {
337
+ lines.push('', '下一步:');
338
+ for (const step of value.nextSteps) lines.push(` • ${step}`);
339
+ }
340
+ return textContent(lines);
341
+ },
342
+ }),
343
+ ),
344
+ );
345
+
346
+ /* ---------------- zipfix_fix_zip ---------------- */
347
+ ctx.effect(() =>
348
+ ctx.tools.register(
349
+ defineTool({
350
+ name: 'zipfix_fix_zip',
351
+ description:
352
+ '按嗅探/指定的编码解码 ZIP 条目名,把内容无损解压成正确中文名,并可生成「修复版 ZIP」(全部条目置位 UTF-8 文件名标志 0x0800,Windows 资源管理器/7-Zip 直接正常显示)。' +
353
+ '逐条校验解压后大小与 CRC32;永不删除源 ZIP、永不覆盖已有文件(重名自动加 _fixed 后缀)。默认 dryRun=true 只返回计划;确认后传 dryRun=false 才落盘。',
354
+ parameters: {
355
+ type: 'object',
356
+ additionalProperties: false,
357
+ properties: {
358
+ zipPath: { type: 'string', description: '待修复 ZIP 的路径。' },
359
+ outputDir: {
360
+ type: 'string',
361
+ description: '输出目录,默认与源 ZIP 同级目录。',
362
+ },
363
+ encoding: {
364
+ type: 'string',
365
+ enum: ['auto', 'utf-8', 'gbk', 'gb18030', 'big5'],
366
+ description: '强制指定条目名编码,默认 auto 嗅探。',
367
+ },
368
+ extract: { type: 'boolean', description: '是否按正确文件名解压,默认 true。' },
369
+ buildFixedZip: { type: 'boolean', description: '是否额外生成修复版 ZIP(置位 0x0800),默认 false。' },
370
+ stripRoot: {
371
+ type: 'boolean',
372
+ description: '是否剥离与 ZIP 同名的冗余顶层目录,默认 true。',
373
+ },
374
+ dryRun: { type: 'boolean', description: '默认 true:只出计划与报告,不改动任何文件;确认后传 false 执行。' },
375
+ force: {
376
+ type: 'boolean',
377
+ description: '默认 false:判定「无需修复」时直接返回、不产生任何改动;传 true 才会强制解压/重建。',
378
+ },
379
+ },
380
+ required: ['zipPath'],
381
+ },
382
+ schema: outputSchema(),
383
+ timeoutMs: 900000,
384
+ async execute(args, exec) {
385
+ const zipPath = await resolvePath(args.zipPath, exec);
386
+ const outputDir = args.outputDir === undefined ? undefined : await resolvePath(args.outputDir, exec);
387
+ const result = await fixZipArchive({
388
+ zipPath,
389
+ outputDir,
390
+ encoding: args.encoding,
391
+ extract: args.extract !== false,
392
+ buildFixedZip: args.buildFixedZip === true,
393
+ stripRoot: args.stripRoot !== false,
394
+ dryRun: args.dryRun !== false,
395
+ force: args.force === true,
396
+ signal: exec.signal,
397
+ });
398
+ const nextSteps = [];
399
+ if (result.status === 'no-fix-needed') {
400
+ if (result.forced === true) {
401
+ nextSteps.push('已按 force:true 强制处理完毕(源文件未删除、未覆盖);如需对比原始结构请以源 ZIP 为准。');
402
+ } else {
403
+ nextSteps.push('文件名编码已合规,无需处理;如需强制解压/重建,请显式传 force:true。');
404
+ }
405
+ } else if (result.dryRun) {
406
+ nextSteps.push('确认计划无误后,用相同参数并设 dryRun=false 执行落盘。');
407
+ }
408
+ if (result.applied?.fixedZipPath) {
409
+ nextSteps.push(`修复版 ZIP 已生成:${result.applied.fixedZipPath}(可直接转发,对方不会乱码)。`);
410
+ }
411
+ if (result.irreversible.length > 0) {
412
+ nextSteps.push('存在 U+FFFD 条目:包内无法还原,如有源包请用 zipfix_match_source 配对。');
413
+ }
414
+ if (result.applied?.report) nextSteps.push(`审计报告:${result.applied.report.markdownPath}`);
415
+ if (nextSteps.length === 0) nextSteps.push('无需进一步操作。');
416
+ return { ...result, nextSteps };
417
+ },
418
+ render(args, value) {
419
+ const lines = [`【ZIP 文件名修复】${value.summary}`, `ZIP:${value.zipPath}`];
420
+ lines.push(`判定:${value.status ?? value.verdict ?? '未知'}|编码:${value.encoding ?? '未知'}(${value.method},置信度 ${value.confidence})`);
421
+ if (value.dryRun) lines.push('模式:dry-run(未改动任何文件)');
422
+ else {
423
+ lines.push(
424
+ `已解压:${value.applied.extractedFiles} 个文件 / ${value.applied.extractedDirectories} 个目录;失败 ${value.applied.extractionFailures} 个`,
425
+ );
426
+ if (value.applied.fixedZipPath) {
427
+ const verification = value.applied.fixedZip;
428
+ lines.push(
429
+ `修复版 ZIP:${value.applied.fixedZipPath}(回读 ${verification.entries} 条目,UTF-8 标志 ${verification.allUtf8Flag ? '全部置位' : '有缺失'},${verification.fullChecked ? 'CRC32 全量校验通过' : '结构校验通过'})`,
430
+ );
431
+ }
432
+ if (value.applied.report) lines.push(`报告:${value.applied.report.markdownPath}`);
433
+ }
434
+ lines.push(...rowLines(value.rows, 6));
435
+ lines.push(...failureLines(value.failures, 4));
436
+ if (value.nextSteps?.length) {
437
+ lines.push('', '下一步:');
438
+ for (const step of value.nextSteps) lines.push(` • ${step}`);
439
+ }
440
+ return textContent(lines);
441
+ },
442
+ }),
443
+ ),
444
+ );
445
+
446
+ /* ---------------- zipfix_rename_dir ---------------- */
447
+ ctx.effect(() =>
448
+ ctx.tools.register(
449
+ defineTool({
450
+ name: 'zipfix_rename_dir',
451
+ description:
452
+ '批量修复「已经解压坏」的目录里的文件名(形态 A:CP437 框线字符 / Latin-1 高位字符误解码)。' +
453
+ '自底向上改名,源码串.encode(cp437|latin-1).decode(gbk) 无损还原;含 U+FFFD 的名字不猜、列入待人工。' +
454
+ '永不覆盖同名文件;默认 dryRun=true 只出计划。',
455
+ parameters: {
456
+ type: 'object',
457
+ additionalProperties: false,
458
+ properties: {
459
+ root: { type: 'string', description: '已解压目录路径。' },
460
+ dryRun: { type: 'boolean', description: '默认 true:只出计划;确认后传 false 执行改名。' },
461
+ recursive: { type: 'boolean', description: '是否递归子目录,默认 true。' },
462
+ verifyHashes: {
463
+ type: 'boolean',
464
+ description: '改名前后是否计算并复核 SHA-256(大目录会慢),默认 false(仅复核 size)。',
465
+ },
466
+ },
467
+ required: ['root'],
468
+ },
469
+ schema: outputSchema(),
470
+ timeoutMs: 900000,
471
+ async execute(args, exec) {
472
+ const root = await resolvePath(args.root, exec);
473
+ const result = await renameDirectory({
474
+ root,
475
+ dryRun: args.dryRun !== false,
476
+ recursive: args.recursive !== false,
477
+ verifyHashes: args.verifyHashes === true,
478
+ signal: exec.signal,
479
+ });
480
+ const nextSteps = [];
481
+ if (result.dryRun && result.stats.planned > 0) nextSteps.push('确认计划后,用相同参数并设 dryRun=false 执行改名。');
482
+ if (result.failures.length > 0) {
483
+ nextSteps.push('含 U+FFFD 或无法识别的名字未改动:若有源 ZIP,用 zipfix_match_source 精确配对还原。');
484
+ }
485
+ if (result.report) nextSteps.push(`审计报告:${result.report.markdownPath}`);
486
+ return { ...result, nextSteps };
487
+ },
488
+ render(args, value) {
489
+ const lines = [`【目录文件名修复】${value.summary}`, `目录:${value.root}`];
490
+ if (value.dryRun) lines.push('模式:dry-run(未改动任何文件)');
491
+ lines.push(`扫描 ${value.stats.scanned} 项:可还原 ${value.stats.planned},已改名 ${value.stats.renamed},失败 ${value.stats.failed},无法识别 ${value.stats.skipped}`);
492
+ lines.push(...rowLines(value.rows, 8));
493
+ lines.push(...failureLines(value.failures, 4));
494
+ if (value.nextSteps?.length) {
495
+ lines.push('', '下一步:');
496
+ for (const step of value.nextSteps) lines.push(` • ${step}`);
497
+ }
498
+ return textContent(lines);
499
+ },
500
+ }),
501
+ ),
502
+ );
503
+
504
+ /* ---------------- zipfix_match_source ---------------- */
505
+ ctx.effect(() =>
506
+ ctx.tools.register(
507
+ defineTool({
508
+ name: 'zipfix_match_source',
509
+ description:
510
+ '形态 B(文件名含 U+FFFD、字节已销毁)的最优修复路径:用源 ZIP 中央目录的 (解压后大小, CRC32) 与磁盘文件内容精确配对,唯一命中才改名,0 个或多个命中一律不猜。' +
511
+ '改名前后记录并复核 SHA-256,内容零改动;默认 dryRun=true。',
512
+ parameters: {
513
+ type: 'object',
514
+ additionalProperties: false,
515
+ properties: {
516
+ directory: { type: 'string', description: '受损文件所在目录(可递归)。' },
517
+ sourceZip: { type: 'string', description: '源 ZIP 路径(原始压缩包)。' },
518
+ encoding: {
519
+ type: 'string',
520
+ enum: ['auto', 'utf-8', 'gbk', 'gb18030', 'big5'],
521
+ description: '源 ZIP 条目名编码,默认 auto 嗅探。',
522
+ },
523
+ dryRun: { type: 'boolean', description: '默认 true:只出配对计划;确认后传 false 执行改名。' },
524
+ recursive: { type: 'boolean', description: '是否递归子目录,默认 true。' },
525
+ },
526
+ required: ['directory', 'sourceZip'],
527
+ },
528
+ schema: outputSchema(),
529
+ timeoutMs: 900000,
530
+ async execute(args, exec) {
531
+ const directory = await resolvePath(args.directory, exec);
532
+ const sourceZip = await resolvePath(args.sourceZip, exec);
533
+ const result = await matchSource({
534
+ directory,
535
+ sourceZip,
536
+ encoding: args.encoding,
537
+ dryRun: args.dryRun !== false,
538
+ recursive: args.recursive !== false,
539
+ signal: exec.signal,
540
+ });
541
+ const nextSteps = [];
542
+ if (result.dryRun && result.stats.matched > 0) {
543
+ nextSteps.push('确认配对结果后,用相同参数并设 dryRun=false 执行改名。');
544
+ }
545
+ if (result.stats.unmatched > 0) {
546
+ nextSteps.push('未配对文件在源 ZIP 中没有 (size, CRC32) 相同的条目,需人工确认或改用 zipfix_verify_names。');
547
+ }
548
+ if (result.report) nextSteps.push(`审计报告:${result.report.markdownPath}`);
549
+ return { ...result, nextSteps };
550
+ },
551
+ render(args, value) {
552
+ const lines = [`【源包 CRC 配对】${value.summary}`, `目录:${value.directory}`, `源 ZIP:${value.sourceZip}(条目名编码 ${value.sourceEncoding ?? '未知'})`];
553
+ if (value.dryRun) lines.push('模式:dry-run(未改动任何文件)');
554
+ lines.push(`扫描 ${value.stats.scanned} 个文件:唯一配对 ${value.stats.matched},已改名 ${value.stats.renamed},未配对 ${value.stats.unmatched},待人工 ${value.stats.failed}`);
555
+ lines.push(...rowLines(value.rows, 8));
556
+ lines.push(...failureLines(value.failures, 4));
557
+ if (value.nextSteps?.length) {
558
+ lines.push('', '下一步:');
559
+ for (const step of value.nextSteps) lines.push(` • ${step}`);
560
+ }
561
+ return textContent(lines);
562
+ },
563
+ }),
564
+ ),
565
+ );
566
+
567
+ /* ---------------- zipfix_verify_names ---------------- */
568
+ ctx.effect(() =>
569
+ ctx.tools.register(
570
+ defineTool({
571
+ name: 'zipfix_verify_names',
572
+ description:
573
+ '形态 B 兜底:内容反推 + 编码指纹验证,不猜名字、不改文件。' +
574
+ '给定当前乱码名与候选正确名,计算「候选名按 GBK 编码后再按 UTF-8 替换解码」的指纹,与乱码名逐字符比对:完全相等才算已验证。' +
575
+ '可选 documentPath 自动从 .docx/.xlsx/.pptx/.pdf 内部抽取标题生成候选名(交接文档 ALG-7)。',
576
+ parameters: {
577
+ type: 'object',
578
+ additionalProperties: false,
579
+ properties: {
580
+ mojibakeName: { type: 'string', description: '当前磁盘上的乱码文件名(含 U+FFFD 也可以)。' },
581
+ candidates: {
582
+ type: 'array',
583
+ items: { type: 'string' },
584
+ description: '候选正确文件名列表(可带扩展名)。',
585
+ },
586
+ documentPath: {
587
+ type: 'string',
588
+ description: '对应的文档文件路径,用于自动抽取标题生成候选名(.docx/.xlsx/.pptx/.pdf)。',
589
+ },
590
+ },
591
+ required: ['mojibakeName'],
592
+ },
593
+ schema: outputSchema(),
594
+ timeoutMs: 300000,
595
+ async execute(args, exec) {
596
+ const documentPath =
597
+ args.documentPath === undefined ? undefined : await resolvePath(args.documentPath, exec);
598
+ const result = await verifyNames({
599
+ mojibakeName: String(args.mojibakeName ?? ''),
600
+ candidates: Array.isArray(args.candidates) ? args.candidates.map(String) : [],
601
+ documentPath,
602
+ });
603
+ const nextSteps = [];
604
+ if (result.verified.length > 0) {
605
+ nextSteps.push('指纹完全吻合,可用文件系统改名工具(或 zipfix_match_source 的等价操作)安全改名。');
606
+ } else {
607
+ nextSteps.push('无候选通过验证:请补充候选名,或提供源 ZIP 用 zipfix_match_source 做数学配对。');
608
+ }
609
+ return { ...result, nextSteps };
610
+ },
611
+ render(args, value) {
612
+ const lines = [`【指纹验证】${value.summary}`, `乱码名:${value.mojibakeName}`];
613
+ lines.push(`U+FFFD ${value.fffdCount} 个,扩展名 ${value.extension || '(无)'}`);
614
+ if (value.document) {
615
+ lines.push(`文档标题(${value.document.kind}):${value.document.titles.slice(0, 5).join(' / ') || '(未抽取到)'}`);
616
+ }
617
+ if (value.candidates.length > 0) {
618
+ lines.push('', '候选验证:');
619
+ for (const item of value.candidates.slice(0, 10)) {
620
+ const mark = item.match === 'exact' ? '✅ 完全吻合' : item.match === 'normalized' ? '✅ 吻合(U+FFFD 折叠后)' : item.match === 'unencodable' ? '⚠ 无法 GBK 编码' : '❌ 不吻合';
621
+ lines.push(` ${mark}:${truncate(item.candidate, 60)}`);
622
+ }
623
+ }
624
+ if (value.nextSteps?.length) {
625
+ lines.push('', '下一步:');
626
+ for (const step of value.nextSteps) lines.push(` • ${step}`);
627
+ }
628
+ return textContent(lines);
629
+ },
630
+ }),
631
+ ),
632
+ );
633
+ }