agentdock-cli 1.1.0 → 1.2.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,154 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runSnapshotCommand = runSnapshotCommand;
4
+ const scan_1 = require("../core/scan");
5
+ const snapshot_1 = require("../core/snapshot");
6
+ const command_error_codes_1 = require("../constants/command-error-codes");
7
+ const command_json_1 = require("../utils/command-json");
8
+ const i18n_1 = require("../i18n");
9
+ function assertAction(action) {
10
+ if (!action || action === 'create')
11
+ return 'create';
12
+ if (action === 'list' || action === '--list')
13
+ return 'list';
14
+ if (action === 'push')
15
+ return 'push';
16
+ if (action === 'pull')
17
+ return 'pull';
18
+ if (action === 'help' || action === '--help' || action === '-h')
19
+ return 'help';
20
+ return null;
21
+ }
22
+ async function runSnapshotCommand(action, target, options = {}) {
23
+ const root = options.root ?? (0, scan_1.defaultScanRoot)();
24
+ const resolved = assertAction(action);
25
+ if (resolved === null) {
26
+ return {
27
+ exitCode: 1,
28
+ stdout: [],
29
+ stderr: [(0, i18n_1.t)('snapshot.usage')],
30
+ };
31
+ }
32
+ if (resolved === 'help') {
33
+ return { exitCode: 0, stdout: [(0, i18n_1.t)('snapshot.usage')], stderr: [] };
34
+ }
35
+ try {
36
+ if (resolved === 'push' || resolved === 'pull') {
37
+ if (!target) {
38
+ return { exitCode: 1, stdout: [], stderr: [(0, i18n_1.t)(`snapshot.${resolved}Usage`)] };
39
+ }
40
+ if (resolved === 'push') {
41
+ const result = await (0, snapshot_1.exportSnapshot)(root, target, options.snapshot, options.force === true);
42
+ if (options.json === true) {
43
+ return {
44
+ exitCode: 0,
45
+ stdout: [(0, command_json_1.toJsonLine)('snapshot', true, { action: 'push', ...result }, [])],
46
+ stderr: [],
47
+ };
48
+ }
49
+ return { exitCode: 0, stdout: [(0, i18n_1.t)('snapshot.pushed', { id: result.id, dest: result.dest })], stderr: [] };
50
+ }
51
+ const result = await (0, snapshot_1.importSnapshots)(root, target, options.force === true);
52
+ if (options.json === true) {
53
+ return {
54
+ exitCode: 0,
55
+ stdout: [(0, command_json_1.toJsonLine)('snapshot', true, { action: 'pull', ...result }, [])],
56
+ stderr: [],
57
+ };
58
+ }
59
+ const lines = [];
60
+ if (result.imported.length > 0) {
61
+ lines.push((0, i18n_1.t)('snapshot.pulled', { count: result.imported.length, ids: result.imported.join(', ') }));
62
+ }
63
+ if (result.skipped.length > 0) {
64
+ lines.push((0, i18n_1.t)('snapshot.pullSkipped', { ids: result.skipped.join(', ') }));
65
+ }
66
+ if (lines.length === 0) {
67
+ lines.push((0, i18n_1.t)('snapshot.pullNone'));
68
+ }
69
+ return { exitCode: 0, stdout: lines, stderr: [] };
70
+ }
71
+ if (resolved === 'list') {
72
+ const snapshots = await (0, snapshot_1.listSnapshots)(root);
73
+ const dir = (0, snapshot_1.snapshotsDir)(root);
74
+ if (options.json === true) {
75
+ return {
76
+ exitCode: 0,
77
+ stdout: [(0, command_json_1.toJsonLine)('snapshot', true, { action: 'list', dir, snapshots }, [])],
78
+ stderr: [],
79
+ };
80
+ }
81
+ if (snapshots.length === 0) {
82
+ return { exitCode: 0, stdout: [(0, i18n_1.t)('snapshot.empty')], stderr: [] };
83
+ }
84
+ const lines = [(0, i18n_1.t)('snapshot.listHeader', { count: snapshots.length, dir })];
85
+ for (const item of snapshots) {
86
+ lines.push((0, i18n_1.t)('snapshot.listItem', {
87
+ id: item.id,
88
+ agent: item.agent,
89
+ files: item.files,
90
+ redacted: item.redacted ? ' [redacted]' : '',
91
+ }));
92
+ }
93
+ return { exitCode: 0, stdout: lines, stderr: [] };
94
+ }
95
+ const agent = options.agent ?? 'all';
96
+ if (options.ifChanged === true) {
97
+ const unchanged = await (0, snapshot_1.findUnchangedSnapshot)(root, agent);
98
+ if (unchanged) {
99
+ if (options.json === true) {
100
+ return {
101
+ exitCode: 0,
102
+ stdout: [(0, command_json_1.toJsonLine)('snapshot', true, {
103
+ action: 'create',
104
+ created: false,
105
+ skipped: true,
106
+ snapshotId: unchanged.id,
107
+ agent,
108
+ root,
109
+ }, [])],
110
+ stderr: [],
111
+ };
112
+ }
113
+ return { exitCode: 0, stdout: [(0, i18n_1.t)('snapshot.unchanged', { id: unchanged.id })], stderr: [] };
114
+ }
115
+ }
116
+ const meta = await (0, snapshot_1.createSnapshot)({ root, agent, redact: options.redact === true });
117
+ if (options.json === true) {
118
+ return {
119
+ exitCode: 0,
120
+ stdout: [(0, command_json_1.toJsonLine)('snapshot', true, { action: 'create', created: true, ...meta }, [])],
121
+ stderr: [],
122
+ };
123
+ }
124
+ return {
125
+ exitCode: 0,
126
+ stdout: [
127
+ (0, i18n_1.t)('snapshot.created', { id: meta.id }),
128
+ (0, i18n_1.t)('snapshot.location', { path: (0, snapshot_1.snapshotsDir)(root) }),
129
+ (0, i18n_1.t)('snapshot.files', {
130
+ count: meta.files.length,
131
+ files: meta.files.map((file) => file.relPath).join(', '),
132
+ }),
133
+ (0, i18n_1.t)('snapshot.counts', {
134
+ top: meta.counts.topLevelKeys,
135
+ env: meta.counts.envKeys,
136
+ mcp: meta.counts.mcpCount,
137
+ }),
138
+ meta.redacted ? (0, i18n_1.t)('snapshot.redacted') : (0, i18n_1.t)('snapshot.plaintext'),
139
+ ],
140
+ stderr: [],
141
+ };
142
+ }
143
+ catch (error) {
144
+ const message = error instanceof Error ? error.message : String(error);
145
+ if (options.json === true) {
146
+ return {
147
+ exitCode: 1,
148
+ stdout: [(0, command_json_1.toJsonLine)('snapshot', false, { action: resolved }, [(0, command_json_1.toJsonError)(command_error_codes_1.COMMAND_ERROR_CODES.SNAPSHOT_FAILED, message)])],
149
+ stderr: [],
150
+ };
151
+ }
152
+ return { exitCode: 1, stdout: [], stderr: [message] };
153
+ }
154
+ }
@@ -27,4 +27,8 @@ exports.COMMAND_ERROR_CODES = {
27
27
  SIGN_KEY_EXISTS: 'SIGN_KEY_EXISTS',
28
28
  SIGN_FAILED: 'SIGN_FAILED',
29
29
  SIGNATURE_INVALID: 'SIGNATURE_INVALID',
30
+ SNAPSHOT_FAILED: 'SNAPSHOT_FAILED',
31
+ SNAPSHOT_NOT_FOUND: 'SNAPSHOT_NOT_FOUND',
32
+ RESTORE_FAILED: 'RESTORE_FAILED',
33
+ RESTORE_NO_UNDO: 'RESTORE_NO_UNDO',
30
34
  };
@@ -13,6 +13,8 @@ const claude_scanner_1 = require("../scanners/claude-scanner");
13
13
  const codex_scanner_1 = require("../scanners/codex-scanner");
14
14
  const sensitive_1 = require("../scanners/sensitive");
15
15
  const supply_chain_1 = require("./supply-chain");
16
+ const snapshot_1 = require("./snapshot");
17
+ const snapshot_diff_1 = require("./snapshot-diff");
16
18
  const smol_toml_1 = require("smol-toml");
17
19
  const fs_1 = require("../utils/fs");
18
20
  // ===== helpers =====
@@ -63,6 +65,207 @@ function makeCheck(id, label, findings, passDetail, remediation) {
63
65
  }
64
66
  return check;
65
67
  }
68
+ const BASELINE_FILES = {
69
+ claude: ['.claude.json', '.claude/settings.json', '.claude/settings.local.json'],
70
+ codex: ['.codex/config.toml'],
71
+ };
72
+ const BASELINE_CRITICAL_KEYS = {
73
+ claude: ['model', 'modelPicker', 'mcpServers', 'env'],
74
+ codex: ['model', 'model_providers', 'mcp_servers'],
75
+ };
76
+ /** 稳定序列化(键排序),避免对象键顺序不同造成"假不一致"。 */
77
+ function stableValue(value) {
78
+ if (Array.isArray(value)) {
79
+ return `[${value.map(stableValue).join(',')}]`;
80
+ }
81
+ if (value && typeof value === 'object') {
82
+ const record = value;
83
+ const keys = Object.keys(record).sort();
84
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${stableValue(record[key])}`).join(',')}}`;
85
+ }
86
+ return JSON.stringify(value) ?? 'null';
87
+ }
88
+ /** 收集 Claude 各配置文件中根级 mcpServers(项目级定义不参与跨文件比对)。 */
89
+ async function collectClaudeMcpSources(root) {
90
+ const sources = [];
91
+ for (const relPath of ['.claude.json', '.claude/settings.json', '.claude/settings.local.json']) {
92
+ const abs = node_path_1.default.join(root, ...relPath.split('/'));
93
+ if (!(await fileExists(abs))) {
94
+ continue;
95
+ }
96
+ try {
97
+ const parsed = JSON.parse(await promises_1.default.readFile(abs, 'utf8'));
98
+ const servers = parsed?.mcpServers;
99
+ if (servers && typeof servers === 'object' && !Array.isArray(servers)) {
100
+ sources.push({ file: abs, servers: servers });
101
+ }
102
+ }
103
+ catch {
104
+ // 解析失败已由 config-valid 检查报告
105
+ }
106
+ }
107
+ return sources;
108
+ }
109
+ /** 同一 MCP id 在多个配置文件中重复定义:值不一致 → warn,值一致 → info。 */
110
+ async function mcpDuplicateCheck(root) {
111
+ const sources = await collectClaudeMcpSources(root);
112
+ const byId = new Map();
113
+ for (const source of sources) {
114
+ for (const [id, value] of Object.entries(source.servers)) {
115
+ const list = byId.get(id) ?? [];
116
+ list.push({ file: source.file, value });
117
+ byId.set(id, list);
118
+ }
119
+ }
120
+ const findings = [];
121
+ for (const [id, defs] of [...byId.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
122
+ if (defs.length < 2) {
123
+ continue;
124
+ }
125
+ const files = defs.map((def) => node_path_1.default.basename(def.file));
126
+ const distinct = new Set(defs.map((def) => stableValue(def.value)));
127
+ if (distinct.size > 1) {
128
+ findings.push({
129
+ severity: 'warn',
130
+ message: `MCP "${id}" 在 ${files.join('、')} 中重复定义且值不一致;重启后 /mcp 可能出现重复项`,
131
+ path: defs.map((def) => def.file).join(', '),
132
+ });
133
+ }
134
+ else {
135
+ findings.push({
136
+ severity: 'info',
137
+ message: `MCP "${id}" 在 ${files.join('、')} 中重复定义(值一致,可清理冗余)`,
138
+ path: defs.map((def) => def.file).join(', '),
139
+ });
140
+ }
141
+ }
142
+ return makeCheck('mcp-duplicate', 'MCP 重复定义', findings, '未发现同一 MCP 在多个配置文件中重复定义', '同一 MCP id 在多处定义时,Claude Code 可能加载出重复项(`/mcp` 出现两次)或按加载顺序覆盖。保留一处(推荐 `.claude.json` 的全局 `mcpServers`),删除 `.claude/settings*.json` 中的重复定义后重启。');
143
+ }
144
+ /**
145
+ * 配置基线:与本 agent 最近一次快照比对,发现大面积顶层键减少或关键项消失时判失败。
146
+ * 无快照时保持 pass,仅提示先建立基线(避免升级后首次体检即报警)。
147
+ */
148
+ async function configBaselineCheck(root, agent) {
149
+ const latest = await (0, snapshot_1.latestSnapshot)(root, agent).catch(() => null);
150
+ if (!latest) {
151
+ return {
152
+ id: 'config-baseline',
153
+ label: '配置基线',
154
+ status: 'pass',
155
+ detail: '尚无配置快照,无法比对;建议运行 `agentdock snapshot` 建立基线',
156
+ findings: [],
157
+ };
158
+ }
159
+ const before = await (0, snapshot_1.readSnapshotContents)(latest);
160
+ const findings = [];
161
+ for (const relPath of BASELINE_FILES[agent]) {
162
+ const beforeBuffer = before.get(relPath);
163
+ if (!beforeBuffer) {
164
+ continue;
165
+ }
166
+ const abs = node_path_1.default.join(root, ...relPath.split('/'));
167
+ let afterText = null;
168
+ try {
169
+ afterText = await promises_1.default.readFile(abs, 'utf8');
170
+ }
171
+ catch {
172
+ afterText = null;
173
+ }
174
+ if (afterText === null) {
175
+ findings.push({ severity: 'error', message: `配置文件消失(快照中存在):${relPath}`, path: abs });
176
+ continue;
177
+ }
178
+ const beforeObj = (0, snapshot_diff_1.parseConfigObject)(relPath, beforeBuffer.toString('utf8'));
179
+ const afterObj = (0, snapshot_diff_1.parseConfigObject)(relPath, afterText);
180
+ if (!beforeObj || !afterObj
181
+ || typeof beforeObj !== 'object' || typeof afterObj !== 'object'
182
+ || Array.isArray(beforeObj) || Array.isArray(afterObj)) {
183
+ continue;
184
+ }
185
+ const beforeKeys = Object.keys(beforeObj);
186
+ const afterKeys = Object.keys(afterObj);
187
+ if (beforeKeys.length >= 5) {
188
+ const drop = (beforeKeys.length - afterKeys.length) / beforeKeys.length;
189
+ if (drop >= 0.3) {
190
+ findings.push({
191
+ severity: 'error',
192
+ message: `顶层配置项从 ${beforeKeys.length} 个减少到 ${afterKeys.length} 个(下降 ${Math.round(drop * 100)}%),疑似被改写`,
193
+ path: abs,
194
+ });
195
+ }
196
+ }
197
+ for (const key of BASELINE_CRITICAL_KEYS[agent]) {
198
+ if (Object.prototype.hasOwnProperty.call(beforeObj, key)
199
+ && !Object.prototype.hasOwnProperty.call(afterObj, key)) {
200
+ findings.push({ severity: 'error', message: `关键配置项消失:${key}`, path: abs });
201
+ }
202
+ }
203
+ }
204
+ return makeCheck('config-baseline', '配置基线', findings, `当前配置与最近快照 ${latest.meta.id} 一致`, '配置相对最近快照出现大面积缺失或关键项消失。先运行 `agentdock diff --since-last` 查看逐项差异;确认需要回滚后运行 `agentdock restore --snapshot <id> --apply`。');
205
+ }
206
+ /** 取差异路径中 `#` 后的首层键,如 `.claude.json#mcpServers.github` → `mcpServers`。 */
207
+ function topLevelKeyOf(changePath) {
208
+ const hash = changePath.indexOf('#');
209
+ const rest = hash >= 0 ? changePath.slice(hash + 1) : changePath;
210
+ return rest.split('.')[0];
211
+ }
212
+ /**
213
+ * 团队基线:与显式指定的快照比对(通常由 `snapshot pull` 导入)。
214
+ * 关键项缺失 → fail;其余差异 → warn。脱敏基线只比结构、不比值。
215
+ */
216
+ async function teamBaselineCheck(root, baselineRef) {
217
+ let baseline;
218
+ try {
219
+ baseline = await (0, snapshot_1.loadSnapshot)(root, baselineRef);
220
+ }
221
+ catch (error) {
222
+ return {
223
+ id: 'team-baseline',
224
+ label: '团队基线偏离',
225
+ status: 'fail',
226
+ detail: `无法读取团队基线:${baselineRef}`,
227
+ findings: [{ severity: 'error', message: error.message }],
228
+ remediation: '先 `agentdock snapshot pull <共享目录>` 导入团队基线,或用 `--baseline <快照目录>` 指定快照路径。',
229
+ };
230
+ }
231
+ const before = await (0, snapshot_1.readSnapshotContents)(baseline);
232
+ const after = new Map();
233
+ for (const relPath of (0, snapshot_1.configFilesFor)(baseline.meta.agent)) {
234
+ try {
235
+ after.set(relPath, await promises_1.default.readFile(node_path_1.default.join(root, ...relPath.split('/'))));
236
+ }
237
+ catch {
238
+ // 当前环境缺少该文件,由 diff 的 removed 条目体现
239
+ }
240
+ }
241
+ const files = [...new Set([...before.keys(), ...after.keys()])];
242
+ const diff = (0, snapshot_diff_1.buildSnapshotDiff)({ from: baseline.meta.id, to: 'current', files, before, after });
243
+ // 脱敏基线的值本来就与当前明文不同,只比较结构(新增 / 删除)
244
+ const changes = baseline.meta.redacted
245
+ ? diff.changes.filter((change) => change.change !== 'modified')
246
+ : diff.changes;
247
+ const critical = new Set(baseline.meta.agent === 'all'
248
+ ? [...BASELINE_CRITICAL_KEYS.claude, ...BASELINE_CRITICAL_KEYS.codex]
249
+ : BASELINE_CRITICAL_KEYS[baseline.meta.agent]);
250
+ const findings = [];
251
+ for (const change of changes) {
252
+ if (change.change === 'removed' && critical.has(topLevelKeyOf(change.path))) {
253
+ findings.push({
254
+ severity: 'error',
255
+ message: `团队基线的关键配置项在当前环境缺失:${change.path}`,
256
+ });
257
+ }
258
+ }
259
+ if (changes.length > 0) {
260
+ const summary = changes.slice(0, 5).map((change) => `${change.change} ${change.path}`).join(';');
261
+ findings.push({
262
+ severity: 'warn',
263
+ message: `与团队基线共有 ${changes.length} 处差异:${summary}${changes.length > 5 ? ' …' : ''}`,
264
+ });
265
+ }
266
+ const scopeNote = baseline.meta.redacted ? '(脱敏基线仅比结构)' : '';
267
+ return makeCheck('team-baseline', '团队基线偏离', findings, `当前配置与团队基线 ${baseline.meta.id} 一致${scopeNote}`, '与团队基线存在差异。先运行 `agentdock diff --snapshot <id>` 查看逐项差异;需要对齐时用 `agentdock restore --snapshot <id> --apply`,确认无误后再重启 Claude/Codex。');
268
+ }
66
269
  /**
67
270
  * Quantized exit code for the doctor command, so CI / automation can tell
68
271
  * apart "clean", "degraded (warnings only)" and "hard failure":
@@ -311,6 +514,10 @@ async function doctorLiveClaude(root) {
311
514
  });
312
515
  }
313
516
  checks.push(supplyChainCheck(supplyFindings));
517
+ // 6. MCP 重复定义:同一 id 在多个配置文件中重复
518
+ checks.push(await mcpDuplicateCheck(root));
519
+ // 7. 配置基线:与最近快照比对,识别大面积改写
520
+ checks.push(await configBaselineCheck(root, 'claude'));
314
521
  return checks;
315
522
  }
316
523
  async function doctorLiveCodex(root) {
@@ -432,6 +639,8 @@ async function doctorLiveCodex(root) {
432
639
  }
433
640
  }
434
641
  checks.push(supplyChainCheck(supplyFindings));
642
+ // 6. 配置基线:与最近快照比对,识别大面积改写
643
+ checks.push(await configBaselineCheck(root, 'codex'));
435
644
  return checks;
436
645
  }
437
646
  async function doctorLive(options) {
@@ -443,6 +652,9 @@ async function doctorLive(options) {
443
652
  if (options.agent === 'codex' || options.agent === 'all') {
444
653
  checks.push(...await doctorLiveCodex(root));
445
654
  }
655
+ if (options.baseline) {
656
+ checks.push(await teamBaselineCheck(root, options.baseline));
657
+ }
446
658
  return finalize('live', options.agent, root, checks);
447
659
  }
448
660
  async function doctorScan(options) {
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseConfigObject = parseConfigObject;
4
+ exports.buildSnapshotDiff = buildSnapshotDiff;
5
+ const smol_toml_1 = require("smol-toml");
6
+ /**
7
+ * 快照比对(v1.2)。
8
+ * 按 JSON / TOML 路径展开后逐键比较,值统一脱敏且截断,
9
+ * 避免把令牌原文打印到终端或 CI 日志。
10
+ */
11
+ const SENSITIVE_PATH = /(token|secret|passw|api[_-]?key|auth|credential|cookie)/i;
12
+ const MAX_VALUE_LENGTH = 120;
13
+ /** 解析配置文件为对象;解析失败或非结构化格式返回 null。 */
14
+ function parseConfigObject(relPath, text) {
15
+ try {
16
+ if (relPath.endsWith('.json')) {
17
+ return JSON.parse(text);
18
+ }
19
+ if (relPath.endsWith('.toml')) {
20
+ return (0, smol_toml_1.parse)(text);
21
+ }
22
+ }
23
+ catch {
24
+ return null;
25
+ }
26
+ return null;
27
+ }
28
+ function flatten(value, prefix, out) {
29
+ if (Array.isArray(value)) {
30
+ if (value.length === 0) {
31
+ out.set(prefix, []);
32
+ }
33
+ value.forEach((item, index) => flatten(item, `${prefix}[${index}]`, out));
34
+ return;
35
+ }
36
+ if (value !== null && typeof value === 'object') {
37
+ const keys = Object.keys(value);
38
+ if (keys.length === 0) {
39
+ out.set(prefix, {});
40
+ }
41
+ for (const key of keys) {
42
+ const child = value[key];
43
+ flatten(child, prefix ? `${prefix}.${key}` : key, out);
44
+ }
45
+ return;
46
+ }
47
+ out.set(prefix, value);
48
+ }
49
+ function mask(text) {
50
+ if (text.length <= 8) {
51
+ return '****';
52
+ }
53
+ return `${text.slice(0, 4)}****${text.slice(-4)}`;
54
+ }
55
+ function renderValue(pathKey, value) {
56
+ const text = typeof value === 'string' ? value : (JSON.stringify(value) ?? String(value));
57
+ if (SENSITIVE_PATH.test(pathKey)) {
58
+ return mask(text);
59
+ }
60
+ return text.length > MAX_VALUE_LENGTH ? `${text.slice(0, MAX_VALUE_LENGTH - 3)}...` : text;
61
+ }
62
+ function buildSnapshotDiff(params) {
63
+ const changes = [];
64
+ for (const relPath of [...params.files].sort()) {
65
+ const beforeText = params.before.get(relPath)?.toString('utf8');
66
+ const afterText = params.after.get(relPath)?.toString('utf8');
67
+ const beforeObj = beforeText === undefined ? undefined : parseConfigObject(relPath, beforeText);
68
+ const afterObj = afterText === undefined ? undefined : parseConfigObject(relPath, afterText);
69
+ if ((beforeText !== undefined && beforeObj === null) || (afterText !== undefined && afterObj === null)) {
70
+ if (beforeText !== afterText) {
71
+ changes.push({
72
+ path: relPath,
73
+ change: beforeText === undefined ? 'added' : afterText === undefined ? 'removed' : 'modified',
74
+ note: '配置解析失败,按整文件比较',
75
+ });
76
+ }
77
+ continue;
78
+ }
79
+ const flatBefore = new Map();
80
+ const flatAfter = new Map();
81
+ if (beforeObj !== undefined) {
82
+ flatten(beforeObj, '', flatBefore);
83
+ }
84
+ if (afterObj !== undefined) {
85
+ flatten(afterObj, '', flatAfter);
86
+ }
87
+ const keys = [...new Set([...flatBefore.keys(), ...flatAfter.keys()])].sort();
88
+ for (const key of keys) {
89
+ const hasBefore = flatBefore.has(key);
90
+ const hasAfter = flatAfter.has(key);
91
+ const pathKey = key ? `${relPath}#${key}` : relPath;
92
+ if (hasBefore && !hasAfter) {
93
+ changes.push({ path: pathKey, change: 'removed', before: renderValue(key, flatBefore.get(key)) });
94
+ continue;
95
+ }
96
+ if (!hasBefore && hasAfter) {
97
+ changes.push({ path: pathKey, change: 'added', after: renderValue(key, flatAfter.get(key)) });
98
+ continue;
99
+ }
100
+ const beforeValue = flatBefore.get(key);
101
+ const afterValue = flatAfter.get(key);
102
+ if (JSON.stringify(beforeValue) !== JSON.stringify(afterValue)) {
103
+ changes.push({
104
+ path: pathKey,
105
+ change: 'modified',
106
+ before: renderValue(key, beforeValue),
107
+ after: renderValue(key, afterValue),
108
+ });
109
+ }
110
+ }
111
+ }
112
+ const added = changes.filter((item) => item.change === 'added').length;
113
+ const removed = changes.filter((item) => item.change === 'removed').length;
114
+ const modified = changes.filter((item) => item.change === 'modified').length;
115
+ return {
116
+ from: params.from,
117
+ to: params.to,
118
+ files: [...params.files].sort(),
119
+ changes,
120
+ summary: `${added} 新增 / ${removed} 删除 / ${modified} 修改`,
121
+ };
122
+ }