@twinsearth/timemachine-dsh-plugin 0.2.1 → 0.2.3

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,387 @@
1
+ /**
2
+ * Repair RESTORE-GUIDE files inside existing restore points.
3
+ *
4
+ * A restore point can be created by an older plugin version without guide
5
+ * files, a copied/imported archive can lose them, or a guide can become stale
6
+ * after the archive metadata changes. The session log is authoritative; the
7
+ * guide is rebuilt from the archive manifest and the point metadata.
8
+ *
9
+ * Repair is conservative:
10
+ * - every non-guide file is verified before anything is rewritten;
11
+ * - a point is rewritten only when a guide entry is missing or differs;
12
+ * - the replacement is verified with the normal archive reader before it
13
+ * replaces the original file.
14
+ */
15
+
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import zlib from 'node:zlib';
19
+
20
+ import { writeTar } from './archive/tar.mjs';
21
+ import {
22
+ GUIDE_SCHEMA,
23
+ guideMarkdown,
24
+ readArchive,
25
+ writeSidecar,
26
+ } from './point.mjs';
27
+ import {
28
+ isInside,
29
+ isSafeArchiveName,
30
+ sha256,
31
+ } from './util/fs.mjs';
32
+
33
+ const SESSION_RE = /^sessions\/([^/]+)\/([^/]+)\/session\.v4\.jsonl\.zstd$/u;
34
+
35
+ function isPlainObject(value) {
36
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
37
+ }
38
+
39
+ function isGuideRel(rel) {
40
+ return typeof rel === 'string' && (rel.endsWith('/RESTORE-GUIDE.json') || rel.endsWith('/RESTORE-GUIDE.md'));
41
+ }
42
+
43
+ function decodeSegment(value) {
44
+ return String(value ?? '').replace(/~([0-9A-Fa-f]{4})/gu, (_match, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
45
+ }
46
+
47
+ function pointSession(point, sessionId) {
48
+ return (point?.sessions ?? []).find((row) => row?.session_id === sessionId) ?? null;
49
+ }
50
+
51
+ function registryWorkspace(point, sessionId) {
52
+ return (point?.workspaces ?? []).find((row) => Array.isArray(row?.sessionIds) && row.sessionIds.includes(sessionId)) ?? null;
53
+ }
54
+
55
+ function currentGuide(map, rel) {
56
+ const data = map.get(rel);
57
+ if (data === undefined) return null;
58
+ try {
59
+ const parsed = JSON.parse(data.toString('utf8'));
60
+ return isPlainObject(parsed) ? parsed : null;
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Verify all non-guide manifest entries. Guide entries are intentionally
68
+ * skipped: a missing or stale guide is the condition this module repairs.
69
+ */
70
+ function verifyBackbone(archive) {
71
+ const rows = Array.isArray(archive.manifest?.files) ? archive.manifest.files : [];
72
+ const seen = new Set();
73
+ for (const row of rows) {
74
+ if (!isPlainObject(row) || !isSafeArchiveName(row.rel)) {
75
+ return `manifest entry has an unsafe path: ${JSON.stringify(row?.rel)}`;
76
+ }
77
+ if (seen.has(row.rel)) return `duplicate manifest entry ${row.rel}`;
78
+ seen.add(row.rel);
79
+ if (isGuideRel(row.rel)) continue;
80
+ const data = archive.map.get(row.rel);
81
+ if (data === undefined) return `missing entry ${row.rel}`;
82
+ if (typeof row.size === 'number' && row.size !== data.length) {
83
+ return `${row.rel}: size ${data.length} != manifest ${row.size}`;
84
+ }
85
+ if (typeof row.sha256 === 'string' && sha256(data) !== row.sha256) {
86
+ return `${row.rel}: sha256 mismatch`;
87
+ }
88
+ }
89
+ return null;
90
+ }
91
+
92
+ function collectSessions(archive) {
93
+ const rows = [];
94
+ const known = new Set();
95
+ for (const row of archive.manifest.files ?? []) {
96
+ if (row?.kind !== 'session') continue;
97
+ const match = SESSION_RE.exec(row.rel);
98
+ if (match === null) continue;
99
+ const data = archive.map.get(row.rel);
100
+ if (data === undefined) continue;
101
+ rows.push({
102
+ sessionId: typeof row.session_id === 'string' && row.session_id !== '' ? row.session_id : decodeSegment(match[2]),
103
+ project: match[1],
104
+ rel: row.rel,
105
+ data,
106
+ });
107
+ known.add(row.rel);
108
+ }
109
+ for (const entry of archive.entries) {
110
+ const match = SESSION_RE.exec(entry.name);
111
+ if (match === null || known.has(entry.name)) continue;
112
+ rows.push({
113
+ sessionId: decodeSegment(match[2]),
114
+ project: match[1],
115
+ rel: entry.name,
116
+ data: entry.data,
117
+ });
118
+ known.add(entry.name);
119
+ }
120
+ return rows;
121
+ }
122
+
123
+ function guideForSession(input) {
124
+ const {
125
+ point, session, sessionId, project, rel, data, existing,
126
+ } = input;
127
+ const meta = pointSession(point, sessionId);
128
+ const registry = registryWorkspace(point, sessionId);
129
+ const workspace = {
130
+ id: meta?.workspace_id ?? registry?.id ?? existing?.workspace_id ?? null,
131
+ path: meta?.workspace_path ?? registry?.path ?? existing?.workspace_path ?? existing?.header?.cwd ?? null,
132
+ title: meta?.workspace_title ?? registry?.title ?? existing?.workspace_title ?? null,
133
+ };
134
+ const archived = meta !== null && meta?.archived !== undefined
135
+ ? meta.archived === true
136
+ : existing?.archived === true;
137
+ const pinned = meta !== null && meta?.pinned !== undefined
138
+ ? meta.pinned === true
139
+ : existing?.pinned === true;
140
+ const header = isPlainObject(existing?.header)
141
+ ? existing.header
142
+ : (workspace.path === null || workspace.path === undefined || workspace.path === ''
143
+ ? {}
144
+ : { cwd: workspace.path });
145
+ const guide = {
146
+ schema: GUIDE_SCHEMA,
147
+ session_id: sessionId,
148
+ workspace_slug: project,
149
+ workspace_id: workspace.id,
150
+ workspace_path: workspace.path,
151
+ workspace_title: workspace.title,
152
+ source_machine: point?.source_machine ?? existing?.source_machine ?? '',
153
+ source_dsh_home: point?.source_dsh_home ?? existing?.source_dsh_home ?? '',
154
+ created_at: point?.created_at ?? existing?.created_at ?? '',
155
+ session_file: rel,
156
+ size: data.length,
157
+ sha256: sha256(data),
158
+ archived,
159
+ pinned,
160
+ header,
161
+ restore_hint:
162
+ 'DSH -> 通用设置 -> DSH 一键还原点(或左侧“时间机器 / 一键还原点”)-> 还原这份。' +
163
+ '还原会把本文件写回 sessions/<project-key>/<Session ID>/,并写入工作区注册表;显示工作区需要重启 DSH 客户端。',
164
+ };
165
+ if (typeof existing?.restore_hint === 'string' && existing.restore_hint !== '') {
166
+ guide.restore_hint = existing.restore_hint;
167
+ }
168
+ return guide;
169
+ }
170
+
171
+ function setGuideRow(rows, rel, data, sessionId, now, existingReason) {
172
+ const next = {
173
+ rel,
174
+ kind: 'guide',
175
+ scope: 'sessions',
176
+ reason: existingReason || 'restore guide rebuilt from the archive manifest',
177
+ size: data.length,
178
+ sha256: sha256(data),
179
+ session_id: sessionId,
180
+ attachment_id: null,
181
+ flags: null,
182
+ mtime_ms: now,
183
+ };
184
+ const index = rows.findIndex((row) => row?.rel === rel);
185
+ if (index >= 0) rows[index] = { ...rows[index], ...next };
186
+ else rows.push(next);
187
+ }
188
+
189
+ function guideRowMatches(row, data) {
190
+ return isPlainObject(row)
191
+ && row.kind === 'guide'
192
+ && row.scope === 'sessions'
193
+ && row.size === data.length
194
+ && row.sha256 === sha256(data);
195
+ }
196
+
197
+ /**
198
+ * Repair one restore point in place. The original is replaced only after a
199
+ * complete archive read of the replacement succeeds.
200
+ * @param {string} file
201
+ * @returns {object}
202
+ */
203
+ export function repairRestorePointGuides(file) {
204
+ const target = path.resolve(file);
205
+ let stat;
206
+ try { stat = fs.statSync(target); } catch {
207
+ return { ok: false, file: target, reason_code: 'TIMEMACHINE_ARCHIVE_INVALID', detail: `${target} does not exist` };
208
+ }
209
+ if (!stat.isFile()) {
210
+ return { ok: false, file: target, reason_code: 'TIMEMACHINE_ARCHIVE_INVALID', detail: `${target} is not a file` };
211
+ }
212
+ const archive = readArchive(target, { verify: false });
213
+ if (!archive.ok) return { ok: false, file: target, reason_code: archive.reason_code, detail: archive.detail };
214
+ const backboneError = verifyBackbone(archive);
215
+ if (backboneError !== null) {
216
+ return { ok: false, file: target, reason_code: 'TIMEMACHINE_ARCHIVE_INVALID', detail: backboneError };
217
+ }
218
+
219
+ const sessions = collectSessions(archive);
220
+ if (sessions.length === 0) {
221
+ return {
222
+ ok: true,
223
+ file: target,
224
+ changed: false,
225
+ sessions: 0,
226
+ guides_repaired: 0,
227
+ detail: '没有会话日志,无需修复',
228
+ bytes_before: stat.size,
229
+ bytes_after: stat.size,
230
+ };
231
+ }
232
+
233
+ const now = Date.now();
234
+ const entriesByName = new Map(archive.entries.map((entry) => [entry.name, { ...entry }]));
235
+ const manifestRows = [...(archive.manifest.files ?? [])];
236
+ const guideRows = new Map(manifestRows.filter((row) => isGuideRel(row?.rel)).map((row) => [row.rel, row]));
237
+ let repairedGuides = 0;
238
+ let changedSessions = 0;
239
+
240
+ for (const session of sessions) {
241
+ const dir = path.posix.dirname(session.rel);
242
+ const jsonRel = `${dir}/RESTORE-GUIDE.json`;
243
+ const mdRel = `${dir}/RESTORE-GUIDE.md`;
244
+ const existing = currentGuide(archive.map, jsonRel);
245
+ const guide = guideForSession({
246
+ point: archive.point,
247
+ session,
248
+ sessionId: session.sessionId,
249
+ project: session.project,
250
+ rel: session.rel,
251
+ data: session.data,
252
+ existing,
253
+ });
254
+ const jsonData = Buffer.from(`${JSON.stringify(guide, null, 2)}\n`, 'utf8');
255
+ const mdData = Buffer.from(guideMarkdown(guide), 'utf8');
256
+ const currentJson = archive.map.get(jsonRel);
257
+ const currentMd = archive.map.get(mdRel);
258
+ const jsonNeedsWrite = currentJson === undefined || !currentJson.equals(jsonData);
259
+ const mdNeedsWrite = currentMd === undefined || !currentMd.equals(mdData);
260
+ const jsonRow = guideRows.get(jsonRel);
261
+ const mdRow = guideRows.get(mdRel);
262
+ const rowNeedsWrite = (jsonRow !== undefined && !guideRowMatches(jsonRow, jsonData))
263
+ || (mdRow !== undefined && !guideRowMatches(mdRow, mdData))
264
+ || jsonRow === undefined
265
+ || mdRow === undefined;
266
+ if (!jsonNeedsWrite && !mdNeedsWrite && !rowNeedsWrite) continue;
267
+
268
+ changedSessions += 1;
269
+ repairedGuides += 1;
270
+ if (jsonNeedsWrite) {
271
+ entriesByName.set(jsonRel, { name: jsonRel, data: jsonData, mode: 0o644, mtimeMs: now });
272
+ }
273
+ if (mdNeedsWrite) {
274
+ entriesByName.set(mdRel, { name: mdRel, data: mdData, mode: 0o644, mtimeMs: now });
275
+ }
276
+ setGuideRow(manifestRows, jsonRel, jsonData, session.sessionId, now, jsonRow?.reason);
277
+ setGuideRow(manifestRows, mdRel, mdData, session.sessionId, now, mdRow?.reason);
278
+ }
279
+
280
+ if (changedSessions === 0) {
281
+ return {
282
+ ok: true,
283
+ file: target,
284
+ changed: false,
285
+ sessions: sessions.length,
286
+ guides_repaired: 0,
287
+ detail: '会话引导完整,无需修复',
288
+ bytes_before: stat.size,
289
+ bytes_after: stat.size,
290
+ sha256: archive.sha256,
291
+ };
292
+ }
293
+
294
+ const point = archive.point;
295
+ const counts = {
296
+ ...(point.counts ?? {}),
297
+ ...(archive.manifest.counts ?? {}),
298
+ sessions: sessions.length,
299
+ guides: sessions.length,
300
+ };
301
+ point.counts = counts;
302
+ point.guides = sessions.map((session) => ({
303
+ session_id: session.sessionId,
304
+ rel: `${path.posix.dirname(session.rel)}/RESTORE-GUIDE.json`,
305
+ markdown: `${path.posix.dirname(session.rel)}/RESTORE-GUIDE.md`,
306
+ }));
307
+ archive.manifest.counts = counts;
308
+ archive.manifest.files = manifestRows;
309
+ archive.manifest.restore_point = point;
310
+
311
+ const manifestData = Buffer.from(`${JSON.stringify(archive.manifest, null, 2)}\n`, 'utf8');
312
+ const pointData = Buffer.from(`${JSON.stringify(point, null, 2)}\n`, 'utf8');
313
+ entriesByName.set('manifest.json', { name: 'manifest.json', data: manifestData, mode: 0o644, mtimeMs: now });
314
+ const pointEntry = entriesByName.get('RESTORE-POINT.json');
315
+ entriesByName.set('RESTORE-POINT.json', {
316
+ name: 'RESTORE-POINT.json',
317
+ data: pointData,
318
+ mode: pointEntry?.mode ?? 0o644,
319
+ mtimeMs: now,
320
+ });
321
+
322
+ const entries = [...entriesByName.values()];
323
+ const zst = zlib.zstdCompressSync(writeTar(entries));
324
+ const tmp = `${target}.repair-${process.pid}-${Date.now()}.tmp`;
325
+ try {
326
+ fs.writeFileSync(tmp, zst, { flag: 'wx', mode: stat.mode });
327
+ const verified = readArchive(tmp);
328
+ if (!verified.ok) throw new Error(`replacement archive failed verification: ${verified.detail}`);
329
+ fs.renameSync(tmp, target);
330
+ } catch (error) {
331
+ try { fs.rmSync(tmp, { force: true }); } catch { /* best effort */ }
332
+ return {
333
+ ok: false,
334
+ file: target,
335
+ reason_code: 'TIMEMACHINE_WRITE_FAILED',
336
+ detail: error instanceof Error ? error.message : String(error),
337
+ bytes_before: stat.size,
338
+ };
339
+ }
340
+
341
+ const digest = sha256(zst);
342
+ let sidecarError = null;
343
+ try {
344
+ writeSidecar(target, { point, counts, sha256: digest, bytes: zst.length });
345
+ } catch (error) {
346
+ sidecarError = error instanceof Error ? error.message : String(error);
347
+ }
348
+ return {
349
+ ok: true,
350
+ file: target,
351
+ changed: true,
352
+ sessions: sessions.length,
353
+ guides_repaired: repairedGuides,
354
+ changed_sessions: changedSessions,
355
+ bytes_before: stat.size,
356
+ bytes_after: zst.length,
357
+ sha256: digest,
358
+ ...(sidecarError === null ? {} : { sidecar_error: sidecarError }),
359
+ detail: `已重建 ${repairedGuides} 份会话引导`,
360
+ };
361
+ }
362
+
363
+ /** Resolve the restore-point files under a root without trusting a caller path. */
364
+ export function resolveRepairTargets(root, file = '') {
365
+ const base = path.resolve(root);
366
+ if (typeof file === 'string' && file.trim() !== '') {
367
+ const target = path.resolve(file.trim());
368
+ if (!isInside(base, target)) {
369
+ return { ok: false, reason_code: 'TIMEMACHINE_FILE_OUTSIDE_ROOT', detail: '还原点文件必须位于当前保存文件夹内' };
370
+ }
371
+ if (!target.endsWith('.tar.zst')) {
372
+ return { ok: false, reason_code: 'TIMEMACHINE_FILE_REQUIRED', detail: '只支持 .tar.zst 还原点' };
373
+ }
374
+ return { ok: true, files: [target] };
375
+ }
376
+ const files = [];
377
+ for (const kind of ['manual', 'auto', 'imported']) {
378
+ const folder = path.join(base, kind);
379
+ let names = [];
380
+ try { names = fs.readdirSync(folder); } catch { names = []; }
381
+ for (const name of names) {
382
+ if (!/^restore-.*\.tar\.zst$/u.test(name)) continue;
383
+ files.push(path.join(folder, name));
384
+ }
385
+ }
386
+ return { ok: true, files };
387
+ }
package/src/plugin.mjs CHANGED
@@ -7,12 +7,14 @@
7
7
  *
8
8
  * GET /api/twinsearth/timemachine/health
9
9
  * GET /api/twinsearth/timemachine/status
10
+ * GET /api/twinsearth/timemachine/stats
10
11
  * GET /api/twinsearth/timemachine/estimate
11
12
  * POST /api/twinsearth/timemachine/create
12
13
  * POST /api/twinsearth/timemachine/plan
13
14
  * POST /api/twinsearth/timemachine/restore
14
15
  * POST /api/twinsearth/timemachine/import
15
16
  * POST /api/twinsearth/timemachine/inspect
17
+ * POST /api/twinsearth/timemachine/repair-guides
16
18
  * POST /api/twinsearth/timemachine/settings
17
19
  * POST /api/twinsearth/timemachine/auto/run
18
20
  */
@@ -26,10 +28,13 @@ import {
26
28
  inspectPoint,
27
29
  pickerUnavailable,
28
30
  plan,
31
+ repairGuides,
29
32
  restore,
30
33
  saveSettings,
31
34
  startAutoScheduler,
32
35
  } from './service.mjs';
36
+ import { startTelemetry } from './telemetry.mjs';
37
+ import { PLUGIN_VERSION } from './version.mjs';
33
38
 
34
39
  export const name = 'timemachine';
35
40
  export const inject = [];
@@ -38,12 +43,14 @@ export const ROUTE_PREFIX = '/api/twinsearth/timemachine';
38
43
  export const ROUTE_PATHS = Object.freeze({
39
44
  health: `${ROUTE_PREFIX}/health`,
40
45
  status: `${ROUTE_PREFIX}/status`,
46
+ stats: `${ROUTE_PREFIX}/stats`,
41
47
  estimate: `${ROUTE_PREFIX}/estimate`,
42
48
  create: `${ROUTE_PREFIX}/create`,
43
49
  plan: `${ROUTE_PREFIX}/plan`,
44
50
  restore: `${ROUTE_PREFIX}/restore`,
45
51
  import: `${ROUTE_PREFIX}/import`,
46
52
  inspect: `${ROUTE_PREFIX}/inspect`,
53
+ repairGuides: `${ROUTE_PREFIX}/repair-guides`,
47
54
  settings: `${ROUTE_PREFIX}/settings`,
48
55
  autoRun: `${ROUTE_PREFIX}/auto/run`,
49
56
  });
@@ -108,8 +115,16 @@ export function registerRoutes(ctx, rawConfig, deps = {}) {
108
115
  });
109
116
  };
110
117
 
111
- register('GET', ROUTE_PATHS.health, async () => json({ ok: true, plugin: name, mounted: true }));
118
+ register('GET', ROUTE_PATHS.health, async () => json({ ok: true, plugin: name, version: PLUGIN_VERSION, mounted: true }));
112
119
  register('GET', ROUTE_PATHS.status, async () => json(getStatus(rawConfig, deps)));
120
+ register('GET', ROUTE_PATHS.stats, async () => json(await (deps.telemetry?.getStats?.() ?? {
121
+ ok: false,
122
+ version: PLUGIN_VERSION,
123
+ online: null,
124
+ sevenDay: null,
125
+ installs: null,
126
+ error: 'telemetry unavailable',
127
+ })));
113
128
  register('GET', ROUTE_PATHS.estimate, async () => json({ ok: true, ...getEstimate(rawConfig, deps) }));
114
129
  register('POST', ROUTE_PATHS.create, async (request) => guarded('create', async () => {
115
130
  const body = await readBody(request);
@@ -146,6 +161,13 @@ export function registerRoutes(ctx, rawConfig, deps = {}) {
146
161
  const result = inspectPoint(rawConfig, body, deps);
147
162
  return json(result, { status: result.ok ? 200 : 400 });
148
163
  });
164
+ register('POST', ROUTE_PATHS.repairGuides, async (request) => {
165
+ const body = await readBody(request);
166
+ return guarded('repair-guides', async () => {
167
+ const result = repairGuides(rawConfig, body, deps);
168
+ return json(result, { status: result.ok ? 200 : 400 });
169
+ });
170
+ });
149
171
  register('POST', ROUTE_PATHS.settings, async (request) => {
150
172
  const body = await readBody(request);
151
173
  const result = saveSettings(rawConfig, body, deps);
@@ -176,6 +198,14 @@ export function apply(ctx, config = {}, deps = {}) {
176
198
  }
177
199
  },
178
200
  };
201
+ if (runtimeDeps.telemetry === undefined) {
202
+ try {
203
+ runtimeDeps.telemetry = startTelemetry({ logger: ctx.logger });
204
+ } catch (error) {
205
+ runtimeDeps.telemetry = null;
206
+ ctx.logger?.warn?.(`${name}: telemetry did not start: ${error instanceof Error ? error.message : String(error)}`);
207
+ }
208
+ }
179
209
  const routes = registerRoutes(ctx, config, runtimeDeps);
180
210
  ctx.logger?.info?.(`${name}: routes ${routes.mounted ? 'mounted' : `not mounted (${routes.reason})`}`);
181
211
  const stopScheduler = startAutoScheduler({
@@ -190,10 +220,12 @@ export function apply(ctx, config = {}, deps = {}) {
190
220
  ctx.effect?.(() => () => {
191
221
  disposed = true;
192
222
  stopScheduler();
223
+ runtimeDeps.telemetry?.stop?.();
193
224
  });
194
225
  const dispose = () => {
195
226
  disposed = true;
196
227
  stopScheduler();
228
+ runtimeDeps.telemetry?.stop?.();
197
229
  };
198
230
  for (const [key, value] of Object.entries({
199
231
  ok: true,
package/src/point.mjs CHANGED
@@ -105,7 +105,7 @@ function workspaceFor(registry, session) {
105
105
  return { id: null, path: session.header?.cwd ?? null, title: null };
106
106
  }
107
107
 
108
- function guideFor(input) {
108
+ export function guideFor(input) {
109
109
  return {
110
110
  schema: GUIDE_SCHEMA,
111
111
  session_id: input.session.session_id,
@@ -128,7 +128,7 @@ function guideFor(input) {
128
128
  };
129
129
  }
130
130
 
131
- function guideMarkdown(guide) {
131
+ export function guideMarkdown(guide) {
132
132
  return [
133
133
  `# 会话还原引导:${guide.session_id}`,
134
134
  '',
package/src/service.mjs CHANGED
@@ -24,10 +24,12 @@ import {
24
24
  selectSessions,
25
25
  } from './point.mjs';
26
26
  import { readProfilePlugins } from './plugins.mjs';
27
+ import { repairRestorePointGuides, resolveRepairTargets } from './guide-repair.mjs';
27
28
  import { planRestore, restorePoint } from './restore.mjs';
28
29
  import { normalizeRegistry } from './scan.mjs';
29
30
  import { atomicWriteJson, ensureDir, readJson } from './util/fs.mjs';
30
31
  import { profileDir, resolveDshHome } from './util/paths.mjs';
32
+ import { PLUGIN_VERSION } from './version.mjs';
31
33
 
32
34
  export const DEFAULT_SETTINGS = Object.freeze({
33
35
  root: '',
@@ -197,6 +199,7 @@ export function getStatus(rawConfig, options = {}) {
197
199
  const registry = normalizeRegistry(readJson(path.join(dshHome, 'storages', 'workspace.json'), null));
198
200
  return {
199
201
  ok: true,
202
+ version: PLUGIN_VERSION,
200
203
  platform: process.platform,
201
204
  platform_label: process.platform === 'win32' ? 'Windows' : process.platform === 'darwin' ? 'macOS' : 'Linux',
202
205
  dsh_home: dshHome,
@@ -374,9 +377,79 @@ export function pickerUnavailable(what) {
374
377
  };
375
378
  }
376
379
 
380
+ /**
381
+ * Repair the RESTORE-GUIDE files inside every healthy restore point under the
382
+ * configured root. An explicit `body.file` limits the repair to one archive.
383
+ */
384
+ export function repairGuides(rawConfig, body = {}, options = {}) {
385
+ const dshHome = resolveDshHome(options.dshHome ?? rawConfig?.dshHome);
386
+ const merged = mergeSettings(rawConfig, dshHome);
387
+ const root = effectiveRoot(merged);
388
+ if (root === '') return { ok: false, reason_code: CODES.ROOT_REQUIRED, detail: '请先选择还原点保存文件夹' };
389
+ const targets = resolveRepairTargets(root, body?.file);
390
+ if (!targets.ok) return targets;
391
+ if (targets.files.length === 0) {
392
+ return {
393
+ ok: true,
394
+ points: [],
395
+ checked_points: 0,
396
+ repaired_points: 0,
397
+ unchanged_points: 0,
398
+ failed_points: 0,
399
+ guides_repaired: 0,
400
+ detail: '没有可修复的还原点',
401
+ };
402
+ }
403
+ const points = targets.files.map((file) => {
404
+ try {
405
+ return repairRestorePointGuides(file);
406
+ } catch (error) {
407
+ return {
408
+ ok: false,
409
+ file,
410
+ reason_code: 'TIMEMACHINE_REPAIR_FAILED',
411
+ detail: error instanceof Error ? error.message : String(error),
412
+ };
413
+ }
414
+ });
415
+ const repaired = points.filter((row) => row.ok === true && row.changed === true).length;
416
+ const unchanged = points.filter((row) => row.ok === true && row.changed !== true).length;
417
+ const failed = points.filter((row) => row.ok !== true).length;
418
+ const guides = points.reduce((sum, row) => sum + (row.ok === true ? (row.guides_repaired ?? 0) : 0), 0);
419
+ const sessions = points.reduce((sum, row) => sum + (row.ok === true ? (row.sessions ?? 0) : 0), 0);
420
+ const detail = failed === points.length
421
+ ? `检查 ${points.length} 个还原点,全部失败`
422
+ : `检查 ${points.length} 个还原点:修复 ${repaired} 个(${guides} 份会话引导),无需修改 ${unchanged} 个${failed > 0 ? `,失败 ${failed} 个` : ''}`;
423
+ if (failed === points.length) {
424
+ return {
425
+ ok: false,
426
+ reason_code: 'TIMEMACHINE_REPAIR_FAILED',
427
+ detail,
428
+ points,
429
+ checked_points: points.length,
430
+ repaired_points: repaired,
431
+ unchanged_points: unchanged,
432
+ failed_points: failed,
433
+ guides_repaired: guides,
434
+ sessions,
435
+ };
436
+ }
437
+ return {
438
+ ok: true,
439
+ partial: failed > 0,
440
+ detail,
441
+ points,
442
+ checked_points: points.length,
443
+ repaired_points: repaired,
444
+ unchanged_points: unchanged,
445
+ failed_points: failed,
446
+ guides_repaired: guides,
447
+ sessions,
448
+ };
449
+ }
450
+
377
451
  /** List one point's contents for the detail drawer. */
378
- export function inspectPoint(rawConfig, body, options = {}) {
379
- const file = typeof body?.file === 'string' ? body.file.trim() : '';
452
+ export function inspectPoint(rawConfig, body, options = {}) { const file = typeof body?.file === 'string' ? body.file.trim() : '';
380
453
  if (file === '') return { ok: false, reason_code: 'TIMEMACHINE_FILE_REQUIRED', detail: 'body.file is required' };
381
454
  const row = inspectRestorePoint(file);
382
455
  if (!row.ok) return row;