@kangyishuai/dsh-session-delete 0.0.0-stage → 0.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/lib/index.js ADDED
@@ -0,0 +1,7 @@
1
+ // @ts-check
2
+ // host 半入口:Cordis 插件(类形态),构造时探测宿主能力并注册 sessionDelete Remote 服务。
3
+ // 改动后需要重启 DSH 桌面版。
4
+ import { SessionDeleteService } from "./service.js";
5
+
6
+ export { SessionDeleteService };
7
+ export default SessionDeleteService;
package/lib/journal.js ADDED
@@ -0,0 +1,136 @@
1
+ // @ts-check
2
+ // 两阶段提交日志:先写 intent(打算做什么),执行,最后标记 done。
3
+ // 启动时扫未完成的条目,决定补做还是回滚 —— 没有它,「安全删除」在断电面前不成立(ADR 0004 §3)。
4
+ import { randomUUID } from "node:crypto";
5
+ import { mkdir, readdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+ import { journalDir, requireInside } from "./paths.js";
8
+
9
+ const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/u;
10
+
11
+ /**
12
+ * @typedef {object} JournalRecord
13
+ * @property {string} id
14
+ * @property {"intent" | "done" | "failed"} state
15
+ * @property {string} action trash / restore / purge
16
+ * @property {string} startedAt
17
+ * @property {string} [sessionId]
18
+ * @property {string} [entryId]
19
+ * @property {string} [digest]
20
+ * @property {string} [detail]
21
+ * @property {Record<string, unknown>} [extra]
22
+ */
23
+
24
+ /** @param {string} file @param {unknown} value @returns {Promise<void>} */
25
+ async function writeAtomic(file, value) {
26
+ const tmp = file + ".tmp";
27
+ await writeFile(tmp, JSON.stringify(value, null, 2), "utf8");
28
+ await rename(tmp, file);
29
+ }
30
+
31
+ /**
32
+ * @param {string} dataRoot
33
+ * @param {string} id
34
+ * @returns {string}
35
+ */
36
+ function recordPath(dataRoot, id) {
37
+ if (!ID_RE.test(id)) throw new Error("invalid journal id");
38
+ const path = join(journalDir(dataRoot), id + ".json");
39
+ requireInside(dataRoot, path);
40
+ return path;
41
+ }
42
+
43
+ /**
44
+ * 开始一次可恢复操作。
45
+ * @param {object} options
46
+ * @param {string} options.dataRoot
47
+ * @param {string} options.action
48
+ * @param {Record<string, unknown>} [options.extra]
49
+ * @returns {Promise<JournalRecord>}
50
+ */
51
+ export async function beginOperation({ dataRoot, action, extra = {} }) {
52
+ await mkdir(journalDir(dataRoot), { recursive: true });
53
+ /** @type {JournalRecord} */
54
+ const record = {
55
+ id: `${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`,
56
+ state: "intent",
57
+ action,
58
+ startedAt: new Date().toISOString(),
59
+ ...extra,
60
+ };
61
+ await writeAtomic(recordPath(dataRoot, record.id), record);
62
+ return record;
63
+ }
64
+
65
+ /**
66
+ * 更新一条操作记录。
67
+ * @param {string} dataRoot
68
+ * @param {string} id
69
+ * @param {Partial<JournalRecord>} patch
70
+ * @returns {Promise<JournalRecord>}
71
+ */
72
+ export async function updateOperation(dataRoot, id, patch) {
73
+ const current = await readOperation(dataRoot, id);
74
+ if (!current) throw new Error(`journal record not found: ${id}`);
75
+ const next = { ...current, ...patch };
76
+ await writeAtomic(recordPath(dataRoot, id), next);
77
+ return next;
78
+ }
79
+
80
+ /**
81
+ * 结束一次操作。成功则删除记录(历史留在 audit.log),失败则保留现场。
82
+ * @param {object} options
83
+ * @param {string} options.dataRoot
84
+ * @param {string} options.id
85
+ * @param {"done" | "failed"} options.state
86
+ * @param {string} [options.detail]
87
+ * @returns {Promise<void>}
88
+ */
89
+ export async function finishOperation({ dataRoot, id, state, detail }) {
90
+ if (state === "done") {
91
+ await unlink(recordPath(dataRoot, id)).catch(() => undefined);
92
+ return;
93
+ }
94
+ await updateOperation(dataRoot, id, { state: "failed", detail });
95
+ }
96
+
97
+ /**
98
+ * @param {string} dataRoot
99
+ * @param {string} id
100
+ * @returns {Promise<JournalRecord | null>}
101
+ */
102
+ export async function readOperation(dataRoot, id) {
103
+ try {
104
+ return JSON.parse(await readFile(recordPath(dataRoot, id), "utf8"));
105
+ } catch {
106
+ return null;
107
+ }
108
+ }
109
+
110
+ /**
111
+ * 列出未完成的操作(启动时自愈入口)。
112
+ * @param {string} dataRoot
113
+ * @returns {Promise<JournalRecord[]>}
114
+ */
115
+ export async function listPending(dataRoot) {
116
+ /** @type {string[]} */
117
+ let names = [];
118
+ try {
119
+ names = await readdir(journalDir(dataRoot));
120
+ } catch {
121
+ return [];
122
+ }
123
+ /** @type {JournalRecord[]} */
124
+ const out = [];
125
+ for (const name of names) {
126
+ if (!name.endsWith(".json")) continue;
127
+ try {
128
+ const record = JSON.parse(await readFile(join(journalDir(dataRoot), name), "utf8"));
129
+ if (record?.state && record.state !== "done") out.push(record);
130
+ } catch {
131
+ // 损坏的记录跳过;不因为一条坏文件阻止插件加载。
132
+ }
133
+ }
134
+ out.sort((a, b) => String(a.startedAt).localeCompare(String(b.startedAt)));
135
+ return out;
136
+ }
package/lib/locate.js ADDED
@@ -0,0 +1,129 @@
1
+ // @ts-check
2
+ // 定位一个会话在磁盘上的目录。优先用后端的 locate()(官方给出的路径),
3
+ // 拿不到时按「扫描 + 匹配已知布局」回退;两种来源都失败就报告,不猜路径。
4
+ import { readdir, stat } from "node:fs/promises";
5
+ import { dirname, join } from "node:path";
6
+ import { encodeSegment, projectKey, requireSessionId, sessionsRoot } from "./paths.js";
7
+
8
+ /**
9
+ * @typedef {object} Location
10
+ * @property {string} path 会话目录的绝对路径。
11
+ * @property {"locate" | "scan"} tier 来源:官方 locate() 还是回退扫描。
12
+ */
13
+
14
+ /** @param {string} path @returns {Promise<boolean>} */
15
+ async function isDirectory(path) {
16
+ try {
17
+ return (await stat(path)).isDirectory();
18
+ } catch {
19
+ return false;
20
+ }
21
+ }
22
+
23
+ /**
24
+ * 由 header 直接算出候选路径(cwd 与 id 都是确定性的)。
25
+ * @param {string} dataRoot
26
+ * @param {string} sessionId
27
+ * @param {string | null | undefined} cwd
28
+ * @returns {string}
29
+ */
30
+ export function candidateFromHeader(dataRoot, sessionId, cwd) {
31
+ const root = sessionsRoot(dataRoot);
32
+ const segment = encodeSegment(sessionId);
33
+ if (typeof cwd === "string" && cwd.length > 0) return join(root, projectKey(cwd), segment);
34
+ return join(root, "_no-cwd", segment);
35
+ }
36
+
37
+ /**
38
+ * 在 sessions 根下逐个项目目录查找该会话目录。
39
+ * @param {string} dataRoot
40
+ * @param {string} sessionId
41
+ * @returns {Promise<string[]>} 命中路径(通常 0 或 1 个)。
42
+ */
43
+ export async function scanForSessionDir(dataRoot, sessionId) {
44
+ const root = sessionsRoot(dataRoot);
45
+ const segment = encodeSegment(sessionId);
46
+ /** @type {string[]} */
47
+ const hits = [];
48
+ let projects;
49
+ try {
50
+ projects = await readdir(root, { withFileTypes: true });
51
+ } catch {
52
+ return hits;
53
+ }
54
+ for (const entry of projects) {
55
+ if (!entry.isDirectory()) continue;
56
+ const candidate = join(root, entry.name, segment);
57
+ if (await isDirectory(candidate)) hits.push(candidate);
58
+ }
59
+ return hits;
60
+ }
61
+
62
+ /**
63
+ * 定位会话目录:locate() → header 推导 → 全项目扫描。
64
+ * @param {object} options
65
+ * @param {string} options.dataRoot
66
+ * @param {string} options.sessionId
67
+ * @param {{ cwd?: string | null, id?: string } | null | undefined} options.header
68
+ * @param {any} [options.persistence]
69
+ * @returns {Promise<{ location: Location | null, ambiguous: string[] }>}
70
+ */
71
+ export async function locateSession({ dataRoot, sessionId, header, persistence }) {
72
+ requireSessionId(sessionId);
73
+
74
+ if (header && typeof persistence?.locate === "function") {
75
+ try {
76
+ const located = persistence.locate(header);
77
+ const path = located?.path;
78
+ if (typeof path === "string" && path.length > 0) {
79
+ const dir = dirname(path);
80
+ if (await isDirectory(dir))
81
+ return { location: { path: dir, tier: "locate" }, ambiguous: [] };
82
+ }
83
+ } catch {
84
+ // 后端没有 locate 或它拒绝了这次查询 —— 回退到扫描。
85
+ }
86
+ }
87
+
88
+ const fromHeader = candidateFromHeader(dataRoot, sessionId, header?.cwd ?? null);
89
+ if (await isDirectory(fromHeader))
90
+ return { location: { path: fromHeader, tier: "scan" }, ambiguous: [] };
91
+
92
+ const hits = await scanForSessionDir(dataRoot, sessionId);
93
+ if (hits.length === 1) return { location: { path: hits[0], tier: "scan" }, ambiguous: [] };
94
+ if (hits.length > 1) return { location: null, ambiguous: hits };
95
+ return { location: null, ambiguous: [] };
96
+ }
97
+
98
+ /**
99
+ * 目录体积(递归,不跟随符号链接)。用于 plan 里展示「将释放多少」。
100
+ * @param {string} path
101
+ * @returns {Promise<number>} 字节数。
102
+ */
103
+ export async function directorySize(path) {
104
+ let total = 0;
105
+ /** @type {{ path: string, name: string }[]} */
106
+ const stack = [{ path, name: path }];
107
+ while (stack.length > 0) {
108
+ const next = /** @type {{ path: string, name: string }} */ (stack.pop());
109
+ let entries;
110
+ try {
111
+ entries = await readdir(next.path, { withFileTypes: true });
112
+ } catch {
113
+ continue;
114
+ }
115
+ for (const entry of entries) {
116
+ const child = join(next.path, entry.name);
117
+ if (entry.isSymbolicLink()) continue;
118
+ if (entry.isDirectory()) stack.push({ path: child, name: child });
119
+ else {
120
+ try {
121
+ total += (await stat(child)).size;
122
+ } catch {
123
+ // 读不到的条目忽略,不影响主流程。
124
+ }
125
+ }
126
+ }
127
+ }
128
+ return total;
129
+ }