@twinsearth/timemachine-dsh-plugin 0.0.0-stage → 0.1.1

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/src/scan.mjs ADDED
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Read-only inventory of a DSH home.
3
+ *
4
+ * Everything the restore point writes is enumerated here first: sessions,
5
+ * attachments, the workspace registry, profile configuration and plugin
6
+ * metadata. Nothing in this module writes to the home.
7
+ */
8
+
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+
12
+ import { readJson } from './util/fs.mjs';
13
+ import { profileDir, resolveDshHome, SESSION_LOG } from './util/paths.mjs';
14
+ import { readSessionHeader } from './session-log.mjs';
15
+
16
+ /** Top-level files inside a profile that belong to DSH itself, not to plugin caches. */
17
+ const PROFILE_CONFIG_FILES = [
18
+ 'package.json',
19
+ 'cordis.patch.yml',
20
+ 'cordis.yml',
21
+ 'pnpm-workspace.yaml',
22
+ ];
23
+
24
+ /** Never archive account material or generated caches even if a caller asks for "everything". */
25
+ export const CREDENTIAL_NAMES = new Set([
26
+ '.credentials.yaml',
27
+ '.credentials.yaml.bak',
28
+ '.anonymous-user-id',
29
+ 'device.key',
30
+ 'device.json',
31
+ ]);
32
+
33
+ /** Normalize the two registry shapes DSH has shipped: object map and array. */
34
+ export function normalizeRegistry(raw) {
35
+ const document = raw !== null && typeof raw === 'object' ? raw : {};
36
+ const table = document?.tables?.workspaces;
37
+ const rows = Array.isArray(table)
38
+ ? table
39
+ : table !== null && typeof table === 'object'
40
+ ? Object.entries(table).map(([id, value]) => ({ id, ...(value ?? {}) }))
41
+ : [];
42
+ const workspaces = rows
43
+ .filter((row) => row !== null && typeof row === 'object')
44
+ .map((row) => ({
45
+ id: typeof row.id === 'string' ? row.id : '',
46
+ path: typeof row.path === 'string' ? row.path : '',
47
+ title: typeof row.title === 'string' ? row.title : '',
48
+ sessionIds: Array.isArray(row.sessionIds) ? row.sessionIds.filter((id) => typeof id === 'string') : [],
49
+ createdAt: row.createdAt ?? null,
50
+ updatedAt: row.updatedAt ?? null,
51
+ }))
52
+ .filter((row) => row.id !== '');
53
+ const global = document?.global !== null && typeof document?.global === 'object' ? document.global : {};
54
+ return {
55
+ document,
56
+ workspaces,
57
+ defaultWorkspaceId: typeof global.defaultWorkspaceId === 'string' ? global.defaultWorkspaceId : null,
58
+ workspaceIds: Array.isArray(global.workspaceIds) ? global.workspaceIds.filter((id) => typeof id === 'string') : [],
59
+ archivedSessionIds: Array.isArray(global.archivedSessionIds) ? global.archivedSessionIds.filter((id) => typeof id === 'string') : [],
60
+ pinnedSessionIds: Array.isArray(global.pinnedSessionIds) ? global.pinnedSessionIds.filter((id) => typeof id === 'string') : [],
61
+ };
62
+ }
63
+
64
+ function readRegistry(dshHome) {
65
+ const file = path.join(dshHome, 'storages', 'workspace.json');
66
+ const raw = readJson(file, null);
67
+ if (raw === null) return { ok: false, file, ...normalizeRegistry({}) };
68
+ return { ok: true, file, ...normalizeRegistry(raw) };
69
+ }
70
+
71
+ function listDirectories(dir) {
72
+ try {
73
+ return fs.readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory());
74
+ } catch {
75
+ return [];
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Enumerate session logs under `<home>/sessions/<project-key>/<session-dir>/`.
81
+ * The session id and cwd come from the log header, which is authoritative; the
82
+ * directory names are only a fallback for a log whose header cannot be read.
83
+ */
84
+ export function scanSessions(dshHome, registry) {
85
+ const root = path.join(dshHome, 'sessions');
86
+ const byId = new Map();
87
+ for (const project of listDirectories(root)) {
88
+ const projectDir = path.join(root, project.name);
89
+ for (const session of listDirectories(projectDir)) {
90
+ const file = path.join(projectDir, session.name, SESSION_LOG);
91
+ let stat;
92
+ try {
93
+ stat = fs.statSync(file);
94
+ } catch {
95
+ continue;
96
+ }
97
+ if (!stat.isFile()) continue;
98
+ const headerInfo = readSessionHeader(file);
99
+ const sessionId = headerInfo.header?.id ?? session.name;
100
+ const cwd = headerInfo.header?.cwd ?? null;
101
+ const row = {
102
+ session_id: sessionId,
103
+ project_key: project.name,
104
+ dir_name: session.name,
105
+ file,
106
+ rel: path.relative(dshHome, file).replaceAll('\\', '/'),
107
+ size: stat.size,
108
+ mtime_ms: stat.mtimeMs,
109
+ cwd,
110
+ header: headerInfo.header,
111
+ header_error: headerInfo.error,
112
+ frame_count: headerInfo.frame_count,
113
+ torn_tail: headerInfo.torn_tail,
114
+ flags: {
115
+ archived: registry.archivedSessionIds.includes(sessionId),
116
+ pinned: registry.pinnedSessionIds.includes(sessionId),
117
+ },
118
+ workspace_id: null,
119
+ workspace_title: null,
120
+ workspace_path: null,
121
+ };
122
+ for (const workspace of registry.workspaces) {
123
+ if (workspace.sessionIds.includes(sessionId)) {
124
+ row.workspace_id = workspace.id;
125
+ row.workspace_title = workspace.title;
126
+ row.workspace_path = workspace.path;
127
+ break;
128
+ }
129
+ }
130
+ const previous = byId.get(sessionId);
131
+ if (previous === undefined || previous.mtime_ms < row.mtime_ms) byId.set(sessionId, row);
132
+ }
133
+ }
134
+ return [...byId.values()].sort((a, b) => a.session_id.localeCompare(b.session_id));
135
+ }
136
+
137
+ /** Enumerate attachment objects under `<home>/attachments/<version>/objects/`. */
138
+ export function scanAttachments(dshHome) {
139
+ const root = path.join(dshHome, 'attachments');
140
+ const rows = [];
141
+ for (const version of listDirectories(root)) {
142
+ const objects = path.join(root, version.name, 'objects');
143
+ const stack = [objects];
144
+ while (stack.length > 0) {
145
+ const dir = stack.pop();
146
+ let entries;
147
+ try {
148
+ entries = fs.readdirSync(dir, { withFileTypes: true });
149
+ } catch {
150
+ continue;
151
+ }
152
+ for (const entry of entries) {
153
+ const full = path.join(dir, entry.name);
154
+ if (entry.isDirectory()) stack.push(full);
155
+ else if (entry.isFile()) {
156
+ let stat;
157
+ try { stat = fs.statSync(full); } catch { continue; }
158
+ rows.push({
159
+ file: full,
160
+ rel: path.relative(dshHome, full).replaceAll('\\', '/'),
161
+ size: stat.size,
162
+ mtime_ms: stat.mtimeMs,
163
+ attachment_id: path.relative(objects, full).replaceAll('\\', '/'),
164
+ });
165
+ }
166
+ }
167
+ }
168
+ }
169
+ return rows;
170
+ }
171
+
172
+ /**
173
+ * Profile and state files that make up "DSH configuration".
174
+ * Account material, plugin caches, node_modules, backups and lockfiles are
175
+ * deliberately absent; see `exclusions` for the reason list written into the
176
+ * restore point.
177
+ */
178
+ export function scanConfig(dshHome, profile = 'desktop') {
179
+ const pdir = profileDir(dshHome, profile);
180
+ const files = [];
181
+ for (const name of PROFILE_CONFIG_FILES) {
182
+ const file = path.join(pdir, name);
183
+ try {
184
+ const stat = fs.statSync(file);
185
+ if (!stat.isFile()) continue;
186
+ files.push({
187
+ file,
188
+ rel: path.relative(dshHome, file).replaceAll('\\', '/'),
189
+ kind: 'config',
190
+ scope: 'config',
191
+ reason: `DSH profile ${name}`,
192
+ size: stat.size,
193
+ mtime_ms: stat.mtimeMs,
194
+ });
195
+ } catch { /* absent is normal */ }
196
+ }
197
+ const storages = path.join(dshHome, 'storages');
198
+ let entries = [];
199
+ try { entries = fs.readdirSync(storages, { withFileTypes: true }); } catch { /* no storages */ }
200
+ for (const entry of entries) {
201
+ if (!entry.isFile() || !entry.name.endsWith('.json')) continue;
202
+ if (entry.name === 'workspace.json' || entry.name.includes('.bak-')) continue;
203
+ const file = path.join(storages, entry.name);
204
+ let stat;
205
+ try { stat = fs.statSync(file); } catch { continue; }
206
+ files.push({
207
+ file,
208
+ rel: path.relative(dshHome, file).replaceAll('\\', '/'),
209
+ kind: 'state',
210
+ scope: 'state',
211
+ reason: `DSH state ${entry.name}`,
212
+ size: stat.size,
213
+ mtime_ms: stat.mtimeMs,
214
+ });
215
+ }
216
+ return files;
217
+ }
218
+
219
+ /** Full inventory; `includeConfig` is applied by the caller, not here. */
220
+ export function scanHome(input = {}) {
221
+ const dshHome = resolveDshHome(input.dshHome);
222
+ const profile = typeof input.profile === 'string' && input.profile !== '' ? input.profile : 'desktop';
223
+ const registry = readRegistry(dshHome);
224
+ return {
225
+ dshHome,
226
+ profile,
227
+ profile_dir: profileDir(dshHome, profile),
228
+ registry,
229
+ sessions: scanSessions(dshHome, registry),
230
+ attachments: scanAttachments(dshHome),
231
+ config: scanConfig(dshHome, profile),
232
+ exists: fs.existsSync(dshHome),
233
+ };
234
+ }
235
+
236
+ /** Exclusions written into a restore point so a human knows what is intentionally absent. */
237
+ export function scanExclusions() {
238
+ return [
239
+ '账户与凭据:.credentials.yaml、.anonymous-user-id、xclient/device.key、llm-deepseek 会话令牌',
240
+ '插件缓存与隔离区:plugin-quarantine、cache、logs、dsh-runtimes',
241
+ 'profile 的 node_modules、pnpm-lock.yaml 与 .bak-* 备份文件',
242
+ '插件私有数据目录(w2m、fang、im、dshm、teams-v2 等)不纳入“DSH 配置”',
243
+ ];
244
+ }
@@ -0,0 +1,448 @@
1
+ /**
2
+ * Product service behind the DSH UI.
3
+ *
4
+ * It owns the two visible stores (`manual/` and `auto/`), the imported store,
5
+ * the automatic schedule, settings persistence and the plugin inventory the
6
+ * settings row renders. Lower-level modules only know file formats.
7
+ */
8
+
9
+ import fs from 'node:fs';
10
+ import os from 'node:os';
11
+ import path from 'node:path';
12
+
13
+ import {
14
+ CODES,
15
+ categoryDir,
16
+ createRestorePoint,
17
+ defaultRoot,
18
+ estimateRestorePoint,
19
+ importRestorePoint,
20
+ listCategory,
21
+ readRestorePoint,
22
+ resolveRoot,
23
+ rootIsDefaultable,
24
+ selectSessions,
25
+ } from './point.mjs';
26
+ import { readProfilePlugins } from './plugins.mjs';
27
+ import { planRestore, restorePoint } from './restore.mjs';
28
+ import { normalizeRegistry } from './scan.mjs';
29
+ import { atomicWriteJson, ensureDir, readJson } from './util/fs.mjs';
30
+ import { profileDir, resolveDshHome } from './util/paths.mjs';
31
+
32
+ export const DEFAULT_SETTINGS = Object.freeze({
33
+ root: '',
34
+ autoEnabled: false,
35
+ autoTime: '22:00',
36
+ keepManual: 2,
37
+ keepAuto: 2,
38
+ sessionScope: 'active',
39
+ includeConfig: true,
40
+ includePlugins: true,
41
+ includeSessions: true,
42
+ includePluginPackages: false,
43
+ includeAttachments: true,
44
+ profile: 'desktop',
45
+ });
46
+
47
+ function oneOf(value, allowed, fallback) {
48
+ return allowed.includes(value) ? value : fallback;
49
+ }
50
+
51
+ function keepCount(value, fallback) {
52
+ return Number.isSafeInteger(value) && value > 0 && value <= 20 ? value : fallback;
53
+ }
54
+
55
+ /** Unknown keys are dropped; every value is range-checked. */
56
+ export function normalizeSettings(raw) {
57
+ const value = raw !== null && typeof raw === 'object' ? raw : {};
58
+ const time = typeof value.autoTime === 'string' && /^([01]\d|2[0-3]):[0-5]\d$/u.test(value.autoTime)
59
+ ? value.autoTime
60
+ : DEFAULT_SETTINGS.autoTime;
61
+ return {
62
+ root: typeof value.root === 'string' ? value.root.trim() : DEFAULT_SETTINGS.root,
63
+ autoEnabled: value.autoEnabled === true,
64
+ autoTime: time,
65
+ keepManual: keepCount(value.keepManual, DEFAULT_SETTINGS.keepManual),
66
+ keepAuto: keepCount(value.keepAuto, DEFAULT_SETTINGS.keepAuto),
67
+ sessionScope: oneOf(value.sessionScope, ['active', 'all', 'archived'], DEFAULT_SETTINGS.sessionScope),
68
+ includeConfig: value.includeConfig !== false,
69
+ includePlugins: value.includePlugins !== false,
70
+ includeSessions: value.includeSessions !== false,
71
+ includePluginPackages: value.includePluginPackages === true,
72
+ includeAttachments: value.includeAttachments !== false,
73
+ profile: typeof value.profile === 'string' && value.profile !== '' ? value.profile : DEFAULT_SETTINGS.profile,
74
+ };
75
+ }
76
+
77
+ export function settingsFile(dshHome, profile = 'desktop') {
78
+ return path.join(profileDir(dshHome, profile), '.timemachine', 'settings.json');
79
+ }
80
+
81
+ /** Settings live in the profile, never inside the restore-point root. */
82
+ export function readSettings(dshHome, profile = 'desktop') {
83
+ const stored = readStoredSettings(dshHome, profile);
84
+ return { ...DEFAULT_SETTINGS, ...(stored ?? {}) };
85
+ }
86
+
87
+ function readStoredSettings(dshHome, profile = 'desktop') {
88
+ const file = settingsFile(dshHome, profile);
89
+ const raw = readJson(file, null);
90
+ if (raw === null || typeof raw !== 'object') return null;
91
+ return normalizeSettings(raw);
92
+ }
93
+
94
+ export function writeSettings(dshHome, profile, patch) {
95
+ const current = readSettings(dshHome, profile);
96
+ const next = normalizeSettings({ ...current, ...patch, profile: current.profile });
97
+ const file = settingsFile(dshHome, profile);
98
+ ensureDir(path.dirname(file));
99
+ atomicWriteJson(file, next);
100
+ return next;
101
+ }
102
+
103
+ /**
104
+ * Stored UI settings win over the plugin row config, except that an empty
105
+ * stored root falls back to the configured root. This lets a user change a
106
+ * value in the UI and still keep it after a host restart.
107
+ */
108
+ function mergeSettings(rawConfig, dshHome) {
109
+ const configured = normalizeSettings(rawConfig ?? {});
110
+ const stored = readStoredSettings(dshHome, configured.profile);
111
+ if (stored === null) return configured;
112
+ const root = stored.root !== '' ? stored.root : (rawConfig?.root ?? '');
113
+ return normalizeSettings({ ...configured, ...stored, root, profile: stored.profile });
114
+ }
115
+
116
+ /** Where a remembered root lives across restarts. */
117
+ function effectiveRoot(settings) {
118
+ const fromSettings = typeof settings.root === 'string' ? settings.root.trim() : '';
119
+ return resolveRoot(fromSettings);
120
+ }
121
+
122
+ function canWrite(root) {
123
+ try {
124
+ fs.mkdirSync(root, { recursive: true });
125
+ const probe = path.join(root, `.timemachine-probe-${process.pid}`);
126
+ fs.writeFileSync(probe, 'ok');
127
+ fs.rmSync(probe, { force: true });
128
+ return true;
129
+ } catch {
130
+ return false;
131
+ }
132
+ }
133
+
134
+ function pluginInventory(dshHome, profile) {
135
+ const info = readProfilePlugins({ dshHome, profile });
136
+ if (!info.ok) return { ok: false, detail: info.detail, profile_dir: info.profile_dir, user: [], third_party: [] };
137
+ let patchText = '';
138
+ try { patchText = fs.readFileSync(path.join(profileDir(dshHome, profile), 'cordis.patch.yml'), 'utf8'); } catch { patchText = ''; }
139
+ const user = info.all_plugins
140
+ .filter((row) => row.kind === 'official' || row.kind === 'experimental' || row.kind === 'self')
141
+ .map((row) => ({
142
+ name: row.name,
143
+ version: row.version,
144
+ kind: row.kind,
145
+ enabled: row.enabled,
146
+ in_bundles: row.source === 'bundle',
147
+ config_yaml: pluginSection(patchText, row.name),
148
+ }));
149
+ return {
150
+ ok: true,
151
+ profile_dir: info.profile_dir,
152
+ patch_file: path.join(info.profile_dir, 'cordis.patch.yml'),
153
+ user,
154
+ third_party: info.plugins,
155
+ };
156
+ }
157
+
158
+ /** The YAML block for one plugin name, shown read-only in the UI. */
159
+ export function pluginSection(text, name) {
160
+ const lines = String(text ?? '').split(/\r?\n/u);
161
+ const blocks = [];
162
+ let current = null;
163
+ for (const line of lines) {
164
+ if (/^\s*-\s+id:/u.test(line)) {
165
+ if (current !== null) blocks.push(current);
166
+ current = [line];
167
+ } else if (current !== null) {
168
+ current.push(line);
169
+ }
170
+ }
171
+ if (current !== null) blocks.push(current);
172
+ for (const block of blocks) {
173
+ if (block.some((line) => new RegExp(`^\\s*name:\\s*['"]?${escapeRegExp(name)}['"]?\\s*$`, 'u').test(line))) {
174
+ return block.join('\n').trimEnd();
175
+ }
176
+ }
177
+ return '';
178
+ }
179
+
180
+ function escapeRegExp(value) {
181
+ return String(value).replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
182
+ }
183
+
184
+ /** Everything the settings row and the panel need in one call. */
185
+ export function getStatus(rawConfig, options = {}) {
186
+ const dshHome = resolveDshHome(options.dshHome ?? rawConfig?.dshHome);
187
+ const merged = mergeSettings(rawConfig, dshHome);
188
+ const root = effectiveRoot(merged);
189
+ const profile = merged.profile;
190
+ const inventory = pluginInventory(dshHome, profile);
191
+ const scan = estimateRestorePoint({ dshHome, profile, sessionScope: merged.sessionScope });
192
+ const stores = {
193
+ manual: root === '' ? [] : listCategory(root, 'manual'),
194
+ auto: root === '' ? [] : listCategory(root, 'auto'),
195
+ imported: root === '' ? [] : listCategory(root, 'imported'),
196
+ };
197
+ const registry = normalizeRegistry(readJson(path.join(dshHome, 'storages', 'workspace.json'), null));
198
+ return {
199
+ ok: true,
200
+ platform: process.platform,
201
+ platform_label: process.platform === 'win32' ? 'Windows' : process.platform === 'darwin' ? 'macOS' : 'Linux',
202
+ dsh_home: dshHome,
203
+ profile,
204
+ profile_ok: inventory.ok,
205
+ profile_dir: inventory.profile_dir,
206
+ root,
207
+ root_default: defaultRoot(),
208
+ root_is_default: root === defaultRoot(),
209
+ root_chosen: root !== '',
210
+ root_defaultable: rootIsDefaultable(),
211
+ root_writable: root !== '' && canWrite(root),
212
+ settings: merged,
213
+ stores: {
214
+ manual: { dir: root === '' ? null : categoryDir(root, 'manual'), points: stores.manual },
215
+ auto: { dir: root === '' ? null : categoryDir(root, 'auto'), points: stores.auto },
216
+ imported: { dir: root === '' ? null : categoryDir(root, 'imported'), points: stores.imported },
217
+ },
218
+ counts: {
219
+ manual: stores.manual.length,
220
+ auto: stores.auto.length,
221
+ imported: stores.imported.length,
222
+ sessions: scan.sessions,
223
+ archived: scan.archived,
224
+ plugins: inventory.third_party.length,
225
+ },
226
+ estimate: scan,
227
+ plugins: {
228
+ user: inventory.user,
229
+ third_party: inventory.third_party,
230
+ },
231
+ workspaces: registry.workspaces.map((workspace) => ({
232
+ id: workspace.id,
233
+ title: workspace.title,
234
+ path: workspace.path,
235
+ sessions: workspace.sessionIds.length,
236
+ })),
237
+ last_auto: readLastAuto(dshHome, profile),
238
+ advanced: { plugin_packages_supported: true },
239
+ };
240
+ }
241
+
242
+ function readLastAuto(dshHome, profile) {
243
+ const raw = readJson(path.join(profileDir(dshHome, profile), '.timemachine', 'last-auto.json'), null);
244
+ return raw !== null && typeof raw === 'object' ? raw : null;
245
+ }
246
+
247
+ function writeLastAuto(dshHome, profile, value) {
248
+ const file = path.join(profileDir(dshHome, profile), '.timemachine', 'last-auto.json');
249
+ try {
250
+ ensureDir(path.dirname(file));
251
+ atomicWriteJson(file, value);
252
+ } catch {
253
+ // The point file itself is the artifact; a bookkeeping failure must not hide it.
254
+ }
255
+ }
256
+
257
+ export function getEstimate(rawConfig, options = {}) {
258
+ const dshHome = resolveDshHome(options.dshHome ?? rawConfig?.dshHome);
259
+ const merged = mergeSettings(rawConfig, dshHome);
260
+ return estimateRestorePoint({ dshHome, profile: merged.profile, sessionScope: merged.sessionScope });
261
+ }
262
+
263
+ function pointInput(merged, dshHome, kind, options) {
264
+ return {
265
+ dshHome,
266
+ root: effectiveRoot(merged),
267
+ kind,
268
+ profile: merged.profile,
269
+ sessionScope: merged.sessionScope,
270
+ includeConfig: merged.includeConfig,
271
+ includePlugins: merged.includePlugins,
272
+ includeSessions: merged.includeSessions,
273
+ includeAttachments: merged.includeAttachments,
274
+ includePluginPackages: merged.includePluginPackages,
275
+ keep: kind === 'auto' ? merged.keepAuto : merged.keepManual,
276
+ runner: options.runner,
277
+ onProgress: options.onProgress,
278
+ };
279
+ }
280
+
281
+ /** One click from the settings row / panel. */
282
+ export async function createManual(rawConfig, options = {}) {
283
+ const dshHome = resolveDshHome(options.dshHome ?? rawConfig?.dshHome);
284
+ const merged = mergeSettings(rawConfig, dshHome);
285
+ const root = effectiveRoot(merged);
286
+ if (root === '') return { ok: false, reason_code: CODES.ROOT_REQUIRED, detail: '请先选择还原点保存文件夹' };
287
+ return createRestorePoint(pointInput(merged, dshHome, 'manual', options));
288
+ }
289
+
290
+ export async function createAuto(rawConfig, options = {}) {
291
+ const dshHome = resolveDshHome(options.dshHome ?? rawConfig?.dshHome);
292
+ const merged = mergeSettings(rawConfig, dshHome);
293
+ const root = effectiveRoot(merged);
294
+ if (root === '') return { ok: false, reason_code: CODES.ROOT_REQUIRED, detail: '请先选择还原点保存文件夹' };
295
+ const result = await createRestorePoint(pointInput(merged, dshHome, 'auto', options));
296
+ const now = new Date().toISOString();
297
+ writeLastAuto(dshHome, merged.profile, result.ok
298
+ ? { at: now, file: result.file, bytes: result.bytes, ok: true }
299
+ : { at: now, ok: false, error: result.detail ?? result.reason_code });
300
+ return result;
301
+ }
302
+
303
+ /** Validate a point and return the restore plan without touching the live home. */
304
+ export function plan(rawConfig, body, options = {}) {
305
+ const file = typeof body?.file === 'string' ? body.file.trim() : '';
306
+ if (file === '') return { ok: false, reason_code: 'TIMEMACHINE_FILE_REQUIRED', detail: 'body.file is required' };
307
+ const dshHome = resolveDshHome(options.dshHome ?? rawConfig?.dshHome);
308
+ const merged = mergeSettings(rawConfig, dshHome);
309
+ return planRestore({
310
+ file,
311
+ dshHome,
312
+ profile: merged.profile,
313
+ includeSessions: body?.includeSessions ?? merged.includeSessions,
314
+ includeConfig: body?.includeConfig ?? merged.includeConfig,
315
+ includePlugins: body?.includePlugins ?? merged.includePlugins,
316
+ useSavedPackages: body?.useSavedPackages === true,
317
+ pathMap: Array.isArray(body?.pathMap) ? body.pathMap : [],
318
+ allowInvalidSessions: body?.allowInvalidSessions === true,
319
+ });
320
+ }
321
+
322
+ /** Plan -> install plugins -> apply; caller must pass confirm. */
323
+ export async function restore(rawConfig, body, options = {}) {
324
+ const file = typeof body?.file === 'string' ? body.file.trim() : '';
325
+ if (file === '') return { ok: false, reason_code: 'TIMEMACHINE_FILE_REQUIRED', detail: 'body.file is required' };
326
+ const dshHome = resolveDshHome(options.dshHome ?? rawConfig?.dshHome);
327
+ const merged = mergeSettings(rawConfig, dshHome);
328
+ return restorePoint({
329
+ file,
330
+ dshHome,
331
+ profile: merged.profile,
332
+ includeSessions: body?.includeSessions ?? merged.includeSessions,
333
+ includeConfig: body?.includeConfig ?? merged.includeConfig,
334
+ includePlugins: body?.includePlugins ?? merged.includePlugins,
335
+ installPlugins: body?.installPlugins !== false,
336
+ useSavedPackages: body?.useSavedPackages === true,
337
+ pathMap: Array.isArray(body?.pathMap) ? body.pathMap : [],
338
+ allowInvalidSessions: body?.allowInvalidSessions === true,
339
+ runner: options.runner,
340
+ pnpmFile: options.pnpmFile,
341
+ onProgress: options.onProgress,
342
+ workspaceRegistry: options.workspaceRegistry ?? options.getWorkspaceRegistry?.(),
343
+ });
344
+ }
345
+
346
+ export function importPoint(rawConfig, body, options = {}) {
347
+ const file = typeof body?.file === 'string' ? body.file.trim() : '';
348
+ if (file === '') return { ok: false, reason_code: 'TIMEMACHINE_FILE_REQUIRED', detail: 'body.file is required' };
349
+ const dshHome = resolveDshHome(options.dshHome ?? rawConfig?.dshHome);
350
+ const merged = mergeSettings(rawConfig, dshHome);
351
+ const root = effectiveRoot(merged);
352
+ if (root === '') return { ok: false, reason_code: CODES.ROOT_REQUIRED, detail: '请先选择还原点保存文件夹' };
353
+ return importRestorePoint({ root, file });
354
+ }
355
+
356
+ /** Persist settings and return the fresh status so both UI surfaces agree. */
357
+ export function saveSettings(rawConfig, patch, options = {}) {
358
+ const dshHome = resolveDshHome(options.dshHome ?? rawConfig?.dshHome);
359
+ const base = mergeSettings(rawConfig, dshHome);
360
+ const current = readSettings(dshHome, base.profile);
361
+ const next = writeSettings(dshHome, base.profile, {
362
+ ...current,
363
+ ...patch,
364
+ root: patch?.root ?? (current.root !== '' ? current.root : base.root),
365
+ });
366
+ return { ok: true, settings: next, status: getStatus({ ...(rawConfig ?? {}), profile: base.profile }, { dshHome }) };
367
+ }
368
+
369
+ export function pickerUnavailable(what) {
370
+ return {
371
+ ok: false,
372
+ reason_code: 'TIMEMACHINE_PICKER_IN_CLIENT',
373
+ detail: `${what} picker 在客户端弹窗(Electron 主进程不向插件开放目录对话框)`,
374
+ };
375
+ }
376
+
377
+ /** 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() : '';
380
+ if (file === '') return { ok: false, reason_code: 'TIMEMACHINE_FILE_REQUIRED', detail: 'body.file is required' };
381
+ const row = readRestorePoint(file);
382
+ if (!row.ok) return row;
383
+ const names = new Set((row.manifest.files ?? []).filter((item) => item.kind === 'session').map((item) => item.session_id));
384
+ return {
385
+ ok: true,
386
+ file: row.file,
387
+ bytes: row.bytes,
388
+ sha256: row.sha256,
389
+ point: row.point,
390
+ counts: row.counts,
391
+ sessions: (row.point.sessions ?? []).filter((session) => names.has(session.session_id)),
392
+ workspaces: row.point.workspaces ?? [],
393
+ plugins: row.point.plugins ?? [],
394
+ user_plugins: row.point.all_plugins ?? [],
395
+ has_plugin_packages: Object.keys(row.point.plugin_package_files ?? {}).length > 0,
396
+ };
397
+ }
398
+
399
+ export function selectForScope(sessions, scope) {
400
+ return selectSessions(sessions, scope);
401
+ }
402
+
403
+ /**
404
+ * Local-time scheduler. Fires once per matching minute, records the slot so a
405
+ * restart inside the same minute does not create duplicates, and unrefs the
406
+ * timer so it never keeps the host process alive.
407
+ */
408
+ export function startAutoScheduler(input) {
409
+ let timer = null;
410
+ let stopped = false;
411
+ const tick = async () => {
412
+ if (stopped) return;
413
+ let delay = 30_000;
414
+ try {
415
+ const dshHome = resolveDshHome(input.dshHome);
416
+ const merged = mergeSettings(input.getConfig?.() ?? {}, dshHome);
417
+ if (merged.autoEnabled && effectiveRoot(merged) !== '') {
418
+ const now = new Date();
419
+ const hhmm = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
420
+ const slot = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${hhmm}`;
421
+ const marker = path.join(profileDir(dshHome, merged.profile), '.timemachine', 'auto-slot.txt');
422
+ let last = '';
423
+ try { last = fs.readFileSync(marker, 'utf8').trim(); } catch { last = ''; }
424
+ if (hhmm === merged.autoTime && last !== slot) {
425
+ ensureDir(path.dirname(marker));
426
+ fs.writeFileSync(marker, slot, 'utf8');
427
+ await input.onRun(merged);
428
+ delay = 30_000;
429
+ }
430
+ }
431
+ } catch (error) {
432
+ input.onError?.(error);
433
+ } finally {
434
+ if (!stopped) {
435
+ timer = setTimeout(tick, delay);
436
+ timer.unref?.();
437
+ }
438
+ }
439
+ };
440
+ timer = setTimeout(tick, 2_000);
441
+ timer.unref?.();
442
+ return () => {
443
+ stopped = true;
444
+ if (timer !== null) clearTimeout(timer);
445
+ };
446
+ }
447
+
448
+ export { os };