agentdock-cli 1.0.1 → 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
  };
@@ -9,6 +9,7 @@ const node_path_1 = __importDefault(require("node:path"));
9
9
  const smol_toml_1 = require("smol-toml");
10
10
  const package_json_1 = __importDefault(require("../../package.json"));
11
11
  const sensitive_1 = require("../scanners/sensitive");
12
+ const supply_chain_1 = require("./supply-chain");
12
13
  const package_lock_1 = require("./package-lock");
13
14
  const CATEGORIES = ['mcp', 'skills', 'agents', 'plugins', 'hooks', 'memory', 'settings'];
14
15
  const LEVEL_LABEL = {
@@ -56,69 +57,7 @@ function summarizeAssets(manifest) {
56
57
  }
57
58
  return assets;
58
59
  }
59
- /** 无版本号 → 远端每次拉取/执行的内容都可能变(供应链风险)。 */
60
- function isPinnedSpec(spec) {
61
- if (!spec) {
62
- return false;
63
- }
64
- const at = spec.startsWith('@') ? spec.indexOf('@', 1) : spec.indexOf('@');
65
- return at > 0;
66
- }
67
- function inspectCommandTokens(tokens, file, add) {
68
- const npxIndex = tokens.findIndex((token) => /(^|[\\/])npx(\.cmd|\.exe)?$/i.test(token));
69
- if (npxIndex >= 0) {
70
- const rest = tokens.slice(npxIndex + 1);
71
- if (rest.includes('-y') || rest.includes('--yes')) {
72
- const spec = rest.find((token) => !token.startsWith('-'));
73
- if (spec && !isPinnedSpec(spec)) {
74
- add({
75
- level: 'high',
76
- id: 'unpinned-npx',
77
- message: `MCP 使用 npx -y 拉取未固定版本的远程包并执行:${spec}`,
78
- evidence: `${file} (${spec})`,
79
- });
80
- }
81
- }
82
- }
83
- const uvxIndex = tokens.findIndex((token) => /(^|[\\/])uvx(\.exe)?$/i.test(token));
84
- if (uvxIndex >= 0) {
85
- const spec = tokens.slice(uvxIndex + 1).find((token) => !token.startsWith('-'));
86
- if (spec && !isPinnedSpec(spec)) {
87
- add({
88
- level: 'medium',
89
- id: 'unpinned-uvx',
90
- message: `MCP 使用 uvx 拉取未固定版本的 Python 包并执行:${spec}`,
91
- evidence: `${file} (${spec})`,
92
- });
93
- }
94
- }
95
- }
96
- /** 从 JSON/TOML 结构里挑出 mcpServers / mcp_servers 定义。 */
97
- function collectMcpDefs(value, out) {
98
- if (Array.isArray(value)) {
99
- for (const item of value) {
100
- collectMcpDefs(item, out);
101
- }
102
- return;
103
- }
104
- if (!value || typeof value !== 'object') {
105
- return;
106
- }
107
- const obj = value;
108
- for (const key of ['mcpServers', 'mcp_servers']) {
109
- const servers = obj[key];
110
- if (servers && typeof servers === 'object' && !Array.isArray(servers)) {
111
- for (const def of Object.values(servers)) {
112
- if (def && typeof def === 'object' && !Array.isArray(def)) {
113
- out.push(def);
114
- }
115
- }
116
- }
117
- }
118
- for (const child of Object.values(obj)) {
119
- collectMcpDefs(child, out);
120
- }
121
- }
60
+ /** 从 JSON/TOML 结构里挑出 mcpServers / mcp_servers 定义,再逐个做供应链与权限检查。 */
122
61
  function inspectStructuredFile(file, text, add) {
123
62
  const ext = node_path_1.default.posix.extname(file).toLowerCase();
124
63
  let parsed;
@@ -129,12 +68,9 @@ function inspectStructuredFile(file, text, add) {
129
68
  return;
130
69
  }
131
70
  const defs = [];
132
- collectMcpDefs(parsed, defs);
71
+ (0, supply_chain_1.collectMcpDefs)(parsed, defs);
133
72
  for (const def of defs) {
134
- const command = typeof def.command === 'string' ? def.command : '';
135
- const args = Array.isArray(def.args) ? def.args.filter((arg) => typeof arg === 'string') : [];
136
- const tokens = `${command} ${args.join(' ')}`.trim().split(/\s+/).filter(Boolean);
137
- inspectCommandTokens(tokens, file, add);
73
+ (0, supply_chain_1.inspectMcpDef)(def, file, add);
138
74
  }
139
75
  inspectPermissions(parsed, file, add);
140
76
  }
@@ -184,29 +120,6 @@ function inspectPermissions(value, file, add) {
184
120
  inspectPermissions(child, file, add);
185
121
  }
186
122
  }
187
- /**
188
- * 自由文本(skill / memory / 脚本)里的 `npx -y` 多为文档示例。
189
- * 逐文件收集后汇总成一条中风险,避免把文档示例误报成高风险。
190
- */
191
- function collectTextNpxSpecs(text) {
192
- const specs = [];
193
- for (const line of text.split(/\r?\n/)) {
194
- const tokens = line.split(/[\s"'`,;:(){}[\]<>]+/).filter(Boolean);
195
- const index = tokens.findIndex((token) => /(^|[\\/])npx(\.cmd|\.exe)?$/i.test(token));
196
- if (index < 0) {
197
- continue;
198
- }
199
- const rest = tokens.slice(index + 1);
200
- if (!rest.includes('-y') && !rest.includes('--yes')) {
201
- continue;
202
- }
203
- const spec = rest.find((token) => !token.startsWith('-'));
204
- if (spec && !isPinnedSpec(spec)) {
205
- specs.push(spec);
206
- }
207
- }
208
- return specs;
209
- }
210
123
  /**
211
124
  * 对一个安装包(目录或 .zip)生成审计清单:
212
125
  * 资产清单 + 密钥处理方式 + 供应链风险 +(有 lock 时)完整性校验。
@@ -248,7 +161,7 @@ async function attestPackage(targetPath) {
248
161
  leaks.push({ file: rel, count: found.length });
249
162
  }
250
163
  inspectStructuredFile(rel, text, (risk) => collector.add(risk));
251
- const textSpecs = collectTextNpxSpecs(text);
164
+ const textSpecs = (0, supply_chain_1.collectTextNpxSpecs)(text);
252
165
  if (textSpecs.length > 0) {
253
166
  textNpxHits += textSpecs.length;
254
167
  textNpxFiles.add(rel);
@@ -12,9 +12,32 @@ const yaml_1 = __importDefault(require("yaml"));
12
12
  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
+ const supply_chain_1 = require("./supply-chain");
16
+ const snapshot_1 = require("./snapshot");
17
+ const snapshot_diff_1 = require("./snapshot-diff");
15
18
  const smol_toml_1 = require("smol-toml");
16
19
  const fs_1 = require("../utils/fs");
17
20
  // ===== helpers =====
21
+ const SUPPLY_CHAIN_REMEDIATION = '为 npx / uvx 指定固定版本(如 `npx -y <包名>@1.2.3`、`uvx <包名>==1.2.3`),避免远端代码在每次安装时任意变化;内网/离线环境可改为本地可执行文件或私有镜像。';
22
+ /** 把供应链风险映射为 doctor 警告级 finding(体检只提醒,不判失败)。 */
23
+ function supplyRiskFinding(risk) {
24
+ return { severity: 'warn', message: risk.message, path: risk.evidence };
25
+ }
26
+ /**
27
+ * 供应链风险检查:未固定版本的 npx -y / uvx 远程拉取(doctor live 复用
28
+ * attest 的共享检测;风险统一为 warn 级,`unpinned-npx` 在 attest 中才是 high)。
29
+ */
30
+ function supplyChainCheck(findings) {
31
+ return makeCheck('supply-chain', '供应链风险', findings, '未发现未固定版本的 npx -y / uvx 远程拉取命令', SUPPLY_CHAIN_REMEDIATION);
32
+ }
33
+ /** 从 JSON/TOML 结构化配置里收集未固定版本的 npx / uvx 拉取。 */
34
+ function supplyFindingsFromStructured(file, parsed, findings) {
35
+ const defs = [];
36
+ (0, supply_chain_1.collectMcpDefs)(parsed, defs);
37
+ for (const def of defs) {
38
+ (0, supply_chain_1.inspectMcpDef)(def, file, (risk) => findings.push(supplyRiskFinding(risk)));
39
+ }
40
+ }
18
41
  async function fileExists(targetPath) {
19
42
  try {
20
43
  await promises_1.default.access(targetPath);
@@ -42,6 +65,207 @@ function makeCheck(id, label, findings, passDetail, remediation) {
42
65
  }
43
66
  return check;
44
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
+ }
45
269
  /**
46
270
  * Quantized exit code for the doctor command, so CI / automation can tell
47
271
  * apart "clean", "degraded (warnings only)" and "hard failure":
@@ -253,6 +477,47 @@ async function doctorLiveClaude(root) {
253
477
  path: p,
254
478
  }));
255
479
  checks.push(makeCheck('run-state', '运行态隔离', runStateFindings, '运行态文件被排除在导出之外'));
480
+ // 5. 供应链风险:未固定版本的 npx -y / uvx 远程拉取
481
+ const supplyFindings = [];
482
+ for (const file of [node_path_1.default.join(claudeDir, 'settings.json'), node_path_1.default.join(root, '.claude.json')]) {
483
+ if (!(await fileExists(file))) {
484
+ continue;
485
+ }
486
+ try {
487
+ supplyFindingsFromStructured(file, JSON.parse(await promises_1.default.readFile(file, 'utf8')), supplyFindings);
488
+ }
489
+ catch {
490
+ // 解析失败已在 config-valid 检查中报告
491
+ }
492
+ }
493
+ // hooks 脚本里的 npx -y 多为文档示例,逐条收集后汇总成一条警告
494
+ const textNpxFiles = new Set();
495
+ let textNpxHits = 0;
496
+ for (const entry of domain.hooks) {
497
+ try {
498
+ const specs = (0, supply_chain_1.collectTextNpxSpecs)(await promises_1.default.readFile(entry.path, 'utf8'));
499
+ if (specs.length > 0) {
500
+ textNpxHits += specs.length;
501
+ textNpxFiles.add(entry.path);
502
+ }
503
+ }
504
+ catch {
505
+ // 不可读脚本跳过
506
+ }
507
+ }
508
+ if (textNpxHits > 0) {
509
+ const files = [...textNpxFiles];
510
+ supplyFindings.push({
511
+ severity: 'warn',
512
+ message: `${files.length} 个 hook 脚本中出现 ${textNpxHits} 处 \`npx -y\` 未固定版本命令(若会被执行请固定版本)`,
513
+ path: files.join(', '),
514
+ });
515
+ }
516
+ checks.push(supplyChainCheck(supplyFindings));
517
+ // 6. MCP 重复定义:同一 id 在多个配置文件中重复
518
+ checks.push(await mcpDuplicateCheck(root));
519
+ // 7. 配置基线:与最近快照比对,识别大面积改写
520
+ checks.push(await configBaselineCheck(root, 'claude'));
256
521
  return checks;
257
522
  }
258
523
  async function doctorLiveCodex(root) {
@@ -363,6 +628,19 @@ async function doctorLiveCodex(root) {
363
628
  path: p,
364
629
  }));
365
630
  checks.push(makeCheck('run-state', '运行态隔离', runStateFindings, '运行态文件被排除在导出之外'));
631
+ // 5. 供应链风险:未固定版本的 npx -y / uvx 远程拉取
632
+ const supplyFindings = [];
633
+ if (await fileExists(configPath)) {
634
+ try {
635
+ supplyFindingsFromStructured(configPath, (0, smol_toml_1.parse)(await promises_1.default.readFile(configPath, 'utf8')), supplyFindings);
636
+ }
637
+ catch {
638
+ // 解析失败已在 config-valid 检查中报告
639
+ }
640
+ }
641
+ checks.push(supplyChainCheck(supplyFindings));
642
+ // 6. 配置基线:与最近快照比对,识别大面积改写
643
+ checks.push(await configBaselineCheck(root, 'codex'));
366
644
  return checks;
367
645
  }
368
646
  async function doctorLive(options) {
@@ -374,6 +652,9 @@ async function doctorLive(options) {
374
652
  if (options.agent === 'codex' || options.agent === 'all') {
375
653
  checks.push(...await doctorLiveCodex(root));
376
654
  }
655
+ if (options.baseline) {
656
+ checks.push(await teamBaselineCheck(root, options.baseline));
657
+ }
377
658
  return finalize('live', options.agent, root, checks);
378
659
  }
379
660
  async function doctorScan(options) {