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.
package/README.md CHANGED
@@ -154,10 +154,14 @@ restore/
154
154
  | `sign` | 对包的 `agentdock.lock.json` 做 detached 签名,默认写出 `<包>.sig`;目录与 zip 均支持 | `agentdock sign ./pkg.zip` |
155
155
  | `install` | 从包安全还原到目标机(越界校验 / 锁 / 原子写 / 幂等);`--dry-run` 只预览不落盘 | `agentdock install ./pkg ~` |
156
156
  | `validate` | 校验 manifest 合法性 | `agentdock validate ./pkg/manifest.resolved.json` |
157
- | `doctor` | 体检环境 / 包:配置健康度、可迁移性、是否泄密(每项附**修复建议**) | `agentdock doctor --agent all --root ~` |
157
+ | `doctor` | 体检环境 / 包:配置健康度、可迁移性、是否泄密、MCP 重复定义(每项附**修复建议**);`--baseline` 与指定团队基线比对 | `agentdock doctor --baseline <id>` |
158
158
  | `report` | 生成可分享的环境健康报告(评分 / 清单 / 检查 / 修复建议,HTML + JSON);`--profile xinchuang` 追加信创适配启发式检查(需人工确认) | `agentdock report --agent all --out ./report` |
159
159
  | `list` | 列出已捕获的 MCP / Skill / Agent 等定义清单 | `agentdock list --package ./pkg` |
160
- | `diff` | 对比「包内容」与「目标机现状」:哪些新增 / 相同 / 变更 / 需合并 / 会冲突(不落盘) | `agentdock diff ./pkg ~` |
160
+ | `diff` | 对比「包内容」与「目标机现状」(不落盘);`--since-last` / `--snapshot <id>` 改为比对配置快照与当前配置 | `agentdock diff ./pkg ~` · `agentdock diff --since-last` |
161
+ | `snapshot` | 采集关键配置文件为本地快照;`list` 查看历史,`--redact` 打码,`--if-changed` 无变化跳过;`push` / `pull` 经共享目录(如内网 Git)分发快照 | `agentdock snapshot --redact` · `agentdock snapshot push ./git-repo` |
162
+ | `history` | 快照时间线:每次变化一行摘要(新增 / 删除 / 修改数量 + 关键路径) | `agentdock history` |
163
+ | `recover` | 按完整度评分列出快照候选并恢复最完整的一份;默认 dry-run,`--apply` 写入,支持 `--undo` | `agentdock recover --apply` |
164
+ | `restore` | 从快照恢复配置:默认 dry-run,`--apply` 才写入;写前自动生成写前快照,`--undo --apply` 可回滚 | `agentdock restore --snapshot latest --apply` |
161
165
  | `config` | 管理 AgentDock 自身配置(`agent` / `out` / `env` 默认值),存于 `~/.agentdock/config.json` | `agentdock config set agent codex` |
162
166
  | `uninstall` | 反向卸载:移除包安装的文件/目录,按「与包内容是否一致」安全删除,merge 条目精确摘回包贡献的键(不动用户改动) | `agentdock uninstall ./pkg ~` |
163
167
  | `sync` | 多机可控同步:`pull` / `push` / `status`,目标为目录或 zip(内网 Git clone 后按目录处理);默认 dry-run,冲突显式列出,`sync --undo` 回滚 | `agentdock sync push /mnt/share/ai-env --apply` |
@@ -219,6 +223,47 @@ AGENTDOCK_SYNC_PASSPHRASE='你的口令' agentdock sync push /mnt/share/ai-env -
219
223
  AGENTDOCK_SYNC_PASSPHRASE='你的口令' agentdock sync pull /mnt/share/ai-env --with-env --apply
220
224
  ```
221
225
 
226
+ ## 配置快照与回滚(snapshot / diff / restore)
227
+
228
+ 用于防止「某次升级 / 插件 / 网关配置把 `~/.claude/settings.json` 大面积改写」这类问题:先留基线,异常时逐项看差异,再一键回滚。
229
+
230
+ ```bash
231
+ # 建立基线:只采集关键配置文件,存到 ~/.agentdock/snapshots/<时间戳>/
232
+ agentdock snapshot
233
+ agentdock snapshot list
234
+ agentdock history # 时间线:每次快照相对上一份改了什么
235
+ agentdock snapshot --if-changed # 挂到启动脚本/计划任务:无变化不重复落盘
236
+ agentdock snapshot --redact # 敏感值打码后保存(结构与键名仍可比对)
237
+
238
+ # 分享 / 换机:经共享目录(内网 Git 工作副本)分发,明文快照默认拒绝导出
239
+ agentdock snapshot push ./agentdock-baseline # 写到 ./.agentdock-baseline/.agentdock-snapshots/<id>/
240
+ agentdock snapshot pull ./agentdock-baseline # 另一台机器导入后可 recover
241
+ agentdock snapshot push ./repo --force # 确需导出明文时才加 --force
242
+
243
+ # 团队基线偏离检查:关键项(model/modelPicker/mcpServers/env)缺失判失败,其余差异告警
244
+ agentdock doctor --agent claude --baseline <快照 id 或路径>
245
+
246
+ # 与最近快照逐键比对(新增 / 删除 / 修改;值统一打码)
247
+ agentdock diff --since-last
248
+ agentdock diff --snapshot latest --exit-code # 有差异时退出码 1,便于 CI
249
+
250
+ # 恢复:默认 dry-run 只预览;--apply 才写入(写前自动再存一份快照)
251
+ agentdock restore --snapshot latest
252
+ agentdock restore --snapshot latest --apply
253
+ agentdock restore --undo --apply # 撤销刚才的恢复
254
+
255
+ # 不确定该用哪份备份时:按完整度评分(文件齐全度 + 顶层键/env/MCP 数量)排序
256
+ agentdock recover # 只看候选与推荐
257
+ agentdock recover --apply # 恢复评分最高的一份
258
+ agentdock recover --snapshot <id> --apply # 指定某一份
259
+ agentdock recover --undo --apply # 撤销
260
+ ```
261
+
262
+ - 快照目录:`~/.agentdock/snapshots/<id>/`,含 `snapshot.json` 元数据与 `files/` 配置文件副本;`~/.agentdock/snapshots/index.json` 为索引。
263
+ - 默认**明文**保存(仅本机、不联网、不上传),请勿把 `~/.agentdock/snapshots` 提交到仓库;需要分享差异时用 `--redact` 重新采集。
264
+ - `doctor` 新增「配置基线」检查:与本 agent 最近快照相比,顶层键减少 ≥30% 或 `model` / `modelPicker` / `mcpServers` / `env` 等关键项消失时判为失败,并给出 `diff` / `restore` 命令。
265
+ - `recover` 的完整度评分:文件齐全度 0–60、顶层键 0–20、env 0–10、MCP 0–10;脱敏快照无法还原真实密钥,扣 20 分。恢复前同样自动生成写前快照。
266
+
222
267
  ## 离线交付(pack / verify / attest)
223
268
 
224
269
  外网调好的环境打成**无网络依赖、密钥零落盘、可校验**的离线包,拷进内网机器一条命令还原。
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentdock-cli",
3
- "version": "1.0.1",
3
+ "version": "1.2.0",
4
4
  "description": "Diagnose, migrate, and back up your AI coding assistant environment (Claude Code / Codex) — Chinese health reports, MCP servers, Skills, Agents, Plugins, Hooks, and memory, with secret isolation.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -36,6 +36,7 @@
36
36
  "dev": "tsx src/cli.ts",
37
37
  "test": "vitest run",
38
38
  "e2e": "tsx scripts/e2e.ts",
39
+ "e2e:sync": "tsx scripts/e2e-sync.ts",
39
40
  "cli": "tsx src/cli.ts",
40
41
  "prepublishOnly": "npm run build",
41
42
  "release:commits": "node scripts/generate-commit-groups.js"
package/dist/src/cli.js CHANGED
@@ -16,6 +16,10 @@ const diff_1 = require("./commands/diff");
16
16
  const config_1 = require("./commands/config");
17
17
  const uninstall_1 = require("./commands/uninstall");
18
18
  const sync_1 = require("./commands/sync");
19
+ const snapshot_1 = require("./commands/snapshot");
20
+ const restore_1 = require("./commands/restore");
21
+ const history_1 = require("./commands/history");
22
+ const recover_1 = require("./commands/recover");
19
23
  const pack_1 = require("./commands/pack");
20
24
  const verify_1 = require("./commands/verify");
21
25
  const attest_1 = require("./commands/attest");
@@ -64,6 +68,33 @@ function parseCliOptions(args) {
64
68
  options.undo = true;
65
69
  continue;
66
70
  }
71
+ if (arg === '--since-last') {
72
+ options.sinceLast = true;
73
+ continue;
74
+ }
75
+ if (arg === '--redact') {
76
+ options.redact = true;
77
+ continue;
78
+ }
79
+ if (arg === '--exit-code') {
80
+ options.exitCode = true;
81
+ continue;
82
+ }
83
+ if (arg === '--if-changed') {
84
+ options.ifChanged = true;
85
+ continue;
86
+ }
87
+ if (arg === '--baseline') {
88
+ const nextArg = args[index + 1];
89
+ if (nextArg && !nextArg.startsWith('--')) {
90
+ options.baseline = nextArg;
91
+ index += 1;
92
+ }
93
+ else {
94
+ positionals.push(arg);
95
+ }
96
+ continue;
97
+ }
67
98
  if (arg === '--zip') {
68
99
  options.zip = true;
69
100
  continue;
@@ -144,13 +175,15 @@ function parseCliOptions(args) {
144
175
  }
145
176
  continue;
146
177
  }
147
- if (arg === '--key' || arg === '--signature') {
178
+ if (arg === '--key' || arg === '--signature' || arg === '--snapshot') {
148
179
  const nextArg = args[index + 1];
149
180
  if (nextArg && !nextArg.startsWith('--')) {
150
181
  if (arg === '--key')
151
182
  options.key = nextArg;
152
183
  if (arg === '--signature')
153
184
  options.signature = nextArg;
185
+ if (arg === '--snapshot')
186
+ options.snapshot = nextArg;
154
187
  index += 1;
155
188
  }
156
189
  else {
@@ -213,6 +246,14 @@ async function runCli(args) {
213
246
  return (0, uninstall_1.runUninstallCommand)(positionals[0], positionals[1], options);
214
247
  case 'sync':
215
248
  return (0, sync_1.runSyncCommand)(positionals[0], positionals[1], options);
249
+ case 'snapshot':
250
+ return (0, snapshot_1.runSnapshotCommand)(positionals[0], positionals[1], options);
251
+ case 'restore':
252
+ return (0, restore_1.runRestoreCommand)(options);
253
+ case 'history':
254
+ return (0, history_1.runHistoryCommand)(options);
255
+ case 'recover':
256
+ return (0, recover_1.runRecoverCommand)(options);
216
257
  default:
217
258
  return {
218
259
  exitCode: 1,
@@ -2,10 +2,81 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.runDiffCommand = runDiffCommand;
4
4
  const installer_1 = require("../core/installer");
5
+ const scan_1 = require("../core/scan");
6
+ const snapshot_1 = require("../core/snapshot");
7
+ const snapshot_diff_1 = require("../core/snapshot-diff");
5
8
  const command_error_codes_1 = require("../constants/command-error-codes");
6
9
  const command_json_1 = require("../utils/command-json");
7
10
  const plan_render_1 = require("../utils/plan-render");
11
+ const i18n_1 = require("../i18n");
12
+ function renderSnapshotDiff(data) {
13
+ const lines = [(0, i18n_1.t)('diff.snapshotHeader', { from: data.from, to: data.to })];
14
+ if (data.changes.length === 0) {
15
+ lines.push(` ${(0, i18n_1.t)('diff.noChanges')}`);
16
+ return lines;
17
+ }
18
+ for (const change of data.changes) {
19
+ const symbol = change.change === 'added' ? '+' : change.change === 'removed' ? '-' : '~';
20
+ lines.push(` ${symbol} ${change.path}${change.note ? ` (${change.note})` : ''}`);
21
+ if (change.before !== undefined) {
22
+ lines.push(` - ${change.before}`);
23
+ }
24
+ if (change.after !== undefined) {
25
+ lines.push(` + ${change.after}`);
26
+ }
27
+ }
28
+ lines.push(` ${data.summary}`);
29
+ return lines;
30
+ }
31
+ async function runSnapshotDiff(options) {
32
+ const root = options.root ?? (0, scan_1.defaultScanRoot)();
33
+ try {
34
+ const snapshot = options.snapshot
35
+ ? await (0, snapshot_1.loadSnapshot)(root, options.snapshot)
36
+ : await (0, snapshot_1.latestSnapshot)(root);
37
+ if (!snapshot) {
38
+ const message = (0, i18n_1.t)('diff.noSnapshot');
39
+ if (options.json === true) {
40
+ return {
41
+ exitCode: 1,
42
+ stdout: [(0, command_json_1.toJsonLine)('diff', false, { from: null, to: 'current' }, [(0, command_json_1.toJsonError)(command_error_codes_1.COMMAND_ERROR_CODES.SNAPSHOT_NOT_FOUND, message)])],
43
+ stderr: [],
44
+ };
45
+ }
46
+ return { exitCode: 1, stdout: [], stderr: [message] };
47
+ }
48
+ const before = await (0, snapshot_1.readSnapshotContents)(snapshot);
49
+ const after = await (0, snapshot_1.readLiveConfig)(root, snapshot.meta.agent);
50
+ const files = new Set([
51
+ ...snapshot.meta.files.map((file) => file.relPath),
52
+ ...after.keys(),
53
+ ]);
54
+ const data = (0, snapshot_diff_1.buildSnapshotDiff)({ from: snapshot.meta.id, to: 'current', files: [...files], before, after });
55
+ const exitCode = options.exitCode === true && data.changes.length > 0 ? 1 : 0;
56
+ if (options.json === true) {
57
+ return { exitCode, stdout: [(0, command_json_1.toJsonLine)('diff', true, data, [])], stderr: [] };
58
+ }
59
+ return { exitCode, stdout: renderSnapshotDiff(data), stderr: [] };
60
+ }
61
+ catch (error) {
62
+ const message = error instanceof Error ? error.message : String(error);
63
+ if (options.json === true) {
64
+ const code = message.startsWith('SNAPSHOT_NOT_FOUND')
65
+ ? command_error_codes_1.COMMAND_ERROR_CODES.SNAPSHOT_NOT_FOUND
66
+ : command_error_codes_1.COMMAND_ERROR_CODES.SNAPSHOT_FAILED;
67
+ return {
68
+ exitCode: 1,
69
+ stdout: [(0, command_json_1.toJsonLine)('diff', false, { from: options.snapshot ?? null, to: 'current' }, [(0, command_json_1.toJsonError)(code, message)])],
70
+ stderr: [],
71
+ };
72
+ }
73
+ return { exitCode: 1, stdout: [], stderr: [message] };
74
+ }
75
+ }
8
76
  async function runDiffCommand(packagePath, targetPath, options = {}) {
77
+ if (options.sinceLast === true || options.snapshot !== undefined) {
78
+ return runSnapshotDiff(options);
79
+ }
9
80
  if (!packagePath) {
10
81
  if (options.json === true) {
11
82
  return {
@@ -18,6 +18,7 @@ async function runDoctorCommand(options = {}) {
18
18
  fromScan: options.fromScan,
19
19
  package: options.package,
20
20
  out,
21
+ baseline: options.baseline,
21
22
  });
22
23
  if (options.json === true) {
23
24
  return {
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runHistoryCommand = runHistoryCommand;
4
+ const scan_1 = require("../core/scan");
5
+ const snapshot_1 = require("../core/snapshot");
6
+ const snapshot_diff_1 = require("../core/snapshot-diff");
7
+ const command_error_codes_1 = require("../constants/command-error-codes");
8
+ const command_json_1 = require("../utils/command-json");
9
+ const i18n_1 = require("../i18n");
10
+ const MAX_HIGHLIGHTS = 5;
11
+ async function diffBetween(older, newer) {
12
+ const before = await (0, snapshot_1.readSnapshotContents)(older);
13
+ const after = await (0, snapshot_1.readSnapshotContents)(newer);
14
+ const files = new Set([
15
+ ...older.meta.files.map((file) => file.relPath),
16
+ ...newer.meta.files.map((file) => file.relPath),
17
+ ]);
18
+ return (0, snapshot_diff_1.buildSnapshotDiff)({ from: older.meta.id, to: newer.meta.id, files: [...files], before, after });
19
+ }
20
+ function matchesAgent(entryAgent, agent) {
21
+ if (!agent || agent === 'all') {
22
+ return true;
23
+ }
24
+ return entryAgent === agent || entryAgent === 'all';
25
+ }
26
+ async function runHistoryCommand(options = {}) {
27
+ const root = options.root ?? (0, scan_1.defaultScanRoot)();
28
+ try {
29
+ const all = await (0, snapshot_1.listSnapshots)(root);
30
+ const filtered = all.filter((entry) => matchesAgent(entry.agent, options.agent));
31
+ const dir = (0, snapshot_1.snapshotsDir)(root);
32
+ if (options.json === true) {
33
+ const entries = await buildEntries(root, filtered);
34
+ const data = { dir, entries };
35
+ return { exitCode: 0, stdout: [(0, command_json_1.toJsonLine)('history', true, data, [])], stderr: [] };
36
+ }
37
+ if (filtered.length === 0) {
38
+ return { exitCode: 0, stdout: [(0, i18n_1.t)('history.empty')], stderr: [] };
39
+ }
40
+ const entries = await buildEntries(root, filtered);
41
+ const lines = [(0, i18n_1.t)('history.header', { count: entries.length, dir })];
42
+ for (const entry of entries) {
43
+ const summary = entry.baseline
44
+ ? (0, i18n_1.t)('history.baseline')
45
+ : (0, i18n_1.t)('history.changes', entry.changes);
46
+ lines.push((0, i18n_1.t)('history.entry', {
47
+ id: entry.id,
48
+ agent: entry.agent,
49
+ files: entry.files,
50
+ summary,
51
+ }));
52
+ for (const highlight of entry.highlights) {
53
+ lines.push((0, i18n_1.t)('history.highlight', { path: highlight }));
54
+ }
55
+ }
56
+ return { exitCode: 0, stdout: lines, stderr: [] };
57
+ }
58
+ catch (error) {
59
+ const message = error instanceof Error ? error.message : String(error);
60
+ if (options.json === true) {
61
+ return {
62
+ exitCode: 1,
63
+ stdout: [(0, command_json_1.toJsonLine)('history', false, { dir: (0, snapshot_1.snapshotsDir)(root), entries: [] }, [(0, command_json_1.toJsonError)(command_error_codes_1.COMMAND_ERROR_CODES.SNAPSHOT_FAILED, message)])],
64
+ stderr: [],
65
+ };
66
+ }
67
+ return { exitCode: 1, stdout: [], stderr: [message] };
68
+ }
69
+ }
70
+ async function buildEntries(root, filtered) {
71
+ const entries = [];
72
+ for (let index = 0; index < filtered.length; index += 1) {
73
+ const item = filtered[index];
74
+ const older = filtered[index + 1];
75
+ if (!older) {
76
+ entries.push({
77
+ id: item.id,
78
+ createdAt: item.createdAt,
79
+ agent: item.agent,
80
+ files: item.files,
81
+ redacted: item.redacted,
82
+ baseline: true,
83
+ changes: { added: 0, removed: 0, modified: 0 },
84
+ highlights: [],
85
+ });
86
+ continue;
87
+ }
88
+ const newerSnapshot = await (0, snapshot_1.loadSnapshot)(root, item.id);
89
+ const olderSnapshot = await (0, snapshot_1.loadSnapshot)(root, older.id);
90
+ const diff = await diffBetween(olderSnapshot, newerSnapshot);
91
+ const changes = { added: 0, removed: 0, modified: 0 };
92
+ for (const change of diff.changes) {
93
+ changes[change.change] += 1;
94
+ }
95
+ entries.push({
96
+ id: item.id,
97
+ createdAt: item.createdAt,
98
+ agent: item.agent,
99
+ files: item.files,
100
+ redacted: item.redacted,
101
+ baseline: false,
102
+ changes,
103
+ highlights: diff.changes.slice(0, MAX_HIGHLIGHTS).map((change) => change.path),
104
+ });
105
+ }
106
+ return entries;
107
+ }
@@ -0,0 +1,180 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runRecoverCommand = runRecoverCommand;
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
+ const ACTION_LABELS = {
10
+ create: 'CREATE ',
11
+ overwrite: 'OVERWRITE',
12
+ skip: 'SKIP ',
13
+ };
14
+ /**
15
+ * 完整度评分:文件齐全度 60 + 顶层键 20 + env 10 + MCP 10,
16
+ * 脱敏快照无法还原真实密钥,扣 20 分。
17
+ */
18
+ function scoreSnapshot(meta) {
19
+ const expected = (0, snapshot_1.configFilesFor)(meta.agent);
20
+ const present = new Set(meta.files.map((file) => file.relPath));
21
+ const missingFiles = expected.filter((relPath) => !present.has(relPath));
22
+ const fileRatio = expected.length === 0 ? 1 : (expected.length - missingFiles.length) / expected.length;
23
+ const breakdown = {
24
+ files: Math.round(fileRatio * 60),
25
+ keys: Math.min(20, meta.counts.topLevelKeys),
26
+ env: Math.min(10, meta.counts.envKeys),
27
+ mcp: Math.min(10, meta.counts.mcpCount * 5),
28
+ redactedPenalty: meta.redacted ? -20 : 0,
29
+ };
30
+ const raw = breakdown.files + breakdown.keys + breakdown.env + breakdown.mcp + breakdown.redactedPenalty;
31
+ return {
32
+ id: meta.id,
33
+ createdAt: meta.createdAt,
34
+ agent: meta.agent,
35
+ files: meta.files.length,
36
+ redacted: meta.redacted,
37
+ score: Math.max(0, Math.min(100, raw)),
38
+ breakdown,
39
+ missingFiles,
40
+ };
41
+ }
42
+ async function buildCandidates(root) {
43
+ const list = await (0, snapshot_1.listSnapshots)(root);
44
+ const candidates = [];
45
+ for (const item of list) {
46
+ const snapshot = await (0, snapshot_1.loadSnapshot)(root, item.id);
47
+ candidates.push(scoreSnapshot(snapshot.meta));
48
+ }
49
+ return candidates.sort((a, b) => b.score - a.score || b.id.localeCompare(a.id));
50
+ }
51
+ function renderCandidates(candidates, dir) {
52
+ const lines = [(0, i18n_1.t)('recover.header', { count: candidates.length, dir })];
53
+ for (const candidate of candidates) {
54
+ lines.push((0, i18n_1.t)('recover.candidate', {
55
+ score: candidate.score,
56
+ id: candidate.id,
57
+ agent: candidate.agent,
58
+ files: candidate.files,
59
+ redacted: candidate.redacted ? ' [redacted]' : '',
60
+ }));
61
+ if (candidate.missingFiles.length > 0) {
62
+ lines.push((0, i18n_1.t)('recover.missing', { files: candidate.missingFiles.join(', ') }));
63
+ }
64
+ }
65
+ return lines;
66
+ }
67
+ function renderPlan(candidate, entries, applied) {
68
+ const mode = applied ? (0, i18n_1.t)('restore.modeApply') : (0, i18n_1.t)('restore.modeDryRun');
69
+ const lines = [(0, i18n_1.t)('recover.planLine', { id: candidate.id, score: candidate.score, mode })];
70
+ for (const entry of entries) {
71
+ lines.push(` ${ACTION_LABELS[entry.action]} ${entry.relPath}`);
72
+ }
73
+ return lines;
74
+ }
75
+ async function runUndo(root, options) {
76
+ const { snapshot, entries } = await (0, snapshot_1.prepareUndo)(root);
77
+ const apply = options.apply === true && options.dryRun !== true;
78
+ const result = apply ? await (0, snapshot_1.applyUndo)(root, snapshot, entries) : undefined;
79
+ if (options.json === true) {
80
+ const data = {
81
+ dir: (0, snapshot_1.snapshotsDir)(root),
82
+ candidates: [],
83
+ restored: result ?? {
84
+ snapshotId: snapshot.meta.id,
85
+ applied: false,
86
+ entries,
87
+ undo: true,
88
+ },
89
+ };
90
+ return { exitCode: 0, stdout: [(0, command_json_1.toJsonLine)('recover', true, data, [])], stderr: [] };
91
+ }
92
+ const mode = apply ? (0, i18n_1.t)('restore.modeApply') : (0, i18n_1.t)('restore.modeDryRun');
93
+ const lines = [(0, i18n_1.t)('restore.undoPlanHeader', { id: snapshot.meta.id, mode })];
94
+ for (const entry of entries) {
95
+ lines.push(` ${ACTION_LABELS[entry.action]} ${entry.relPath}`);
96
+ }
97
+ if (result) {
98
+ lines.push((0, i18n_1.t)('recover.undone', {
99
+ count: result.entries.filter((entry) => entry.action !== 'skip').length,
100
+ id: snapshot.meta.id,
101
+ }));
102
+ }
103
+ return { exitCode: 0, stdout: lines, stderr: [] };
104
+ }
105
+ async function runRecoverCommand(options = {}) {
106
+ const root = options.root ?? (0, scan_1.defaultScanRoot)();
107
+ try {
108
+ if (options.undo === true) {
109
+ return await runUndo(root, options);
110
+ }
111
+ const candidates = await buildCandidates(root);
112
+ if (candidates.length === 0) {
113
+ if (options.json === true) {
114
+ const data = { dir: (0, snapshot_1.snapshotsDir)(root), candidates: [] };
115
+ return { exitCode: 0, stdout: [(0, command_json_1.toJsonLine)('recover', true, data, [])], stderr: [] };
116
+ }
117
+ return { exitCode: 0, stdout: [(0, i18n_1.t)('recover.empty')], stderr: [] };
118
+ }
119
+ const recommended = candidates[0].id;
120
+ const chosen = options.snapshot
121
+ ? candidates.find((candidate) => candidate.id === options.snapshot)
122
+ ?? scoreSnapshot((await (0, snapshot_1.loadSnapshot)(root, options.snapshot)).meta)
123
+ : candidates[0];
124
+ const apply = options.apply === true && options.dryRun !== true;
125
+ let result;
126
+ let planEntries;
127
+ if (apply) {
128
+ const snapshot = await (0, snapshot_1.loadSnapshot)(root, chosen.id);
129
+ const entries = await (0, snapshot_1.planRestore)(root, snapshot);
130
+ result = await (0, snapshot_1.applyRestore)(root, snapshot, entries);
131
+ planEntries = result.entries;
132
+ }
133
+ else if (options.snapshot) {
134
+ planEntries = await (0, snapshot_1.planRestore)(root, await (0, snapshot_1.loadSnapshot)(root, chosen.id));
135
+ }
136
+ if (options.json === true) {
137
+ const data = {
138
+ dir: (0, snapshot_1.snapshotsDir)(root),
139
+ candidates,
140
+ recommended,
141
+ restored: result,
142
+ };
143
+ return { exitCode: 0, stdout: [(0, command_json_1.toJsonLine)('recover', true, data, [])], stderr: [] };
144
+ }
145
+ const lines = renderCandidates(candidates, (0, snapshot_1.snapshotsDir)(root));
146
+ lines.push((0, i18n_1.t)('recover.recommended', { id: recommended }));
147
+ if (planEntries) {
148
+ lines.push(...renderPlan(chosen, planEntries, apply));
149
+ }
150
+ if (result) {
151
+ lines.push((0, i18n_1.t)('recover.applied', {
152
+ count: result.entries.filter((entry) => entry.action !== 'skip').length,
153
+ id: chosen.id,
154
+ }));
155
+ if (result.backupSnapshotId) {
156
+ lines.push((0, i18n_1.t)('recover.backup', { id: result.backupSnapshotId }));
157
+ }
158
+ }
159
+ else if (!options.snapshot) {
160
+ lines.push((0, i18n_1.t)('recover.hint'));
161
+ }
162
+ return { exitCode: 0, stdout: lines, stderr: [] };
163
+ }
164
+ catch (error) {
165
+ const message = error instanceof Error ? error.message : String(error);
166
+ if (options.json === true) {
167
+ const code = message.startsWith('RESTORE_NO_UNDO')
168
+ ? command_error_codes_1.COMMAND_ERROR_CODES.RESTORE_NO_UNDO
169
+ : message.startsWith('SNAPSHOT_NOT_FOUND')
170
+ ? command_error_codes_1.COMMAND_ERROR_CODES.SNAPSHOT_NOT_FOUND
171
+ : command_error_codes_1.COMMAND_ERROR_CODES.RESTORE_FAILED;
172
+ return {
173
+ exitCode: 1,
174
+ stdout: [(0, command_json_1.toJsonLine)('recover', false, { snapshot: options.snapshot ?? null, undo: options.undo === true }, [(0, command_json_1.toJsonError)(code, message)])],
175
+ stderr: [],
176
+ };
177
+ }
178
+ return { exitCode: 1, stdout: [], stderr: [message] };
179
+ }
180
+ }
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runRestoreCommand = runRestoreCommand;
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
+ const ACTION_LABELS = {
10
+ create: 'CREATE ',
11
+ overwrite: 'OVERWRITE',
12
+ skip: 'SKIP ',
13
+ };
14
+ function renderPlan(snapshot, entries, applied, undo) {
15
+ const mode = applied ? (0, i18n_1.t)('restore.modeApply') : (0, i18n_1.t)('restore.modeDryRun');
16
+ const lines = [
17
+ undo
18
+ ? (0, i18n_1.t)('restore.undoPlanHeader', { id: snapshot.meta.id, mode })
19
+ : (0, i18n_1.t)('restore.planHeader', { id: snapshot.meta.id, mode }),
20
+ ];
21
+ for (const entry of entries) {
22
+ lines.push(` ${ACTION_LABELS[entry.action]} ${entry.relPath}`);
23
+ }
24
+ return lines;
25
+ }
26
+ async function runRestoreCommand(options = {}) {
27
+ const root = options.root ?? (0, scan_1.defaultScanRoot)();
28
+ try {
29
+ if (options.undo === true) {
30
+ const { snapshot, entries } = await (0, snapshot_1.prepareUndo)(root);
31
+ const apply = options.apply === true && options.dryRun !== true;
32
+ let result;
33
+ if (apply) {
34
+ result = await (0, snapshot_1.applyUndo)(root, snapshot, entries);
35
+ }
36
+ if (options.json === true) {
37
+ const data = result ?? {
38
+ snapshotId: snapshot.meta.id,
39
+ applied: false,
40
+ entries,
41
+ undo: true,
42
+ };
43
+ return { exitCode: 0, stdout: [(0, command_json_1.toJsonLine)('restore', true, data, [])], stderr: [] };
44
+ }
45
+ const lines = renderPlan(snapshot, entries, apply, true);
46
+ if (result) {
47
+ lines.push((0, i18n_1.t)('restore.undone', { count: result.entries.filter((entry) => entry.action !== 'skip').length, id: snapshot.meta.id }));
48
+ }
49
+ return { exitCode: 0, stdout: lines, stderr: [] };
50
+ }
51
+ if (!options.snapshot) {
52
+ if (options.json === true) {
53
+ return {
54
+ exitCode: 1,
55
+ stdout: [(0, command_json_1.toJsonLine)('restore', false, { snapshot: null, undo: false }, [(0, command_json_1.toJsonError)(command_error_codes_1.COMMAND_ERROR_CODES.MISSING_ARGUMENT, (0, i18n_1.t)('restore.usage'))])],
56
+ stderr: [],
57
+ };
58
+ }
59
+ return { exitCode: 1, stdout: [], stderr: [(0, i18n_1.t)('restore.usage')] };
60
+ }
61
+ const snapshot = await (0, snapshot_1.loadSnapshot)(root, options.snapshot);
62
+ const entries = await (0, snapshot_1.planRestore)(root, snapshot);
63
+ const apply = options.apply === true && options.dryRun !== true;
64
+ let result;
65
+ if (apply) {
66
+ result = await (0, snapshot_1.applyRestore)(root, snapshot, entries);
67
+ }
68
+ if (options.json === true) {
69
+ const data = result ?? {
70
+ snapshotId: snapshot.meta.id,
71
+ applied: false,
72
+ entries,
73
+ undo: false,
74
+ };
75
+ return { exitCode: 0, stdout: [(0, command_json_1.toJsonLine)('restore', true, data, [])], stderr: [] };
76
+ }
77
+ const lines = renderPlan(snapshot, entries, apply, false);
78
+ if (result) {
79
+ const changed = result.entries.filter((entry) => entry.action !== 'skip').length;
80
+ lines.push((0, i18n_1.t)('restore.applied', { count: changed, id: snapshot.meta.id }));
81
+ if (result.backupSnapshotId) {
82
+ lines.push((0, i18n_1.t)('restore.backup', { id: result.backupSnapshotId }));
83
+ }
84
+ }
85
+ return { exitCode: 0, stdout: lines, stderr: [] };
86
+ }
87
+ catch (error) {
88
+ const message = error instanceof Error ? error.message : String(error);
89
+ if (options.json === true) {
90
+ const code = message.startsWith('RESTORE_NO_UNDO')
91
+ ? command_error_codes_1.COMMAND_ERROR_CODES.RESTORE_NO_UNDO
92
+ : message.startsWith('SNAPSHOT_NOT_FOUND')
93
+ ? command_error_codes_1.COMMAND_ERROR_CODES.SNAPSHOT_NOT_FOUND
94
+ : command_error_codes_1.COMMAND_ERROR_CODES.RESTORE_FAILED;
95
+ return {
96
+ exitCode: 1,
97
+ stdout: [(0, command_json_1.toJsonLine)('restore', false, { snapshot: options.snapshot ?? null, undo: options.undo === true }, [(0, command_json_1.toJsonError)(code, message)])],
98
+ stderr: [],
99
+ };
100
+ }
101
+ return { exitCode: 1, stdout: [], stderr: [message] };
102
+ }
103
+ }