agentdock-cli 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -129,7 +129,9 @@ restore/
129
129
  | `export` | 把扫描产物打包成可迁移包(默认打码,`--env` 回注) | `agentdock export --from-scan ./out/agentdock.scan.yml --out ./pkg` |
130
130
  | `install` | 从包安全还原到目标机(越界校验 / 锁 / 原子写 / 幂等) | `agentdock install ./pkg ~` |
131
131
  | `validate` | 校验 manifest 合法性 | `agentdock validate ./pkg/manifest.resolved.json` |
132
- | `doctor` | 体检环境 / 包:配置健康度、可迁移性、是否泄密 | `agentdock doctor --agent all --root ~` |
132
+ | `doctor` | 体检环境 / 包:配置健康度、可迁移性、是否泄密(每项附**修复建议**) | `agentdock doctor --agent all --root ~` |
133
+
134
+ `doctor` 退出码已量化,便于 CI / 自动化区分严重度:**0** = 全通过、**1** = 仅有警告(可迁移但有隐患)、**2** = 存在失败(需处理)。加 `--json` 可机读,remediation 字段随报告一同返回。
133
135
  | `list` | 列出已捕获的 MCP / Skill / Agent 等定义清单 | `agentdock list --package ./pkg` |
134
136
 
135
137
  支持的双助手:**Claude Code**(JSON:`settings.json` + `.claude.json`)与 **Codex**(TOML:`config.toml` + `AGENTS.md`)。
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentdock-cli",
3
- "version": "0.4.2",
3
+ "version": "0.5.0",
4
4
  "description": "Migrate, back up, and version your AI coding assistant environment (Claude Code / Codex) — MCP servers, Skills, Agents, Plugins, Hooks, and memory — as a portable, secret-isolated package.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -21,7 +21,7 @@ async function runDoctorCommand(options = {}) {
21
21
  });
22
22
  if (options.json === true) {
23
23
  return {
24
- exitCode: report.healthy ? 0 : 1,
24
+ exitCode: (0, doctor_1.doctorExitCode)(report),
25
25
  stdout: [(0, command_json_1.toJsonLine)('doctor', report.healthy, report, [])],
26
26
  stderr: [],
27
27
  };
@@ -29,21 +29,27 @@ async function runDoctorCommand(options = {}) {
29
29
  const lines = [
30
30
  `Doctor (${report.mode})${report.agent ? ` agent=${report.agent}` : ''}`,
31
31
  report.summary,
32
- ...report.checks.map((check) => ` [${check.status.toUpperCase()}] ${check.label} — ${check.detail}`),
32
+ ...report.checks.flatMap((check) => {
33
+ const out2 = [` [${check.status.toUpperCase()}] ${check.label} — ${check.detail}`];
34
+ if (check.remediation && check.status !== 'pass') {
35
+ out2.push(` → 建议: ${check.remediation}`);
36
+ }
37
+ return out2;
38
+ }),
33
39
  ...(report.reportPath ? [`report: ${report.reportPath}`] : []),
34
40
  ];
35
- return { exitCode: report.healthy ? 0 : 1, stdout: lines, stderr: [] };
41
+ return { exitCode: (0, doctor_1.doctorExitCode)(report), stdout: lines, stderr: [] };
36
42
  }
37
43
  catch (error) {
38
44
  const message = error instanceof Error ? error.message : String(error);
39
45
  if (options.json === true) {
40
46
  const data = { mode: 'live', agent, target: '', healthy: false, checks: [], summary: message };
41
47
  return {
42
- exitCode: 1,
48
+ exitCode: 2,
43
49
  stdout: [(0, command_json_1.toJsonLine)('doctor', false, data, [(0, command_json_1.toJsonError)(command_error_codes_1.COMMAND_ERROR_CODES.DOCTOR_FAILED, message)])],
44
50
  stderr: [],
45
51
  };
46
52
  }
47
- return { exitCode: 1, stdout: [], stderr: [message] };
53
+ return { exitCode: 2, stdout: [], stderr: [message] };
48
54
  }
49
55
  }
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.doctorExitCode = doctorExitCode;
6
7
  exports.runDoctor = runDoctor;
7
8
  const node_os_1 = __importDefault(require("node:os"));
8
9
  const promises_1 = __importDefault(require("node:fs/promises"));
@@ -30,12 +31,29 @@ function aggregateStatus(statuses) {
30
31
  return 'warn';
31
32
  return 'pass';
32
33
  }
33
- function makeCheck(id, label, findings, passDetail) {
34
+ function makeCheck(id, label, findings, passDetail, remediation) {
34
35
  const errors = findings.filter((f) => f.severity === 'error').length;
35
36
  const warns = findings.filter((f) => f.severity === 'warn').length;
36
37
  const status = errors > 0 ? 'fail' : warns > 0 ? 'warn' : 'pass';
37
38
  const detail = status === 'pass' ? passDetail : `${errors} 错误 / ${warns} 警告`;
38
- return { id, label, status, detail, findings };
39
+ const check = { id, label, status, detail, findings };
40
+ if (remediation && status !== 'pass') {
41
+ check.remediation = remediation;
42
+ }
43
+ return check;
44
+ }
45
+ /**
46
+ * Quantized exit code for the doctor command, so CI / automation can tell
47
+ * apart "clean", "degraded (warnings only)" and "hard failure":
48
+ * pass → 0, warn → 1, fail → 2.
49
+ */
50
+ function doctorExitCode(report) {
51
+ const worst = aggregateStatus(report.checks.map((c) => c.status));
52
+ if (worst === 'fail')
53
+ return 2;
54
+ if (worst === 'warn')
55
+ return 1;
56
+ return 0;
39
57
  }
40
58
  function finalize(mode, agent, target, checks) {
41
59
  const status = aggregateStatus(checks.map((c) => c.status));
@@ -44,7 +62,7 @@ function finalize(mode, agent, target, checks) {
44
62
  const warnCount = checks.filter((c) => c.status === 'warn').length;
45
63
  const summary = healthy
46
64
  ? `环境健康:${checks.length} 项检查通过${warnCount ? `,${warnCount} 项警告` : ''}`
47
- : `发现问题:${failCount} 项失败 / ${warnCount} 项警告,请检查上方详情`;
65
+ : `发现问题:${failCount} 项失败 / ${warnCount} 项警告,可参考各项【建议】处理`;
48
66
  return { mode, agent, target, healthy, checks, summary };
49
67
  }
50
68
  async function walkForRunState(dir) {
@@ -136,6 +154,7 @@ async function doctorLiveClaude(root) {
136
154
  status: 'warn',
137
155
  detail: `未找到 ${claudeDir},无可体检的 Claude 环境`,
138
156
  findings: [],
157
+ remediation: '确认 `--root` 指向正确的用户主目录(默认 os.homedir()),或先安装 Claude Code 生成配置后再体检。',
139
158
  });
140
159
  return checks;
141
160
  }
@@ -164,7 +183,7 @@ async function doctorLiveClaude(root) {
164
183
  }
165
184
  }
166
185
  }
167
- checks.push(makeCheck('config-valid', '配置文件合法', parseFindings, 'Claude 配置文件均为合法 JSON'));
186
+ checks.push(makeCheck('config-valid', '配置文件合法', parseFindings, 'Claude 配置文件均为合法 JSON', '修复配置文件语法后重试(见上方路径与报错);也可运行 `agentdock validate` 精确定位问题行。'));
168
187
  // 2. 可迁移完整性(scan 会捕获的内容)
169
188
  const counts = {
170
189
  mcp: domain.mcp.length,
@@ -182,6 +201,9 @@ async function doctorLiveClaude(root) {
182
201
  status: total > 0 ? 'pass' : 'warn',
183
202
  detail: `将捕获 MCP:${counts.mcp} Skill:${counts.skills} Agent:${counts.agents} Plugin:${counts.plugins} Hook:${counts.hooks} 记忆:${counts.memory} settings:${counts.settings}`,
184
203
  findings: scan.notes.map((note) => ({ severity: 'info', message: note })),
204
+ remediation: total > 0
205
+ ? undefined
206
+ : '未捕获到可迁移内容。确认目标机已安装 Claude/Codex 且配置位于默认路径,或用 `--root` 指定正确的用户主目录后重新 `scan`。',
185
207
  });
186
208
  // 3. 敏感泄露风险
187
209
  // scan 只打码 JSON settings / mcpServers;skills/agents/memory/hooks/plugins 是原文复制。
@@ -198,7 +220,7 @@ async function doctorLiveClaude(root) {
198
220
  if (leaks.length) {
199
221
  leakFindings.push({
200
222
  severity: 'error',
201
- message: `在"原文复制"文件中发现 ${leaks.length} 处疑似真实令牌,scan 不会对其打码,迁移会泄露`,
223
+ message: `在"原文复制"文件(skills/agents/memory/hooks/plugins)中发现 ${leaks.length} 处疑似真实令牌;scan 不在扫描期打码,但 \`export --from-scan\` 会自动打码(安全),不会随包泄露`,
202
224
  path: entry.path,
203
225
  });
204
226
  }
@@ -222,7 +244,7 @@ async function doctorLiveClaude(root) {
222
244
  }
223
245
  }
224
246
  }
225
- checks.push(makeCheck('secret-leak', '敏感泄露风险', leakFindings, '导出时令牌会被隔离,不会随包泄露'));
247
+ checks.push(makeCheck('secret-leak', '敏感泄露风险', leakFindings, '导出时令牌会被隔离,不会随包泄露', '免费文本中的明文令牌,`scan` 不在扫描期打码,但 `export --from-scan` 会自动打码(安全),不会随包泄露;若 `doctor --package` 仍报泄露,说明该文件未被正确打码,可手动将明文替换为 `{{AGENTDOCK_<AGENT>_<KEY>}}` 占位符。'));
226
248
  // 4. 运行态隔离
227
249
  const runState = await walkForRunState(claudeDir);
228
250
  const runStateFindings = runState.map((p) => ({
@@ -243,6 +265,7 @@ async function doctorLiveCodex(root) {
243
265
  status: 'warn',
244
266
  detail: `未找到 ${codexDir},无可体检的 Codex 环境`,
245
267
  findings: [],
268
+ remediation: '确认 `--root` 指向正确的用户主目录(默认 os.homedir()),或先安装 Codex 生成配置后再体检。',
246
269
  });
247
270
  return checks;
248
271
  }
@@ -262,7 +285,7 @@ async function doctorLiveCodex(root) {
262
285
  else {
263
286
  parseFindings.push({ severity: 'warn', message: '未找到 .codex/config.toml', path: configPath });
264
287
  }
265
- checks.push(makeCheck('config-valid', '配置文件合法', parseFindings, 'Codex config.toml 为合法 TOML'));
288
+ checks.push(makeCheck('config-valid', '配置文件合法', parseFindings, 'Codex config.toml 为合法 TOML', '修复 config.toml 语法后重试(见上方路径与报错);也可运行 `agentdock validate` 精确定位问题行。'));
266
289
  // 2. 可迁移完整性
267
290
  let mcpCount = 0;
268
291
  if (await fileExists(configPath)) {
@@ -291,6 +314,9 @@ async function doctorLiveCodex(root) {
291
314
  status: total > 0 ? 'pass' : 'warn',
292
315
  detail: `将捕获 MCP:${counts.mcp} 记忆:${counts.memory} settings:${counts.settings}`,
293
316
  findings: scan.notes.map((note) => ({ severity: 'info', message: note })),
317
+ remediation: total > 0
318
+ ? undefined
319
+ : '未捕获到可迁移内容。确认目标机已安装 Codex 且配置位于默认路径,或用 `--root` 指定正确的用户主目录后重新 `scan`。',
294
320
  });
295
321
  // 3. 敏感泄露风险
296
322
  const verbatimEntries = [
@@ -306,7 +332,7 @@ async function doctorLiveCodex(root) {
306
332
  if (leaks.length) {
307
333
  leakFindings.push({
308
334
  severity: 'error',
309
- message: `在"原文复制"文件中发现 ${leaks.length} 处疑似真实令牌,scan 不会对其打码,迁移会泄露`,
335
+ message: `在"原文复制"文件(skills/agents/memory/hooks/plugins)中发现 ${leaks.length} 处疑似真实令牌;scan 不在扫描期打码,但 \`export --from-scan\` 会自动打码(安全),不会随包泄露`,
310
336
  path: entry.path,
311
337
  });
312
338
  }
@@ -328,7 +354,7 @@ async function doctorLiveCodex(root) {
328
354
  // ignore
329
355
  }
330
356
  }
331
- checks.push(makeCheck('secret-leak', '敏感泄露风险', leakFindings, '导出时令牌会被隔离,不会随包泄露'));
357
+ checks.push(makeCheck('secret-leak', '敏感泄露风险', leakFindings, '导出时令牌会被隔离,不会随包泄露', '免费文本中的明文令牌,`scan` 不在扫描期打码,但 `export --from-scan` 会自动打码(安全),不会随包泄露;若 `doctor --package` 仍报泄露,说明该文件未被正确打码,可手动将明文替换为 `{{AGENTDOCK_<AGENT>_<KEY>}}` 占位符。'));
332
358
  // 4. 运行态隔离
333
359
  const runState = await walkForRunState(codexDir);
334
360
  const runStateFindings = runState.map((p) => ({
@@ -360,6 +386,7 @@ async function doctorScan(options) {
360
386
  status: 'fail',
361
387
  detail: `未找到 ${scanPath}`,
362
388
  findings: [],
389
+ remediation: '确认 `--from-scan` 指向正确的 `agentdock.scan.yml` 路径;若尚未扫描,先运行 `agentdock scan --agent all --out <目录>`。',
363
390
  });
364
391
  return finalize('scan', options.agent, scanPath, checks);
365
392
  }
@@ -377,7 +404,7 @@ async function doctorScan(options) {
377
404
  }
378
405
  }
379
406
  }
380
- checks.push(makeCheck('ref-integrity', '引用完整性', missing, '所有记录的源文件仍存在,可完整还原'));
407
+ checks.push(makeCheck('ref-integrity', '引用完整性', missing, '所有记录的源文件仍存在,可完整还原', '部分源文件已不存在,`install` 时将跳过这些条目导致还原不完整。请重新运行 `agentdock scan` 刷新 manifest,或确认这些路径在目标机上仍可用。'));
381
408
  // 2. 产物泄露扫描
382
409
  const leaks = await walkForLeaks(dir);
383
410
  const leakFindings = leaks.map((leak) => ({
@@ -385,7 +412,7 @@ async function doctorScan(options) {
385
412
  message: `发现 ${leak.leaks.length} 处疑似真实令牌`,
386
413
  path: leak.file,
387
414
  }));
388
- checks.push(makeCheck('artifact-leak', '产物无泄露', leakFindings, '扫描产物中未发现真实令牌'));
415
+ checks.push(makeCheck('artifact-leak', '产物无泄露', leakFindings, '扫描产物中未发现真实令牌', '扫描产物含真实令牌,切勿提交或分发。重新运行 `scan`(确保敏感文件未被 verbatim 复制),或使用 `export --from-scan <scan> --env <你的.env>` 以占位符打包、真实值留在本机 `.env`。'));
389
416
  // 3. 运行态未入产物
390
417
  const runState = await walkForRunState(dir);
391
418
  const runStateFindings = runState.map((p) => ({
@@ -393,15 +420,16 @@ async function doctorScan(options) {
393
420
  message: '运行态文件出现在产物中(绝不应导出)',
394
421
  path: p,
395
422
  }));
396
- checks.push(makeCheck('artifact-runstate', '产物无运行态', runStateFindings, '产物中不含运行态文件'));
423
+ checks.push(makeCheck('artifact-runstate', '产物无运行态', runStateFindings, '产物中不含运行态文件', '运行态文件(auth.json / cache / sessions 等)绝不应出现在产物中,否则会携带凭据或臃肿数据。检查 `scan` 是否误将其纳入,删除后重新 `export`。'));
397
424
  // 4. 占位符一致性:隔离的机密数量应与 .env.example 中定义的占位符数量一致
398
425
  // 注意:测试 harness 下字符串比较(includes / Set.has / 属性访问)对这类
399
426
  // 大写占位符字符串存在已知异常,故此处只比较"数量"(数值比较安全且确定)
400
427
  const envPath = node_path_1.default.join(dir, '.env.example');
428
+ const hasEnv = await fileExists(envPath);
401
429
  const consistencyFindings = [];
402
- if (await fileExists(envPath)) {
430
+ let definedCount = 0;
431
+ if (hasEnv) {
403
432
  const envText = await promises_1.default.readFile(envPath, 'utf8');
404
- let definedCount = 0;
405
433
  for (const raw of envText.split(/\r?\n/)) {
406
434
  const line = raw.trim();
407
435
  if (!line || line.startsWith('#')) {
@@ -422,7 +450,12 @@ async function doctorScan(options) {
422
450
  else if (manifest.secrets.length > 0) {
423
451
  consistencyFindings.push({ severity: 'warn', message: '存在隔离机密但缺少 .env.example' });
424
452
  }
425
- checks.push(makeCheck('placeholder-consistency', '占位符一致', consistencyFindings, '所有隔离机密均有对应 .env.example 占位'));
453
+ const placeholderRemediation = manifest.secrets.length > 0 && definedCount < manifest.secrets.length
454
+ ? `隔离了 ${manifest.secrets.length} 个机密但 \`.env.example\` 只定义了 ${definedCount} 个占位符。补齐缺失的 \`AGENTDOCK_*\` 变量名(与 manifest.secrets 中的 key 一致),确保 \`install\`/回注后真实值能正确落位。`
455
+ : (manifest.secrets.length > 0 && !hasEnv
456
+ ? '存在隔离机密但缺少 `.env.example`。运行 `scan` 会一并生成 `.env.example`;若为手动构造产物,请补一个列出所有 `AGENTDOCK_*` 占位符的 `.env.example`。'
457
+ : undefined);
458
+ checks.push(makeCheck('placeholder-consistency', '占位符一致', consistencyFindings, '所有隔离机密均有对应 .env.example 占位', placeholderRemediation));
426
459
  return finalize('scan', options.agent, scanPath, checks);
427
460
  }
428
461
  async function doctorPackage(options) {
@@ -435,6 +468,7 @@ async function doctorPackage(options) {
435
468
  status: 'fail',
436
469
  detail: `未找到 ${pkgDir}`,
437
470
  findings: [],
471
+ remediation: '确认 `--package` 指向正确的安装包目录(即 `export` 产出的目录)。',
438
472
  });
439
473
  return finalize('package', options.agent, pkgDir, checks);
440
474
  }
@@ -446,14 +480,14 @@ async function doctorPackage(options) {
446
480
  message: `发现 ${leak.leaks.length} 处疑似真实令牌`,
447
481
  path: leak.file,
448
482
  }));
449
- checks.push(makeCheck('pkg-leak', '安装包无泄露', leakFindings, '安装包中未发现真实令牌'));
483
+ checks.push(makeCheck('pkg-leak', '安装包无泄露', leakFindings, '安装包中未发现真实令牌', '安装包含真实令牌,切勿分发或在目标机直接 `install`。重新运行 `scan`(确保敏感文件未被 verbatim 复制),或使用 `export --from-scan <scan> --env <你的.env>` 以占位符打包。'));
450
484
  const runState = await walkForRunState(scanDir);
451
485
  const runStateFindings = runState.map((p) => ({
452
486
  severity: 'error',
453
487
  message: '运行态文件出现在安装包中',
454
488
  path: p,
455
489
  }));
456
- checks.push(makeCheck('pkg-runstate', '安装包无运行态', runStateFindings, '安装包中不含运行态文件'));
490
+ checks.push(makeCheck('pkg-runstate', '安装包无运行态', runStateFindings, '安装包中不含运行态文件', '运行态文件(auth.json / cache / sessions 等)不应出现在安装包中。检查 `scan` 是否误将其纳入,删除后重新 `export`。'));
457
491
  return finalize('package', options.agent, pkgDir, checks);
458
492
  }
459
493
  // ===== report rendering =====
@@ -475,6 +509,9 @@ function renderDoctorReport(report) {
475
509
  const mark = finding.severity === 'error' ? 'X' : finding.severity === 'warn' ? '!' : 'i';
476
510
  lines.push(` - [${mark}] ${finding.message}${finding.path ? ` (\`${finding.path}\`)` : ''}`);
477
511
  }
512
+ if (check.remediation) {
513
+ lines.push(`- **建议**: ${check.remediation}`);
514
+ }
478
515
  lines.push('');
479
516
  }
480
517
  return lines.join('\n');
@@ -53,6 +53,39 @@ async function isIdenticalDirectory(targetPath, sourcePath) {
53
53
  }
54
54
  return true;
55
55
  }
56
+ /**
57
+ * Recursively merge `source` into `target`. Objects merge key-by-key
58
+ * (source wins on name conflict); arrays / primitives are replaced by source.
59
+ * Used so a merged `.claude.json` keeps the target's other top-level
60
+ * keys and its existing mcpServers while the package's servers win.
61
+ */
62
+ function deepMerge(target, source) {
63
+ if (typeof source !== 'object' || source === null || Array.isArray(source)) {
64
+ return source;
65
+ }
66
+ if (typeof target !== 'object' || target === null || Array.isArray(target)) {
67
+ return source;
68
+ }
69
+ const out = { ...target };
70
+ for (const [key, value] of Object.entries(source)) {
71
+ out[key] = deepMerge(target[key], value);
72
+ }
73
+ return out;
74
+ }
75
+ async function mergeJsonFile(from, to) {
76
+ const source = JSON.parse(await promises_1.default.readFile(from, 'utf8'));
77
+ let target = {};
78
+ if (await (0, fs_1.pathExists)(to)) {
79
+ try {
80
+ target = JSON.parse(await promises_1.default.readFile(to, 'utf8'));
81
+ }
82
+ catch {
83
+ target = {};
84
+ }
85
+ }
86
+ const merged = deepMerge(target, source);
87
+ await (0, fs_1.writeJsonFile)(to, merged);
88
+ }
56
89
  async function installPackage(packagePath, explicitTargetPath, overwrite = false) {
57
90
  const packageRoot = node_path_1.default.resolve(packagePath);
58
91
  const manifestSnapshotPath = node_path_1.default.join(packageRoot, 'manifest.resolved.json');
@@ -75,6 +108,7 @@ async function installPackage(packagePath, explicitTargetPath, overwrite = false
75
108
  from: (0, fs_1.safeResolveWithin)(packageRoot, source.from, 'source.from'),
76
109
  to: (0, fs_1.safeResolveWithin)(targetRoot, source.to, 'source.to'),
77
110
  kind: source.kind,
111
+ merge: source.merge ?? false,
78
112
  })),
79
113
  ...installPlan.templates.map((template) => ({
80
114
  from: (0, fs_1.safeResolveWithin)(packageRoot, template.from, 'template.from'),
@@ -89,6 +123,10 @@ async function installPackage(packagePath, explicitTargetPath, overwrite = false
89
123
  try {
90
124
  const conflicts = [];
91
125
  for (const entry of entries) {
126
+ // Merge entries blend into the existing target; they never conflict.
127
+ if (entry.merge) {
128
+ continue;
129
+ }
92
130
  if (!(await (0, fs_1.pathExists)(entry.to))) {
93
131
  continue;
94
132
  }
@@ -110,6 +148,12 @@ async function installPackage(packagePath, explicitTargetPath, overwrite = false
110
148
  throw new Error(`Install conflict detected:\n${conflicts.join('\n')}`);
111
149
  }
112
150
  for (const entry of entries) {
151
+ if (entry.merge) {
152
+ // Deep-merge JSON into the existing target (preserving other
153
+ // top-level keys / other mcpServers). Never clobbers it.
154
+ await mergeJsonFile(entry.from, entry.to);
155
+ continue;
156
+ }
113
157
  if (entry.kind === 'directory') {
114
158
  await (0, fs_1.copyDirectorySafe)(entry.from, entry.to);
115
159
  }
@@ -95,7 +95,45 @@ async function exportFromScan(options) {
95
95
  const payloadSourcesRoot = node_path_1.default.join(outputPath, 'payload', 'sources');
96
96
  await (0, fs_1.ensureDirectory)(payloadSourcesRoot);
97
97
  const sources = [];
98
+ const freeTextSecrets = [];
98
99
  const toFrom = (diskRel) => `payload/sources/${diskRel}`;
100
+ /**
101
+ * Walk a copied directory and mask (or re-inject, when `env` is set)
102
+ * leaked secret tokens in every text file. Skips files with no leak and
103
+ * no placeholder so binaries / clean files are never rewritten.
104
+ */
105
+ async function processDirectoryTexts(dir, agent) {
106
+ let entries;
107
+ try {
108
+ entries = await promises_1.default.readdir(dir, { withFileTypes: true });
109
+ }
110
+ catch {
111
+ return;
112
+ }
113
+ for (const entry of entries) {
114
+ const full = node_path_1.default.join(dir, entry.name);
115
+ if (entry.isDirectory()) {
116
+ await processDirectoryTexts(full, agent);
117
+ continue;
118
+ }
119
+ let content;
120
+ try {
121
+ content = await promises_1.default.readFile(full, 'utf8');
122
+ }
123
+ catch {
124
+ continue; // unreadable / binary — leave untouched
125
+ }
126
+ const hasLeak = (0, sensitive_1.findSecretLeaks)(content).length > 0;
127
+ const hasPlaceholder = env ? /\{\{AGENTDOCK_[A-Z0-9_]+\}\}/.test(content) : false;
128
+ if (!hasLeak && !hasPlaceholder) {
129
+ continue;
130
+ }
131
+ const out = env
132
+ ? (0, sensitive_1.injectSecretsInText)((0, sensitive_1.maskSecretsInText)(content, agent, freeTextSecrets), env)
133
+ : (0, sensitive_1.maskSecretsInText)(content, agent, freeTextSecrets);
134
+ await (0, fs_1.writeTextFile)(full, out);
135
+ }
136
+ }
99
137
  for (const [agentName, domain] of Object.entries(manifest.agents)) {
100
138
  if (!domain) {
101
139
  continue;
@@ -125,7 +163,11 @@ async function exportFromScan(options) {
125
163
  const diskRel = '.agentdock-mcp.json';
126
164
  const content = JSON.stringify(merged, null, 2);
127
165
  await (0, fs_1.writeTextFile)(node_path_1.default.join(payloadSourcesRoot, diskRel), content);
128
- sources.push({ id: `${agent}-mcp-merged`, kind: 'file', from: toFrom(diskRel), to: '.claude.json' });
166
+ // `merge: true` → installer deep-merges this JSON into the target's
167
+ // existing file (preserving other top-level keys / other mcpServers)
168
+ // instead of overwriting it. Makes `install` safe on a machine
169
+ // that already has a `.claude.json`.
170
+ sources.push({ id: `${agent}-mcp-merged`, kind: 'file', from: toFrom(diskRel), to: '.claude.json', merge: true });
129
171
  }
130
172
  // --- Everything else ---
131
173
  for (const entry of iterEntries(domain)) {
@@ -140,8 +182,10 @@ async function exportFromScan(options) {
140
182
  const kind = stat.isDirectory() ? 'directory' : 'file';
141
183
  const targetDisk = node_path_1.default.join(payloadSourcesRoot, rel);
142
184
  if (kind === 'directory') {
143
- // verbatim recursive copy (skill dirs); re-injection skipped for directories in v0.3
185
+ // recursive copy (skill dirs), then mask/inject any leaked
186
+ // tokens inside the copied text files (prevents plaintext riding into the package)
144
187
  await (0, fs_1.copyDirectorySafe)(entry.path, targetDisk);
188
+ await processDirectoryTexts(targetDisk, agent);
145
189
  }
146
190
  else if (entry.kind === 'settings') {
147
191
  if (node_path_1.default.extname(entry.path) === '.toml') {
@@ -175,11 +219,28 @@ async function exportFromScan(options) {
175
219
  }
176
220
  else {
177
221
  // skill .md / agent .md / plugin json / hook script / memory md:
178
- // copied verbatim. In v0.2 `scan` isolates secrets only from settings
179
- // + mcpServers, so masking free text or plugin registries here would
180
- // risk false-positive corruption. Re-injection is handled at the
181
- // object level for JSON secrets above.
182
- await (0, fs_1.copyFileSafe)(entry.path, targetDisk);
222
+ // mask (or re-inject when `env` is set) any leaked secret tokens
223
+ // so plaintext never rides into the package. Clean files (no leak,
224
+ // no placeholder) are copied verbatim.
225
+ let content;
226
+ try {
227
+ content = await promises_1.default.readFile(entry.path, 'utf8');
228
+ }
229
+ catch {
230
+ await (0, fs_1.copyFileSafe)(entry.path, targetDisk);
231
+ continue;
232
+ }
233
+ const hasLeak = (0, sensitive_1.findSecretLeaks)(content).length > 0;
234
+ const hasPlaceholder = env ? /\{\{AGENTDOCK_[A-Z0-9_]+\}\}/.test(content) : false;
235
+ if (!hasLeak && !hasPlaceholder) {
236
+ await (0, fs_1.copyFileSafe)(entry.path, targetDisk);
237
+ }
238
+ else {
239
+ const out = env
240
+ ? (0, sensitive_1.injectSecretsInText)((0, sensitive_1.maskSecretsInText)(content, agent, freeTextSecrets), env)
241
+ : (0, sensitive_1.maskSecretsInText)(content, agent, freeTextSecrets);
242
+ await (0, fs_1.writeTextFile)(targetDisk, out);
243
+ }
183
244
  }
184
245
  sources.push({ id: entry.id, kind, from: toFrom(rel), to: rel });
185
246
  }
@@ -192,7 +253,23 @@ async function exportFromScan(options) {
192
253
  const snapshotPath = node_path_1.default.join(outputPath, 'manifest.resolved.json');
193
254
  const installPlanPath = node_path_1.default.join(outputPath, 'meta', 'install-plan.json');
194
255
  const packageMetadataPath = node_path_1.default.join(outputPath, 'package.json');
195
- await (0, fs_1.writeJsonFile)(snapshotPath, manifest);
256
+ const envExamplePath = node_path_1.default.join(outputPath, '.env.example');
257
+ // Free-text secrets discovered during export are folded into the resolved
258
+ // manifest + the package's own `.env.example` so `--env` re-injection
259
+ // and `doctor --package` stay consistent end-to-end.
260
+ const augmentedSecrets = [
261
+ ...manifest.secrets,
262
+ ...freeTextSecrets.map((secret) => ({
263
+ key: secret.key,
264
+ source: secret.source,
265
+ sample: secret.sample,
266
+ })),
267
+ ];
268
+ const resolvedManifest = {
269
+ ...manifest,
270
+ secrets: augmentedSecrets,
271
+ };
272
+ await (0, fs_1.writeJsonFile)(snapshotPath, resolvedManifest);
196
273
  await (0, fs_1.writeJsonFile)(installPlanPath, installPlan);
197
274
  await (0, fs_1.writeJsonFile)(packageMetadataPath, {
198
275
  name: 'agentdock-scan-package',
@@ -200,6 +277,7 @@ async function exportFromScan(options) {
200
277
  project: manifest.project.name,
201
278
  manifestVersion: 3,
202
279
  });
280
+ await (0, fs_1.writeTextFile)(envExamplePath, (0, sensitive_1.renderEnvExample)(augmentedSecrets));
203
281
  return { outputPath, snapshotPath, installPlanPath };
204
282
  }
205
283
  finally {
@@ -16,6 +16,8 @@ exports.maskSecret = maskSecret;
16
16
  exports.collectSecrets = collectSecrets;
17
17
  exports.secretKeyName = secretKeyName;
18
18
  exports.maskSecretsInPlace = maskSecretsInPlace;
19
+ exports.maskSecretsInText = maskSecretsInText;
20
+ exports.injectSecretsInText = injectSecretsInText;
19
21
  exports.renderEnvExample = renderEnvExample;
20
22
  const SECRET_KEY_PATTERN = /(token|api[_-]?key|secret|password|passwd|auth|private[_-]?key|credential|access[_-]?key)/i;
21
23
  const SECRET_VALUE_PATTERNS = [
@@ -156,6 +158,53 @@ function maskSecretsInPlace(node, basePath, agent, secretsEnv, seen = new WeakSe
156
158
  }
157
159
  }
158
160
  }
161
+ /**
162
+ * Stable short hash so the same token maps to the same placeholder key across
163
+ * files (keeps `.env.example` / re-injection deduped and deterministic).
164
+ */
165
+ function stableHash(input) {
166
+ let h = 0x811c9dc5;
167
+ for (let i = 0; i < input.length; i++) {
168
+ h ^= input.charCodeAt(i);
169
+ h = Math.imul(h, 0x01000193);
170
+ }
171
+ return (h >>> 0).toString(36).toUpperCase().padStart(7, '0').slice(0, 7);
172
+ }
173
+ /**
174
+ * Mask every secret token found in free text (skills/agents/memory/hooks `.md`,
175
+ * etc.) with a stable `{{AGENTDOCK_<AGENT>_FREETEXT_<HASH>}}` placeholder,
176
+ * and record each as a secret so `.env.example` + `--env` re-injection stay
177
+ * consistent. Replaces the previous verbatim copy that let real tokens ride
178
+ * into the package. Detection uses the same value patterns as `looksLikeSecret`
179
+ * / `findSecretLeaks`.
180
+ */
181
+ function maskSecretsInText(text, agent, accumulator) {
182
+ const tokens = [...new Set(findSecretLeaks(text))];
183
+ if (tokens.length === 0) {
184
+ return text;
185
+ }
186
+ // Longest tokens first so a prefix token can't swallow a longer one.
187
+ tokens.sort((a, b) => b.length - a.length);
188
+ let out = text;
189
+ for (const token of tokens) {
190
+ const key = `AGENTDOCK_${agent.toUpperCase()}_FREETEXT_${stableHash(token)}`;
191
+ const placeholder = `{{${key}}}`;
192
+ if (out.includes(placeholder)) {
193
+ continue;
194
+ }
195
+ out = out.split(token).join(placeholder);
196
+ accumulator.push({ key, sample: maskSecret(token), source: 'freetext' });
197
+ }
198
+ return out;
199
+ }
200
+ /**
201
+ * Re-inject real values into free text for an `--env` export. Placeholders use
202
+ * the same `{{AGENTDOCK_*_FREETEXT_*}}` names emitted by `maskSecretsInText`,
203
+ * keyed by the env file's `AGENTDOCK_*` keys.
204
+ */
205
+ function injectSecretsInText(text, secretsEnv) {
206
+ return text.replace(/\{\{(AGENTDOCK_[A-Z0-9_]+)\}\}/g, (match, key) => secretsEnv[key] !== undefined ? secretsEnv[key] : match);
207
+ }
159
208
  /**
160
209
  * Render a `.env.example` from isolated secrets. Only placeholder keys are
161
210
  * written — never the real values, which stay on the source machine.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentdock-cli",
3
- "version": "0.4.2",
3
+ "version": "0.5.0",
4
4
  "description": "Migrate, back up, and version your AI coding assistant environment (Claude Code / Codex) — MCP servers, Skills, Agents, Plugins, Hooks, and memory — as a portable, secret-isolated package.",
5
5
  "keywords": [
6
6
  "claude-code",