@xsok/dsh-enhanced 0.0.0-stage → 0.2.2-10

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,255 @@
1
+ /**
2
+ * `storages/workspace.json` merge for the pure-JS engine.
3
+ *
4
+ * Rules, matching `Merge-WorkspaceJson` in the PowerShell engine:
5
+ * - entries join by (localized) path, not by uuid;
6
+ * - the newer `updatedAt` is the base record, older unknowns fill the gaps;
7
+ * - `sessionIds` is a union, `createdAt` the earliest, tombstoned ids dropped;
8
+ * - the share gets every group, this machine only groups whose folder exists;
9
+ * - `global` keeps the union of archived/pinned, unknown fields preserved.
10
+ */
11
+ import { promises as fsp } from 'node:fs';
12
+ import path from 'node:path';
13
+ import { WORKSPACE_LEDGER, readJson as readLedgerJson, readLedger, writeJsonAtomic, writeLedger } from './ledger.js';
14
+
15
+ async function readJson(file) {
16
+ try {
17
+ const text = await fsp.readFile(file, 'utf8');
18
+ return { doc: JSON.parse(text), valid: true };
19
+ } catch (error) {
20
+ return { doc: null, valid: error?.code === 'ENOENT' };
21
+ }
22
+ }
23
+
24
+ function entriesOf(doc, source) {
25
+ const table = doc?.tables?.workspaces;
26
+ if (table === null || typeof table !== 'object') return [];
27
+ return Object.entries(table).map(([uuid, value]) => ({
28
+ uuid,
29
+ path: typeof value?.path === 'string' ? value.path : '',
30
+ title: typeof value?.title === 'string' ? value.title : '',
31
+ sessionIds: Array.isArray(value?.sessionIds) ? value.sessionIds.filter(Boolean) : [],
32
+ createdAt: typeof value?.createdAt === 'string' ? value.createdAt : '',
33
+ updatedAt: typeof value?.updatedAt === 'string' ? value.updatedAt : '',
34
+ source,
35
+ raw: value,
36
+ }));
37
+ }
38
+
39
+ function timeOf(value) {
40
+ const parsed = Date.parse(value ?? '');
41
+ return Number.isFinite(parsed) ? parsed : 0;
42
+ }
43
+
44
+ function unionInto(target, values) {
45
+ for (const value of values) {
46
+ if (value !== undefined && value !== null && !target.includes(value)) target.push(value);
47
+ }
48
+ return target;
49
+ }
50
+
51
+ /**
52
+ * Merge both documents.
53
+ * @param options - `resolvePath` localizes a remote path, `isDirectory` decides
54
+ * whether the group is registered locally, `tombstones` is a Set of session ids.
55
+ */
56
+ export async function mergeWorkspaceDocuments(localDoc, sharedDoc, options = {}) {
57
+ const {
58
+ resolvePath = (value) => value,
59
+ isDirectory = () => false,
60
+ tombstones = new Set(),
61
+ stateDir = null,
62
+ machineId = null,
63
+ apply = true,
64
+ sessionCwd = null,
65
+ } = options;
66
+
67
+ // Workspace deletions used to be silent: the other machine's document still
68
+ // listed the path, so the union added it back. A ledger plus a per-machine
69
+ // snapshot fixes that, and a workspace that reappears counts as restored.
70
+ const localEntries = entriesOf(localDoc, 'local');
71
+ let workspaceLedger = { version: 1, deleted: {} };
72
+ let snapshot = { paths: {} };
73
+ if (stateDir !== null && machineId !== null) {
74
+ workspaceLedger = await readLedger(stateDir, WORKSPACE_LEDGER);
75
+ snapshot = (await readLedgerJson(path.join(stateDir, `workspace-${machineId}.json`), undefined)) ?? { paths: {} };
76
+ const localByPath = new Map(localEntries.map((entry) => [entry.path, entry]));
77
+ const now = new Date().toISOString();
78
+ for (const [entryPath, info] of Object.entries(snapshot.paths ?? {})) {
79
+ if (entryPath === '') continue;
80
+ if (localByPath.has(entryPath)) continue;
81
+ const uuid = typeof info?.uuid === 'string' && info.uuid !== '' ? info.uuid : entryPath;
82
+ if (workspaceLedger.deleted[uuid] !== undefined) continue;
83
+ workspaceLedger.deleted[uuid] = { at: now, path: entryPath, title: info?.title ?? '', source: 'local' };
84
+ }
85
+ const localByUuid = new Map(localEntries.map((entry) => [entry.uuid, entry]));
86
+ for (const [uuid, record] of Object.entries(workspaceLedger.deleted)) {
87
+ const entry = localByUuid.get(uuid) ?? localByPath.get(record.path ?? '');
88
+ if (entry === undefined) continue;
89
+ if (timeOf(entry.updatedAt) > timeOf(record.at) + 1) delete workspaceLedger.deleted[uuid];
90
+ }
91
+ }
92
+
93
+ const deletedPaths = new Set(Object.values(workspaceLedger.deleted).map((record) => record.path).filter(Boolean));
94
+ const deletedUuids = new Set(Object.keys(workspaceLedger.deleted));
95
+
96
+ const merged = new Map();
97
+ for (const entry of [...localEntries, ...entriesOf(sharedDoc, 'shared')]) {
98
+ if (deletedUuids.has(entry.uuid) || (entry.path !== '' && deletedPaths.has(entry.path))) continue;
99
+ // The resolver is allowed to be async (the JS engine localizes remote
100
+ // paths through `fs.realpath`). Awaiting it is mandatory: a Promise stored
101
+ // in `path` serializes to `{}`, which the host's workspace schema rejects
102
+ // and then refuses to activate the whole registry.
103
+ const key = await resolvePath(entry.path);
104
+ if (typeof key !== 'string' || key === '') continue;
105
+ const current = merged.get(key);
106
+ if (current === undefined) {
107
+ merged.set(key, { ...entry, path: key, others: [] });
108
+ continue;
109
+ }
110
+ const newer = timeOf(entry.updatedAt) > timeOf(current.updatedAt);
111
+ if (newer) {
112
+ if (current.raw !== undefined) current.others.push(current.raw);
113
+ current.uuid = entry.uuid;
114
+ current.title = entry.title;
115
+ current.updatedAt = entry.updatedAt;
116
+ current.raw = entry.raw;
117
+ } else if (entry.raw !== undefined) {
118
+ current.others.push(entry.raw);
119
+ }
120
+ unionInto(current.sessionIds, entry.sessionIds);
121
+ if (timeOf(entry.createdAt) < timeOf(current.createdAt)) current.createdAt = entry.createdAt;
122
+ }
123
+
124
+ const shared = {};
125
+ const local = {};
126
+ const missing = [];
127
+ for (const entry of merged.values()) {
128
+ const ids = entry.sessionIds.filter((id) => !tombstones.has(id));
129
+ const record = { ...(entry.raw ?? {}) };
130
+ for (const other of entry.others) {
131
+ for (const [field, value] of Object.entries(other ?? {})) {
132
+ if (!(field in record)) record[field] = value;
133
+ }
134
+ }
135
+ record.path = entry.path;
136
+ // Never let a non-string path reach the document: the host validates every
137
+ // record with `path: z.string()` at startup, and a single bad value kills
138
+ // the whole workspace registry service.
139
+ if (typeof record.path !== 'string' || record.path === '') continue;
140
+ record.title = entry.title;
141
+ record.sessionIds = ids;
142
+ if (entry.createdAt !== '') record.createdAt = entry.createdAt;
143
+ if (entry.updatedAt !== '') record.updatedAt = entry.updatedAt;
144
+ shared[entry.uuid] = record;
145
+ if (await isDirectory(entry.path)) local[entry.uuid] = record;
146
+ else missing.push({ title: entry.title, path: entry.path });
147
+ }
148
+
149
+ // A session belongs to one workspace only. Older merges unioned membership, so a
150
+ // moved session stayed listed under its previous workspace; resolve the real one
151
+ // from the session header and drop the rest.
152
+ if (typeof sessionCwd === 'function') {
153
+ const owners = new Map();
154
+ for (const [uuid, record] of Object.entries(shared)) {
155
+ for (const id of record.sessionIds) {
156
+ const list = owners.get(id) ?? [];
157
+ list.push(uuid);
158
+ owners.set(id, list);
159
+ }
160
+ }
161
+ for (const [id, uuids] of owners) {
162
+ if (uuids.length < 2) continue;
163
+ let cwd = null;
164
+ try {
165
+ cwd = await sessionCwd(id);
166
+ } catch {
167
+ cwd = null;
168
+ }
169
+ const normalized = typeof cwd === 'string' && cwd !== '' ? await resolvePath(cwd) : null;
170
+ const keep = normalized === null
171
+ ? uuids[0]
172
+ : (uuids.find((uuid) => shared[uuid]?.path === normalized) ?? uuids[0]);
173
+ for (const uuid of uuids) {
174
+ if (uuid === keep) continue;
175
+ shared[uuid].sessionIds = shared[uuid].sessionIds.filter((value) => value !== id);
176
+ }
177
+ }
178
+ }
179
+
180
+ const archived = [];
181
+ const pinned = [];
182
+ let initialized = false;
183
+ const extraGlobal = {};
184
+ for (const doc of [localDoc, sharedDoc]) {
185
+ const global = doc?.global;
186
+ if (global === null || typeof global !== 'object') continue;
187
+ if (global.initialized === true) initialized = true;
188
+ unionInto(archived, (Array.isArray(global.archivedSessionIds) ? global.archivedSessionIds : []).filter((id) => id && !tombstones.has(id)));
189
+ unionInto(pinned, (Array.isArray(global.pinnedSessionIds) ? global.pinnedSessionIds : []).filter((id) => id && !tombstones.has(id)));
190
+ for (const [field, value] of Object.entries(global)) {
191
+ if (['initialized', 'workspaceIds', 'archivedSessionIds', 'pinnedSessionIds'].includes(field)) continue;
192
+ if (!(field in extraGlobal)) extraGlobal[field] = value;
193
+ }
194
+ }
195
+
196
+ // The document schema version must never go backwards: a newer app would
197
+ // otherwise re-run its migration against data it already migrated.
198
+ let unitName = 'workspace';
199
+ let unitVersion = 2;
200
+ for (const doc of [localDoc, sharedDoc]) {
201
+ if (doc?.unit === null || typeof doc?.unit !== 'object') continue;
202
+ if (typeof doc.unit.name === 'string' && doc.unit.name !== '') unitName = doc.unit.name;
203
+ if (Number(doc.unit.version) > unitVersion) unitVersion = Number(doc.unit.version);
204
+ }
205
+
206
+ const preferredOrder = (() => {
207
+ const fromLocal = Array.isArray(localDoc?.global?.workspaceIds) ? localDoc.global.workspaceIds : [];
208
+ const fromShared = Array.isArray(sharedDoc?.global?.workspaceIds) ? sharedDoc.global.workspaceIds : [];
209
+ return fromLocal.length > 0 ? fromLocal : fromShared;
210
+ })();
211
+ const orderOf = (workspaces) => {
212
+ const present = Object.keys(workspaces);
213
+ const ordered = preferredOrder.filter((id) => present.includes(id));
214
+ for (const id of present) if (!ordered.includes(id)) ordered.push(id);
215
+ return ordered;
216
+ };
217
+
218
+ const build = (workspaces) => {
219
+ const doc = JSON.parse(JSON.stringify(localDoc ?? sharedDoc ?? {}));
220
+ doc.unit = { name: unitName, version: unitVersion };
221
+ doc.tables = doc.tables ?? {};
222
+ doc.tables.workspaces = workspaces;
223
+ doc.global = { ...(doc.global ?? {}), ...extraGlobal, initialized, workspaceIds: orderOf(workspaces), archivedSessionIds: archived, pinnedSessionIds: pinned };
224
+ return doc;
225
+ };
226
+
227
+ if (apply && stateDir !== null && machineId !== null) {
228
+ const pathsNow = {};
229
+ for (const entry of entriesOf(localDoc, 'local')) {
230
+ if (entry.path !== '') pathsNow[entry.path] = { uuid: entry.uuid, title: entry.title };
231
+ }
232
+ // Re-read the local document after the merge so a restored group is recorded.
233
+ for (const value of Object.values(local)) {
234
+ if (typeof value?.path === 'string' && value.path !== '') {
235
+ pathsNow[value.path] = { uuid: pathsNow[value.path]?.uuid ?? '', title: value.title ?? '' };
236
+ }
237
+ }
238
+ await writeJsonAtomic(path.join(stateDir, `workspace-${machineId}.json`), { version: 1, machine: machineId, paths: pathsNow, updatedAt: new Date().toISOString() });
239
+ await writeLedger(stateDir, WORKSPACE_LEDGER, workspaceLedger);
240
+ }
241
+
242
+ return { shared: build(shared), local: build(local), missing, unitVersion, deleted: deletedUuids.size };
243
+ }
244
+
245
+ /** Read both files, merge, and return the two documents plus the missing folders. */
246
+ export async function mergeWorkspaceFiles(deps) {
247
+ const { localFile, sharedFile, ...rest } = deps;
248
+ const localRead = await readJson(localFile);
249
+ const sharedRead = await readJson(sharedFile);
250
+ if (!localRead.valid || !sharedRead.valid) {
251
+ return { skipped: 'workspace.json 无效或正在写入,本次不合并', missing: [] };
252
+ }
253
+ if (localRead.doc === null && sharedRead.doc === null) return { skipped: '两侧都没有 workspace.json', missing: [] };
254
+ return await mergeWorkspaceDocuments(localRead.doc, sharedRead.doc, rest);
255
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Multi-frame zstd container used by DSH session logs.
3
+ *
4
+ * Node's zstd decoder stops at the first frame, so the frame boundaries have to
5
+ * be walked by hand. The algorithm matches `tools/dsh-zstd-helper.js` and DSH's
6
+ * own `scanZstdFrames`: a truncated tail (an append interrupted by a crash) is
7
+ * dropped instead of failing the whole file.
8
+ */
9
+ import zlib from 'node:zlib';
10
+
11
+ const ZSTD_MAGIC = 4247762216; // 0xFD2FB528 little-endian
12
+
13
+ /** Frame byte ranges of one buffer; empty when the file holds no complete frame. */
14
+ export function scanFrames(buf) {
15
+ const frames = [];
16
+ let offset = 0;
17
+ while (offset < buf.length) {
18
+ const start = offset;
19
+ if (buf.length - offset < 4 || buf.readUInt32LE(offset) !== ZSTD_MAGIC) break;
20
+ offset += 4;
21
+ if (offset === buf.length) break;
22
+ const descriptor = buf.readUInt8(offset);
23
+ offset += 1;
24
+ if ((descriptor & 24) !== 0) break;
25
+ const contentSizeFlag = descriptor >>> 6;
26
+ const singleSegment = (descriptor & 32) !== 0;
27
+ const checksum = (descriptor & 4) !== 0;
28
+ const dictionaryFlag = descriptor & 3;
29
+ const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag;
30
+ const contentSizeBytes = contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : 1 << contentSizeFlag;
31
+ const remainingHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes;
32
+ if (buf.length - offset < remainingHeaderBytes) break;
33
+ offset += remainingHeaderBytes;
34
+ for (;;) {
35
+ if (buf.length - offset < 3) return frames;
36
+ const blockHeader = buf.readUIntLE(offset, 3);
37
+ offset += 3;
38
+ const lastBlock = (blockHeader & 1) !== 0;
39
+ const blockType = (blockHeader >>> 1) & 3;
40
+ const blockSize = blockHeader >>> 3;
41
+ if (blockType === 3) return frames;
42
+ const payloadBytes = blockType === 1 ? 1 : blockSize;
43
+ if (buf.length - offset < payloadBytes) return frames;
44
+ offset += payloadBytes;
45
+ if (lastBlock) break;
46
+ }
47
+ if (checksum) {
48
+ if (buf.length - offset < 4) return frames;
49
+ offset += 4;
50
+ }
51
+ frames.push({ start, end: offset });
52
+ }
53
+ return frames;
54
+ }
55
+
56
+ /** Concatenated plaintext of every complete frame. */
57
+ export function decodeFrames(buf, frames = scanFrames(buf)) {
58
+ const parts = [];
59
+ for (const frame of frames) {
60
+ parts.push(zlib.zstdDecompressSync(buf.subarray(frame.start, frame.end)));
61
+ }
62
+ return Buffer.concat(parts);
63
+ }
64
+
65
+ /** Whole-file decode; a plain .jsonl file is returned as-is. */
66
+ export function decodeBuffer(buf, isZstd = true) {
67
+ if (!isZstd) return buf;
68
+ const frames = scanFrames(buf);
69
+ if (frames.length === 0) throw Object.assign(new Error('文件中没有完整的 zstd 帧(可能是残缺写入)'), { code: 'zstd-empty' });
70
+ return decodeFrames(buf, frames);
71
+ }
72
+
73
+ /** Compress one frame's plaintext as a single zstd frame. */
74
+ export function encodeFrame(text) {
75
+ return zlib.zstdCompressSync(Buffer.from(text, 'utf8'));
76
+ }
77
+
78
+ /** Compress one line as its own frame, matching the append semantics. */
79
+ export function encodeLine(line) {
80
+ return zlib.zstdCompressSync(Buffer.from(`${line}\n`, 'utf8'));
81
+ }
82
+
83
+ /** Compress a list of lines into one multi-frame container. */
84
+ export function encodeLines(lines) {
85
+ return Buffer.concat(lines.map((line) => encodeLine(line)));
86
+ }
87
+
88
+ /** Split decoded text into non-empty lines. */
89
+ export function splitLines(text) {
90
+ return text.split('\n').filter((line) => line !== '');
91
+ }
@@ -0,0 +1,289 @@
1
+ /**
2
+ * Environment self-check for DSH增强.
3
+ *
4
+ * Everything the plugin relies on but does not own is probed here: host services,
5
+ * the Node features the engine needs, and the on-disk formats it reads and writes.
6
+ * A failed check never throws; it is reported so the user can export a report.
7
+ */
8
+ import { promises as fsp } from 'node:fs';
9
+ import { pluginVersion } from './version.js';
10
+ import path from 'node:path';
11
+ import os from 'node:os';
12
+ import zlib from 'node:zlib';
13
+ import { scanFrames } from './engine/zstd.js';
14
+ import { scanSessions, projectKey } from './engine/scan.js';
15
+
16
+
17
+
18
+ async function readJson(file) {
19
+ try {
20
+ return JSON.parse(await fsp.readFile(file, 'utf8'));
21
+ } catch {
22
+ return undefined;
23
+ }
24
+ }
25
+
26
+ async function exists(target) {
27
+ try {
28
+ await fsp.access(target);
29
+ return true;
30
+ } catch {
31
+ return false;
32
+ }
33
+ }
34
+
35
+ /** Best-effort host application version: env first, then the packaged manifest. */
36
+ export async function appVersion() {
37
+ const candidates = [
38
+ process.env.DSH_CLIENT_VERSION,
39
+ process.env.DSH_APP_VERSION,
40
+ process.env.DSH_VERSION,
41
+ ];
42
+ for (const value of candidates) {
43
+ if (typeof value === 'string' && value.trim() !== '') return { version: value.trim(), source: 'env' };
44
+ }
45
+ const resources = [
46
+ typeof process.resourcesPath === 'string' ? process.resourcesPath : null,
47
+ process.execPath === undefined ? null : path.join(path.dirname(process.execPath), 'resources'),
48
+ ].filter(Boolean);
49
+ for (const base of resources) {
50
+ for (const entry of ['app.asar', 'app']) {
51
+ const manifest = path.join(base, entry, 'package.json');
52
+ const doc = await readJson(manifest);
53
+ if (typeof doc?.version === 'string' && doc.version !== '') {
54
+ return { version: doc.version, source: manifest };
55
+ }
56
+ }
57
+ }
58
+ return { version: null, source: 'unknown' };
59
+ }
60
+
61
+ function check(id, label, ok, detail, severity = 'high') {
62
+ return { id, label, ok, detail, severity };
63
+ }
64
+
65
+ /**
66
+ * Run every probe.
67
+ * @returns `{ ok, checks, appVersion, pluginVersion, checkedAt }`.
68
+ */
69
+ export async function runEnvironmentCheck(deps) {
70
+ const { paths, ctx } = deps;
71
+ const checks = [];
72
+
73
+ // 1. host services the plugin injects
74
+ const services = ['webServer', 'connection', 'sessionPersistence', 'workspaceRegistry'];
75
+ for (const key of services) {
76
+ const service = ctx?.get?.(key);
77
+ checks.push(check(`service:${key}`, `宿主服务 ${key}`, service !== undefined, service === undefined ? '未注册(插件可能无法正常工作)' : '可用'));
78
+ }
79
+
80
+ const registry = ctx?.get?.('workspaceRegistry');
81
+ const registryMethods = ['get', 'list', 'resolveByPath', 'unpinSession', 'unarchiveSession'];
82
+ const missingRegistry = registry === undefined ? registryMethods : registryMethods.filter((name) => typeof registry[name] !== 'function');
83
+ checks.push(check('methods:workspaceRegistry', '工作区注册表方法完整', missingRegistry.length === 0, missingRegistry.length === 0 ? '全部存在' : `缺少:${missingRegistry.join('、')}`));
84
+
85
+ // Membership edits live on one Workspace instance, not on the registry.
86
+ const workspaceMethods = ['attachSession', 'detachSession', 'insertSessionBefore'];
87
+ let sampleWorkspace;
88
+ try {
89
+ sampleWorkspace = registry?.list?.()[0];
90
+ } catch {
91
+ sampleWorkspace = undefined;
92
+ }
93
+ if (sampleWorkspace === undefined) {
94
+ checks.push(check('methods:workspace', '工作区成员接口', true, '暂无工作区,跳过该项', 'low'));
95
+ } else {
96
+ const missingWorkspace = workspaceMethods.filter((name) => typeof sampleWorkspace[name] !== 'function');
97
+ checks.push(check('methods:workspace', '工作区成员接口', missingWorkspace.length === 0, missingWorkspace.length === 0 ? '全部存在' : `缺少:${missingWorkspace.join('、')}`));
98
+ }
99
+
100
+ const agents = ctx?.get?.('agents');
101
+ const agentSample = Array.isArray(agents?.list?.()) ? agents.list()[0] : undefined;
102
+ checks.push(check(
103
+ 'methods:agents',
104
+ '会话状态接口可用',
105
+ typeof agents?.list === 'function' && (agentSample === undefined || 'status' in agentSample),
106
+ typeof agents?.list === 'function' ? '可读取 status' : '缺少 agents.list',
107
+ 'medium',
108
+ ));
109
+
110
+ // 2. runtime features the engine needs
111
+ checks.push(check(
112
+ 'node:zstd',
113
+ 'Node zstd 能力',
114
+ typeof zlib.zstdCompressSync === 'function' && typeof zlib.zstdDecompressSync === 'function',
115
+ typeof zlib.zstdCompressSync === 'function' ? '可用' : '当前 Node 缺少 zstd,会话读写不可用',
116
+ ));
117
+ checks.push(check('node:fetch', 'Node fetch 可用', typeof fetch === 'function', typeof fetch === 'function' ? '可用' : '缺少 fetch,WebDAV 不可用'));
118
+
119
+ // 3. session format
120
+ const sessionsRoot = path.join(paths.home, 'sessions');
121
+ const sessions = await scanSessions(sessionsRoot);
122
+ if (sessions.size === 0) {
123
+ checks.push(check('format:sessions', '会话文件格式', false, '未找到任何会话,无法验证格式', 'medium'));
124
+ } else {
125
+ const sample = sessions.values().next().value;
126
+ let detail = '无法读取样本会话';
127
+ let ok = false;
128
+ try {
129
+ const buffer = await fsp.readFile(sample.file);
130
+ const frames = scanFrames(buffer);
131
+ const text = frames.length === 0 ? '' : zlib.zstdDecompressSync(buffer.subarray(frames[0].start, frames[0].end)).toString('utf8');
132
+ const header = text.split('\n').find((line) => line.trim() !== '');
133
+ const parsed = header === undefined ? undefined : JSON.parse(header);
134
+ ok = frames.length > 0 && parsed?.type === 'session' && typeof parsed.id === 'string' && typeof parsed.cwd === 'string';
135
+ detail = ok
136
+ ? `帧数 ${String(frames.length)},首行字段齐全`
137
+ : `帧数 ${String(frames.length)},首行 ${ok ? '正常' : '缺少 type/id/cwd'}`;
138
+ } catch (error) {
139
+ detail = `读取失败:${String(error?.message ?? error)}`;
140
+ }
141
+ checks.push(check('format:sessions', '会话文件格式', ok, detail));
142
+
143
+ // projectKey must still match the folder the host chose
144
+ const expected = projectKey(sample.projectKey.startsWith('--') ? sample.projectKey : '');
145
+ const dirName = path.basename(path.dirname(path.dirname(sample.file)));
146
+ checks.push(check(
147
+ 'format:projectKey',
148
+ '项目目录命名规则',
149
+ dirName === sample.projectKey || expected === '',
150
+ `目录 ${dirName},记录 ${sample.projectKey}`,
151
+ 'medium',
152
+ ));
153
+ }
154
+
155
+ // 4. workspace.json schema
156
+ const workspaceFile = path.join(paths.home, 'storages', 'workspace.json');
157
+ const workspaceDoc = await readJson(workspaceFile);
158
+ if (workspaceDoc === undefined) {
159
+ checks.push(check('format:workspace', 'workspace.json 结构', false, '文件缺失或无法解析', 'medium'));
160
+ } else {
161
+ const unitVersion = Number(workspaceDoc.unit?.version);
162
+ const table = workspaceDoc.tables?.workspaces;
163
+ const records = table !== null && typeof table === 'object' ? Object.values(table) : [];
164
+ const badPaths = records.filter((record) => typeof record?.path !== 'string' || record.path === '').length;
165
+ checks.push(check(
166
+ 'format:workspace',
167
+ 'workspace.json 结构',
168
+ records.length > 0 && badPaths === 0 && Number.isFinite(unitVersion),
169
+ `版本 ${String(unitVersion)},分组 ${String(records.length)} 个${badPaths > 0 ? `,其中 ${String(badPaths)} 个 path 非法` : ''}`,
170
+ ));
171
+ }
172
+
173
+ // 5. title cache shape (optional)
174
+ const shardDir = path.join(paths.home, 'storages', 'session_projcache', 'sessions');
175
+ if (await exists(shardDir)) {
176
+ let entries = [];
177
+ try {
178
+ entries = (await fsp.readdir(shardDir)).filter((name) => name.endsWith('.json')).slice(0, 3);
179
+ } catch {
180
+ entries = [];
181
+ }
182
+ let ok = entries.length === 0;
183
+ let detail = '暂无缓存分片';
184
+ for (const name of entries) {
185
+ const doc = await readJson(path.join(shardDir, name));
186
+ const rows = doc?.record?.rows ?? doc?.rows;
187
+ if (rows !== undefined && rows !== null) {
188
+ ok = true;
189
+ detail = 'record.rows 结构可读';
190
+ break;
191
+ }
192
+ }
193
+ checks.push(check('format:titles', '会话标题缓存结构', ok, detail, 'low'));
194
+ }
195
+
196
+ // 6. attachments layout (optional)
197
+ const attachmentsRoot = path.join(paths.home, 'attachments', 'v1');
198
+ checks.push(check(
199
+ 'format:attachments',
200
+ '附件目录结构',
201
+ await exists(attachmentsRoot),
202
+ (await exists(path.join(attachmentsRoot, 'objects'))) ? 'objects 目录存在' : '尚无附件对象',
203
+ 'low',
204
+ ));
205
+
206
+ // 7. profile config used by the sync
207
+ const profile = process.env.DSH_PROFILE ?? 'desktop';
208
+ const patchFile = path.join(paths.home, 'profiles', profile, 'cordis.patch.yml');
209
+ checks.push(check('file:profile', '当前 profile 补丁文件', await exists(patchFile), patchFile, 'low'));
210
+
211
+ // 8. data directory writable
212
+ let writable = false;
213
+ try {
214
+ const probe = path.join(paths.base, `.env-check-${String(process.pid)}.tmp`);
215
+ await fsp.writeFile(probe, 'ok', 'utf8');
216
+ await fsp.rm(probe, { force: true });
217
+ writable = true;
218
+ } catch {
219
+ writable = false;
220
+ }
221
+ checks.push(check('fs:data', '插件数据目录可写', writable, paths.base));
222
+
223
+ // 9. host version detectable
224
+ const version = await appVersion();
225
+ checks.push(check('app:version', '主程序版本可识别', version.version !== null, version.version ?? '无法读取(版本变化提醒不可用,其余检测不受影响)', 'low'));
226
+
227
+ const failed = checks.filter((item) => item.ok !== true);
228
+ return {
229
+ ok: failed.length === 0,
230
+ checkedAt: new Date().toISOString(),
231
+ pluginVersion: pluginVersion(),
232
+ appVersion: version.version,
233
+ appVersionSource: version.source,
234
+ checks,
235
+ failedCount: failed.length,
236
+ };
237
+ }
238
+
239
+ /** Where the desktop report is written. */
240
+ function desktopDirectory() {
241
+ const desktop = path.join(os.homedir(), 'Desktop');
242
+ return desktop;
243
+ }
244
+
245
+ /** Where the last-seen application version is remembered. */
246
+ function recordFile(paths) {
247
+ return path.join(paths.base, 'env-check.json');
248
+ }
249
+
250
+ /** Read the remembered version. */
251
+ export async function readEnvRecord(paths) {
252
+ return (await readJson(recordFile(paths))) ?? {};
253
+ }
254
+
255
+ /** Remember the current application version. */
256
+ export async function writeEnvRecord(paths, patch) {
257
+ const current = await readEnvRecord(paths);
258
+ await fsp.writeFile(recordFile(paths), `${JSON.stringify({ ...current, ...patch }, null, 2)}\n`, 'utf8');
259
+ return { ...current, ...patch };
260
+ }
261
+
262
+ /** Write the report and return its path. */
263
+ export async function writeEnvironmentReport(deps, result) {
264
+ const target = desktopDirectory();
265
+ const stamp = new Date().toISOString().replace(/[:.]/gu, '-').slice(0, 19);
266
+ const file = path.join(target, `DSH增强-环境检测-${stamp}.md`);
267
+ const lines = [
268
+ '# DSH增强 · 环境检测报告',
269
+ '',
270
+ `- 检测时间:${result.checkedAt}`,
271
+ `- 插件版本:V${result.pluginVersion}`,
272
+ `- 主程序版本:${result.appVersion ?? '未知'}`,
273
+ `- 结论:${result.ok ? '全部通过' : `发现 ${String(result.failedCount)} 项风险`}`,
274
+ '',
275
+ '## 检测明细',
276
+ '',
277
+ '| 结果 | 项目 | 说明 | 严重度 |',
278
+ '| --- | --- | --- | --- |',
279
+ ...result.checks.map((item) => `| ${item.ok ? '通过' : '**异常**'} | ${item.label} | ${String(item.detail ?? '').replace(/\|/gu, '\\|')} | ${item.severity} |`),
280
+ '',
281
+ '## 说明',
282
+ '',
283
+ '- 异常项按严重度排序观察:high 表示可能直接影响会话数据,medium 表示部分功能失效,low 表示可忽略。',
284
+ '- 若“会话文件格式”或“workspace.json 结构”异常,建议升级插件版本,而不要继续同步。',
285
+ ];
286
+ await fsp.mkdir(target, { recursive: true }).catch(() => {});
287
+ await fsp.writeFile(file, `${lines.join('\n')}\n`, 'utf8');
288
+ return { ok: true, path: file };
289
+ }