@xiao-53/dsh-mindmap 0.0.0-stage → 0.4.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.
package/lib/index.js ADDED
@@ -0,0 +1,2701 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __knownSymbol = (name2, symbol) => (symbol = Symbol[name2]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name2);
5
+ var __typeError = (msg) => {
6
+ throw TypeError(msg);
7
+ };
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
+ var __decoratorStart = (base3) => [, , , __create(base3?.[__knownSymbol("metadata")] ?? null)];
11
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
12
+ var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
13
+ var __decoratorContext = (kind, name2, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name: name2, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
14
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
15
+ var __runInitializers = (array, flags, self, value) => {
16
+ for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
17
+ return value;
18
+ };
19
+ var __decorateElement = (array, flags, name2, decorators, target, extra) => {
20
+ var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
21
+ var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
22
+ var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
23
+ var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name2]() {
24
+ return __privateGet(this, extra);
25
+ }, set [name2](x) {
26
+ return __privateSet(this, extra, x);
27
+ } }, name2));
28
+ k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name2) : __name(target, name2);
29
+ for (var i = decorators.length - 1; i >= 0; i--) {
30
+ ctx = __decoratorContext(k, name2, done = {}, array[3], extraInitializers);
31
+ if (k) {
32
+ ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name2 in x };
33
+ if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name2];
34
+ if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name2] = y;
35
+ }
36
+ it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
37
+ if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
38
+ else if (typeof it !== "object" || it === null) __typeError("Object expected");
39
+ else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
40
+ }
41
+ return k || __decoratorMetadata(array, target), desc && __defProp(target, name2, desc), p ? k ^ 4 ? extra : desc : target;
42
+ };
43
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
44
+ var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
45
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
46
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
47
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
48
+
49
+ // src/shared/note-position.ts
50
+ import { z as z3 } from "zod";
51
+
52
+ // src/shared/fingerprint.ts
53
+ async function digest(input) {
54
+ const bytes = typeof input === "string" ? new TextEncoder().encode(input) : Uint8Array.from(input);
55
+ const hash2 = await crypto.subtle.digest("SHA-256", bytes);
56
+ return Array.from(
57
+ new Uint8Array(hash2),
58
+ (b) => b.toString(16).padStart(2, "0")
59
+ ).join("");
60
+ }
61
+ async function fingerprint(files) {
62
+ return digest(
63
+ JSON.stringify(
64
+ files.filter((f) => !/(^|\/)(exports|\.transactions)(\/|$)/.test(f.path)).toSorted((a, b) => a.path.localeCompare(b.path))
65
+ )
66
+ );
67
+ }
68
+ function canonicalJson(input) {
69
+ return JSON.stringify(input, (_key, value) => value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : value) ?? "null";
70
+ }
71
+
72
+ // src/shared/note-markdown.ts
73
+ import { Marked } from "marked";
74
+
75
+ // src/shared/note-plot.ts
76
+ import { z as z2 } from "zod";
77
+
78
+ // src/shared/plot-expression.ts
79
+ var functions = {
80
+ sin: Math.sin,
81
+ cos: Math.cos,
82
+ tan: Math.tan,
83
+ sqrt: Math.sqrt,
84
+ abs: Math.abs,
85
+ exp: Math.exp,
86
+ ln: Math.log
87
+ };
88
+ function parsePlotExpression(source) {
89
+ if (!source.trim() || source.length > 256) throw new Error("\u51FD\u6570\u5F0F\u987B\u4E3A 1\u2013256 \u5B57\u7B26");
90
+ const tokens = source.match(/(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|[A-Za-z]+|[^\s]/g) ?? [];
91
+ let cursor = 0;
92
+ const take = (token) => {
93
+ if (tokens[cursor] !== token) return false;
94
+ cursor++;
95
+ return true;
96
+ };
97
+ const precedence = { "+": 1, "-": 1, "*": 2, "/": 2, "^": 4 };
98
+ function expression(min, depth) {
99
+ if (depth > 32) throw new Error("\u51FD\u6570\u5F0F\u5D4C\u5957\u8D85\u8FC7 32 \u5C42");
100
+ const token = tokens[cursor++];
101
+ let left;
102
+ if (token === "(") {
103
+ left = expression(0, depth + 1);
104
+ if (!take(")")) throw new Error("\u51FD\u6570\u5F0F\u7F3A\u5C11\u53F3\u62EC\u53F7");
105
+ } else if (token === "+" || token === "-") {
106
+ const operand = expression(3, depth + 1);
107
+ left = token === "-" ? { kind: "negative", operand } : operand;
108
+ } else if (token === "x" || token === "pi" || token === "e") {
109
+ left = { kind: token };
110
+ } else if (token && Object.hasOwn(functions, token)) {
111
+ if (!take("(")) throw new Error("\u51FD\u6570\u53C2\u6570\u987B\u653E\u5728\u62EC\u53F7\u5185");
112
+ const operand = expression(0, depth + 1);
113
+ if (!take(")")) throw new Error("\u51FD\u6570\u5F0F\u7F3A\u5C11\u53F3\u62EC\u53F7");
114
+ left = { kind: "call", name: token, operand };
115
+ } else if (token && /^[.\d]/.test(token) && Number.isFinite(Number(token))) {
116
+ left = { kind: "number", value: Number(token) };
117
+ } else {
118
+ throw new Error("\u51FD\u6570\u5F0F\u542B\u65E0\u6548\u6570\u503C\u6216\u4E0D\u652F\u6301\u7684\u8BED\u6CD5");
119
+ }
120
+ while (tokens[cursor] !== void 0) {
121
+ const op2 = tokens[cursor];
122
+ const level = Object.hasOwn(precedence, op2) ? precedence[op2] : 0;
123
+ if (!level || level < min) break;
124
+ cursor++;
125
+ left = { kind: "binary", op: op2, left, right: expression(level + (op2 === "^" ? 0 : 1), depth + 1) };
126
+ }
127
+ return left;
128
+ }
129
+ const tree = expression(0, 0);
130
+ if (cursor !== tokens.length) throw new Error("\u51FD\u6570\u5F0F\u542B\u591A\u4F59\u5185\u5BB9\uFF0C\u4E58\u6CD5\u987B\u4F7F\u7528 *");
131
+ return tree;
132
+ }
133
+
134
+ // src/shared/validate-map.ts
135
+ import { z } from "zod";
136
+
137
+ // src/shared/map-types.ts
138
+ var categories = ["blue", "sage", "plum", "gold", "terra"];
139
+ var icons = [
140
+ "book",
141
+ "atom",
142
+ "layers",
143
+ "branch",
144
+ "target",
145
+ "spark",
146
+ "flask",
147
+ "check",
148
+ "alert",
149
+ "formula",
150
+ "link",
151
+ "grid",
152
+ "idea",
153
+ "arrows"
154
+ ];
155
+
156
+ // src/shared/validate-map.ts
157
+ var idSchema = z.string().regex(/^[A-Za-z0-9_-]+$/, "\u8EAB\u4EFD\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u6216\u77ED\u6A2A\u7EBF");
158
+ var title = z.string().trim().min(1, "\u6807\u9898\u4E0D\u80FD\u4E3A\u7A7A");
159
+ var mapSchema = z.strictObject({
160
+ schemaVersion: z.literal(1),
161
+ id: idSchema,
162
+ title,
163
+ rootViewId: idSchema,
164
+ nodes: z.array(
165
+ z.strictObject({
166
+ id: idSchema,
167
+ title,
168
+ summary: z.string(),
169
+ category: z.enum(categories),
170
+ icon: z.enum(icons),
171
+ notePath: z.string().min(1).optional(),
172
+ childViewId: idSchema.optional()
173
+ })
174
+ ),
175
+ views: z.array(
176
+ z.strictObject({
177
+ id: idSchema,
178
+ title,
179
+ parentViewId: idSchema.nullable(),
180
+ centerNodeId: idSchema.optional(),
181
+ groups: z.array(
182
+ z.strictObject({
183
+ id: idSchema,
184
+ title,
185
+ number: z.string(),
186
+ category: z.enum(categories)
187
+ })
188
+ ),
189
+ occurrences: z.array(
190
+ z.strictObject({ nodeId: idSchema, groupId: idSchema.optional() })
191
+ ),
192
+ relationIds: z.array(idSchema)
193
+ })
194
+ ),
195
+ relations: z.array(
196
+ z.strictObject({
197
+ id: idSchema,
198
+ fromNodeId: idSchema,
199
+ toNodeId: idSchema,
200
+ type: z.enum(["dependency", "supplement"]),
201
+ label: z.string().optional()
202
+ })
203
+ )
204
+ });
205
+ function validateMap(input, directoryId) {
206
+ const parsed = mapSchema.safeParse(input);
207
+ if (!parsed.success)
208
+ return {
209
+ ok: false,
210
+ diagnostics: parsed.error.issues.map((i) => ({
211
+ path: ["map.json", ...i.path].join("."),
212
+ code: "invalid_data",
213
+ message: i.message
214
+ }))
215
+ };
216
+ const map = parsed.data;
217
+ const diagnostics = [];
218
+ const fail = (path, message) => diagnostics.push({
219
+ path: `map.json.${path}`,
220
+ message,
221
+ code: "invalid_data"
222
+ });
223
+ const unique = (ids, path) => {
224
+ const seen = /* @__PURE__ */ new Set();
225
+ ids.forEach((id) => {
226
+ if (seen.has(id)) fail(path, `\u91CD\u590D\u8EAB\u4EFD ${id}`);
227
+ seen.add(id);
228
+ });
229
+ };
230
+ unique(
231
+ map.nodes.map((n) => n.id),
232
+ "nodes"
233
+ );
234
+ unique(
235
+ map.views.map((v) => v.id),
236
+ "views"
237
+ );
238
+ unique(
239
+ map.relations.map((r) => r.id),
240
+ "relations"
241
+ );
242
+ if (directoryId !== void 0 && map.id !== directoryId)
243
+ fail("id", "\u5730\u56FE\u8EAB\u4EFD\u4E0E\u76EE\u5F55\u540D\u4E0D\u4E00\u81F4");
244
+ const nodes = new Map(map.nodes.map((n) => [n.id, n]));
245
+ const views = new Map(map.views.map((v) => [v.id, v]));
246
+ const relations = new Map(map.relations.map((r) => [r.id, r]));
247
+ const root = views.get(map.rootViewId);
248
+ if (!root || root.parentViewId !== null || map.views.filter((v) => v.parentViewId === null).length !== 1)
249
+ fail("rootViewId", "\u5FC5\u987B\u6307\u5411\u552F\u4E00\u6839\u89C6\u56FE\uFF0C\u6839\u7236\u7EA7\u4E3A null");
250
+ const paths = /* @__PURE__ */ new Set();
251
+ for (const n of map.nodes) {
252
+ if (n.notePath) {
253
+ const p = n.notePath.replaceAll("\\", "/").toLowerCase();
254
+ if (paths.has(p))
255
+ fail(`nodes.${n.id}.notePath`, "\u4E00\u4EFD\u7B14\u8BB0\u4E0D\u80FD\u5C5E\u4E8E\u4E0D\u540C\u8282\u70B9");
256
+ paths.add(p);
257
+ }
258
+ if (n.childViewId && views.get(n.childViewId)?.centerNodeId !== n.id)
259
+ fail(`nodes.${n.id}.childViewId`, "\u5B50\u56FE\u4E0D\u5B58\u5728\u6216\u4E2D\u5FC3\u8282\u70B9\u672A\u6307\u56DE\u5F53\u524D\u8282\u70B9");
260
+ }
261
+ for (const v of map.views) {
262
+ unique(
263
+ v.groups.map((g) => g.id),
264
+ `views.${v.id}.groups`
265
+ );
266
+ unique(
267
+ v.occurrences.map((o) => o.nodeId),
268
+ `views.${v.id}.occurrences`
269
+ );
270
+ unique(v.relationIds, `views.${v.id}.relationIds`);
271
+ const seen = /* @__PURE__ */ new Set();
272
+ let cursor = v;
273
+ while (cursor && cursor.id !== map.rootViewId) {
274
+ if (seen.has(cursor.id)) {
275
+ fail(`views.${v.id}.parentViewId`, "\u89C6\u56FE\u7236\u7EA7\u6210\u73AF");
276
+ break;
277
+ }
278
+ seen.add(cursor.id);
279
+ cursor = cursor.parentViewId === null ? void 0 : views.get(cursor.parentViewId);
280
+ }
281
+ if (!cursor) fail(`views.${v.id}.parentViewId`, "\u7236\u7EA7\u8DEF\u5F84\u672A\u5230\u8FBE\u6839\u89C6\u56FE");
282
+ if (v.centerNodeId && nodes.get(v.centerNodeId)?.childViewId !== v.id)
283
+ fail(`views.${v.id}.centerNodeId`, "\u4E2D\u5FC3\u8282\u70B9\u4E0E childViewId \u4E0D\u4E00\u81F4");
284
+ const present = new Set(v.occurrences.map((o) => o.nodeId));
285
+ const groups = new Set(v.groups.map((g) => g.id));
286
+ for (const o of v.occurrences) {
287
+ if (!nodes.has(o.nodeId))
288
+ fail(`views.${v.id}.occurrences.${o.nodeId}`, "\u8282\u70B9\u4E0D\u5B58\u5728");
289
+ if (o.groupId && !groups.has(o.groupId))
290
+ fail(
291
+ `views.${v.id}.occurrences.${o.nodeId}.groupId`,
292
+ "\u5206\u7EC4\u4E0D\u5C5E\u4E8E\u6B64\u89C6\u56FE"
293
+ );
294
+ }
295
+ for (const rid of v.relationIds) {
296
+ const r = relations.get(rid);
297
+ if (!r || !present.has(r.fromNodeId) || !present.has(r.toNodeId))
298
+ fail(
299
+ `views.${v.id}.relationIds.${rid}`,
300
+ "\u5173\u7CFB\u4E0D\u5B58\u5728\u6216\u89C6\u56FE\u672A\u5305\u542B\u4E24\u4E2A\u7AEF\u70B9"
301
+ );
302
+ }
303
+ }
304
+ for (const r of map.relations)
305
+ if (!nodes.has(r.fromNodeId) || !nodes.has(r.toNodeId))
306
+ fail(`relations.${r.id}`, "\u5173\u7CFB\u7AEF\u70B9\u4E0D\u5B58\u5728");
307
+ return diagnostics.length ? { ok: false, diagnostics } : { ok: true, value: map };
308
+ }
309
+
310
+ // src/shared/note-plot.ts
311
+ var shortText = z2.string().max(120).refine((value) => !!value.trim() && !/[\p{Cc}\u2028\u2029]/u.test(value));
312
+ var range = z2.tuple([z2.number(), z2.number()]).refine(([lo, hi]) => lo < hi);
313
+ var base = { version: z2.literal(1), id: idSchema, title: shortText.optional() };
314
+ var functionSchema = z2.strictObject({
315
+ ...base,
316
+ kind: z2.literal("function"),
317
+ xRange: range.optional(),
318
+ yRange: range.optional(),
319
+ series: z2.array(z2.strictObject({ expression: z2.string().min(1).max(256), label: shortText.optional() })).min(1).max(3)
320
+ });
321
+ var statisticsSchema = z2.strictObject({
322
+ ...base,
323
+ kind: z2.enum(["bar", "line"]),
324
+ categories: z2.array(shortText).min(1).max(100).optional(),
325
+ series: z2.array(z2.strictObject({
326
+ label: shortText,
327
+ values: z2.array(z2.number().nullable()).min(1).max(100),
328
+ unit: shortText.optional()
329
+ })).min(1).max(3)
330
+ });
331
+ var parseSizeLimit = 128 * 1024;
332
+ function parsePlotData(json) {
333
+ if (json.length > parseSizeLimit || new TextEncoder().encode(json).length > parseSizeLimit)
334
+ return { error: "\u56FE\u5757 JSON \u8D85\u8FC7 128 KiB" };
335
+ let value;
336
+ try {
337
+ value = JSON.parse(json);
338
+ } catch {
339
+ return { error: "\u56FE\u5757 JSON \u65E0\u6CD5\u8BFB\u53D6" };
340
+ }
341
+ const fields = value;
342
+ const id = idSchema.safeParse(fields?.id).data;
343
+ if (fields?.version !== 1) return { id, error: "\u56FE\u5757\u7F3A\u5C11\u7248\u672C\u6216\u7248\u672C\u4E0D\u53D7\u652F\u6301" };
344
+ if (fields.kind === "function") {
345
+ const result2 = functionSchema.safeParse(value);
346
+ if (!result2.success) return { id, error: "\u51FD\u6570\u56FE\u5B57\u6BB5\u3001\u7CFB\u5217\u6216\u8303\u56F4\u65E0\u6548" };
347
+ const data = {
348
+ ...result2.data,
349
+ xRange: result2.data.xRange ?? [-5, 5],
350
+ yRange: result2.data.yRange ?? [-5, 5]
351
+ };
352
+ try {
353
+ return { id, data, expressions: data.series.map((item) => parsePlotExpression(item.expression)) };
354
+ } catch (error) {
355
+ return { id, error: error.message };
356
+ }
357
+ }
358
+ const result = statisticsSchema.safeParse(value);
359
+ if (!result.success) return { id, error: "\u7EDF\u8BA1\u56FE\u5B57\u6BB5\u6216\u7C7B\u578B\u65E0\u6548" };
360
+ const { series, categories: categories2, kind } = result.data;
361
+ const size = series[0].values.length;
362
+ if (kind === "bar" && !categories2 || categories2 && categories2.length !== size || series.some((item) => item.values.length !== size))
363
+ return { id, error: "\u7EDF\u8BA1\u56FE\u987B\u63D0\u4F9B\u7B49\u957F\u7684\u6570\u636E\u4E0E\u7C7B\u76EE\uFF1B\u67F1\u72B6\u56FE\u5FC5\u987B\u63D0\u4F9B\u7C7B\u76EE" };
364
+ return { id, data: { ...result.data, categories: categories2 ?? Array.from({ length: size }, (_, i) => String(i + 1)) } };
365
+ }
366
+ var isPlot = (token) => token.type === "notePlot";
367
+
368
+ // src/shared/note-markdown.ts
369
+ var escaped = (text2, at) => {
370
+ let count = 0;
371
+ while (at > 0 && text2[--at] === "\\") count++;
372
+ return count % 2 !== 0;
373
+ };
374
+ function inlineFormula(src) {
375
+ const parens = src.startsWith("\\(");
376
+ if (!parens && (!src.startsWith("$") || src[1] === "$" || /\s/.test(src[1] ?? " "))) return;
377
+ const line = src.slice(0, 8194).split("\n", 1)[0];
378
+ const start = parens ? 2 : 1;
379
+ const close = parens ? "\\)" : "$";
380
+ if (!parens && /^\$\d+(?:[.,]\d+)*[,;。!?:、]/.test(line)) return;
381
+ for (let end = line.indexOf(close, start); end >= 0; end = line.indexOf(close, end + close.length)) {
382
+ if (escaped(line, end)) continue;
383
+ const tex = line.slice(start, end);
384
+ if (!tex.trim() || !parens && (/\s$/.test(tex) || /[\d$]/.test(line[end + 1] ?? ""))) return;
385
+ return { type: "formulaInline", raw: line.slice(0, end + close.length), source: line.slice(0, end + close.length), tex, delimiter: parens ? "\\(" : "$" };
386
+ }
387
+ }
388
+ function blockFormula(src) {
389
+ const match = /^ {0,3}(\$\$|\\\[)([^\n]*)/.exec(src);
390
+ if (!match) return;
391
+ const [, open, rest] = match;
392
+ const closing = open === "$$" ? "$$" : "\\]";
393
+ const line = rest.trimEnd();
394
+ if (line.endsWith(closing) && !escaped(line, line.length - closing.length)) {
395
+ const tex = line.slice(0, -closing.length);
396
+ if (tex.trim() && !tex.includes(closing))
397
+ return { type: "formulaBlock", raw: match[0], source: match[0], tex, delimiter: open };
398
+ return;
399
+ }
400
+ if (rest.trim()) return;
401
+ let offset2 = match[0].length + 1;
402
+ const start = offset2;
403
+ while (offset2 < src.length) {
404
+ const next = src.indexOf("\n", offset2);
405
+ const end = next < 0 ? src.length : next;
406
+ const row = src.slice(offset2, end);
407
+ if (row.replace(/^ {0,3}/, "").trimEnd() === closing) {
408
+ const tex = src.slice(start, offset2 - 1);
409
+ if (tex.trim()) return { type: "formulaBlock", raw: src.slice(0, end), source: src.slice(0, end), tex, delimiter: open };
410
+ return;
411
+ }
412
+ if (!row.trim() || /^ {0,3}(?:#{1,6}\s|[~`]{3,})/.test(row) || end - start > 24576) return;
413
+ offset2 = end + 1;
414
+ }
415
+ }
416
+ var block = {
417
+ name: "formulaBlock",
418
+ level: "block",
419
+ start: (source) => /(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(source)?.index,
420
+ tokenizer: blockFormula
421
+ };
422
+ var inline = {
423
+ name: "formulaInline",
424
+ level: "inline",
425
+ start: (source) => {
426
+ const match = /[\\$]/.exec(source);
427
+ return match?.index;
428
+ },
429
+ tokenizer(src) {
430
+ if (src.startsWith("$$")) return { type: "text", raw: "$$", text: "$$" };
431
+ return inlineFormula(src);
432
+ }
433
+ };
434
+ var sourceOffsets = /* @__PURE__ */ new WeakMap();
435
+ var plotBlock = {
436
+ name: "notePlot",
437
+ level: "block",
438
+ tokenizer(src, tokens) {
439
+ if (tokens !== this.lexer.tokens) return;
440
+ const opening = /^ {0,3}(\x60{3,})dsh-plot[ \t]*(?:\n|$)/.exec(src);
441
+ const input = sourceOffsets.get(this.lexer);
442
+ if (!opening || !input) return;
443
+ const begin = opening[0].length;
444
+ let end = begin;
445
+ let closing = begin - Number(opening[0].endsWith("\n"));
446
+ let closed = false;
447
+ for (let cursor = begin; cursor < src.length; ) {
448
+ const next = src.indexOf("\n", cursor);
449
+ end = next === -1 ? src.length : next;
450
+ const line = src.slice(cursor, end);
451
+ const ticks = /^ {0,3}(\x60{3,})[ \t]*$/.exec(line);
452
+ if (ticks && ticks[1].length >= opening[1].length) {
453
+ closing = cursor;
454
+ closed = true;
455
+ break;
456
+ }
457
+ if (!line.trim() || /^ {0,3}(?:\x60{3,}|~{3,})/.test(line)) {
458
+ end = closing;
459
+ break;
460
+ }
461
+ closing = end;
462
+ cursor = end + 1;
463
+ }
464
+ end = closed ? end : closing;
465
+ const offset2 = input.length - src.length;
466
+ const start = input.originalOffset(offset2);
467
+ const finish = input.originalOffset(offset2 + end);
468
+ const token = {
469
+ type: "notePlot",
470
+ raw: src.slice(0, end),
471
+ source: input.source.slice(start, finish),
472
+ start,
473
+ end: finish,
474
+ ...closed ? parsePlotData(src.slice(begin, closing)) : { error: "\u56FE\u5757\u7F3A\u5C11\u7ED3\u675F\u56F4\u680F" }
475
+ };
476
+ return token;
477
+ }
478
+ };
479
+ var markdown = new Marked({ gfm: true, breaks: true, extensions: [block, inline, plotBlock] });
480
+ function formulaFromRaw(raw) {
481
+ const first = blockFormula(raw) ?? inlineFormula(raw);
482
+ return first?.source === raw ? first : void 0;
483
+ }
484
+ function lexNote(source) {
485
+ if (!source.includes("dsh-plot")) return markdown.lexer(source);
486
+ const lexer = new markdown.Lexer(markdown.defaults);
487
+ const breaks = [];
488
+ for (const match of source.matchAll(/\r\n/g)) breaks.push(match.index + 1 - breaks.length);
489
+ sourceOffsets.set(lexer, {
490
+ source,
491
+ length: source.length - breaks.length,
492
+ originalOffset(offset2) {
493
+ let lo = 0, hi = breaks.length;
494
+ while (lo < hi) {
495
+ const mid = lo + hi >>> 1;
496
+ if (breaks[mid] <= offset2) lo = mid + 1;
497
+ else hi = mid;
498
+ }
499
+ return offset2 + lo;
500
+ }
501
+ });
502
+ const tokens = lexer.lex(source);
503
+ const plots = tokens.filter(isPlot);
504
+ const ids = /* @__PURE__ */ new Set();
505
+ const duplicates = /* @__PURE__ */ new Set();
506
+ for (const { id } of plots) if (id) {
507
+ if (ids.has(id)) duplicates.add(id);
508
+ ids.add(id);
509
+ }
510
+ for (const token of plots) if (token.id && duplicates.has(token.id)) {
511
+ token.error = "\u56FE\u5757 ID \u91CD\u590D";
512
+ delete token.data;
513
+ delete token.expressions;
514
+ }
515
+ return tokens;
516
+ }
517
+ var notePlots = (source) => source.includes("dsh-plot") ? lexNote(source).filter(isPlot) : [];
518
+ var isFormula = (token) => token.type === "formulaInline" || token.type === "formulaBlock";
519
+ function noteBlocks(source, tokens = lexNote(source)) {
520
+ const normalized = source.replace(/\r\n?/g, "\n");
521
+ const breaks = [...source.matchAll(/\r\n/g)].map((match, index) => match.index + 1 - index);
522
+ const original = (at) => {
523
+ let lo = 0, hi = breaks.length;
524
+ while (lo < hi) {
525
+ const middle = lo + hi >>> 1;
526
+ if (breaks[middle] <= at) lo = middle + 1;
527
+ else hi = middle;
528
+ }
529
+ return at + lo;
530
+ };
531
+ const positions = /* @__PURE__ */ new WeakMap();
532
+ const blocks = [];
533
+ function findRange(raw, from, limit, projected) {
534
+ const direct = normalized.indexOf(raw, from);
535
+ if (!projected || !raw.includes("\n")) return direct < 0 ? void 0 : { at: direct, end: direct + raw.length };
536
+ const rows = raw.split("\n");
537
+ const first = rows[0];
538
+ for (let at = normalized.indexOf(first, from); at >= 0 && at < limit; at = normalized.indexOf(first, at + 1)) {
539
+ if (direct >= 0 && at >= direct) return { at: direct, end: direct + raw.length };
540
+ let end = at + first.length;
541
+ for (const row of rows.slice(1)) {
542
+ if (normalized[end] !== "\n") {
543
+ end = -1;
544
+ break;
545
+ }
546
+ end++;
547
+ if (!row) continue;
548
+ const next = normalized.indexOf(row, end);
549
+ if (next < end || next + row.length > limit || !/^[> \t]*$/.test(normalized.slice(end, next))) {
550
+ end = -1;
551
+ break;
552
+ }
553
+ end = next + row.length;
554
+ }
555
+ if (end >= at) return { at, end };
556
+ }
557
+ return void 0;
558
+ }
559
+ function scan(items, from, limit, top = false, projected = false) {
560
+ for (const token of items) {
561
+ if (!token.raw.length) continue;
562
+ const match = findRange(token.raw, from, limit, projected);
563
+ if (!match || match.end > limit || top && /\S/.test(normalized.slice(from, match.at))) {
564
+ if (top) return;
565
+ continue;
566
+ }
567
+ const { at, end } = match;
568
+ from = end;
569
+ const range2 = { start: original(at), end: original(from) };
570
+ positions.set(token, range2);
571
+ if (top && token.type !== "space") {
572
+ while (range2.end > range2.start && /[\r\n]/.test(source[range2.end - 1])) range2.end--;
573
+ blocks.push({ token, ...range2 });
574
+ }
575
+ const nested = token.tokens;
576
+ const prefix = token.type === "heading" ? /^ {0,3}#{1,6}(?:[ \t]+|$)/.exec(token.raw)?.[0].length : token.type === "blockquote" ? /^ {0,3}>[ \t]?/.exec(token.raw)?.[0].length : token.type === "list_item" ? /^\s*(?:[-+*]|\d{1,9}[.)])[ \t]+/.exec(token.raw)?.[0].length : token.type === "strong" || token.type === "del" ? 2 : token.type === "em" ? 1 : 0;
577
+ if (nested) scan(nested, at + (prefix ?? 0), from, false, projected || token.type === "blockquote" || token.type === "list_item");
578
+ else if (token.type === "list") scan(token.items, at, from, false, projected);
579
+ }
580
+ }
581
+ scan(tokens, 0, normalized.length, true);
582
+ return { positions, blocks };
583
+ }
584
+ function inlineSourcePoints(source, token, start) {
585
+ const text2 = token.text;
586
+ if (token.type !== "text" || token.raw !== text2 || token.tokens?.length) return;
587
+ const offsets = [start];
588
+ let offset2 = start;
589
+ for (const char of token.raw) {
590
+ offset2 += char === "\n" && source.startsWith("\r\n", offset2) ? 2 : char.length;
591
+ if (char.length === 2) offsets.push(-1);
592
+ offsets.push(offset2);
593
+ }
594
+ if (source.slice(start, offset2).replace(/\r\n?/g, "\n") === token.raw) return offsets;
595
+ }
596
+ function insertNoteBlock(source, at, block2) {
597
+ const eol = /\r\n|\n|\r/.exec(source)?.[0] ?? "\n";
598
+ const before = source.slice(0, at), after = source.slice(at);
599
+ const lines = (edge) => (edge.match(/\r\n|\n|\r/g) ?? []).length;
600
+ const left = /\s*$/.exec(before)[0], right = /^\s*/.exec(after)[0];
601
+ const leading = before.trim() ? eol.repeat(Math.max(0, 2 - lines(left))) : "";
602
+ const trailing = after.trim() ? eol.repeat(Math.max(0, 2 - lines(right))) : "";
603
+ return { markdown: before + leading + block2 + trailing + after, start: at + leading.length };
604
+ }
605
+ function manualPlotDelta(before, after) {
606
+ const previous = notePlots(before), next = notePlots(after);
607
+ const invalid = (items) => items.filter((plot) => !plot.data).map((plot) => plot.source);
608
+ const oldInvalid = invalid(previous), newInvalid = invalid(next);
609
+ if (oldInvalid.length !== newInvalid.length || oldInvalid.some((source, index) => source !== newInvalid[index])) return;
610
+ const prior = new Map(previous.flatMap((plot) => plot.data ? [[plot.data.id, plot.source]] : []));
611
+ const current = new Map(next.flatMap((plot) => plot.data ? [[plot.data.id, plot.source]] : []));
612
+ for (const [id, source] of current) if (prior.has(id) && prior.get(id) !== source) return;
613
+ return {
614
+ removed: [...prior].filter(([id]) => !current.has(id)),
615
+ restored: [...current].filter(([id]) => !prior.has(id))
616
+ };
617
+ }
618
+
619
+ // src/shared/note-math.ts
620
+ import katex from "katex";
621
+ var cache = /* @__PURE__ */ new Map();
622
+ function mathMarkup(tex, display) {
623
+ if (!tex.trim() || tex.length > 4096) return null;
624
+ const key = String(Number(display)) + tex;
625
+ if (cache.has(key)) return cache.get(key);
626
+ let html = null;
627
+ let denied = false;
628
+ try {
629
+ const rendered = katex.renderToString(tex, {
630
+ displayMode: display,
631
+ output: "htmlAndMathml",
632
+ throwOnError: true,
633
+ trust: () => {
634
+ denied = true;
635
+ return false;
636
+ },
637
+ maxExpand: 200,
638
+ maxSize: 20,
639
+ macros: {}
640
+ });
641
+ if (!denied) html = rendered;
642
+ } catch {
643
+ }
644
+ if (cache.size >= 64) cache.delete(cache.keys().next().value);
645
+ cache.set(key, html);
646
+ return html;
647
+ }
648
+
649
+ // src/shared/note-position.ts
650
+ var sha = z3.string().regex(/^[a-f0-9]{64}$/);
651
+ var offset = z3.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
652
+ var base2 = { version: z3.literal(1), mapId: idSchema, nodeId: idSchema, noteDigest: sha };
653
+ var noteAnchorSchema = z3.discriminatedUnion("kind", [
654
+ z3.strictObject({ ...base2, kind: z3.literal("start") }),
655
+ z3.strictObject({
656
+ ...base2,
657
+ version: z3.literal(2),
658
+ kind: z3.literal("gap"),
659
+ offset,
660
+ previousBlockDigest: sha.nullable(),
661
+ nextBlockDigest: sha.nullable()
662
+ }),
663
+ z3.strictObject({
664
+ ...base2,
665
+ kind: z3.literal("block"),
666
+ blockStart: offset,
667
+ blockLength: offset.positive(),
668
+ blockDigest: sha,
669
+ clickOffset: offset,
670
+ previousBlockDigest: sha.nullable(),
671
+ nextBlockDigest: sha.nullable()
672
+ })
673
+ ]);
674
+ var noteInsertKind = z3.enum(["inline_formula", "display_formula", "plot"]);
675
+ function* inlineTokens(token) {
676
+ if (["code", "codespan", "link", "image", "html", "escape", "table"].includes(token.type)) return;
677
+ yield token;
678
+ const nested = token.tokens ?? (token.type === "list" ? token.items : []);
679
+ for (const child of nested) yield* inlineTokens(child);
680
+ }
681
+ function hasInlineBoundary(source, block2, at, positions) {
682
+ for (const token of inlineTokens(block2.token)) {
683
+ const range2 = positions.get(token);
684
+ if (range2 && at >= range2.start && at <= range2.end && inlineSourcePoints(source, token, range2.start)?.includes(at)) return true;
685
+ }
686
+ return false;
687
+ }
688
+ var blockDigest = (source, block2) => block2 ? digest(source.slice(block2.start, block2.end)) : null;
689
+ function gapOffset(source, blocks, index) {
690
+ const start = blocks[index - 1]?.end ?? 0;
691
+ const end = blocks[index]?.start ?? source.length;
692
+ if (start <= end && !source.slice(start, end).trim()) return start;
693
+ }
694
+ async function locateNoteAnchor(source, anchor) {
695
+ if (anchor.kind === "start") return source.trim() ? void 0 : { inline: 0, after: 0 };
696
+ const { blocks, positions } = noteBlocks(source);
697
+ const exact = await digest(source) === anchor.noteDigest;
698
+ if (anchor.kind === "gap") {
699
+ const hashes = await Promise.all(blocks.map((block2) => blockDigest(source, block2)));
700
+ let found;
701
+ for (let index = 0; index <= blocks.length; index++) {
702
+ if ((hashes[index - 1] ?? null) !== anchor.previousBlockDigest || (hashes[index] ?? null) !== anchor.nextBlockDigest) continue;
703
+ const at = gapOffset(source, blocks, index);
704
+ if (at === void 0 || exact && at !== anchor.offset) continue;
705
+ if (found) return;
706
+ found = { inline: at, after: at, gapIndex: index };
707
+ }
708
+ return found;
709
+ }
710
+ if (anchor.clickOffset > anchor.blockLength) return;
711
+ const possible = await Promise.all(blocks.map(async (block2, index) => {
712
+ if (block2.end - block2.start !== anchor.blockLength || exact && block2.start !== anchor.blockStart) return;
713
+ const at = block2.start + anchor.clickOffset;
714
+ if (!hasInlineBoundary(source, block2, at, positions) || await blockDigest(source, block2) !== anchor.blockDigest) return;
715
+ if (!exact && (await blockDigest(source, blocks[index - 1]) !== anchor.previousBlockDigest || await blockDigest(source, blocks[index + 1]) !== anchor.nextBlockDigest)) return;
716
+ return { inline: at, after: block2.token.type === "paragraph" ? block2.end : void 0, block: block2 };
717
+ }));
718
+ const matches = possible.filter((match) => match !== void 0);
719
+ if (matches.length === 1) return matches[0];
720
+ }
721
+ async function insertAnchoredNote(source, anchor, kind, fragment) {
722
+ const location = await locateNoteAnchor(source, anchor);
723
+ if (!location) throw new Error("\u539F\u4F4D\u7F6E\u5DF2\u53D8\u5316\u6216\u65E0\u6CD5\u552F\u4E00\u786E\u8BA4\uFF0C\u8BF7\u91CD\u65B0\u9009\u70B9");
724
+ const inline2 = kind === "inline_formula";
725
+ const raw = fragment.trim();
726
+ const token = kind === "plot" ? noteBlocks(raw).blocks[0]?.token : formulaFromRaw(raw.replace(/\r\n?/g, "\n"));
727
+ if (kind === "plot") {
728
+ if (!token || !isPlot(token) || !token.data || token.source !== raw) throw new Error("\u8BF7\u63D0\u4F9B\u4E00\u5F20\u5B8C\u6574\u4E14\u6709\u6548\u7684\u56FE\u8868");
729
+ } else if (!token || !isFormula(token) || token.type === "formulaInline" !== inline2 || mathMarkup(token.tex, !inline2) === null) {
730
+ throw new Error("\u8BF7\u63D0\u4F9B\u4E00\u4E2A\u4E0E\u63D2\u5165\u4F4D\u7F6E\u5339\u914D\u7684\u6709\u6548\u516C\u5F0F");
731
+ }
732
+ if (!inline2 && location.after === void 0) throw new Error("\u8BF7\u5728\u53EF\u63D2\u5165\u72EC\u7ACB\u5185\u5BB9\u7684\u6B63\u6587\u6BB5\u843D\u91CD\u65B0\u9009\u70B9");
733
+ const at = inline2 ? location.inline : location.after;
734
+ const result = inline2 && location.gapIndex === void 0 ? { markdown: source.slice(0, at) + raw + source.slice(at), start: at } : insertNoteBlock(source, at, raw);
735
+ const { blocks, positions } = noteBlocks(result.markdown);
736
+ const end = result.start + raw.length;
737
+ const matches = ({ token: item, start, end: finish }) => item.type === token.type && start === result.start && finish === end;
738
+ if (!inline2) {
739
+ if (!blocks.some((block2) => matches(block2) && (!isPlot(block2.token) || !!block2.token.data)))
740
+ throw new Error("\u63D2\u5165\u4F1A\u6539\u53D8\u5468\u56F4\u6B63\u6587\u89E3\u6790\uFF0C\u8BF7\u91CD\u65B0\u9009\u70B9");
741
+ } else {
742
+ const target = blocks.find((block2) => block2.start <= result.start && block2.end >= end);
743
+ if (!target || location.gapIndex !== void 0 && (target.token.type !== "paragraph" || target.start !== result.start || target.end !== end) || ![...inlineTokens(target.token)].some((item) => {
744
+ const range2 = positions.get(item);
745
+ return range2 && matches({ token: item, ...range2 });
746
+ })) throw new Error("\u70B9\u51FB\u5904\u65E0\u6CD5\u4FDD\u7559\u884C\u5185\u516C\u5F0F\u8FB9\u754C\uFF0C\u8BF7\u91CD\u65B0\u9009\u70B9");
747
+ }
748
+ const previous = noteBlocks(source).blocks;
749
+ const unchanged = inline2 && location.block ? previous.filter((block2) => block2.start !== location.block?.start) : previous;
750
+ for (const block2 of unchanged) {
751
+ const delta = block2.start >= at ? result.markdown.length - source.length : 0;
752
+ if (!blocks.some((next) => next.start === block2.start + delta && next.end === block2.end + delta && next.token.type === block2.token.type))
753
+ throw new Error("\u63D2\u5165\u4F1A\u6539\u53D8\u5468\u56F4\u6B63\u6587\u89E3\u6790\uFF0C\u8BF7\u91CD\u65B0\u9009\u70B9");
754
+ }
755
+ return result.markdown;
756
+ }
757
+
758
+ // src/server/edit-service.ts
759
+ import { z as z7 } from "zod";
760
+
761
+ // src/shared/validate-layout.ts
762
+ import { z as z4 } from "zod";
763
+ var finite = z4.number().finite();
764
+ var layoutSchema = z4.strictObject({
765
+ schemaVersion: z4.union([z4.literal(1), z4.literal(2)]),
766
+ mapId: idSchema,
767
+ views: z4.array(
768
+ z4.strictObject({
769
+ viewId: idSchema,
770
+ mode: z4.enum(["vertical", "grid", "columns"]).optional(),
771
+ nodes: z4.array(
772
+ z4.strictObject({
773
+ nodeId: idSchema,
774
+ x: finite,
775
+ y: finite,
776
+ width: finite.positive(),
777
+ manual: z4.boolean()
778
+ })
779
+ ),
780
+ groups: z4.array(
781
+ z4.strictObject({
782
+ groupId: idSchema,
783
+ x: finite,
784
+ y: finite,
785
+ width: finite.positive(),
786
+ height: finite.positive()
787
+ })
788
+ )
789
+ })
790
+ )
791
+ });
792
+ function validateLayout(input, map) {
793
+ if (input === void 0) return { ok: true, value: void 0 };
794
+ const p = layoutSchema.safeParse(input);
795
+ if (!p.success)
796
+ return {
797
+ ok: false,
798
+ diagnostics: p.error.issues.map((i) => ({
799
+ path: ["layout.json", ...i.path].join("."),
800
+ message: i.message,
801
+ code: "invalid_layout"
802
+ }))
803
+ };
804
+ const errors = [];
805
+ if (p.data.schemaVersion === 1 && p.data.views.some((v) => v.mode !== void 0)) errors.push("v1 \u5E03\u5C40\u4E0D\u80FD\u5305\u542B\u6392\u5217\u6A21\u5F0F");
806
+ if (p.data.schemaVersion === 2 && p.data.views.some((v) => !v.mode)) errors.push("v2 \u5E03\u5C40\u5FC5\u987B\u5305\u542B\u6392\u5217\u6A21\u5F0F");
807
+ if (p.data.mapId !== map.id) errors.push("mapId \u5FC5\u987B\u4E0E\u5730\u56FE\u4E00\u81F4");
808
+ const check = (ids, path) => {
809
+ if (new Set(ids).size !== ids.length) errors.push(`${path} \u5305\u542B\u91CD\u590D\u8EAB\u4EFD`);
810
+ };
811
+ check(
812
+ p.data.views.map((v) => v.viewId),
813
+ "views"
814
+ );
815
+ for (const v of p.data.views) {
816
+ check(
817
+ v.nodes.map((n) => n.nodeId),
818
+ `views.${v.viewId}.nodes`
819
+ );
820
+ check(
821
+ v.groups.map((g) => g.groupId),
822
+ `views.${v.viewId}.groups`
823
+ );
824
+ }
825
+ return errors.length ? {
826
+ ok: false,
827
+ diagnostics: errors.map((message) => ({
828
+ path: "layout.json",
829
+ message,
830
+ code: "invalid_layout"
831
+ }))
832
+ } : { ok: true, value: p.data };
833
+ }
834
+
835
+ // src/shared/image-resource.ts
836
+ import { z as z5 } from "zod";
837
+ var IMAGE_LIMIT = 8 * 1024 * 1024;
838
+ var imageAssetSchema = z5.strictObject({
839
+ schemaVersion: z5.literal(1),
840
+ kind: z5.literal("image"),
841
+ id: z5.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
842
+ mimeType: z5.enum(["image/png", "image/jpeg", "image/webp"]),
843
+ encoding: z5.literal("base64"),
844
+ byteLength: z5.number().int().positive().max(IMAGE_LIMIT),
845
+ sha256: z5.string().regex(/^[a-f0-9]{64}$/),
846
+ data: z5.string().max(Math.ceil(IMAGE_LIMIT / 3) * 4)
847
+ });
848
+ async function validateImage(input) {
849
+ const asset = imageAssetSchema.parse(input);
850
+ let bytes;
851
+ try {
852
+ if (asset.data.length % 4 || /[^A-Za-z0-9+/=]/.test(asset.data)) throw new Error("base64");
853
+ const binary = atob(asset.data);
854
+ if (btoa(binary) !== asset.data) throw new Error("base64");
855
+ bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
856
+ } catch {
857
+ throw Object.assign(new Error("\u56FE\u7247\u7F16\u7801\u65E0\u6548"), { code: "invalid_image" });
858
+ }
859
+ const signature = asset.mimeType === "image/png" ? [137, 80, 78, 71, 13, 10, 26, 10].every((v, i) => bytes[i] === v) : asset.mimeType === "image/jpeg" ? bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255 : new TextDecoder().decode(bytes.slice(0, 4)) === "RIFF" && new TextDecoder().decode(bytes.slice(8, 12)) === "WEBP";
860
+ if (!signature || bytes.length !== asset.byteLength || await digest(bytes) !== asset.sha256) throw Object.assign(new Error("\u56FE\u7247\u683C\u5F0F\u3001\u957F\u5EA6\u6216\u6458\u8981\u4E0D\u5339\u914D"), { code: "invalid_image" });
861
+ return asset;
862
+ }
863
+ var imageUrl = (a) => `data:${a.mimeType};base64,${a.data}`;
864
+
865
+ // src/server/map-files.ts
866
+ import { posix } from "node:path";
867
+ import { walkTokens } from "marked";
868
+ var DATA_ROOT = "dsh-knowledge-maps";
869
+ var AtlasError = class extends Error {
870
+ code;
871
+ diagnostics;
872
+ constructor(code, message, diagnostics = []) {
873
+ super(message);
874
+ this.code = code;
875
+ this.diagnostics = diagnostics;
876
+ }
877
+ };
878
+ var errorCode = (e) => typeof e === "object" && e !== null && "code" in e ? String(e.code) : e instanceof SyntaxError || e instanceof Error && e.name === "ZodError" ? "invalid_data" : "storage_failure";
879
+ var missing = (e) => ["workspace-file/not-found", "FS_NOT_FOUND"].includes(errorCode(e));
880
+ function localPath(path) {
881
+ const raw = path.replaceAll("\\", "/");
882
+ if (!raw || raw.includes("\0") || raw.startsWith("/") || /^[A-Za-z][A-Za-z0-9+.-]*:/.test(raw))
883
+ throw new AtlasError("path_outside_map", `\u62D2\u7EDD\u975E\u76F8\u5BF9\u8DEF\u5F84\uFF1A${path}`);
884
+ const normalized = posix.normalize(raw);
885
+ if (normalized === ".." || normalized.startsWith("../"))
886
+ throw new AtlasError("path_outside_map", `\u8DEF\u5F84\u8D8A\u754C\uFF1A${path}`);
887
+ return normalized;
888
+ }
889
+ function mapPath(id, path) {
890
+ if (!/^[A-Za-z0-9_-]+$/.test(id))
891
+ throw new AtlasError("invalid_data", "\u5730\u56FE\u8EAB\u4EFD\u975E\u6CD5");
892
+ return `${DATA_ROOT}/${id}/${localPath(path)}`;
893
+ }
894
+ function createHostFiles(ctx, scope, signal, policy) {
895
+ const targets = /* @__PURE__ */ new Map();
896
+ async function boundary(path, mapId, assetsOnly = false) {
897
+ const root = await ctx.fs.resolve(scope.workspaceRoot, { signal });
898
+ const data = await ctx.fs.resolve(DATA_ROOT, {
899
+ cwd: scope.workspaceRoot,
900
+ signal
901
+ });
902
+ const map = await ctx.fs.resolve(`${DATA_ROOT}/${mapId}`, {
903
+ cwd: scope.workspaceRoot,
904
+ signal
905
+ });
906
+ const target = await ctx.fs.resolve(path, {
907
+ cwd: scope.workspaceRoot,
908
+ signal
909
+ });
910
+ if (!ctx.fs.contains(root, data) || !ctx.fs.contains(data, map) || !ctx.fs.contains(map, target) || target.targetKey === map.targetKey)
911
+ throw new AtlasError("path_outside_map", `\u771F\u5B9E\u8DEF\u5F84\u8D8A\u8FC7\u5730\u56FE\u8FB9\u754C\uFF1A${path}`);
912
+ if (assetsOnly) {
913
+ const assets = await ctx.fs.resolve(`${DATA_ROOT}/${mapId}/assets`, {
914
+ cwd: scope.workspaceRoot,
915
+ signal
916
+ });
917
+ if (!ctx.fs.contains(map, assets) || !ctx.fs.contains(assets, target))
918
+ throw new AtlasError("path_outside_map", `\u8D44\u6E90\u4E0D\u5728\u672C\u56FE assets\uFF1A${path}`);
919
+ }
920
+ targets.set(path, target);
921
+ return target;
922
+ }
923
+ return {
924
+ workspaceKey: scope.workspaceRoot,
925
+ async read(path, mapId, assetsOnly) {
926
+ const target = await boundary(path, mapId, assetsOnly);
927
+ const chunks = [];
928
+ let version;
929
+ let offset2 = 0;
930
+ while (true) {
931
+ const page = await ctx.workspaceFiles.readBytes(
932
+ scope,
933
+ path,
934
+ { range: { offset: offset2, length: 1024 * 1024 } },
935
+ signal
936
+ );
937
+ if (version !== void 0 && version !== page.version)
938
+ throw new AtlasError("version_conflict", `${path} \u5728\u8BFB\u53D6\u4E2D\u53D1\u751F\u53D8\u5316`);
939
+ version = page.version;
940
+ chunks.push(page.data);
941
+ offset2 += page.data.length;
942
+ if (offset2 > 64 * 1024 * 1024)
943
+ throw new AtlasError(
944
+ "too_large",
945
+ `${path} \u8D85\u8FC7\u63D2\u4EF6\u5355\u6587\u4EF6 64 MiB \u4E0A\u9650`
946
+ );
947
+ if (page.eof) break;
948
+ if (page.data.length === 0)
949
+ throw new AtlasError("storage_failure", `${path} \u5206\u9875\u8BFB\u53D6\u6CA1\u6709\u524D\u8FDB`);
950
+ }
951
+ const bytes = new Uint8Array(offset2);
952
+ let cursor = 0;
953
+ for (const chunk of chunks) {
954
+ bytes.set(chunk, cursor);
955
+ cursor += chunk.length;
956
+ }
957
+ const after = await ctx.workspaceFiles.stat(scope, path, signal);
958
+ if (after.version !== version || (await boundary(path, mapId, assetsOnly)).targetKey !== target.targetKey)
959
+ throw new AtlasError(
960
+ "version_conflict",
961
+ `${path} \u8BFB\u53D6\u671F\u95F4\u8EAB\u4EFD\u6216\u7248\u672C\u53D8\u5316`
962
+ );
963
+ return {
964
+ bytes,
965
+ version: after.version,
966
+ identity: String(target.targetKey)
967
+ };
968
+ },
969
+ async absent(path) {
970
+ const id = path.split("/")[1];
971
+ if (id) await boundary(path, id);
972
+ try {
973
+ await ctx.workspaceFiles.stat(scope, path, signal);
974
+ return false;
975
+ } catch (e) {
976
+ if (missing(e)) return true;
977
+ throw e;
978
+ }
979
+ },
980
+ async list() {
981
+ try {
982
+ const root = await ctx.fs.resolve(scope.workspaceRoot, { signal });
983
+ const data = await ctx.fs.resolve(DATA_ROOT, {
984
+ cwd: scope.workspaceRoot,
985
+ signal
986
+ });
987
+ if (!ctx.fs.contains(root, data))
988
+ throw new AtlasError("path_outside_map", "\u5730\u56FE\u6570\u636E\u76EE\u5F55\u8D8A\u8FC7\u5DE5\u4F5C\u533A");
989
+ const listing = await ctx.workspaceFiles.list(scope, DATA_ROOT, signal);
990
+ if (listing.truncated)
991
+ throw new AtlasError(
992
+ "too_large",
993
+ "\u5730\u56FE\u76EE\u5F55\u5217\u4E3E\u88AB\u5BBF\u4E3B\u622A\u65AD\uFF0C\u8BF7\u51CF\u5C11\u76EE\u5F55\u6570\u91CF\u540E\u91CD\u8BD5"
994
+ );
995
+ return listing.entries.filter((e) => e.type === "directory").map((e) => e.name);
996
+ } catch (e) {
997
+ if (missing(e)) return [];
998
+ throw e;
999
+ }
1000
+ },
1001
+ async listEntries(id, relative) {
1002
+ const path = mapPath(id, relative);
1003
+ await boundary(`${path}/.boundary`, id);
1004
+ const entry = await ctx.fs.lstat(path, { cwd: scope.workspaceRoot }, signal);
1005
+ if (!entry || entry.type !== "directory") throw new AtlasError("invalid_data", "\u5360\u4F4D\u76EE\u5F55\u5FC5\u987B\u4E3A\u666E\u901A\u76EE\u5F55");
1006
+ const listing = await ctx.workspaceFiles.list(scope, path, signal);
1007
+ if (listing.truncated) throw new AtlasError("too_large", "\u5360\u4F4D\u76EE\u5F55\u5217\u4E3E\u88AB\u622A\u65AD\uFF0C\u4FDD\u7559\u539F\u8D44\u6599");
1008
+ for (const child of listing.entries) {
1009
+ const info = await ctx.fs.lstat(`${path}/${child.name}`, { cwd: scope.workspaceRoot }, signal);
1010
+ if (!info || info.type !== child.type) throw new AtlasError("version_conflict", "\u5360\u4F4D\u76EE\u5F55\u542B\u94FE\u63A5\u6216\u8BFB\u53D6\u671F\u95F4\u53D1\u751F\u53D8\u5316");
1011
+ }
1012
+ return listing.entries;
1013
+ },
1014
+ async writeLayout(id, text2, expectedVersion) {
1015
+ const path = mapPath(id, "layout.json");
1016
+ const target = await boundary(path, id);
1017
+ const entry = await ctx.fs.lstat(
1018
+ path,
1019
+ { cwd: scope.workspaceRoot },
1020
+ signal
1021
+ );
1022
+ if (entry && entry.type !== "file")
1023
+ throw new AtlasError("path_outside_map", "\u5E03\u5C40\u76EE\u6807\u5FC5\u987B\u662F\u666E\u901A\u6587\u4EF6");
1024
+ const info = await ctx.fs.stat(target, signal);
1025
+ if ((info?.version ?? void 0) !== expectedVersion)
1026
+ throw new AtlasError("version_conflict", "\u5E03\u5C40\u6587\u4EF6\u5DF2\u53D8\u5316");
1027
+ await ctx.fs.writeText(
1028
+ target,
1029
+ text2,
1030
+ info ? { kind: "replaceIfVersion", version: info.version } : { kind: "createIfAbsent" },
1031
+ signal,
1032
+ policy
1033
+ );
1034
+ }
1035
+ };
1036
+ }
1037
+ var decode = (bytes) => new TextDecoder("utf-8", { fatal: true }).decode(bytes);
1038
+ async function inspectCreatePlaceholder(port, id, cleanupLock) {
1039
+ if (!port.listEntries || !await port.absent(mapPath(id, "map.json"))) return void 0;
1040
+ const root = await port.listEntries(id, ".");
1041
+ if (!root.some((e) => e.name === ".transactions" && e.type === "directory")) return void 0;
1042
+ if (root.some((e) => e.name !== ".transactions" && !(e.name === "notes" && e.type === "directory"))) return void 0;
1043
+ if (root.some((e) => e.name === "notes") && (await port.listEntries(id, "notes")).length) return void 0;
1044
+ const transactions = await port.listEntries(id, ".transactions");
1045
+ const operations = transactions.filter((e) => e.type === "directory" && /^[A-Za-z0-9_-]+$/.test(e.name));
1046
+ const discarded = transactions.some((e) => e.name === "discarded-create.json" && e.type === "file");
1047
+ if (operations.length !== 1 || transactions.length !== operations.length + (cleanupLock ? 1 : 0) + (discarded ? 1 : 0)) return void 0;
1048
+ if (cleanupLock) {
1049
+ if (!transactions.some((e) => e.name === "active.json" && e.type === "file")) return void 0;
1050
+ if (decode((await port.read(mapPath(id, ".transactions/active.json"), id)).bytes) !== cleanupLock) return void 0;
1051
+ }
1052
+ const operationId = operations[0].name;
1053
+ const expectedId = "map-" + (await digest(new TextEncoder().encode(JSON.stringify({ operationId })))).slice(0, 32);
1054
+ if (id !== expectedId) return void 0;
1055
+ const prefix = `.transactions/${operationId}`;
1056
+ const entries = await port.listEntries(id, prefix);
1057
+ if (!entries.length && !discarded || entries.some((e) => e.type !== "file" || !["reservation.json", "failed.json"].includes(e.name))) return void 0;
1058
+ let request;
1059
+ let state = "reserved";
1060
+ if (discarded) {
1061
+ const record = JSON.parse(decode((await port.read(mapPath(id, ".transactions/discarded-create.json"), id)).bytes));
1062
+ if (!record || record.kind !== "discarded_create" || record.mapId !== id || record.operationId !== operationId || typeof record.request !== "string" || !/^[a-f0-9]{64}$/.test(record.request)) return void 0;
1063
+ request = record.request;
1064
+ }
1065
+ for (const entry of entries) {
1066
+ const raw = decode((await port.read(mapPath(id, `${prefix}/${entry.name}`), id)).bytes);
1067
+ let value = raw;
1068
+ if (entry.name === "failed.json") {
1069
+ const failure = JSON.parse(raw);
1070
+ if (!failure || failure.kind !== "failed_create" || failure.operationId !== operationId || typeof failure.code !== "string") return void 0;
1071
+ value = failure.request;
1072
+ state = "failed";
1073
+ }
1074
+ if (typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value) || request !== void 0 && request !== value) return void 0;
1075
+ request = value;
1076
+ }
1077
+ if (entries.some((e) => e.name === "reservation.json")) state = "reserved";
1078
+ if (discarded) state = entries.length ? "cleanup_pending" : "discarded";
1079
+ if (!await port.absent(mapPath(id, "map.json")) || !await port.absent(mapPath(id, ".transactions/purge.json"))) return void 0;
1080
+ if (!cleanupLock && !await port.absent(mapPath(id, ".transactions/active.json"))) return void 0;
1081
+ return { mapId: id, operationId, request, state };
1082
+ }
1083
+ async function listedPlaceholder(port, id) {
1084
+ try {
1085
+ return await inspectCreatePlaceholder(port, id);
1086
+ } catch {
1087
+ return void 0;
1088
+ }
1089
+ }
1090
+ async function readSnapshot(port, mapId, allowResourceErrors = false) {
1091
+ const resourceErrors = [];
1092
+ const files = [];
1093
+ const records = /* @__PURE__ */ new Map();
1094
+ async function read(relative, assetsOnly = false) {
1095
+ const path = mapPath(mapId, relative);
1096
+ const cached = records.get(path);
1097
+ if (cached) return cached;
1098
+ const record = await port.read(path, mapId, assetsOnly);
1099
+ records.set(path, record);
1100
+ files.push({
1101
+ path,
1102
+ version: record.version,
1103
+ digest: await digest(record.bytes)
1104
+ });
1105
+ return record;
1106
+ }
1107
+ const structure = validateMap(
1108
+ JSON.parse(decode((await read("map.json")).bytes)),
1109
+ mapId
1110
+ );
1111
+ if (!structure.ok)
1112
+ throw new AtlasError(
1113
+ "invalid_data",
1114
+ "\u5730\u56FE\u7ED3\u6784\u6821\u9A8C\u5931\u8D25",
1115
+ structure.diagnostics
1116
+ );
1117
+ const map = structure.value;
1118
+ if (!await port.absent(mapPath(mapId, ".transactions/active.json")))
1119
+ throw new AtlasError(
1120
+ "recovery_required",
1121
+ "\u5730\u56FE\u5B58\u5728\u6D3B\u52A8\u6216\u5F85\u6062\u590D\u64CD\u4F5C\uFF0C\u6682\u4E0D\u5F00\u653E"
1122
+ );
1123
+ if (!await port.absent(mapPath(mapId, ".transactions/purge.json")))
1124
+ throw new AtlasError("purge_pending", "\u5730\u56FE\u6B63\u5728\u6C38\u4E45\u5220\u9664\u6216\u5DF2\u5220\u9664\uFF1B\u8BF7\u5728\u56DE\u6536\u7AD9\u91CD\u8BD5\u672A\u5B8C\u6210\u7684\u5220\u9664");
1125
+ const layoutAbsent = await port.absent(mapPath(mapId, "layout.json"));
1126
+ const layoutInput = layoutAbsent ? void 0 : JSON.parse(decode((await read("layout.json")).bytes));
1127
+ const layout = validateLayout(layoutInput, map);
1128
+ if (!layout.ok)
1129
+ throw new AtlasError(
1130
+ "invalid_layout",
1131
+ "\u5E03\u5C40\u6587\u4EF6\u6821\u9A8C\u5931\u8D25",
1132
+ layout.diagnostics
1133
+ );
1134
+ const notes = /* @__PURE__ */ Object.create(null);
1135
+ const resources = /* @__PURE__ */ Object.create(null);
1136
+ const noteIdentities = /* @__PURE__ */ new Set();
1137
+ for (const node2 of map.nodes) {
1138
+ notes[node2.id] = "";
1139
+ if (!node2.notePath) continue;
1140
+ const path = localPath(node2.notePath);
1141
+ if (!/\.md$/i.test(path) || /(^|\/)(exports|\.transactions)(\/|$)/.test(path))
1142
+ throw new AtlasError(
1143
+ "invalid_data",
1144
+ `${node2.id} \u7684 notePath \u5FC5\u987B\u662F\u5730\u56FE\u5185 Markdown \u6587\u4EF6`
1145
+ );
1146
+ const record = await read(path);
1147
+ if (noteIdentities.has(record.identity))
1148
+ throw new AtlasError(
1149
+ "invalid_data",
1150
+ `\u4E0D\u540C\u8282\u70B9\u5F15\u7528\u4E86\u540C\u4E00\u7B14\u8BB0\u6587\u4EF6\uFF1A${path}`
1151
+ );
1152
+ noteIdentities.add(record.identity);
1153
+ const text2 = decode(record.bytes);
1154
+ notes[node2.id] = text2;
1155
+ const local = /* @__PURE__ */ new Set();
1156
+ walkTokens(lexNote(text2), (token) => {
1157
+ if ((token.type === "image" || token.type === "link") && "href" in token && typeof token.href === "string" && !/^(https?:|mailto:|#)/i.test(token.href))
1158
+ local.add(token.href);
1159
+ });
1160
+ for (const href of local) {
1161
+ const clean = decodeURIComponent(href.split(/[?#]/)[0]);
1162
+ const relative = localPath(posix.join(posix.dirname(path), clean));
1163
+ if (!relative.startsWith("assets/"))
1164
+ throw new AtlasError(
1165
+ "path_outside_map",
1166
+ `\u672C\u5730\u8D44\u6E90\u5FC5\u987B\u4F4D\u4E8E assets\uFF1A${href}`
1167
+ );
1168
+ try {
1169
+ const asset = await read(relative, true);
1170
+ if (relative.endsWith(".image.json")) {
1171
+ const image = await validateImage(JSON.parse(decode(asset.bytes)));
1172
+ if (relative !== `assets/${image.id}.image.json`) throw new AtlasError("invalid_data", "\u56FE\u7247\u8EAB\u4EFD\u4E0E\u8DEF\u5F84\u4E0D\u7B26");
1173
+ resources[`${node2.id}:${href}`] = imageUrl(image);
1174
+ continue;
1175
+ }
1176
+ const mime = {
1177
+ png: "image/png",
1178
+ jpg: "image/jpeg",
1179
+ jpeg: "image/jpeg",
1180
+ gif: "image/gif",
1181
+ webp: "image/webp",
1182
+ pdf: "application/pdf",
1183
+ txt: "text/plain"
1184
+ }[posix.extname(relative).slice(1).toLowerCase()];
1185
+ if (!mime)
1186
+ throw new AtlasError(
1187
+ "invalid_data",
1188
+ `\u8D44\u6E90\u7C7B\u578B\u4E0D\u53D7\u652F\u6301\uFF1A${href}\uFF1B\u652F\u6301 png/jpg/gif/webp/pdf/txt`
1189
+ );
1190
+ resources[`${node2.id}:${href}`] = `data:${mime};base64,${Buffer.from(asset.bytes).toString("base64")}`;
1191
+ } catch (e) {
1192
+ if (!allowResourceErrors || !(missing(e) || ["invalid_data", "invalid_image", "too_large"].includes(errorCode(e)))) throw e;
1193
+ resourceErrors.push({ path: `${node2.id}:${href}`, code: "resource_unavailable", message: String(e) });
1194
+ }
1195
+ }
1196
+ }
1197
+ for (const file of files) {
1198
+ const again = await port.read(
1199
+ file.path,
1200
+ mapId,
1201
+ file.path.startsWith(`${DATA_ROOT}/${mapId}/assets/`)
1202
+ );
1203
+ if (again.version !== file.version || await digest(again.bytes) !== file.digest || again.identity !== records.get(file.path)?.identity)
1204
+ throw new AtlasError("version_conflict", `${file.path} \u52A0\u8F7D\u671F\u95F4\u5DF2\u53D8\u5316`);
1205
+ }
1206
+ if (layoutAbsent && !await port.absent(mapPath(mapId, "layout.json")))
1207
+ throw new AtlasError("version_conflict", "\u52A0\u8F7D\u671F\u95F4\u65B0\u589E\u4E86\u5E03\u5C40");
1208
+ if (!await port.absent(mapPath(mapId, ".transactions/active.json")))
1209
+ throw new AtlasError("recovery_required", "\u8BFB\u53D6\u671F\u95F4\u5730\u56FE\u5F00\u59CB\u63D0\u4EA4");
1210
+ return {
1211
+ map,
1212
+ layout: layout.value,
1213
+ notes,
1214
+ resources,
1215
+ files,
1216
+ fingerprint: resourceErrors.length ? "" : await fingerprint(files),
1217
+ writable: !resourceErrors.length,
1218
+ diagnostics: resourceErrors,
1219
+ workspaceKey: port.workspaceKey
1220
+ };
1221
+ }
1222
+ async function listMapHeaders(port, excluded = /* @__PURE__ */ new Set()) {
1223
+ const ids = (await port.list()).filter((id) => !excluded.has(id));
1224
+ const entries = new Array(ids.length);
1225
+ const incompleteCreates = [];
1226
+ let next = 0;
1227
+ const worker = async () => {
1228
+ while (next < ids.length) {
1229
+ const index = next++;
1230
+ const id = ids[index];
1231
+ try {
1232
+ const placeholder = await listedPlaceholder(port, id);
1233
+ if (placeholder) {
1234
+ if (placeholder.state !== "discarded") incompleteCreates.push({ mapId: id, operationId: placeholder.operationId, state: placeholder.state });
1235
+ continue;
1236
+ }
1237
+ const inactive = async () => {
1238
+ if (!await port.absent(mapPath(id, ".transactions/active.json"))) throw new AtlasError("recovery_required", "\u5730\u56FE\u6B63\u5728\u63D0\u4EA4\u6216\u5F85\u6062\u590D");
1239
+ if (!await port.absent(mapPath(id, ".transactions/purge.json"))) throw new AtlasError("purge_pending", "\u5730\u56FE\u6B63\u5728\u6C38\u4E45\u5220\u9664\u6216\u5DF2\u5220\u9664");
1240
+ };
1241
+ await inactive();
1242
+ const record = await port.read(mapPath(id, "map.json"), id);
1243
+ const checked = validateMap(JSON.parse(decode(record.bytes)), id);
1244
+ if (!checked.ok) throw new AtlasError("invalid_data", "\u5730\u56FE\u7ED3\u6784\u6821\u9A8C\u5931\u8D25", checked.diagnostics);
1245
+ await inactive();
1246
+ entries[index] = { id, title: checked.value.title };
1247
+ } catch (e) {
1248
+ entries[index] = { path: `${DATA_ROOT}/${id}`, code: errorCode(e), message: e instanceof Error ? e.message : String(e) };
1249
+ }
1250
+ }
1251
+ };
1252
+ await Promise.all(Array.from({ length: Math.min(4, ids.length) }, worker));
1253
+ return { maps: entries.filter((entry) => !!entry && "id" in entry), diagnostics: entries.filter((entry) => !!entry && "path" in entry), incompleteCreates: incompleteCreates.sort((a, b) => a.mapId.localeCompare(b.mapId)) };
1254
+ }
1255
+ async function listMaps(port) {
1256
+ const result = { maps: [], diagnostics: [], incompleteCreates: [] };
1257
+ for (const id of await port.list()) {
1258
+ try {
1259
+ const placeholder = await listedPlaceholder(port, id);
1260
+ if (placeholder) {
1261
+ if (placeholder.state !== "discarded") result.incompleteCreates.push({ mapId: id, operationId: placeholder.operationId, state: placeholder.state });
1262
+ continue;
1263
+ }
1264
+ const snap = await readSnapshot(port, id);
1265
+ result.maps.push({ id, title: snap.map.title });
1266
+ } catch (e) {
1267
+ result.diagnostics.push({
1268
+ path: `${DATA_ROOT}/${id}`,
1269
+ code: errorCode(e),
1270
+ message: e instanceof Error ? e.message : String(e)
1271
+ });
1272
+ }
1273
+ }
1274
+ return result;
1275
+ }
1276
+ async function saveLayout(port, mapId, expectedFingerprint, layout, allowManual = false) {
1277
+ const current = await readSnapshot(port, mapId);
1278
+ if (current.fingerprint !== expectedFingerprint)
1279
+ throw new AtlasError("version_conflict", "\u5185\u5BB9\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5\u4FDD\u5B58\u5E03\u5C40");
1280
+ const validated = validateLayout(layout, current.map);
1281
+ if (!validated.ok)
1282
+ throw new AtlasError(
1283
+ "invalid_layout",
1284
+ "\u62D2\u7EDD\u4FDD\u5B58\u65E0\u6548\u5E03\u5C40",
1285
+ validated.diagnostics
1286
+ );
1287
+ if (layout.views.length !== current.map.views.length || current.map.views.some((v) => {
1288
+ const positioned = layout.views.find((p) => p.viewId === v.id);
1289
+ return !positioned || positioned.nodes.length !== v.occurrences.length || positioned.groups.length !== v.groups.length || positioned.nodes.some(
1290
+ (n) => !v.occurrences.some((o) => o.nodeId === n.nodeId)
1291
+ ) || positioned.groups.some(
1292
+ (g) => !v.groups.some((item) => item.id === g.groupId)
1293
+ );
1294
+ }))
1295
+ throw new AtlasError(
1296
+ "invalid_layout",
1297
+ "\u4FDD\u5B58\u7684\u5E03\u5C40\u5FC5\u987B\u4E0E\u5F53\u524D\u89C6\u56FE\u3001\u51FA\u73B0\u4F4D\u7F6E\u548C\u5206\u7EC4\u4E00\u4E00\u5BF9\u5E94"
1298
+ );
1299
+ for (const view2 of allowManual ? [] : current.layout?.views ?? [])
1300
+ for (const node2 of view2.nodes) {
1301
+ const next = layout.views.find((v) => v.viewId === view2.viewId)?.nodes.find((n) => n.nodeId === node2.nodeId);
1302
+ if (next && (next.x !== node2.x || next.y !== node2.y || next.width !== node2.width || next.manual !== node2.manual))
1303
+ throw new AtlasError(
1304
+ "invalid_layout",
1305
+ "\u9996\u671F\u8865\u4F4D\u4E0D\u80FD\u6539\u52A8\u5DF2\u6709\u8282\u70B9\u7684\u4F4D\u7F6E\u3001\u5BBD\u5EA6\u6216\u624B\u52A8\u6807\u8BB0"
1306
+ );
1307
+ }
1308
+ await port.writeLayout(
1309
+ mapId,
1310
+ `${JSON.stringify(layout, null, 2)}
1311
+ `,
1312
+ current.files.find((f) => f.path === mapPath(mapId, "layout.json"))?.version
1313
+ );
1314
+ return readSnapshot(port, mapId);
1315
+ }
1316
+
1317
+ // src/server/tools/schemas.ts
1318
+ import { z as z6 } from "zod";
1319
+ var node = mapSchema.shape.nodes.element.omit({ notePath: true, childViewId: true });
1320
+ var view = mapSchema.shape.views.element;
1321
+ var relation = mapSchema.shape.relations.element;
1322
+ var group = view.shape.groups.element;
1323
+ var op = (name2, fields) => z6.strictObject({ op: z6.literal(name2), ...fields });
1324
+ var changesSchema = z6.array(z6.union([
1325
+ op("set_map_title", { title: z6.string().trim().min(1) }),
1326
+ op("add_node", { node }),
1327
+ op("update_node", { nodeId: idSchema, fields: node.omit({ id: true }).partial() }),
1328
+ op("insert_note_content", { nodeId: idSchema, anchor: noteAnchorSchema, kind: noteInsertKind, markdown: z6.string().min(1).max(136 * 1024) }),
1329
+ op("set_note", { nodeId: idSchema, markdown: z6.string() }),
1330
+ op("remove_note", { nodeId: idSchema }),
1331
+ op("add_view", { view }),
1332
+ op("update_view", { viewId: idSchema, fields: view.pick({ title: true, parentViewId: true, centerNodeId: true }).partial() }),
1333
+ op("set_child_view", { nodeId: idSchema, viewId: idSchema.nullable() }),
1334
+ op("add_group", { viewId: idSchema, group }),
1335
+ op("update_group", { viewId: idSchema, groupId: idSchema, fields: group.omit({ id: true }).partial() }),
1336
+ op("remove_group", { viewId: idSchema, groupId: idSchema }),
1337
+ op("put_occurrence", { viewId: idSchema, nodeId: idSchema, groupId: idSchema.optional() }),
1338
+ op("remove_occurrence", { viewId: idSchema, nodeId: idSchema }),
1339
+ op("add_relation", { relation }),
1340
+ op("update_relation", { relationId: idSchema, fields: relation.omit({ id: true }).partial() }),
1341
+ op("remove_relation", { relationId: idSchema }),
1342
+ op("set_view_relations", { viewId: idSchema, relationIds: z6.array(idSchema) }),
1343
+ op("delete_node", { nodeId: idSchema }),
1344
+ op("delete_view", { viewId: idSchema })
1345
+ ])).min(1).refine((changes) => changes.length === 1 || changes.every((change) => change.op !== "insert_note_content"), "\u4E00\u6B21\u53EA\u63D0\u4EA4\u4E00\u5904\u6B63\u6587\u5B9A\u4F4D\u63D2\u5165");
1346
+ var contentSchema = mapSchema.omit({ id: true, schemaVersion: true }).extend({ nodes: z6.array(node.extend({ childViewId: idSchema.optional() })) });
1347
+ var createSchema = z6.strictObject({ operationId: idSchema, content: contentSchema, notes: z6.record(idSchema, z6.string()) });
1348
+ var readSchema = z6.strictObject({ mapId: idSchema, nodeIds: z6.array(idSchema).optional(), viewIds: z6.array(idSchema).optional(), query: z6.string().optional(), cursor: z6.string().optional() });
1349
+ var previewSchema = z6.strictObject({ mapId: idSchema, expectedFingerprint: z6.string().min(1), changes: changesSchema });
1350
+ var applySchema = previewSchema.extend({ operationId: idSchema, previewToken: z6.string().optional() });
1351
+ var cleanupCreateSchema = z6.strictObject({ mapId: idSchema, operationId: idSchema });
1352
+
1353
+ // src/server/tools/candidate.ts
1354
+ function validateCandidatePlots(before, after, map) {
1355
+ const removals = [];
1356
+ for (const nodeId of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])) {
1357
+ const previousText = Object.hasOwn(before, nodeId) ? before[nodeId] : "";
1358
+ const nextText = Object.hasOwn(after, nodeId) ? after[nodeId] : "";
1359
+ if (previousText === nextText) continue;
1360
+ const previous = notePlots(previousText);
1361
+ const next = notePlots(nextText);
1362
+ const priorErrors = /* @__PURE__ */ new Map();
1363
+ const errorKey = (plot) => JSON.stringify([plot.error, plot.source]);
1364
+ for (const plot of previous) if (plot.error) {
1365
+ const key = errorKey(plot);
1366
+ priorErrors.set(key, (priorErrors.get(key) ?? 0) + 1);
1367
+ }
1368
+ for (const plot of next) if (plot.error) {
1369
+ const key = errorKey(plot);
1370
+ const count = priorErrors.get(key) ?? 0;
1371
+ if (!count) {
1372
+ const notePath = map.nodes.find((node2) => node2.id === nodeId)?.notePath ?? `notes/${nodeId}.md`;
1373
+ throw new AtlasError("invalid_data", "\u56FE\u5757\u5019\u9009\u65E0\u6548", [{
1374
+ path: notePath,
1375
+ code: "invalid_plot",
1376
+ message: plot.id ? `\u56FE\u5757 ${plot.id}\uFF1A${plot.error}` : plot.error
1377
+ }]);
1378
+ }
1379
+ priorErrors.set(key, count - 1);
1380
+ }
1381
+ const remainingIds = /* @__PURE__ */ new Map();
1382
+ for (const { id } of next) if (id) remainingIds.set(id, (remainingIds.get(id) ?? 0) + 1);
1383
+ for (const plot of previous) {
1384
+ if (!plot.id) continue;
1385
+ const count = remainingIds.get(plot.id) ?? 0;
1386
+ if (!count) removals.push(`\u56FE\u5757 ${nodeId}/${plot.id}`);
1387
+ else remainingIds.set(plot.id, count - 1);
1388
+ }
1389
+ for (const [key, count] of priorErrors) {
1390
+ if (count && previous.some((plot) => !plot.id && errorKey(plot) === key))
1391
+ removals.push(`\u7B14\u8BB0 ${nodeId} \u4E2D\u7684\u65E0\u6548\u56FE\u5757 \xD7 ${count}`);
1392
+ }
1393
+ }
1394
+ return [...new Set(removals)];
1395
+ }
1396
+ function candidate(snapshot, input) {
1397
+ const changes = changesSchema.parse(input);
1398
+ const map = structuredClone(snapshot.map);
1399
+ const notes = { ...snapshot.notes };
1400
+ const affected = /* @__PURE__ */ new Set();
1401
+ const removals = [];
1402
+ const find = (items, id, key = "id") => {
1403
+ const found = items.find((x) => x[key] === id);
1404
+ if (!found) throw new AtlasError("invalid_data", `\u5BF9\u8C61\u4E0D\u5B58\u5728\uFF1A${id}`);
1405
+ return found;
1406
+ };
1407
+ const prune = () => {
1408
+ for (const v of map.views) v.relationIds = v.relationIds.filter((id) => {
1409
+ const r = map.relations.find((r2) => r2.id === id);
1410
+ return r && [r.fromNodeId, r.toNodeId].every((n) => v.occurrences.some((o) => o.nodeId === n));
1411
+ });
1412
+ };
1413
+ for (const c of changes) {
1414
+ for (const id of [c.nodeId, c.viewId, c.relationId, c.groupId, c.node?.id, c.view?.id, c.relation?.id, c.group?.id]) if (id) affected.add(id);
1415
+ const v = c.viewId ? find(map.views, c.viewId) : void 0;
1416
+ switch (c.op) {
1417
+ case "set_map_title":
1418
+ map.title = c.title;
1419
+ break;
1420
+ case "add_node":
1421
+ map.nodes.push(c.node);
1422
+ notes[c.node.id] = "";
1423
+ break;
1424
+ case "update_node":
1425
+ Object.assign(find(map.nodes, c.nodeId), c.fields);
1426
+ break;
1427
+ case "insert_note_content":
1428
+ throw new AtlasError("invalid_data", "\u6B63\u6587\u4F4D\u7F6E\u987B\u5148\u5728\u5F53\u524D\u7B14\u8BB0\u4E2D\u6838\u9A8C");
1429
+ case "set_note":
1430
+ case "remove_note": {
1431
+ const n = find(map.nodes, c.nodeId);
1432
+ const text2 = c.op === "set_note" ? c.markdown : "";
1433
+ notes[n.id] = text2;
1434
+ if (text2) n.notePath ??= `notes/${n.id}.md`;
1435
+ else {
1436
+ if (n.notePath) removals.push(`\u7B14\u8BB0 ${n.id}`);
1437
+ delete n.notePath;
1438
+ }
1439
+ break;
1440
+ }
1441
+ case "add_view":
1442
+ map.views.push(c.view);
1443
+ break;
1444
+ case "update_view":
1445
+ Object.assign(v, c.fields);
1446
+ break;
1447
+ case "set_child_view": {
1448
+ const n = find(map.nodes, c.nodeId);
1449
+ if (n.childViewId && n.childViewId !== c.viewId) throw new AtlasError("invalid_data", "\u5DF2\u6709\u5B50\u56FE\u5FC5\u987B\u590D\u7528\uFF1B\u5148\u663E\u5F0F\u89E3\u9664\u539F\u5173\u8054");
1450
+ if (c.viewId) {
1451
+ n.childViewId = c.viewId;
1452
+ v.centerNodeId = n.id;
1453
+ } else {
1454
+ if (n.childViewId) delete find(map.views, n.childViewId).centerNodeId;
1455
+ delete n.childViewId;
1456
+ }
1457
+ break;
1458
+ }
1459
+ case "add_group":
1460
+ v.groups.push(c.group);
1461
+ break;
1462
+ case "update_group":
1463
+ Object.assign(find(v.groups, c.groupId), c.fields);
1464
+ break;
1465
+ case "remove_group":
1466
+ find(v.groups, c.groupId);
1467
+ v.groups = v.groups.filter((g) => g.id !== c.groupId);
1468
+ removals.push(`\u5206\u7EC4 ${c.viewId}/${c.groupId}`);
1469
+ break;
1470
+ case "put_occurrence": {
1471
+ find(map.nodes, c.nodeId);
1472
+ const old = v.occurrences.find((o) => o.nodeId === c.nodeId);
1473
+ const next = { nodeId: c.nodeId, ...c.groupId ? { groupId: c.groupId } : {} };
1474
+ if (old) Object.assign(old, { groupId: void 0 }, next);
1475
+ else v.occurrences.push(next);
1476
+ break;
1477
+ }
1478
+ case "remove_occurrence":
1479
+ find(v.occurrences, c.nodeId, "nodeId");
1480
+ v.occurrences = v.occurrences.filter((o) => o.nodeId !== c.nodeId);
1481
+ removals.push(`\u51FA\u73B0\u4F4D\u7F6E ${c.viewId}/${c.nodeId}`);
1482
+ prune();
1483
+ break;
1484
+ case "add_relation":
1485
+ map.relations.push(c.relation);
1486
+ break;
1487
+ case "update_relation":
1488
+ Object.assign(find(map.relations, c.relationId), c.fields);
1489
+ break;
1490
+ case "remove_relation":
1491
+ find(map.relations, c.relationId);
1492
+ map.relations = map.relations.filter((r) => r.id !== c.relationId);
1493
+ removals.push(`\u5173\u7CFB ${c.relationId}`);
1494
+ prune();
1495
+ break;
1496
+ case "set_view_relations":
1497
+ v.relationIds = c.relationIds;
1498
+ break;
1499
+ case "delete_node": {
1500
+ const n = find(map.nodes, c.nodeId);
1501
+ removals.push(`\u8282\u70B9 ${n.id}`, ...n.notePath ? [`\u7B14\u8BB0 ${n.id}`] : [], ...map.views.filter((v2) => v2.occurrences.some((o) => o.nodeId === n.id)).map((v2) => `\u51FA\u73B0\u4F4D\u7F6E ${v2.id}/${n.id}`), ...map.relations.filter((r) => r.fromNodeId === n.id || r.toNodeId === n.id).map((r) => `\u5173\u7CFB ${r.id}`));
1502
+ if (n.childViewId) throw new AtlasError("invalid_data", "\u8BF7\u5148\u5904\u7406\u5173\u8054\u5B50\u56FE\uFF0C\u518D\u5220\u9664\u8282\u70B9");
1503
+ map.nodes = map.nodes.filter((x) => x.id !== n.id);
1504
+ delete notes[n.id];
1505
+ for (const v2 of map.views) v2.occurrences = v2.occurrences.filter((o) => o.nodeId !== n.id);
1506
+ map.relations = map.relations.filter((r) => r.fromNodeId !== n.id && r.toNodeId !== n.id);
1507
+ prune();
1508
+ break;
1509
+ }
1510
+ case "delete_view":
1511
+ find(map.views, c.viewId);
1512
+ removals.push(`\u89C6\u56FE ${c.viewId}`, ...v.groups.map((g) => `\u5206\u7EC4 ${v.id}/${g.id}`), ...v.occurrences.map((o) => `\u51FA\u73B0\u4F4D\u7F6E ${v.id}/${o.nodeId}`), ...v.relationIds.map((id) => `\u89C6\u56FE\u5173\u7CFB\u5F15\u7528 ${v.id}/${id}`));
1513
+ map.views = map.views.filter((x) => x.id !== c.viewId);
1514
+ break;
1515
+ }
1516
+ }
1517
+ const checked = validateMap(map, map.id);
1518
+ if (!checked.ok) throw new AtlasError("invalid_data", "\u5019\u9009\u7ED3\u6784\u65E0\u6548", checked.diagnostics);
1519
+ return { map: checked.value, notes, affectedIds: [...affected], removals };
1520
+ }
1521
+
1522
+ // src/server/tools/storage.ts
1523
+ import { randomUUID } from "node:crypto";
1524
+ function transactionPort(ctx, scope, mapId, policy) {
1525
+ const signal = new AbortController().signal;
1526
+ async function target(path) {
1527
+ const relative = mapPath(mapId, path);
1528
+ const root = await ctx.fs.resolve(scope.workspaceRoot, { signal });
1529
+ const data = await ctx.fs.resolve("dsh-knowledge-maps", { cwd: scope.workspaceRoot, signal });
1530
+ const map = await ctx.fs.resolve(mapPath(mapId, "."), { cwd: scope.workspaceRoot, signal });
1531
+ const file = await ctx.fs.resolve(relative, { cwd: scope.workspaceRoot, signal });
1532
+ if (!ctx.fs.contains(root, data) || !ctx.fs.contains(data, map) || !ctx.fs.contains(map, file) || map.targetKey === file.targetKey) throw new AtlasError("path_outside_map", "\u771F\u5B9E\u8DEF\u5F84\u8D8A\u8FC7\u5730\u56FE\u8FB9\u754C");
1533
+ if (/^assets\/[A-Za-z0-9_-]+\.image\.json$/.test(path)) {
1534
+ const assets = await ctx.fs.resolve(mapPath(mapId, "assets"), { cwd: scope.workspaceRoot, signal });
1535
+ if (!ctx.fs.contains(map, assets) || !ctx.fs.contains(assets, file) || assets.targetKey === file.targetKey)
1536
+ throw new AtlasError("path_outside_map", "\u56FE\u7247\u76EE\u6807\u5FC5\u987B\u4F4D\u4E8E\u672C\u56FE assets");
1537
+ }
1538
+ const entry = await ctx.fs.lstat(relative, { cwd: scope.workspaceRoot }, signal);
1539
+ if (entry && entry.type !== "file") throw new AtlasError("path_outside_map", "\u5199\u5165\u76EE\u6807\u5FC5\u987B\u4E3A\u666E\u901A\u6587\u4EF6");
1540
+ return file;
1541
+ }
1542
+ return {
1543
+ async read(path) {
1544
+ const t = await target(path);
1545
+ const before = await ctx.fs.stat(t, signal);
1546
+ if (!before) return null;
1547
+ const text2 = await ctx.fs.readText(t, signal);
1548
+ if ((await ctx.fs.stat(t, signal))?.version !== before.version) throw new AtlasError("version_conflict", "\u6587\u4EF6\u8BFB\u53D6\u4E2D\u53D8\u5316");
1549
+ return { text: text2, version: String(before.version) };
1550
+ },
1551
+ async put(path, text2, version) {
1552
+ const written = await ctx.fs.writeText(await target(path), text2, version === null ? { kind: "createIfAbsent" } : { kind: "replaceIfVersion", version }, signal, policy);
1553
+ return String(written.version);
1554
+ },
1555
+ async remove(path, version) {
1556
+ await ctx.fs.deleteFile(await target(path), { version }, signal, policy);
1557
+ }
1558
+ };
1559
+ }
1560
+ async function releaseFailedCreate(ctx, scope, mapId, operationId, request, policy, code) {
1561
+ const signal = new AbortController().signal;
1562
+ const files = createHostFiles(ctx, scope, signal, policy);
1563
+ const metadata = transactionPort(ctx, scope, mapId, policy);
1564
+ const matches = (state2) => state2?.operationId === operationId && state2.request === request;
1565
+ if (!await metadata.read(`.transactions/${operationId}/reservation.json`) && !await metadata.read(`.transactions/${operationId}/failed.json`)) return true;
1566
+ const state = await inspectCreatePlaceholder(files, mapId);
1567
+ if (!matches(state)) return false;
1568
+ if (state?.state === "discarded") return true;
1569
+ const lockText = JSON.stringify({ kind: "create-cleanup", owner: randomUUID(), operationId, request });
1570
+ await metadata.put(".transactions/active.json", lockText, null);
1571
+ try {
1572
+ const current = await inspectCreatePlaceholder(files, mapId, lockText);
1573
+ if (!matches(current)) return false;
1574
+ const prefix = `.transactions/${operationId}`;
1575
+ if (current?.state === "cleanup_pending" || current?.state === "discarded") {
1576
+ for (const name2 of ["reservation.json", "failed.json"]) {
1577
+ const path = `${prefix}/${name2}`;
1578
+ const record = await metadata.read(path);
1579
+ if (!record) continue;
1580
+ const binding = name2 === "reservation.json" ? record.text : JSON.parse(record.text).request;
1581
+ if (binding !== request) throw new AtlasError("operation_conflict", "\u521B\u5EFA\u8D44\u6599\u5DF2\u53D8\u5316\uFF0C\u505C\u6B62\u6E05\u7406");
1582
+ await metadata.remove(path, record.version);
1583
+ }
1584
+ return true;
1585
+ }
1586
+ const failed = await metadata.read(`${prefix}/failed.json`);
1587
+ if (!failed) await metadata.put(`${prefix}/failed.json`, JSON.stringify({ kind: "failed_create", operationId, request, code }), null);
1588
+ const reservation = await metadata.read(`${prefix}/reservation.json`);
1589
+ if (reservation) {
1590
+ if (reservation.text !== request) throw new AtlasError("operation_conflict", "\u521B\u5EFA\u5360\u4F4D\u5DF2\u6539\u53D8\uFF0C\u4FDD\u7559\u8D44\u6599");
1591
+ await metadata.remove(`${prefix}/reservation.json`, reservation.version);
1592
+ }
1593
+ return true;
1594
+ } finally {
1595
+ const lock = await metadata.read(".transactions/active.json");
1596
+ if (lock?.text === lockText) await metadata.remove(".transactions/active.json", lock.version);
1597
+ }
1598
+ }
1599
+
1600
+ // src/server/transaction.ts
1601
+ var CommitError = class extends Error {
1602
+ code;
1603
+ constructor(code, message) {
1604
+ super(message);
1605
+ this.code = code;
1606
+ }
1607
+ };
1608
+ var assetPath = (path) => /^assets\/[A-Za-z0-9_-]{1,128}\.image\.json$/.test(path);
1609
+ function journalText(journal) {
1610
+ const text2 = JSON.stringify(journal);
1611
+ if (new TextEncoder().encode(text2).length > 48 * 1024 * 1024) throw new CommitError("resource_too_large", "\u4E8B\u52A1\u8BB0\u5F55\u8D85\u8FC7 48 MiB");
1612
+ return text2;
1613
+ }
1614
+ var active = ".transactions/active.json";
1615
+ var receipt = (id) => {
1616
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) throw new CommitError("invalid_data", "\u64CD\u4F5CID\u65E0\u6548");
1617
+ return `.transactions/${id}/result.json`;
1618
+ };
1619
+ function parseJournal(text2) {
1620
+ const j = JSON.parse(text2);
1621
+ const validPath = (path) => typeof path === "string" && !path.includes("\\") && !path.startsWith("/") && !path.split("/").some((p) => !p || p === "." || p === ".." || p === ".transactions" || p === "exports" || p.includes(":")) && (path === "map.json" || path === "layout.json" || path.endsWith(".md") || /^assets\/[A-Za-z0-9_-]{1,128}\.image\.json$/.test(path));
1622
+ if (!j || typeof j.owner !== "string" || typeof j.request !== "string" || !["prepared", "committed"].includes(j.state) || !Array.isArray(j.changes) || j.changes.some((c) => !c || !validPath(c.path) || c.afterVersion !== void 0 && typeof c.afterVersion !== "string" || assetPath(c.path) && (c.before !== null || typeof c.after !== "string") || c.after !== null && typeof c.after !== "string" || c.before !== null && (!c.before || typeof c.before.text !== "string" || typeof c.before.version !== "string")) || new Set(j.changes.map((c) => c.path)).size !== j.changes.length) throw new CommitError("recovery_required", "\u6062\u590D\u8BB0\u5F55\u65E0\u6548\uFF1B\u672A\u4FEE\u6539\u6587\u4EF6\uFF0C\u4FDD\u7559\u8D44\u6599");
1623
+ receipt(j.operationId);
1624
+ return j;
1625
+ }
1626
+ var Transactions = class {
1627
+ port;
1628
+ owner;
1629
+ constructor(port, owner) {
1630
+ this.port = port;
1631
+ this.owner = owner;
1632
+ }
1633
+ async replay(id, request) {
1634
+ if (await this.port.read(active)) throw new CommitError("recovery_required", "\u6D3B\u52A8\u63D0\u4EA4\u5C1A\u672A\u7ED3\u675F\uFF0C\u4E0D\u80FD\u91CD\u653E\u6210\u529F\u7ED3\u679C");
1635
+ const record = await this.port.read(receipt(id));
1636
+ if (!record) return void 0;
1637
+ const data = JSON.parse(record.text);
1638
+ if (data.request !== request) throw new CommitError("operation_conflict", "\u540C\u4E00operationId\u4E0D\u80FD\u7528\u4E8E\u4E0D\u540C\u8BF7\u6C42");
1639
+ return data.result;
1640
+ }
1641
+ async recover() {
1642
+ const record = await this.port.read(active);
1643
+ if (!record) return;
1644
+ const journal = parseJournal(record.text);
1645
+ if (journal.state === "committed") {
1646
+ for (const c of journal.changes) if ((await this.port.read(c.path))?.text !== (c.after ?? void 0)) throw new CommitError("recovery_required", `\u5DF2\u63D0\u4EA4\u6587\u4EF6\u53D1\u751F\u5916\u90E8\u53D8\u5316\uFF1A${c.path}`);
1647
+ await this.finish(journal);
1648
+ } else {
1649
+ for (const c of [...journal.changes].reverse()) {
1650
+ const now = await this.port.read(c.path);
1651
+ if ((now?.text ?? null) === (c.before?.text ?? null)) continue;
1652
+ if ((now?.text ?? null) !== c.after) throw new CommitError("recovery_required", `\u5916\u90E8\u51B2\u7A81\uFF0C\u4FDD\u7559\u6062\u590D\u8D44\u6599\uFF1A${c.path}`);
1653
+ if (assetPath(c.path) && now && (!c.afterVersion || now.version !== c.afterVersion)) throw new CommitError("recovery_required", `\u8D44\u6E90\u5199\u5165\u7248\u672C\u65E0\u6CD5\u8BC1\u660E\uFF0C\u4FDD\u7559\u6587\u4EF6\uFF1A${c.path}`);
1654
+ if (c.before) await this.port.put(c.path, c.before.text, now?.version ?? null);
1655
+ else if (now) await this.port.remove(c.path, now.version);
1656
+ }
1657
+ }
1658
+ const current = await this.port.read(active);
1659
+ if (current?.text !== record.text) throw new CommitError("recovery_required", "\u6D3B\u52A8\u8BB0\u5F55\u53D1\u751F\u53D8\u5316");
1660
+ await this.port.remove(active, current.version);
1661
+ }
1662
+ async finish(journal) {
1663
+ const path = receipt(journal.operationId);
1664
+ const text2 = JSON.stringify({ request: journal.request, result: journal.result });
1665
+ const prior = await this.port.read(path);
1666
+ if (prior && prior.text !== text2) throw new CommitError("recovery_required", "\u64CD\u4F5C\u7ED3\u679C\u8BB0\u5F55\u51B2\u7A81");
1667
+ if (!prior) await this.port.put(path, text2, null);
1668
+ }
1669
+ async commit(operationId, request, changes, result, verify, finalize) {
1670
+ const prior = await this.replay(operationId, request);
1671
+ if (prior !== void 0) return prior;
1672
+ const journal = { owner: this.owner, operationId, request, state: "prepared", changes, result };
1673
+ if (new TextEncoder().encode(JSON.stringify(journal)).length + 4096 + changes.filter((c) => assetPath(c.path)).length * 512 > 48 * 1024 * 1024) throw new CommitError("resource_too_large", "\u4E8B\u52A1\u8BB0\u5F55\u8D85\u8FC7 48 MiB\uFF0C\u672A\u5199\u5165");
1674
+ parseJournal(JSON.stringify(journal));
1675
+ if (await this.port.read(active)) throw new CommitError("recovery_required", "\u5DF2\u6709\u6D3B\u52A8\u64CD\u4F5C\uFF1B\u539F\u64CD\u4F5C\u7ED3\u675F\u540E\u518D\u6062\u590D");
1676
+ let committed = false;
1677
+ let claimed = false;
1678
+ try {
1679
+ await this.port.put(active, journalText(journal), null);
1680
+ claimed = true;
1681
+ await verify();
1682
+ for (const c of changes) {
1683
+ const now = await this.port.read(c.path);
1684
+ if ((now?.version ?? null) !== (c.before?.version ?? null)) throw new CommitError("version_conflict", `\u6587\u4EF6\u53D8\u5316\uFF1A${c.path}`);
1685
+ if (c.after === null) {
1686
+ if (now) await this.port.remove(c.path, now.version);
1687
+ } else {
1688
+ const writtenVersion = await this.port.put(c.path, c.after, now?.version ?? null);
1689
+ if (assetPath(c.path)) {
1690
+ if (!writtenVersion || writtenVersion.length > 256) throw new CommitError("recovery_required", "\u5BBF\u4E3B\u672A\u8FD4\u56DE\u8D44\u6E90\u5199\u5165\u7248\u672C\uFF0C\u4FDD\u7559\u6062\u590D\u8D44\u6599");
1691
+ c.afterVersion = writtenVersion;
1692
+ const lock2 = await this.port.read(active);
1693
+ if (!lock2 || JSON.parse(lock2.text).owner !== this.owner) throw new CommitError("recovery_required", "\u8D44\u6E90\u63D0\u4EA4\u671F\u95F4\u8BA4\u9886\u53D8\u5316");
1694
+ await this.port.put(active, journalText(journal), lock2.version);
1695
+ }
1696
+ }
1697
+ }
1698
+ for (const c of changes) {
1699
+ const written = await this.port.read(c.path);
1700
+ if (written?.text !== (c.after ?? void 0) || c.afterVersion && written?.version !== c.afterVersion)
1701
+ throw new CommitError("version_conflict", `\u63D0\u4EA4\u590D\u8BFB\u5931\u8D25\uFF1A${c.path}`);
1702
+ }
1703
+ if (finalize) journal.result = await finalize();
1704
+ const lock = await this.port.read(active);
1705
+ if (!lock || JSON.parse(lock.text).owner !== this.owner) throw new CommitError("recovery_required", "\u64CD\u4F5C\u8BB0\u5F55\u53D8\u5316");
1706
+ journal.state = "committed";
1707
+ await this.port.put(active, journalText(journal), lock.version);
1708
+ committed = true;
1709
+ await this.finish(journal);
1710
+ const done = await this.port.read(active);
1711
+ if (done) await this.port.remove(active, done.version);
1712
+ return journal.result;
1713
+ } catch (e) {
1714
+ try {
1715
+ const lock = await this.port.read(active);
1716
+ if (!lock && committed && await this.replay(operationId, request) !== void 0) return journal.result;
1717
+ if (!lock && !claimed) throw e;
1718
+ if (!lock || JSON.parse(lock.text).owner !== this.owner) throw new Error("\u6D3B\u52A8\u64CD\u4F5C\u5C5E\u4E8E\u5176\u4ED6\u6240\u6709\u8005\u6216\u8BB0\u5F55\u4E22\u5931");
1719
+ committed ||= JSON.parse(lock.text).state === "committed";
1720
+ await this.recover();
1721
+ } catch (recovery) {
1722
+ throw new CommitError("recovery_required", `\u4FDD\u7559\u64CD\u4F5C\u8D44\u6599\uFF1A${String(e)}\uFF1B${String(recovery)}`);
1723
+ }
1724
+ if (committed) return journal.result;
1725
+ throw new CommitError("failed_rolled_back", `\u63D0\u4EA4\u5931\u8D25\uFF0C\u5DF2\u56DE\u9000\uFF1A${String(e)}`);
1726
+ }
1727
+ }
1728
+ };
1729
+
1730
+ // src/server/edit-service.ts
1731
+ var editSchema = z7.discriminatedUnion("kind", [
1732
+ z7.strictObject({ kind: z7.literal("details"), nodeId: idSchema, title: z7.string().trim().min(1), summary: z7.string(), markdown: z7.string(), images: z7.array(imageAssetSchema) }),
1733
+ z7.strictObject({ kind: z7.literal("layout"), viewId: idSchema, layout: layoutSchema.shape.views.element })
1734
+ ]);
1735
+ var commitEditSchema = z7.strictObject({ op: z7.literal("commitEdit"), mapId: idSchema, expectedWorkspaceKey: z7.string().min(1), expectedFingerprint: z7.string().min(1), operationId: idSchema, removedPlots: z7.array(idSchema).max(256).optional(), edit: editSchema });
1736
+ var editStatusSchema = z7.strictObject({ op: z7.literal("editStatus"), mapId: idSchema, expectedWorkspaceKey: z7.string().min(1), operationId: idSchema, requestDigest: z7.string().regex(/^[a-f0-9]{64}$/) });
1737
+ var notePaths = /* @__PURE__ */ new Map();
1738
+ function acceptEditMemory(memory, operationId, request, fingerprint2) {
1739
+ const pending = memory?.pending;
1740
+ if (!memory || !pending || pending.operationId !== operationId || pending.request !== request) return;
1741
+ for (const key of pending.restored) memory.plots.delete(key);
1742
+ for (const [key, hash2] of pending.removed) {
1743
+ memory.plots.delete(key);
1744
+ memory.plots.set(key, hash2);
1745
+ }
1746
+ while (memory.plots.size > 256) memory.plots.delete(memory.plots.keys().next().value);
1747
+ memory.pending = void 0;
1748
+ memory.fingerprint = fingerprint2;
1749
+ }
1750
+ var noteKey = (scope, mapId) => JSON.stringify([scope.sessionId, scope.workspaceRoot, mapId]);
1751
+ async function editStatus(ctx, scope, req, signal) {
1752
+ const port = createHostFiles(ctx, scope, signal);
1753
+ const readOnly = {
1754
+ read: async (path) => {
1755
+ const full = mapPath(req.mapId, path);
1756
+ if (await port.absent(full)) return null;
1757
+ const record = await port.read(full, req.mapId);
1758
+ return { text: new TextDecoder("utf-8", { fatal: true }).decode(record.bytes), version: record.version };
1759
+ },
1760
+ put: async () => {
1761
+ throw new AtlasError("permission_denied", "\u56DE\u6267\u67E5\u8BE2\u4E0D\u5199\u5165");
1762
+ },
1763
+ remove: async () => {
1764
+ throw new AtlasError("permission_denied", "\u56DE\u6267\u67E5\u8BE2\u4E0D\u5220\u9664");
1765
+ }
1766
+ };
1767
+ const receipt2 = await new Transactions(readOnly, crypto.randomUUID()).replay(req.operationId, req.requestDigest);
1768
+ const snapshot = await readSnapshot(port, req.mapId);
1769
+ if (receipt2 && snapshot.fingerprint !== receipt2.committedFingerprint) throw new AtlasError("version_conflict", "\u8BE5\u64CD\u4F5C\u5DF2\u63D0\u4EA4\uFF0C\u4F46\u78C1\u76D8\u5DF2\u6709\u540E\u7EED\u7248\u672C\uFF1B\u672C\u5730\u526F\u672C\u4FDD\u7559");
1770
+ const memory = notePaths.get(noteKey(scope, req.mapId));
1771
+ if (receipt2) acceptEditMemory(memory, req.operationId, req.requestDigest, snapshot.fingerprint);
1772
+ return { state: receipt2 ? "committed" : "absent", snapshot, committedFingerprint: receipt2?.committedFingerprint };
1773
+ }
1774
+ function overlayFiles(port, mapId, files) {
1775
+ const relative = (path) => path.slice(mapPath(mapId, "map.json").length - "map.json".length);
1776
+ return {
1777
+ ...port,
1778
+ absent: async (path) => path === mapPath(mapId, ".transactions/active.json") ? true : files.has(relative(path)) ? files.get(relative(path)) === null : port.absent(path),
1779
+ read: async (path, id, assetsOnly) => {
1780
+ const key = relative(path);
1781
+ if (!files.has(key)) return port.read(path, id, assetsOnly);
1782
+ const text2 = files.get(key);
1783
+ if (text2 === null) throw new AtlasError("invalid_data", "\u5019\u9009\u5F15\u7528\u5DF2\u5220\u9664\u6587\u4EF6");
1784
+ return { bytes: new TextEncoder().encode(text2), version: "candidate", identity: path };
1785
+ }
1786
+ };
1787
+ }
1788
+ async function fileMutations(port, files) {
1789
+ const result = [];
1790
+ for (const [path, after] of files) {
1791
+ const before = await port.read(path);
1792
+ if ((before?.text ?? null) !== after) result.push({ path, before, after });
1793
+ }
1794
+ return result;
1795
+ }
1796
+ async function commitEdit(ctx, scope, req, policy, signal) {
1797
+ if (new TextEncoder().encode(JSON.stringify(req)).length > 24 * 1024 * 1024) throw new AtlasError("resource_too_large", "\u8BF7\u6C42\u8D85\u8FC7 24 MiB");
1798
+ const port = createHostFiles(ctx, scope, signal, policy), txPort = transactionPort(ctx, scope, req.mapId, policy);
1799
+ const tx = new Transactions(txPort, crypto.randomUUID()), request = await digest(canonicalJson(req));
1800
+ const replay = await tx.replay(req.operationId, request);
1801
+ if (replay) {
1802
+ const snapshot2 = await readSnapshot(port, req.mapId);
1803
+ if (snapshot2.fingerprint !== replay.committedFingerprint) throw new AtlasError("version_conflict", "\u8BE5\u64CD\u4F5C\u5DF2\u4FDD\u5B58\uFF0C\u4F46\u968F\u540E\u51FA\u73B0\u5916\u90E8\u4FEE\u6539\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6");
1804
+ acceptEditMemory(notePaths.get(noteKey(scope, req.mapId)), req.operationId, request, snapshot2.fingerprint);
1805
+ return { ...replay, snapshot: snapshot2 };
1806
+ }
1807
+ const snapshot = await readSnapshot(port, req.mapId);
1808
+ if (snapshot.fingerprint !== req.expectedFingerprint) throw new AtlasError("version_conflict", "\u5730\u56FE\u5DF2\u53D8\u5316\uFF0C\u4FDD\u7559\u672C\u5730\u4FEE\u6539");
1809
+ const memoryKey = noteKey(scope, req.mapId);
1810
+ let memory = notePaths.get(memoryKey);
1811
+ if (!memory || memory.fingerprint !== snapshot.fingerprint) {
1812
+ memory = { fingerprint: snapshot.fingerprint, paths: /* @__PURE__ */ new Map(), plots: /* @__PURE__ */ new Map() };
1813
+ notePaths.set(memoryKey, memory);
1814
+ }
1815
+ for (const n of snapshot.map.nodes) if (n.notePath) memory.paths.set(n.id, n.notePath);
1816
+ const plotChanges = { operationId: req.operationId, request, removed: [], restored: [] };
1817
+ const files = /* @__PURE__ */ new Map(), json = (v) => JSON.stringify(v, null, 2) + "\n";
1818
+ if (req.edit.kind === "details") {
1819
+ const e = req.edit, node2 = snapshot.map.nodes.find((n) => n.id === e.nodeId);
1820
+ if (!node2) throw new AtlasError("invalid_data", "\u8282\u70B9\u4E0D\u5B58\u5728");
1821
+ const delta = manualPlotDelta(snapshot.notes[e.nodeId] ?? "", e.markdown);
1822
+ const removals = new Set(req.removedPlots ?? []);
1823
+ if (!delta || removals.size !== delta.removed.length || delta.removed.some(([id]) => !removals.has(id)))
1824
+ throw new AtlasError("invalid_data", "\u624B\u52A8\u7F16\u8F91\u53EA\u80FD\u79FB\u52A8\u6216\u663E\u5F0F\u5220\u9664\u5DF2\u5B58\u5728\u7684\u56FE\u8868");
1825
+ const key = (id) => JSON.stringify([e.nodeId, id]);
1826
+ for (const [id, raw] of delta.restored) {
1827
+ if (memory.plots.get(key(id)) !== await digest(raw))
1828
+ throw new AtlasError("invalid_data", "\u53EA\u80FD\u64A4\u9500\u5F53\u524D\u4F1A\u8BDD\u5DF2\u4FDD\u5B58\u7684\u6574\u56FE\u5220\u9664");
1829
+ plotChanges.restored.push(key(id));
1830
+ }
1831
+ for (const [id, raw] of delta.removed) plotChanges.removed.push([key(id), await digest(raw)]);
1832
+ const proposal2 = candidate(snapshot, [{ op: "update_node", nodeId: e.nodeId, fields: { title: e.title, summary: e.summary } }, e.markdown ? { op: "set_note", nodeId: e.nodeId, markdown: e.markdown } : { op: "remove_note", nodeId: e.nodeId }]);
1833
+ const note = proposal2.map.nodes.find((n) => n.id === e.nodeId);
1834
+ if (e.markdown && !node2.notePath && memory.paths.has(e.nodeId)) note.notePath = memory.paths.get(e.nodeId);
1835
+ if (note.notePath && snapshot.map.nodes.some((n) => n.id !== e.nodeId && n.notePath === note.notePath)) throw new AtlasError("invalid_data", "\u539F\u7B14\u8BB0\u8DEF\u5F84\u5DF2\u88AB\u5176\u4ED6\u8282\u70B9\u5360\u7528");
1836
+ if (JSON.stringify(proposal2.map) !== JSON.stringify(snapshot.map)) files.set("map.json", json(proposal2.map));
1837
+ if (note.notePath) {
1838
+ if (!node2.notePath && await txPort.read(note.notePath)) throw new AtlasError("version_conflict", "\u7B14\u8BB0\u76EE\u6807\u5DF2\u6709\u6587\u4EF6\uFF0C\u4FDD\u7559\u672C\u5730\u5185\u5BB9");
1839
+ files.set(note.notePath, e.markdown);
1840
+ } else if (node2.notePath) files.set(node2.notePath, null);
1841
+ let total = 0;
1842
+ const seen = /* @__PURE__ */ new Set();
1843
+ for (const raw of e.images) {
1844
+ const asset = await validateImage(raw);
1845
+ if (seen.has(asset.id)) throw new AtlasError("invalid_data", "\u91CD\u590D\u56FE\u7247 ID");
1846
+ seen.add(asset.id);
1847
+ const path = `assets/${asset.id}.image.json`;
1848
+ if (!e.markdown.includes(asset.id + ".image.json")) throw new AtlasError("invalid_data", "\u4E0D\u4FDD\u5B58\u6B63\u6587\u672A\u4F7F\u7528\u7684\u65B0\u589E\u56FE\u7247");
1849
+ const existing = await txPort.read(path), content = json(asset);
1850
+ if (existing) {
1851
+ const prior = await validateImage(JSON.parse(existing.text));
1852
+ if (JSON.stringify(prior) !== JSON.stringify(asset)) throw new AtlasError("operation_conflict", "\u56FE\u7247 ID \u5DF2\u88AB\u5176\u4ED6\u5185\u5BB9\u5360\u7528");
1853
+ }
1854
+ if (!existing) {
1855
+ total += asset.byteLength;
1856
+ if (total > 16 * 1024 * 1024) throw new AtlasError("resource_too_large", "\u5355\u6B21\u65B0\u589E\u56FE\u7247\u8D85\u8FC7 16 MiB");
1857
+ files.set(path, content);
1858
+ }
1859
+ }
1860
+ } else {
1861
+ if (req.removedPlots?.length) throw new AtlasError("invalid_data", "\u5E03\u5C40\u8BF7\u6C42\u4E0D\u80FD\u5305\u542B\u56FE\u8868\u5220\u9664");
1862
+ const e = req.edit, view2 = snapshot.map.views.find((v) => v.id === e.viewId);
1863
+ if (!view2 || e.layout.viewId !== e.viewId || e.layout.nodes.some((n) => !view2.occurrences.some((o) => o.nodeId === n.nodeId)) || e.layout.groups.some((g) => !view2.groups.some((x) => x.id === g.groupId))) throw new AtlasError("invalid_data", "\u5E03\u5C40\u76EE\u6807\u8D8A\u754C");
1864
+ if (!e.layout.mode || e.layout.nodes.length !== view2.occurrences.length || e.layout.groups.length !== view2.groups.length) throw new AtlasError("invalid_data", "\u5E03\u5C40\u5FC5\u987B\u5305\u542B\u5B8C\u6574\u76EE\u6807\u89C6\u56FE");
1865
+ const others = (snapshot.layout?.views ?? []).filter((v) => v.viewId !== e.viewId).map((v) => ({ ...v, mode: v.mode ?? "vertical" }));
1866
+ files.set("layout.json", json({ schemaVersion: 2, mapId: snapshot.map.id, views: [...others, e.layout] }));
1867
+ }
1868
+ const proposal = await readSnapshot(overlayFiles(port, req.mapId, files), req.mapId);
1869
+ for (const relative of files.keys()) {
1870
+ if (relative.endsWith(".image.json") && !proposal.files.some((f) => f.path === mapPath(req.mapId, relative)))
1871
+ throw new AtlasError("invalid_data", "\u65B0\u589E\u56FE\u7247\u672A\u88AB\u6B63\u6587\u5F15\u7528");
1872
+ }
1873
+ const ordered = new Map([...files].sort(([a], [b]) => Number(b.endsWith(".image.json")) - Number(a.endsWith(".image.json"))));
1874
+ const mutations = await fileMutations(txPort, ordered);
1875
+ for (const change of mutations) if (change.before && !snapshot.files.some((f) => f.path === mapPath(req.mapId, change.path))) throw new AtlasError("version_conflict", "\u65B0\u6587\u4EF6\u76EE\u6807\u5DF2\u88AB\u5916\u90E8\u5360\u7528");
1876
+ if (!mutations.length) return { operationId: req.operationId, committedFingerprint: snapshot.fingerprint, snapshot, noChange: true };
1877
+ const livePort = overlayFiles(port, req.mapId, /* @__PURE__ */ new Map());
1878
+ memory.pending = plotChanges;
1879
+ const result = await tx.commit(req.operationId, request, mutations, { operationId: req.operationId, noChange: false }, async () => {
1880
+ signal.throwIfAborted();
1881
+ if ((await readSnapshot(livePort, req.mapId)).fingerprint !== req.expectedFingerprint) throw new AtlasError("version_conflict", "\u63D0\u4EA4\u524D\u5730\u56FE\u53D8\u5316");
1882
+ }, async () => {
1883
+ signal.throwIfAborted();
1884
+ const after = await readSnapshot(livePort, req.mapId);
1885
+ const changes = new Set(mutations.map((change) => mapPath(req.mapId, change.path)));
1886
+ if (after.files.length !== proposal.files.length || proposal.files.some((expected) => {
1887
+ const actual = after.files.find((f) => f.path === expected.path);
1888
+ return !actual || actual.digest !== expected.digest || !changes.has(expected.path) && actual.version !== expected.version && expected.version !== "candidate";
1889
+ })) throw new AtlasError("version_conflict", "\u5019\u9009\u4EE5\u5916\u6587\u4EF6\u5728\u4FDD\u5B58\u671F\u95F4\u53D8\u5316");
1890
+ return { operationId: req.operationId, noChange: false, committedFingerprint: after.fingerprint };
1891
+ });
1892
+ acceptEditMemory(memory, req.operationId, request, result.committedFingerprint);
1893
+ const saved = await readSnapshot(port, req.mapId);
1894
+ if (saved.fingerprint !== result.committedFingerprint) throw new AtlasError("version_conflict", "\u4FDD\u5B58\u540E\u51FA\u73B0\u5916\u90E8\u4FEE\u6539");
1895
+ return { ...result, snapshot: saved };
1896
+ }
1897
+
1898
+ // src/server/map-queue.ts
1899
+ var queues = /* @__PURE__ */ new Map();
1900
+ async function serializeMap(key, run) {
1901
+ const pending = (queues.get(key) ?? Promise.resolve()).catch(() => {
1902
+ }).then(run);
1903
+ queues.set(key, pending);
1904
+ try {
1905
+ return await pending;
1906
+ } finally {
1907
+ if (queues.get(key) === pending) queues.delete(key);
1908
+ }
1909
+ }
1910
+
1911
+ // src/server/tools/index.ts
1912
+ import { defineTool } from "@deepseek-ai/dsh-tools";
1913
+ import { z as z9 } from "zod";
1914
+ import { randomUUID as randomUUID4 } from "node:crypto";
1915
+
1916
+ // src/server/library-files.ts
1917
+ import { randomUUID as randomUUID2 } from "node:crypto";
1918
+
1919
+ // src/shared/library.ts
1920
+ import { z as z8 } from "zod";
1921
+ var librarySchema = z8.strictObject({
1922
+ schemaVersion: z8.literal(1),
1923
+ folders: z8.array(z8.strictObject({
1924
+ id: idSchema,
1925
+ title: z8.string().trim().min(1).max(120),
1926
+ parentId: idSchema.nullable()
1927
+ })),
1928
+ mapFolders: z8.record(idSchema, idSchema),
1929
+ rootMapOrder: z8.array(idSchema).optional(),
1930
+ folderMapOrders: z8.record(idSchema, z8.array(idSchema)).optional(),
1931
+ deletedMapIds: z8.array(idSchema).optional(),
1932
+ deletedMapTitles: z8.record(idSchema, z8.string()).optional(),
1933
+ purgedMapIds: z8.array(idSchema).optional(),
1934
+ purgingMapIds: z8.array(idSchema).optional()
1935
+ }).superRefine((library, ctx) => {
1936
+ const ids = new Set(library.folders.map((f) => f.id));
1937
+ const fail = (message) => ctx.addIssue({ code: "custom", message });
1938
+ if (ids.size !== library.folders.length) fail("\u6587\u4EF6\u5939\u8EAB\u4EFD\u91CD\u590D");
1939
+ for (const folder of library.folders) {
1940
+ const seen = /* @__PURE__ */ new Set([folder.id]);
1941
+ let parent = folder.parentId;
1942
+ while (parent) {
1943
+ if (!ids.has(parent)) {
1944
+ fail("\u7236\u6587\u4EF6\u5939\u4E0D\u5B58\u5728");
1945
+ break;
1946
+ }
1947
+ if (seen.has(parent)) {
1948
+ fail("\u6587\u4EF6\u5939\u5C42\u7EA7\u4E0D\u80FD\u5FAA\u73AF");
1949
+ break;
1950
+ }
1951
+ seen.add(parent);
1952
+ parent = library.folders.find((f) => f.id === parent).parentId;
1953
+ }
1954
+ }
1955
+ for (const folderId of Object.values(library.mapFolders))
1956
+ if (!ids.has(folderId)) fail("\u5BFC\u56FE\u6240\u5C5E\u6587\u4EF6\u5939\u4E0D\u5B58\u5728");
1957
+ const orderedMaps = /* @__PURE__ */ new Set();
1958
+ const checkOrder = (list) => {
1959
+ const local = /* @__PURE__ */ new Set();
1960
+ for (const mapId of list) {
1961
+ if (local.has(mapId)) {
1962
+ fail("\u5BFC\u56FE\u6392\u5E8F\u5B58\u5728\u91CD\u590D\u8EAB\u4EFD");
1963
+ return false;
1964
+ }
1965
+ if (orderedMaps.has(mapId)) {
1966
+ fail("\u5BFC\u56FE\u4E0D\u80FD\u540C\u65F6\u51FA\u73B0\u5728\u591A\u4E2A\u6392\u5E8F\u5217\u8868\u4E2D");
1967
+ return false;
1968
+ }
1969
+ local.add(mapId);
1970
+ orderedMaps.add(mapId);
1971
+ }
1972
+ return true;
1973
+ };
1974
+ if (library.rootMapOrder) checkOrder(library.rootMapOrder);
1975
+ for (const [folderId, list] of Object.entries(library.folderMapOrders ?? {})) {
1976
+ if (!ids.has(folderId)) {
1977
+ fail("\u5BFC\u56FE\u6392\u5E8F\u6240\u5C5E\u6587\u4EF6\u5939\u4E0D\u5B58\u5728");
1978
+ break;
1979
+ }
1980
+ if (!checkOrder(list)) break;
1981
+ }
1982
+ });
1983
+ var emptyLibrary = () => ({ schemaVersion: 1, folders: [], mapFolders: {} });
1984
+
1985
+ // src/server/library-files.ts
1986
+ function libraryFiles(ctx, scope, signal, policy) {
1987
+ async function targetFor(path) {
1988
+ const root = await ctx.fs.resolve(scope.workspaceRoot, { signal });
1989
+ const data = await ctx.fs.resolve(DATA_ROOT, { cwd: scope.workspaceRoot, signal });
1990
+ const target = await ctx.fs.resolve(path, { cwd: scope.workspaceRoot, signal });
1991
+ if (!ctx.fs.contains(root, data) || !ctx.fs.contains(data, target) || data.targetKey === target.targetKey)
1992
+ throw new AtlasError("path_outside_map", "\u76EE\u5F55\u7D22\u5F15\u6216\u65B0\u5BFC\u56FE\u8D8A\u8FC7\u5DE5\u4F5C\u533A\u6570\u636E\u8FB9\u754C");
1993
+ const entry = await ctx.fs.lstat(path, { cwd: scope.workspaceRoot }, signal);
1994
+ if (entry && entry.type !== "file") throw new AtlasError("invalid_data", "\u76EE\u6807\u5FC5\u987B\u662F\u666E\u901A\u6587\u4EF6");
1995
+ return target;
1996
+ }
1997
+ async function read() {
1998
+ const target = await targetFor(`${DATA_ROOT}/library.json`);
1999
+ const before = await ctx.fs.stat(target, signal);
2000
+ if (!before) return { data: emptyLibrary(), version: null, workspaceKey: scope.workspaceRoot };
2001
+ const data = librarySchema.parse(JSON.parse(await ctx.fs.readText(target, signal)));
2002
+ const after = await ctx.fs.stat(target, signal);
2003
+ if (before.version !== after?.version) throw new AtlasError("version_conflict", "\u76EE\u5F55\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0");
2004
+ return { data, version: String(after.version), workspaceKey: scope.workspaceRoot };
2005
+ }
2006
+ return {
2007
+ read,
2008
+ async rename(map, title2, version) {
2009
+ const target = await targetFor(`${DATA_ROOT}/${map.id}/map.json`);
2010
+ const mapRoot = await ctx.fs.resolve(`${DATA_ROOT}/${map.id}`, { cwd: scope.workspaceRoot, signal });
2011
+ if (!ctx.fs.contains(mapRoot, target) || mapRoot.targetKey === target.targetKey)
2012
+ throw new AtlasError("path_outside_map", "\u540D\u79F0\u5199\u5165\u8D8A\u8FC7\u5730\u56FE\u8FB9\u754C");
2013
+ const checked = mapSchema.parse({ ...map, title: title2, views: map.views.map((view2) => view2.id === map.rootViewId && view2.title === map.title ? { ...view2, title: title2 } : view2) });
2014
+ await ctx.fs.writeText(target, `${JSON.stringify(checked, null, 2)}
2015
+ `, { kind: "replaceIfVersion", version }, signal, policy);
2016
+ },
2017
+ async save(data, version) {
2018
+ const checked = librarySchema.parse(data);
2019
+ const target = await targetFor(`${DATA_ROOT}/library.json`);
2020
+ await ctx.fs.writeText(
2021
+ target,
2022
+ `${JSON.stringify(checked, null, 2)}
2023
+ `,
2024
+ version === null ? { kind: "createIfAbsent" } : { kind: "replaceIfVersion", version },
2025
+ signal,
2026
+ policy
2027
+ );
2028
+ return read();
2029
+ },
2030
+ async create(title2) {
2031
+ const id = randomUUID2();
2032
+ const map = mapSchema.parse({
2033
+ schemaVersion: 1,
2034
+ id,
2035
+ title: title2,
2036
+ rootViewId: "root",
2037
+ nodes: [],
2038
+ views: [{ id: "root", title: title2, parentViewId: null, groups: [], occurrences: [], relationIds: [] }],
2039
+ relations: []
2040
+ });
2041
+ const target = await targetFor(`${DATA_ROOT}/${id}/map.json`);
2042
+ await ctx.fs.writeText(target, `${JSON.stringify(map, null, 2)}
2043
+ `, { kind: "createIfAbsent" }, signal, policy);
2044
+ return id;
2045
+ }
2046
+ };
2047
+ }
2048
+
2049
+ // src/shared/layout.ts
2050
+ var heightKey = (viewId, nodeId) => `${viewId}/${nodeId}`;
2051
+ var nodeHeight = (h, viewId, nodeId) => h[heightKey(viewId, nodeId)] ?? 130;
2052
+ function fillLayout(map, previous, heights) {
2053
+ return {
2054
+ schemaVersion: previous?.schemaVersion ?? 1,
2055
+ mapId: map.id,
2056
+ views: map.views.map((view2) => {
2057
+ const old = previous?.views.find((v) => v.viewId === view2.id);
2058
+ const nodes = (old?.nodes ?? []).filter((n) => view2.occurrences.some((o) => o.nodeId === n.nodeId)).map((n) => ({ ...n }));
2059
+ let groupY = 48;
2060
+ const groups = [];
2061
+ const buckets = [...view2.groups.map((g) => g.id), void 0];
2062
+ for (const groupId of buckets) {
2063
+ const members = view2.occurrences.filter((o) => o.groupId === groupId);
2064
+ const oldGroup = old?.groups.find((g) => g.groupId === groupId);
2065
+ const x = oldGroup?.x ?? 42;
2066
+ const y = oldGroup?.y ?? groupY;
2067
+ for (const [index, occurrence] of members.entries()) {
2068
+ if (nodes.some((n2) => n2.nodeId === occurrence.nodeId)) continue;
2069
+ const n = {
2070
+ nodeId: occurrence.nodeId,
2071
+ x: x + 36 + index % 3 * 327,
2072
+ y: y + 56,
2073
+ width: 236,
2074
+ manual: false
2075
+ };
2076
+ const height = nodeHeight(heights, view2.id, n.nodeId);
2077
+ while (nodes.some(
2078
+ (other) => n.x < other.x + other.width + 24 && n.x + n.width + 24 > other.x && n.y < other.y + nodeHeight(heights, view2.id, other.nodeId) + 24 && n.y + height + 24 > other.y
2079
+ ))
2080
+ n.y += height + 32;
2081
+ nodes.push(n);
2082
+ }
2083
+ const inside = nodes.filter(
2084
+ (n) => members.some((o) => o.nodeId === n.nodeId)
2085
+ );
2086
+ if (groupId) {
2087
+ if (oldGroup) {
2088
+ groups.push({ ...oldGroup });
2089
+ groupY = oldGroup.y + oldGroup.height + 19;
2090
+ continue;
2091
+ }
2092
+ const left = Math.min(x, ...inside.map((n) => n.x - 24));
2093
+ const top = Math.min(y, ...inside.map((n) => n.y - 62));
2094
+ const right = Math.max(
2095
+ x + 1058,
2096
+ ...inside.map((n) => n.x + n.width + 24)
2097
+ );
2098
+ const bottom = Math.max(
2099
+ y + 178,
2100
+ ...inside.map(
2101
+ (n) => n.y + nodeHeight(heights, view2.id, n.nodeId) + 24
2102
+ )
2103
+ );
2104
+ groups.push({
2105
+ groupId,
2106
+ x: left,
2107
+ y: top,
2108
+ width: right - left,
2109
+ height: bottom - top
2110
+ });
2111
+ groupY = bottom + 19;
2112
+ }
2113
+ }
2114
+ return { viewId: view2.id, nodes, groups, ...previous?.schemaVersion === 2 ? { mode: old?.mode ?? "vertical" } : {} };
2115
+ })
2116
+ };
2117
+ }
2118
+
2119
+ // src/server/cleanup-create.ts
2120
+ import { randomUUID as randomUUID3 } from "node:crypto";
2121
+ async function cleanupCreate(ctx, scope, mapId, operationId, policy, signal) {
2122
+ signal.throwIfAborted();
2123
+ if (policy.mode === "read-only") throw new AtlasError("permission_denied", "\u53EA\u8BFB\u4F1A\u8BDD\u4E0D\u80FD\u6E05\u7406\u521B\u5EFA\u8BB0\u5F55");
2124
+ if (policy.workspaceRoot !== scope.workspaceRoot) throw new AtlasError("workspace_changed", "\u6E05\u7406\u5DE5\u4F5C\u533A\u5DF2\u53D8\u5316");
2125
+ const files = createHostFiles(ctx, scope, new AbortController().signal, policy);
2126
+ const metadata = transactionPort(ctx, scope, mapId, policy);
2127
+ const prior = await inspectCreatePlaceholder(files, mapId);
2128
+ if (!prior || prior.operationId !== operationId) throw new AtlasError("cleanup_refused", "\u53EA\u80FD\u6E05\u7406\u5DF2\u8BC6\u522B\u4E14\u6CA1\u6709\u6D3B\u52A8\u4E8B\u52A1\u7684\u672A\u5B8C\u6210\u521B\u5EFA\uFF1B\u5B8C\u6574\u5730\u56FE\u3001\u672A\u77E5\u5185\u5BB9\u53CA\u5F85\u6062\u590D\u8D44\u6599\u4FDD\u7559");
2129
+ if (prior.state === "discarded") return { status: "success", mapId, operationId, summary: "\u8BE5\u521B\u5EFA\u8BB0\u5F55\u5DF2\u6E05\u7406\uFF0C\u65E7\u8BF7\u6C42\u5DF2\u4F5C\u5E9F" };
2130
+ const lockText = JSON.stringify({ kind: "create-cleanup", owner: randomUUID3(), operationId, request: prior.request });
2131
+ signal.throwIfAborted();
2132
+ await metadata.put(".transactions/active.json", lockText, null);
2133
+ try {
2134
+ const current = await inspectCreatePlaceholder(files, mapId, lockText);
2135
+ if (!current || current.operationId !== operationId || current.request !== prior.request) throw new AtlasError("cleanup_refused", "\u521B\u5EFA\u72B6\u6001\u5DF2\u53D8\u5316\uFF0C\u672A\u5220\u9664\u8D44\u6599");
2136
+ const marker = ".transactions/discarded-create.json";
2137
+ if (!await metadata.read(marker)) await metadata.put(marker, JSON.stringify({ kind: "discarded_create", mapId, operationId, request: current.request }), null);
2138
+ for (const name2 of ["reservation.json", "failed.json"]) {
2139
+ const path = `.transactions/${operationId}/${name2}`;
2140
+ const record = await metadata.read(path);
2141
+ if (!record) continue;
2142
+ const request = name2 === "reservation.json" ? record.text : JSON.parse(record.text).request;
2143
+ if (request !== current.request) throw new AtlasError("operation_conflict", "\u521B\u5EFA\u8BB0\u5F55\u5DF2\u53D8\u5316\uFF0C\u505C\u6B62\u6E05\u7406");
2144
+ await metadata.remove(path, record.version);
2145
+ }
2146
+ const after = await inspectCreatePlaceholder(files, mapId, lockText);
2147
+ if (after?.state !== "discarded") throw new AtlasError("cleanup_incomplete", "\u8BF7\u6C42\u5DF2\u4F5C\u5E9F\uFF0C\u53D1\u73B0\u989D\u5916\u5185\u5BB9\u6216\u72B6\u6001\u53D8\u5316\uFF0C\u4FDD\u7559\u73B0\u573A");
2148
+ return { status: "success", mapId, operationId, summary: "\u672A\u5B8C\u6210\u521B\u5EFA\u5DF2\u6E05\u7406\uFF0C\u65E7\u8BF7\u6C42\u5DF2\u4F5C\u5E9F" };
2149
+ } finally {
2150
+ const lock = await metadata.read(".transactions/active.json");
2151
+ if (lock?.text === lockText) await metadata.remove(".transactions/active.json", lock.version);
2152
+ }
2153
+ }
2154
+
2155
+ // src/server/tools/index.ts
2156
+ var text = (value) => JSON.stringify(value, null, 2) + "\n";
2157
+ var hash = (value) => digest(new TextEncoder().encode(JSON.stringify(value)));
2158
+ function parameters(schema) {
2159
+ function convert(s) {
2160
+ if (s.anyOf) return { oneOf: s.anyOf.map(convert) };
2161
+ const out = { type: s.type ?? "json" };
2162
+ if (s.enum) out.enum = s.enum;
2163
+ if (s.const !== void 0) out.const = s.const;
2164
+ if (s.type === "object") {
2165
+ out.additionalProperties = s.additionalProperties !== false;
2166
+ out.properties = Object.fromEntries(Object.entries(s.properties ?? {}).map(([k, v]) => [k, { ...convert(v), ...s.required?.includes(k) ? { required: true } : {} }]));
2167
+ }
2168
+ if (s.items) out.items = convert(s.items);
2169
+ return out;
2170
+ }
2171
+ return convert(z9.toJSONSchema(schema)).properties;
2172
+ }
2173
+ function registerTools(ctx) {
2174
+ const owner = randomUUID4();
2175
+ const previews = /* @__PURE__ */ new Map();
2176
+ async function binding(exec) {
2177
+ if (!exec.agent) throw new AtlasError("session_unavailable", "\u5730\u56FE\u5DE5\u5177\u9700\u8981\u6765\u6E90\u4F1A\u8BDD");
2178
+ const policy = ctx.sandboxPolicy.resolve({ session: exec.agent.session });
2179
+ const workspaceRoot = policy.workspaceRoot;
2180
+ const scope = { sessionId: exec.agent.id, workspaceRoot };
2181
+ return { scope, policy, port: createHostFiles(ctx, scope, exec.signal, policy) };
2182
+ }
2183
+ async function invoke(name2, raw, exec) {
2184
+ const { scope, policy, port } = await binding(exec);
2185
+ if (name2 === "atlas_list") {
2186
+ z9.strictObject({}).parse(raw);
2187
+ const listing = await listMaps(port);
2188
+ const library = (await libraryFiles(ctx, scope, exec.signal).read()).data;
2189
+ const deleted = [...library.deletedMapIds ?? [], ...library.purgedMapIds ?? []];
2190
+ return { status: "success", maps: listing.maps.filter((m) => !deleted.includes(m.id)), diagnostics: listing.diagnostics.filter((d) => !(library.purgedMapIds ?? []).includes(d.path.split("/")[1])), incompleteCreates: listing.incompleteCreates };
2191
+ }
2192
+ if (name2 === "atlas_cleanup_create") {
2193
+ const args2 = cleanupCreateSchema.parse(raw);
2194
+ if (policy.mode === "read-only") throw new AtlasError("permission_denied", "\u53EA\u8BFB\u4F1A\u8BDD\u4E0D\u80FD\u6E05\u7406\u521B\u5EFA\u8BB0\u5F55");
2195
+ const outcome = await ctx.approval.request({ agent: exec.agent, toolName: name2, callId: exec.callId, reason: `\u6E05\u7406\u672A\u5B8C\u6210\u521B\u5EFA ${args2.mapId}\uFF0C\u4F5C\u5E9F\u539F\u8BF7\u6C42 ${args2.operationId}\uFF1B\u4E0D\u4F1A\u5220\u9664\u5B8C\u6574\u5730\u56FE\u3002`, signal: exec.signal });
2196
+ if (outcome !== "allowed-once") throw new AtlasError("approval_required", "\u6E05\u7406\u672A\u83B7\u5BBF\u4E3B\u6388\u6743");
2197
+ return cleanupCreate(ctx, scope, args2.mapId, args2.operationId, policy, exec.signal);
2198
+ }
2199
+ const args = (name2 === "atlas_read" ? readSchema : name2 === "atlas_create" ? createSchema : name2 === "atlas_preview" ? previewSchema : applySchema).parse(raw);
2200
+ const request = await hash(args);
2201
+ const mapId = name2 === "atlas_create" ? "map-" + (await hash({ operationId: args.operationId })).slice(0, 32) : args.mapId;
2202
+ const libraryState = (await libraryFiles(ctx, scope, exec.signal).read()).data;
2203
+ if (libraryState.deletedMapIds?.includes(mapId) || libraryState.purgedMapIds?.includes(mapId)) throw new AtlasError("map_deleted", "\u5BFC\u56FE\u5DF2\u5728\u56DE\u6536\u7AD9");
2204
+ const txPort = transactionPort(ctx, scope, mapId, policy);
2205
+ const tx = new Transactions(txPort, owner);
2206
+ if (await txPort.read(".transactions/discarded-create.json")) throw new AtlasError("create_discarded", "\u6B64\u521B\u5EFA\u8BF7\u6C42\u5DF2\u88AB\u6E05\u7406\u5E76\u4F5C\u5E9F\uFF1B\u5982\u9700\u91CD\u65B0\u521B\u5EFA\uFF0C\u8BF7\u4F7F\u7528\u65B0\u7684operationId");
2207
+ if (name2 === "atlas_create" || name2 === "atlas_apply") {
2208
+ const replay = await tx.replay(args.operationId, request);
2209
+ if (replay !== void 0) return replay;
2210
+ }
2211
+ if (name2 === "atlas_create") {
2212
+ if (policy.mode === "read-only") throw new AtlasError("permission_denied", "\u5F53\u524D\u4F1A\u8BDD\u4E3A\u53EA\u8BFB");
2213
+ const reservationPath = `.transactions/${args.operationId}/reservation.json`;
2214
+ const reservation = await txPort.read(reservationPath);
2215
+ if (reservation && reservation.text !== request) throw new AtlasError("operation_conflict", "\u521B\u5EFA\u8BF7\u6C42ID\u5DF2\u7528\u4E8E\u5176\u4ED6\u5185\u5BB9");
2216
+ const failed = await txPort.read(`.transactions/${args.operationId}/failed.json`);
2217
+ if (failed) {
2218
+ const record = JSON.parse(failed.text);
2219
+ if (!record || record.kind !== "failed_create" || record.operationId !== args.operationId || record.request !== request) throw new AtlasError("operation_conflict", "\u5931\u8D25\u521B\u5EFA\u8BF7\u6C42ID\u5DF2\u7528\u4E8E\u5176\u4ED6\u5185\u5BB9\u6216\u8BB0\u5F55\u65E0\u6548");
2220
+ }
2221
+ }
2222
+ let snapshot;
2223
+ if (name2 !== "atlas_create") snapshot = await readSnapshot(port, mapId);
2224
+ if (name2 === "atlas_read") {
2225
+ const selected = snapshot.map.nodes.filter((n) => (!args.nodeIds || args.nodeIds.includes(n.id)) && (!args.viewIds || snapshot.map.views.some((v) => args.viewIds.includes(v.id) && (v.centerNodeId === n.id || v.occurrences.some((o) => o.nodeId === n.id)))) && (!args.query || [n.title, n.summary, snapshot.notes[n.id]].join(" ").toLowerCase().includes(args.query.toLowerCase())));
2226
+ const selector = await hash({ nodeIds: args.nodeIds, viewIds: args.viewIds, query: args.query });
2227
+ let offset2 = 0;
2228
+ if (args.cursor) {
2229
+ let cursor;
2230
+ try {
2231
+ cursor = JSON.parse(Buffer.from(args.cursor, "base64url").toString());
2232
+ } catch {
2233
+ throw new AtlasError("invalid_cursor", "\u5206\u9875\u6E38\u6807\u65E0\u6548");
2234
+ }
2235
+ ;
2236
+ if (cursor.version !== snapshot.fingerprint || cursor.selector !== selector || cursor.mapId !== mapId || cursor.workspace !== scope.workspaceRoot) throw new AtlasError("cursor_expired", "\u5730\u56FE\u6216\u7B5B\u9009\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6");
2237
+ offset2 = cursor.offset;
2238
+ if (!Number.isSafeInteger(offset2) || offset2 < 0 || offset2 > selected.length) throw new AtlasError("invalid_cursor", "\u5206\u9875\u4F4D\u7F6E\u65E0\u6548");
2239
+ }
2240
+ const page = selected.slice(offset2, offset2 + 10);
2241
+ return { status: "success", map: snapshot.map, notes: Object.fromEntries(page.map((n) => [n.id, snapshot.notes[n.id]])), fingerprint: snapshot.fingerprint, notesTotal: selected.length, nextCursor: offset2 + 10 < selected.length ? Buffer.from(JSON.stringify({ version: snapshot.fingerprint, selector, mapId, workspace: scope.workspaceRoot, offset: offset2 + 10 })).toString("base64url") : null };
2242
+ }
2243
+ if (snapshot && snapshot.fingerprint !== args.expectedFingerprint) throw new AtlasError("version_conflict", "\u5730\u56FE\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6");
2244
+ let proposal;
2245
+ let newAnchoredPath;
2246
+ if (name2 === "atlas_create") {
2247
+ const map = { ...args.content, id: mapId, schemaVersion: 1 };
2248
+ for (const nodeId of Object.keys(args.notes)) if (!map.nodes.some((n) => n.id === nodeId)) throw new AtlasError("invalid_data", `\u7B14\u8BB0\u8282\u70B9\u4E0D\u5B58\u5728\uFF1A${nodeId}`);
2249
+ for (const n of map.nodes) if (args.notes[n.id]) n.notePath = `notes/${n.id}.md`;
2250
+ const checked = validateMap(map, mapId);
2251
+ if (!checked.ok) throw new AtlasError("invalid_data", "\u521B\u5EFA\u7ED3\u6784\u65E0\u6548", checked.diagnostics);
2252
+ proposal = { map: checked.value, notes: args.notes, affectedIds: map.nodes.map((n) => n.id), removals: [] };
2253
+ } else {
2254
+ const change = args.changes[0];
2255
+ if (change.op === "insert_note_content") {
2256
+ const node2 = snapshot.map.nodes.find((item) => item.id === change.nodeId);
2257
+ if (!node2 || change.anchor.mapId !== mapId || change.anchor.nodeId !== node2.id)
2258
+ throw new AtlasError("invalid_data", "\u6B63\u6587\u4F4D\u7F6E\u5F15\u7528\u4E0E\u76EE\u6807\u5730\u56FE\u6216\u8282\u70B9\u4E0D\u4E00\u81F4");
2259
+ let markdown2;
2260
+ try {
2261
+ markdown2 = await insertAnchoredNote(snapshot.notes[node2.id] ?? "", change.anchor, change.kind, change.markdown);
2262
+ } catch (error) {
2263
+ throw new AtlasError("invalid_data", error.message);
2264
+ }
2265
+ proposal = candidate(snapshot, [{ op: "set_note", nodeId: node2.id, markdown: markdown2 }]);
2266
+ if (!node2.notePath) {
2267
+ newAnchoredPath = proposal.map.nodes.find((item) => item.id === node2.id)?.notePath;
2268
+ if (newAnchoredPath && await txPort.read(newAnchoredPath))
2269
+ throw new AtlasError("version_conflict", "\u7B14\u8BB0\u76EE\u6807\u5DF2\u88AB\u5360\u7528\uFF0C\u539F\u6587\u4EF6\u5DF2\u4FDD\u7559");
2270
+ }
2271
+ } else proposal = candidate(snapshot, args.changes);
2272
+ }
2273
+ proposal.removals.push(...validateCandidatePlots(snapshot?.notes ?? {}, proposal.notes, proposal.map));
2274
+ const files = /* @__PURE__ */ new Map();
2275
+ if (!snapshot || JSON.stringify(snapshot.map) !== JSON.stringify(proposal.map)) files.set("map.json", text(proposal.map));
2276
+ for (const n of proposal.map.nodes) if (n.notePath) files.set(n.notePath, proposal.notes[n.id] ?? "");
2277
+ for (const n of snapshot?.map.nodes ?? []) if (n.notePath && !proposal.map.nodes.some((next) => next.notePath === n.notePath)) files.set(n.notePath, null);
2278
+ const membership = (map) => map.views.map((v) => ({ id: v.id, groups: v.groups.map((g) => g.id), occurrences: v.occurrences }));
2279
+ if (snapshot?.layout && JSON.stringify(membership(snapshot.map)) !== JSON.stringify(membership(proposal.map))) files.set("layout.json", text(fillLayout(proposal.map, snapshot.layout, {})));
2280
+ const overlay = overlayFiles(port, mapId, files);
2281
+ await readSnapshot(overlay, mapId);
2282
+ if (name2 === "atlas_preview") {
2283
+ const token = randomUUID4();
2284
+ previews.set(token, { workspace: scope.workspaceRoot, mapId, fingerprint: snapshot.fingerprint, request: await hash(args.changes), removals: proposal.removals, approved: false });
2285
+ return { status: "preview", previewToken: token, affectedIds: proposal.affectedIds, removals: proposal.removals, summary: "\u5019\u9009\u5DF2\u6821\u9A8C\uFF0C\u5C1A\u672A\u4FDD\u5B58" };
2286
+ }
2287
+ if (policy.mode === "read-only") throw new AtlasError("permission_denied", "\u5F53\u524D\u4F1A\u8BDD\u4E3A\u53EA\u8BFB");
2288
+ if (proposal.removals.length) {
2289
+ const preview = previews.get(args.previewToken);
2290
+ if (!preview || preview.workspace !== scope.workspaceRoot || preview.mapId !== mapId || preview.fingerprint !== snapshot.fingerprint || preview.request !== await hash(args.changes)) throw new AtlasError("preview_required", "\u5220\u9664\u987B\u5148\u9884\u89C8\u5F53\u524D\u7248\u672C\u5F71\u54CD");
2291
+ if (!preview.approved) {
2292
+ const outcome = await ctx.approval.request({ agent: exec.agent, toolName: name2, callId: exec.callId, reason: "\u5220\u9664\u5F71\u54CD\uFF1A" + proposal.removals.join("\u3001"), signal: exec.signal });
2293
+ if (outcome !== "allowed-once") throw new AtlasError("approval_required", "\u5220\u9664\u672A\u83B7\u5BBF\u4E3B\u6388\u6743");
2294
+ preview.approved = true;
2295
+ }
2296
+ }
2297
+ let reservationReady = false;
2298
+ try {
2299
+ if (name2 === "atlas_create") {
2300
+ exec.signal.throwIfAborted();
2301
+ if (await txPort.read(".transactions/discarded-create.json")) throw new AtlasError("create_discarded", "\u521B\u5EFA\u8BF7\u6C42\u5DF2\u88AB\u6E05\u7406\u5E76\u4F5C\u5E9F\uFF0C\u505C\u6B62\u5360\u4F4D");
2302
+ const path = `.transactions/${args.operationId}/reservation.json`;
2303
+ const reservation = await txPort.read(path);
2304
+ if (reservation && reservation.text !== request) throw new AtlasError("operation_conflict", "\u521B\u5EFA\u8BF7\u6C42ID\u5DF2\u7528\u4E8E\u5176\u4ED6\u5185\u5BB9");
2305
+ if ((await port.list()).includes(mapId)) {
2306
+ const placeholder = await inspectCreatePlaceholder(port, mapId);
2307
+ if (!placeholder || placeholder.state === "discarded" || placeholder.state === "cleanup_pending" || placeholder.operationId !== args.operationId || placeholder.request !== request) throw new AtlasError("unknown_directory", "\u4E0D\u63A5\u7BA1\u5DF2\u6709\u672A\u77E5\u76EE\u5F55\u3001\u5DF2\u6E05\u7406\u6216\u975E\u7A7A\u521B\u5EFA\u76EE\u5F55");
2308
+ }
2309
+ reservationReady = true;
2310
+ if (!reservation) await txPort.put(path, request, null);
2311
+ }
2312
+ const mutations = await fileMutations(txPort, files);
2313
+ if (newAnchoredPath && !mutations.some((item) => item.path === newAnchoredPath && item.before === null))
2314
+ throw new AtlasError("version_conflict", "\u7B14\u8BB0\u76EE\u6807\u5DF2\u88AB\u5360\u7528\uFF0C\u539F\u6587\u4EF6\u5DF2\u4FDD\u7559");
2315
+ const result = { status: "success", operationId: args.operationId, mapId, affectedIds: proposal.affectedIds, summary: name2 === "atlas_create" ? "\u601D\u7EF4\u5BFC\u56FE\u5DF2\u521B\u5EFA" : "\u53D8\u66F4\u5DF2\u4FDD\u5B58" };
2316
+ const saved = await tx.commit(args.operationId, request, mutations, result, async () => {
2317
+ exec.signal.throwIfAborted();
2318
+ if (await txPort.read(".transactions/discarded-create.json")) throw new AtlasError("create_discarded", "\u521B\u5EFA\u8BF7\u6C42\u5DF2\u88AB\u6E05\u7406\u5E76\u4F5C\u5E9F\uFF0C\u505C\u6B62\u63D0\u4EA4");
2319
+ if (snapshot) {
2320
+ const live = await readSnapshot({ ...port, absent: async (path) => path === mapPath(mapId, ".transactions/active.json") ? true : port.absent(path) }, mapId);
2321
+ if (live.fingerprint !== snapshot.fingerprint) throw new AtlasError("version_conflict", "\u63D0\u4EA4\u524D\u7248\u672C\u53D8\u5316");
2322
+ } else if (!await port.absent(mapPath(mapId, "map.json"))) throw new AtlasError("version_conflict", "\u521B\u5EFA\u76EE\u6807\u5DF2\u5B58\u5728");
2323
+ }, async () => ({ ...result, fingerprint: (await readSnapshot({ ...port, absent: async (path) => path === mapPath(mapId, ".transactions/active.json") ? true : port.absent(path) }, mapId)).fingerprint }));
2324
+ return saved;
2325
+ } catch (e) {
2326
+ if (reservationReady && errorCode(e) !== "recovery_required") {
2327
+ try {
2328
+ if (!await releaseFailedCreate(ctx, scope, mapId, args.operationId, request, policy, errorCode(e))) {
2329
+ throw new Error("\u53D1\u73B0\u672A\u77E5\u5185\u5BB9\u6216\u6D3B\u52A8\u72B6\u6001\uFF0C\u4FDD\u7559\u521B\u5EFA\u8D44\u6599");
2330
+ }
2331
+ } catch (cleanup) {
2332
+ throw new AtlasError(errorCode(e), String(e), [
2333
+ ...e instanceof AtlasError ? e.diagnostics : [],
2334
+ { path: mapPath(mapId, "."), code: "cleanup_incomplete", message: `\u521B\u5EFA\u6E05\u7406\u672A\u5B8C\u6210\uFF0C\u539F\u8D44\u6599\u4FDD\u7559\uFF1A${String(cleanup)}` }
2335
+ ]);
2336
+ }
2337
+ }
2338
+ throw e;
2339
+ }
2340
+ }
2341
+ for (const [name2, schema, description] of [
2342
+ ["atlas_list", z9.strictObject({}), "\u5217\u51FA\u5F53\u524D\u5DE5\u4F5C\u533A\u6709\u6548\u601D\u7EF4\u5BFC\u56FE\u3002"],
2343
+ ["atlas_read", readSchema, "\u8BFB\u53D6\u5B8C\u6574\u7ED3\u6784\u53CA\u5206\u9875\u7B14\u8BB0\u3001\u7A33\u5B9AID\u548C\u7248\u672C\uFF1B\u6CBFnextCursor\u8BFB\u53D6\u5269\u4F59\u7B14\u8BB0\u3002"],
2344
+ ["atlas_create", createSchema, "\u521B\u5EFA\u901A\u7528\u601D\u7EF4\u5BFC\u56FE\uFF1A\u67B6\u6784\u8BBE\u8BA1\u3001\u77E5\u8BC6\u6574\u7406\u7B49\u3002\u53EA\u63D0\u4F9B\u5185\u5BB9\u548CMarkdown\uFF0C\u4E0D\u63D0\u4F9B\u8DEF\u5F84\u3001\u5E03\u5C40\u6216\u754C\u9762\u4EE3\u7801\u3002"],
2345
+ ["atlas_preview", previewSchema, "\u9884\u89C8\u6709\u5E8F\u53D8\u66F4\u53CA\u5220\u9664\u5F71\u54CD\uFF0C\u4E0D\u4FDD\u5B58\u3002"],
2346
+ ["atlas_apply", applySchema, "\u6761\u4EF6\u63D0\u4EA4\u6700\u5C0F\u53D8\u66F4\uFF1B\u6B63\u6587\u4F4D\u7F6E\u5F15\u7528\u4F7F\u7528\u5355\u9879 insert_note_content\u3002\u5220\u9664\u987B\u5F53\u524D\u7248\u672C\u9884\u89C8\u4E0E\u5BBF\u4E3B\u6388\u6743\u3002\u76F8\u540C\u8BF7\u6C42\u91CD\u8BD5\u590D\u7528operationId\u3002"],
2347
+ ["atlas_cleanup_create", cleanupCreateSchema, "\u7528\u6237\u8981\u6C42\u6E05\u7406\u65F6\uFF0C\u6E05\u7406atlas_list.incompleteCreates\u4E2D\u7684\u6307\u5B9A\u8BB0\u5F55\u5E76\u4F5C\u5E9F\u539F\u521B\u5EFA\u8BF7\u6C42\uFF1B\u987B\u5BBF\u4E3B\u6388\u6743\u3002\u62D2\u7EDD\u5B8C\u6574\u5730\u56FE\u3001\u672A\u77E5\u5185\u5BB9\u4E0E\u6D3B\u52A8\u4E8B\u52A1\uFF0C\u4E0D\u63A5\u53D7\u4EFB\u610F\u8DEF\u5F84\u3002"]
2348
+ ]) ctx.tools.register(defineTool({ name: name2, description, parameters: parameters(schema), output: { schema: { type: "json" }, render: (_args, value) => [{ type: "text", text: JSON.stringify(value) }] }, async execute(args, exec) {
2349
+ try {
2350
+ const { scope } = await binding(exec);
2351
+ const parsed = args;
2352
+ const id = name2 === "atlas_create" ? "map-" + (await hash({ operationId: parsed.operationId })).slice(0, 32) : parsed.mapId ?? "";
2353
+ return await serializeMap(`${scope.workspaceRoot}\0${id}`, () => invoke(name2, args, exec));
2354
+ } catch (e) {
2355
+ return { status: errorCode(e), message: String(e), diagnostics: e instanceof AtlasError ? e.diagnostics : [] };
2356
+ }
2357
+ } }));
2358
+ }
2359
+
2360
+ // src/server/prompts/authoring.ts
2361
+ var mindmapDescription = "\u5728\u5DE5\u4F5C\u533A\u521B\u5EFA\u3001\u8BFB\u53D6\u4E0E\u7EF4\u62A4\u601D\u7EF4\u5BFC\u56FE\uFF0C\u6309\u89C6\u56FE\u7EC4\u7EC7\u8282\u70B9\u548C\u8BE6\u60C5\uFF0C\u6309\u6587\u672C\u3001\u56FE\u8868\u6216\u6B63\u6587\u4F4D\u7F6E\u5F15\u7528\u67E5\u627E\u548C\u4FEE\u6539\u5185\u5BB9\u3002";
2362
+ var mindmapAuthoring = `\u901A\u8FC7\u5F53\u524D\u5DE5\u4F5C\u533A\u7684\u601D\u7EF4\u5BFC\u56FE\u63D2\u4EF6\u521B\u5EFA\u3001\u8BFB\u53D6\u548C\u7EF4\u62A4\u5730\u56FE\u3002\u7528\u6237\u7528 /mindmap \u968F\u9700\u6C42\u624B\u52A8\u53D1\u9001\u540E\uFF0C\u6309\u672C\u6B21\u4EFB\u52A1\u6267\u884C\uFF1B\u53EA\u6709\u6280\u80FD\u540D\u800C\u6CA1\u6709\u4EFB\u52A1\u65F6\uFF0C\u7B80\u77ED\u8BF4\u660E\u53EF\u65B0\u5EFA\u3001\u8865\u5145\u6216\u4FEE\u6539\u5BFC\u56FE\uFF0C\u7B49\u5F85\u5177\u4F53\u9700\u6C42\uFF0C\u4E0D\u521B\u5EFA\u7A7A\u56FE\u3002
2363
+
2364
+ ## \u786E\u5B9A\u4EFB\u52A1\u548C\u76EE\u6807
2365
+ - \u590D\u7528\u7528\u6237\u5DF2\u7ED9\u51FA\u7684\u6750\u6599\u3001\u7528\u9014\u3001\u5730\u56FE\u5F15\u7528\u548C\u5BF9\u8C61ID\u3002\u8981\u6C42\u6E05\u695A\u5C31\u6267\u884C\uFF1B\u4EC5\u5728\u76EE\u6807\u6216\u5220\u9664\u8303\u56F4\u5B58\u5728\u5B9E\u8D28\u6B67\u4E49\u65F6\u8BE2\u95EE\uFF0C\u4E0D\u8981\u6C42\u7528\u6237\u586B\u5199\u4E00\u5957\u56FA\u5B9A\u95EE\u5377\u3002\u8BA8\u8BBA\u7EC4\u7EC7\u65B9\u6848\u6216\u89E3\u91CA\u5185\u5BB9\u65F6\u5148\u56DE\u7B54\uFF0C\u4E0D\u80FD\u636E\u6B64\u64C5\u81EA\u4FDD\u5B58\u4FEE\u6539\u3002
2366
+ - \u65B0\u5EFA\uFF1A\u4F9D\u636E\u672C\u6B21\u6750\u6599\u7EC4\u7EC7 content \u548C notes\uFF0C\u76F4\u63A5 atlas_create\uFF1B\u65E0\u9700\u5148\u5217\u56FE\u68C0\u67E5\u540C\u540D\uFF0C\u65B0\u56FE\u540C\u540D\u4E5F\u6709\u72EC\u7ACB\u8EAB\u4EFD\u3002\u4EC5\u5F53\u7528\u6237\u8981\u6C42\u67E5\u627E\u3001\u67E5\u91CD\u6216\u590D\u7528\u5DF2\u6709\u56FE\u65F6\uFF0C\u624D\u4E3A\u8BE5\u4EFB\u52A1\u67E5\u8BE2\u5DF2\u6709\u5730\u56FE\u3002
2367
+ - \u9605\u8BFB\u6216\u4FEE\u6539\u5DF2\u6709\u56FE\uFF1A\u5148\u786E\u5B9A\u76EE\u6807 mapId\uFF1B\u4EC5\u5728\u76EE\u6807\u8EAB\u4EFD\u672A\u77E5\u65F6\u7528 atlas_list \u6309\u6807\u9898\u5B9A\u4F4D\uFF0C\u540C\u540D\u65E0\u6CD5\u533A\u5206\u65F6\u8BA9\u7528\u6237\u9009\u62E9\u3002\u5DF2\u6709\u660E\u786E mapId \u5C31\u76F4\u63A5 atlas_read\u3002\u4E0D\u80FD\u5047\u8BBE\u6A21\u578B\u77E5\u9053\u4FA7\u680F\u5F53\u524D\u6253\u5F00\u6216\u9009\u4E2D\u7684\u5BF9\u8C61\u3002
2368
+ - atlas_read \u7528\u4E8E\u83B7\u53D6\u672C\u6B21\u4EFB\u52A1\u786E\u5B9E\u9700\u8981\u7684\u5DF2\u6709\u5185\u5BB9\u3002\u6BCF\u6B21\u8FD4\u56DE\u5B8C\u6574\u7ED3\u6784\uFF0Cnotes \u624D\u53D7 nodeIds/viewIds/query \u7B5B\u9009\u5E76\u5206\u9875\uFF1B\u6309\u4EFB\u52A1\u8BFB\u53D6\u76F8\u5173\u6B63\u6587\uFF0C\u4FDD\u6301\u7B5B\u9009\u53C2\u6570\u4E0D\u53D8\u6CBF nextCursor \u8BFB\u5B8C\u6240\u9700\u7B14\u8BB0\uFF0C\u4FEE\u6539\u65F6\u4FDD\u7559\u8FD4\u56DE\u7684 fingerprint\u3002\u4E0D\u5F97\u628A\u9996\u6279 notes \u5F53\u6210\u5168\u56FE\u6B63\u6587\uFF0C\u4E5F\u4E0D\u4E3A\u6539\u4E00\u4E2A\u6807\u9898\u8BFB\u53D6\u5168\u90E8\u65E0\u5173\u7B14\u8BB0\u3002
2369
+ - \u521B\u5EFA\u683C\u5F0F\u4F9D\u636E\u672Cskill\u7684\u5951\u7EA6\u3001\u793A\u4F8B\u53CA\u5DE5\u5177\u53C2\u6570\uFF0C\u4E0D\u4F9D\u8D56\u7528\u6237\u5386\u53F2\u5730\u56FE\u3002\u4E0D\u8981\u4E3A\u4E86\u5B66\u4E60\u683C\u5F0F\u800C\u641C\u7D22\u63D2\u4EF6\u6E90\u7801\u3001\u8BFB\u53D6\u65E0\u5173\u5730\u56FE\u6216\u5148\u521B\u5EFA\u8BD5\u9A8C\u56FE\uFF1B\u53EA\u6709\u672C\u6B21\u5185\u5BB9\u4EFB\u52A1\u9700\u8981\u6216\u7528\u6237\u6307\u5B9A\u53C2\u8003\u65F6\u624D\u8BFB\u5BF9\u5E94\u5730\u56FE\u3002\u5386\u53F2\u5B9E\u4F8B\u4E2D\u7684\u4E00\u79CD\u5408\u6CD5\u5199\u6CD5\u4E0D\u6784\u6210\u5FC5\u586B\u89C4\u5219\uFF1B\u6821\u9A8C\u5931\u8D25\u65F6\u6309\u5DE5\u5177\u8BCA\u65AD\u4FEE\u6B63\u5B9E\u9645\u4EFB\u52A1\u7684\u5019\u9009\u3002
2370
+
2371
+ ## \u7EC4\u7EC7\u53EF\u8BFB\u5185\u5BB9
2372
+ - \u8282\u70B9\u8868\u793A\u53EF\u72EC\u7ACB\u547D\u540D\u3001\u5F15\u7528\u548C\u5C55\u5F00\u7684\u6982\u5FF5\u3001\u7EC4\u4EF6\u3001\u6B65\u9AA4\u6216\u51B3\u7B56\u3002\u6807\u9898\u7B80\u77ED\u660E\u786E\uFF1Bsummary \u53EA\u6982\u62EC\u672C\u8282\u70B9\uFF0C\u4E0D\u585E\u957F\u6B63\u6587\u3002\u89E3\u91CA\u3001\u63A5\u53E3\u3001\u7EA6\u675F\u3001\u516C\u5F0F\u3001\u793A\u4F8B\u653E\u5165\u6309 nodeId \u63D0\u4F9B\u7684 Markdown\uFF0C\u5185\u5BB9\u8DB3\u591F\u624D\u521B\u5EFA\u7B14\u8BB0\uFF0C\u4E0D\u586B\u5360\u4F4D\u7AE0\u8282\u3002
2373
+ - \u5148\u786E\u5B9A\u603B\u89C8\u8981\u56DE\u7B54\u7684\u95EE\u9898\uFF0C\u53EA\u653E\u4E3B\u8981\u4E3B\u9898\u3001\u5173\u952E\u6B65\u9AA4\u548C\u5FC5\u8981\u5173\u7CFB\u3002\u53EF\u72EC\u7ACB\u5C55\u5F00\u7684\u7ED3\u6784\u653E\u8FDB\u6240\u5C5E\u8282\u70B9\u7684\u5B50\u56FE\uFF1B\u5C5E\u4E8E\u540C\u4E00\u5BF9\u8C61\u7684\u5B9A\u4E49\u3001\u89E3\u91CA\u3001\u53C2\u6570\u3001\u516C\u5F0F\u548C\u793A\u4F8B\u5199\u8FDB\u8BE6\u60C5\u3002\u6BD4\u5982 30 \u6B65\u6D41\u7A0B\u53EF\u5728\u603B\u89C8\u5C55\u793A\u51E0\u4E2A\u6709\u610F\u4E49\u7684\u9636\u6BB5\uFF0C\u518D\u5728\u5404\u9636\u6BB5\u7684\u5B50\u56FE\u6216\u8BE6\u60C5\u5B8C\u6574\u4FDD\u7559\u5177\u4F53\u6B65\u9AA4\u3002
2374
+ - \u9ED8\u8BA4\u6BCF\u4E2A\u89C6\u56FE\u6700\u591A 20 \u4E2A\u663E\u793A\u8282\u70B9\uFF0C\u80FD\u8BB2\u6E05\u695A\u5C31\u5C11\u653E\u3002\u6309\u6BCF\u4E2A\u89C6\u56FE\u7684 occurrences \u8BA1\u6570\uFF0C\u540C\u9875\u591A\u4E2A groups \u5408\u8BA1\u3002\u751F\u6210\u6216\u6269\u5C55\u524D\u9884\u4F30\uFF0C\u63D0\u4EA4\u524D\u590D\u6838\u3002\u9884\u8BA1\u8D85\u51FA\u65F6\u6309\u5B9E\u9645\u4E3B\u9898\u6216\u9636\u6BB5\u62C6\u5206\uFF0C\u5E76\u786E\u8BA4\u6750\u6599\u4ECD\u80FD\u5728\u5B50\u56FE\u6216\u8BE6\u60C5\u627E\u5230\u3002\u7528\u6237\u660E\u786E\u8981\u6C42\u540C\u9875\u5C55\u793A\u65F6\u6309\u8981\u6C42\u7EC4\u7EC7\u3002
2375
+ - \u5206\u7EC4\u7528\u4E8E\u540C\u5C42\u5206\u533A\uFF0C\u5B50\u56FE\u7528\u4E8E\u5C55\u5F00\u67D0\u4E2A\u8282\u70B9\u7684\u5185\u90E8\u7ED3\u6784\u3002\u6839\u636E\u5185\u5BB9\u51B3\u5B9A\u662F\u5426\u7EE7\u7EED\u4E0B\u94BB\uFF0C\u4F18\u5148\u590D\u7528\u5DF2\u6709\u5B50\u56FE\u3002
2376
+ - \u67B6\u6784\u56FE\u56F4\u7ED5\u804C\u8D23\u3001\u6A21\u5757\u8FB9\u754C\u548C\u771F\u5B9E\u4F9D\u8D56\uFF1B\u6D41\u7A0B\u56FE\u56F4\u7ED5\u6B65\u9AA4\u3001\u5206\u652F\u6761\u4EF6\u548C\u6D41\u5411\uFF1B\u77E5\u8BC6\u56FE\u56F4\u7ED5\u6982\u5FF5\u3001\u524D\u63D0\u548C\u8054\u7CFB\u3002\u6309\u4E3B\u9898\u9009\u62E9\u7EC4\u7EC7\u65B9\u5F0F\uFF0C\u4E0D\u628A\u6240\u6709\u5185\u5BB9\u5F3A\u5236\u6539\u6210\u8BFE\u7A0B\u7AE0\u8282\u3002
2377
+ - \u540C\u4E00\u5BF9\u8C61\u8DE8\u89C6\u56FE\u51FA\u73B0\u65F6\u590D\u7528\u8282\u70B9ID\u3001\u6B63\u6587\u548C childViewId\uFF0C\u4F7F\u7528 occurrences \u8868\u8FBE\u51FA\u73B0\u4F4D\u7F6E\u3002\u5DF2\u6709\u5B50\u56FE\u4F18\u5148\u6269\u5C55\uFF1B\u5171\u4EAB\u5B50\u56FE\u7684 parentViewId \u662F\u56FA\u5B9A\u5BFC\u822A\u5F52\u5C5E\uFF0C\u4E0D\u56E0\u5176\u4ED6\u5165\u53E3\u51FA\u73B0\u5C31\u6539\u5199\u3002
2378
+ - \u5173\u7CFB\u5FC5\u987B\u6709\u5185\u5BB9\u4F9D\u636E\uFF0C\u65B9\u5411\u4ECE fromNodeId \u6307\u5411 toNodeId\u3002dependency \u8868\u8FBE\u524D\u7F6E\u3001\u4F9D\u8D56\u6216\u4E3B\u6D41\u7A0B\uFF0C\u524D\u7F6E\u6307\u5411\u540E\u7EED\uFF1Bsupplement \u8868\u8FBE\u8865\u5145\u6216\u5BF9\u6BD4\u3002\u540C\u7EC4\u3001\u540C\u7EA7\u6216\u4F4D\u7F6E\u76F8\u90BB\u4E0D\u6784\u6210\u5173\u7CFB\u4F9D\u636E\u3002\u9010\u6761\u68C0\u67E5\u65B9\u5411\u4E0E\u89C6\u56FE\u7AEF\u70B9\uFF0C\u5B64\u7ACB\u8282\u70B9\u6838\u5BF9\u662F\u5426\u6F0F\u5173\u7CFB\uFF0C\u6709\u72EC\u7ACB\u542B\u4E49\u65F6\u5141\u8BB8\u4FDD\u7559\uFF0C\u4E0D\u51D1\u8FDE\u7EBF\u3002label \u901A\u5E38\u7701\u7565\uFF0C\u4EC5\u5728\u6807\u9898\u4E0D\u80FD\u8BF4\u660E\u5173\u7CFB\u3001\u5206\u652F\u6761\u4EF6\u7B49\u5FC5\u8981\u573A\u5408\u586B\u5199\u3002
2379
+ - category \u548C icon \u4F7F\u7528\u73B0\u6709\u679A\u4E3E\uFF0C\u540C\u7C7B\u5185\u5BB9\u5728\u56FE\u5185\u4FDD\u6301\u4E00\u81F4\u3002\u6B63\u6587\u6309\u4E3B\u9898\u91C7\u7528\u804C\u8D23\u3001\u63A5\u53E3\u3001\u89C4\u5219\u3001\u793A\u4F8B\u3001\u6CE8\u610F\u4E8B\u9879\u7B49\u5FC5\u8981\u7AE0\u8282\uFF0C\u4FDD\u7559\u5DF2\u6709\u4F5C\u8005\u987A\u5E8F\uFF1B\u516C\u5F0F\u8BF4\u660E\u7B26\u53F7\u3001\u6761\u4EF6\u53CA\u5FC5\u8981\u5355\u4F4D\u3002LaTeX \u884C\u5185\u7528 $\u2026$\uFF0C\u957F\u516C\u5F0F\u7528\u72EC\u7ACB\u6210\u884C\u7684 $$\u2026$$\uFF0C\u516C\u5F0F\u653E\u5728 Markdown \u6B63\u6587\u3002\u6750\u6599\u4E2D\u7684\u4E0D\u786E\u5B9A\u5185\u5BB9\u6807\u660E\u5F85\u6838\u5B9E\uFF0C\u4E0D\u7F16\u9020\u6765\u6E90\u3001\u4E8B\u5B9E\u6216\u8D44\u6E90\u8DEF\u5F84\u3002
2380
+
2381
+ ## \u8282\u70B9\u8BE6\u60C5\u7684\u7F16\u8F91\u4E0E\u5F15\u7528
2382
+ - \u9700\u8981\u6307\u5BFC\u7528\u6237\u64CD\u4F5C\u65F6\uFF0C\u4ECE\u8BE6\u60C5\u5E95\u90E8\u300C\u590D\u5236\u5185\u5BB9\u300D\u65C1\u7684\u300C\u7F16\u8F91\u300D\u5F00\u59CB\u3002\u6807\u9898\u3001\u7C97\u659C\u4F53\u3001\u5217\u8868\u548C\u516C\u5F0F\u53EF\u5728\u6B63\u6587\u539F\u4F4D\u6539\uFF0C\u5149\u6807\u8FDB\u5165\u65F6\u53EF\u7F16\u8F91 Markdown \u6807\u8BB0\uFF0C\u79BB\u5F00\u540E\u6062\u590D\u6392\u7248\u3002\u5B8C\u6210\u8F93\u5165\u540E\u81EA\u52A8\u4FDD\u5B58\uFF0C\u6B63\u6587\u5185\u53EF\u7528 Ctrl+Z / Ctrl+Y \u64A4\u9500\u6216\u91CD\u505A\u3002
2383
+ - \u7528\u6237\u53EF\u5728\u7F16\u8F91\u6001\u76F4\u63A5\u62D6\u52A8\u56FE\u7247\u3001\u7528\u628A\u624B\u62D6\u52A8\u56FE\u8868\u5230\u6B63\u6587\u5757\u4E4B\u95F4\uFF0C\u4E5F\u53EF\u5220\u9664\u5BF9\u5E94\u5F15\u7528\u6216\u6574\u5F20\u56FE\u3002\u56FE\u8868\u6570\u636E\u7531\u7528\u6237\u63CF\u8FF0\u9700\u6C42\u540E\u901A\u8FC7\u4E0B\u6587\u7684 atlas \u6D41\u7A0B\u66F4\u65B0\u3002\u5DF2\u6709\u56FE\u7247\u8DEF\u5F84\u6309\u539F\u5F15\u7528\u4FDD\u7559\uFF0C\u4E0A\u4F20\u56FE\u7247\u548C\u5BFC\u51FA\u53EA\u8BFB HTML \u901A\u8FC7\u4FA7\u680F\u754C\u9762\u5B8C\u6210\u3002
2384
+ - \u9700\u8981\u8BF7 DSH \u6DFB\u52A0\u5185\u5BB9\u65F6\uFF0C\u5F15\u5BFC\u7528\u6237\u5728\u7F16\u8F91\u6001\u6B63\u6587\u53F3\u952E\u9009\u62E9\u300C\u6DFB\u52A0\u56FE\u8868/\u516C\u5F0F\u300D\uFF0C\u6216\u5728\u5757\u95F4\u7A7A\u767D\u9009\u300C\u6DFB\u52A0\u6B64\u4F4D\u7F6E\u5230\u6B63\u6587\u300D\uFF0C\u7136\u540E\u5199\u660E\u9700\u6C42\u5E76\u624B\u52A8\u53D1\u9001\u3002\u4FEE\u6539\u5DF2\u6709\u56FE\u8868\u53EF\u5148\u7528\u56FE\u8868\u53F3\u952E\u52A0\u5165\u5F15\u7528\u3002\u8BFB\u5230\u7528\u6237\u53D1\u6765\u7684\u9009\u6587\u3001\u56FE\u8868\u6216\u4F4D\u7F6E\u5F15\u7528\u65F6\uFF0C\u4EE5\u5176\u4E2D\u7684\u6765\u6E90\u6807\u8BC6\u5B9A\u4F4D\u3002
2385
+
2386
+ ## \u8282\u70B9\u7B14\u8BB0\u56FE\u5757
2387
+ - \u7528\u6237\u8981\u6C42\u7ED8\u56FE\u65F6\uFF0C\u5728\u76EE\u6807\u8282\u70B9\u6B63\u6587\u63D2\u5165\u9876\u5C42 dsh-plot \u56F4\u680F\uFF0C\u9996\u884C\u7528\u4E09\u4E2A\u53CD\u5F15\u53F7\u63A5 dsh-plot\uFF0C\u672B\u884C\u7528\u4E09\u4E2A\u53CD\u5F15\u53F7\uFF0C\u4E2D\u95F4\u53EA\u653E JSON\uFF0C\u56F4\u680F\u524D\u540E\u7559\u7A7A\u884C\u3002\u53EA\u7ED9\u6570\u636E\uFF0C\u7531\u63D2\u4EF6\u7ED8\u5236\u3002
2388
+ - \u51FD\u6570\u56FE\u793A\u4F8B\uFF1A{"version":1,"id":"quadratic","kind":"function","title":"\u4E8C\u6B21\u51FD\u6570","series":[{"expression":"x^2"}]}\u3002\u540C\u8F74\u53EF\u653E 1\u20133 \u6761\u5F0F\u5B50\uFF0C\u6BCF\u5F0F\u81F3\u591A 256 \u5B57\u7B26\uFF0Clabel \u53EF\u9009\u3002\u4F7F\u7528 x\u3001pi/e\u3001\u56DB\u5219\u3001\u663E\u5F0F\u4E58\u53F7\u3001\u62EC\u53F7\u3001\u5E42\u548C sin\u3001cos\u3001tan\u3001sqrt\u3001abs\u3001exp\u3001ln\uFF1B\u4E09\u89D2\u51FD\u6570\u7528\u5F27\u5EA6\u3002xRange/yRange \u5404\u9ED8\u8BA4 [-5,5]\uFF0C\u53EF\u5206\u522B\u7ED9\u4E24\u4E2A\u4E25\u683C\u9012\u589E\u6709\u9650\u6570\u3002
2389
+ - \u67F1\u72B6\u56FE\u793A\u4F8B\uFF1A{"version":1,"id":"counts","kind":"bar","categories":["\u7532","\u4E59"],"series":[{"label":"\u8BA1\u6570","unit":"\u6B21","values":[0,3]}]}\u3002kind \u4E5F\u53EF\u7528 line\uFF0C\u6298\u7EBF\u53EF\u7701\u7565 categories\uFF0C\u6309 1 \u8D77\u7684\u5E8F\u53F7\u7ED8\u5236\u3002\u6BCF\u56FE 1\u20133 \u7CFB\u5217\uFF0C\u6BCF\u7CFB\u5217 1\u2013100 \u4E2A\u7B49\u957F\u503C\uFF0C\u7EDF\u4E00\u6309\u7C7B\u76EE\u987A\u5E8F\uFF1Bnull \u8868\u793A\u7F3A\u503C\uFF0C0 \u662F\u5DF2\u77E5\u6570\u503C\u3002\u4FDD\u7559\u539F\u5355\u4F4D\u548C\u771F\u5B9E\u6570\u636E\uFF1B\u7F3A\u5C11\u6240\u9700\u6570\u636E\u65F6\u8BF4\u660E\u6216\u6309\u7528\u6237\u6388\u6743\u53D6\u5F97\uFF0C\u4E0D\u63A8\u6D4B\u6210\u4E8B\u5B9E\u3002
2390
+ - \u56FE\u5757 ID \u5728\u8282\u70B9\u7B14\u8BB0\u5185\u552F\u4E00\uFF0C\u4FEE\u6539\u4FDD\u7559 ID\u3002\u540C\u540D\u56FE\u6309\u5730\u56FE\u3001\u8282\u70B9\u548C\u56FE\u5757 ID \u5B9A\u4F4D\u3002
2391
+
2392
+ ## \u65B0\u5EFA\u5951\u7EA6\u4E0E\u5B8C\u6574\u793A\u4F8B
2393
+ - atlas_create \u53C2\u6570\u4E3A operationId\u3001content\u3001notes\u3002content \u53EA\u542B title/rootViewId/nodes/views/relations\uFF1B\u4E0D\u4F20\u5730\u56FE id/schemaVersion\u3001notePath\u3001\u5E03\u5C40\u6216\u754C\u9762\u4EE3\u7801\uFF0C\u5730\u56FE\u8EAB\u4EFD\u548C\u7B14\u8BB0\u8DEF\u5F84\u7531\u63D2\u4EF6\u5206\u914D\u3002notes \u662F\u8282\u70B9ID\u5230Markdown\u5B57\u7B26\u4E32\u7684\u5BF9\u8C61\uFF1B\u65E0\u6B63\u6587\u7684\u8282\u70B9\u7701\u7565\u5BF9\u5E94\u952E\uFF0C\u5168\u90E8\u65E0\u6B63\u6587\u65F6\u4F20 {}\u3002\u6B63\u6587\u4E0D\u5199\u8FDB nodes\uFF0Cnotes \u4E2D\u7684\u6BCF\u4E2A\u952E\u5FC5\u987B\u5BF9\u5E94\u672C\u6B21 content.nodes \u7684\u8282\u70B9ID\u3002
2394
+ - nodes \u5B9A\u4E49\u5BF9\u8C61\uFF0Cviews[].occurrences \u51B3\u5B9A\u54EA\u4E9B\u8282\u70B9\u663E\u793A\u5728\u8BE5\u89C6\u56FE\uFF1B\u5B9A\u4E49\u8282\u70B9\u672C\u8EAB\u4E0D\u4F1A\u81EA\u52A8\u8BA9\u5B83\u663E\u793A\u3002groups \u5B9A\u4E49\u89C6\u56FE\u5185\u5206\u533A\uFF0CgroupId \u53EA\u80FD\u5F15\u7528\u540C\u4E00\u89C6\u56FE\u7684\u5206\u7EC4\uFF1Bgroups \u53EF\u4EE5\u4E3A\u7A7A\uFF0C\u672A\u5206\u7EC4\u7684\u51FA\u73B0\u4F4D\u7F6E\u7701\u7565 groupId\u3002\u5FC5\u586B\u6570\u7EC4\u5373\u4F7F\u4E3A\u7A7A\u4E5F\u8981\u63D0\u4F9B\u3002
2395
+ - relations \u5B9A\u4E49\u5168\u56FE\u5173\u7CFB\uFF0Cviews[].relationIds \u51B3\u5B9A\u8BE5\u89C6\u56FE\u663E\u793A\u7684\u5173\u7CFB\uFF1B\u53EA\u5B9A\u4E49\u5168\u56FE\u5173\u7CFB\u4E0D\u4F1A\u81EA\u52A8\u5C55\u793A\u3002\u5C55\u793A\u5173\u7CFB\u7684\u4E24\u4E2A\u7AEF\u70B9\u90FD\u5FC5\u987B\u5728\u8BE5\u89C6\u56FE\u7684 occurrences \u4E2D\uFF0CcenterNodeId \u4E0D\u66FF\u4EE3\u51FA\u73B0\u4F4D\u7F6E\u3002
2396
+ - centerNodeId \u8868\u793A\u5B50\u56FE\u6240\u5C5E\u8282\u70B9\uFF0C\u4E0D\u662F\u6BCF\u5F20\u56FE\u90FD\u9700\u8981\u7684\u201C\u753B\u5E03\u4E2D\u5FC3\u201D\u3002\u666E\u901A\u6839\u89C6\u56FE\u7701\u7565\u5B83\uFF1B\u6709\u5B50\u56FE\u65F6\uFF0C\u6240\u5C5E\u8282\u70B9\u7684 childViewId \u4E0E\u5B50\u56FE\u7684 centerNodeId \u53CC\u5411\u5BF9\u5E94\uFF0C\u5B50\u56FE parentViewId \u6307\u5411\u5176\u5BFC\u822A\u7236\u89C6\u56FE\u3002\u6240\u5C5E\u8282\u70B9\u53EF\u4EE5\u4E0D\u51FA\u73B0\u5728\u81EA\u5DF1\u7684\u5B50\u56FE\u753B\u5E03\uFF1B\u53EA\u6709\u9700\u8981\u5C55\u793A\u5B83\u6216\u8BA9\u5B83\u53C2\u4E0E\u672C\u89C6\u56FE\u8FDE\u7EBF\u65F6\u624D\u628A\u5B83\u52A0\u5165 occurrences\u3002\u4E0D\u56E0\u8BBE\u7F6E centerNodeId \u5C31\u590D\u5236\u8282\u70B9\u6216\u5F3A\u5236\u52A0\u5165\u5206\u7EC4\u3002
2397
+
2398
+ \u4E0B\u9762\u662F\u4E24\u8282\u70B9\u3001\u4E00\u5206\u7EC4\u3001\u4E00\u5173\u7CFB\u3001\u4E00\u6839\u89C6\u56FE\u53CA\u8282\u70B9\u6B63\u6587\u7684\u5B8C\u6574\u521B\u5EFA\u53C2\u6570\u793A\u4F8B\uFF0C\u4EC5\u8BF4\u660E\u5B57\u6BB5\u7EC4\u5408\u3002\u5B9E\u9645\u4EFB\u52A1\u6309\u6750\u6599\u7EC4\u7EC7\u5185\u5BB9\u5E76\u5206\u914D\u672C\u6B21 operationId\uFF0C\u4E0D\u7167\u642C\u4E3B\u9898\u3001\u8282\u70B9\u6570\u91CF\u6216\u5148\u4FDD\u5B58\u6B64\u793A\u4F8B\u3002
2399
+ {
2400
+ "operationId": "example-request-flow-001",
2401
+ "content": {
2402
+ "title": "\u8BF7\u6C42\u5904\u7406\u6D41\u7A0B",
2403
+ "rootViewId": "overview",
2404
+ "nodes": [
2405
+ {"id": "receive", "title": "\u63A5\u6536\u8BF7\u6C42", "summary": "\u8BFB\u53D6\u5E76\u6821\u9A8C\u8BF7\u6C42\u53C2\u6570", "category": "blue", "icon": "arrows"},
2406
+ {"id": "process", "title": "\u5904\u7406\u8BF7\u6C42", "summary": "\u4F9D\u636E\u6709\u6548\u53C2\u6570\u6267\u884C\u5904\u7406", "category": "blue", "icon": "check"}
2407
+ ],
2408
+ "views": [{
2409
+ "id": "overview", "title": "\u6D41\u7A0B\u603B\u89C8", "parentViewId": null,
2410
+ "groups": [{"id": "main", "title": "\u5904\u7406\u6D41\u7A0B", "number": "1", "category": "blue"}],
2411
+ "occurrences": [{"nodeId": "receive", "groupId": "main"}, {"nodeId": "process", "groupId": "main"}],
2412
+ "relationIds": ["receive-process"]
2413
+ }],
2414
+ "relations": [{"id": "receive-process", "fromNodeId": "receive", "toNodeId": "process", "type": "dependency"}]
2415
+ },
2416
+ "notes": {"receive": "## \u804C\u8D23\\n\u8BFB\u53D6\u5E76\u6821\u9A8C\u8BF7\u6C42\u53C2\u6570\uFF0C\u6821\u9A8C\u901A\u8FC7\u540E\u4EA4\u7ED9\u5904\u7406\u6B65\u9AA4\u3002"}
2417
+ }
2418
+ \u793A\u4F8B\u4E2D\u6839\u89C6\u56FE\u6CA1\u6709 centerNodeId\uFF1B\u6B63\u6587\u53EA\u5C5E\u4E8E receive\uFF0Cprocess \u6CA1\u6709\u7B14\u8BB0\uFF1Breceive-process \u540C\u65F6\u6709\u5168\u56FE\u5B9A\u4E49\u548C\u89C6\u56FE\u5C55\u793A\u5F15\u7528\u3002\u5B9E\u9645\u5185\u5BB9\u9700\u8981\u5B50\u56FE\u65F6\uFF0C\u5728\u540C\u4E00\u6B21\u521B\u5EFA\u4E2D\u8865\u9F50\u6240\u5C5E\u8282\u70B9 childViewId \u4E0E\u5B50\u56FE centerNodeId/parentViewId\uFF0C\u65E0\u9700\u53E6\u627E\u5386\u53F2\u5730\u56FE\u4F5C\u683C\u5F0F\u6837\u4F8B\u3002
2419
+
2420
+ \u5927\u6750\u6599\u6309\u7528\u6237\u8303\u56F4\u5B8C\u6210\uFF1B\u9700\u8981\u5206\u6279\u65F6\uFF0C\u6BCF\u6B21\u4FDD\u5B58\u8BED\u4E49\u5B8C\u6574\u7684\u7ED3\u6784\u5E76\u8BF4\u660E\u5C1A\u672A\u5B8C\u6210\u7684\u8303\u56F4\uFF0C\u4E0D\u628A\u6982\u89C8\u58F0\u79F0\u4E3A\u5168\u91CF\u5B8C\u6210\u3002
2421
+
2422
+ ## \u5C40\u90E8\u4FEE\u6539
2423
+ - \u6309\u5DF2\u6709\u56FE\u8868\u5F15\u7528\u4FEE\u6539\u65F6\uFF0C\u5148\u7528 atlas_read \u91CD\u8BFB\u76EE\u6807\u8282\u70B9\uFF0C\u6309\u56FE\u5757 ID \u548C\u5F15\u7528\u5FEB\u7167\u6838\u5BF9\u3002\u53EA\u6709\u5468\u56F4\u6587\u5B57\u53D8\u52A8\u65F6\uFF0C\u7528\u6700\u65B0 fingerprint \u7EE7\u7EED\uFF1B\u76EE\u6807\u56FE\u5757\u5DF2\u53D8\u5316\u3001\u627E\u4E0D\u5230\u6216\u65E0\u6CD5\u6838\u5BF9\u65F6\uFF0C\u8BF4\u660E\u60C5\u51B5\u5E76\u8BF7\u7528\u6237\u91CD\u65B0\u5F15\u7528\u3002
2424
+ - \u4FEE\u6539\u7528 atlas_apply \u7684\u6709\u5E8F changes\uFF0C\u4EC5\u6539\u53D8\u8981\u6C42\u6D89\u53CA\u7684\u5BF9\u8C61\u4E0E\u5B57\u6BB5\uFF0C\u4FDD\u7559\u65E0\u5173\u5185\u5BB9\u3001\u7A33\u5B9AID\u548C\u624B\u52A8\u4F4D\u7F6E\u3002\u4FEE\u6539\u6B63\u6587\u7528 set_note\uFF1B\u5B83\u66FF\u6362\u8BE5\u8282\u70B9\u6574\u7BC7\u6B63\u6587\uFF0C\u56E0\u6B64\u5148\u8BFB\u5B8C\u76EE\u6807\u7B14\u8BB0\u5E76\u4FDD\u7559\u672A\u8981\u6C42\u6539\u52A8\u7684\u6BB5\u843D\uFF0C\u4E0D\u628A\u5C40\u90E8\u8865\u5145\u5F53\u6210\u6574\u7BC7\u66FF\u6362\u5185\u5BB9\u3002
2425
+ - \u5E38\u89C4\u56FE\u5757\u589E\u5220\u6539\u7528 set_note\u3002\u5220\u9664\u56FE\u5757\u5148\u7528 atlas_preview \u6838\u5BF9\u56FE\u5757\u5220\u9664\u5F71\u54CD\uFF0C\u518D\u63D0\u4EA4\u540C\u4E00\u7248\u672C\u3001\u540C\u4E00\u5019\u9009\u548C previewToken\uFF0C\u7531\u5BBF\u4E3B\u5904\u7406\u6388\u6743\u3002\u7248\u672C\u51B2\u7A81\u540E\u91CD\u8BFB\u65F6\u91CD\u65B0\u6838\u5BF9\u76EE\u6807\u56FE\u5757\uFF0C\u4E0D\u6309\u540C\u540D\u6216\u4F4D\u7F6E\u731C\u6D4B\u3002
2426
+ - \u65B0\u589E\u8282\u70B9\u8981 add_node \u5E76 put_occurrence \u5230\u76EE\u6807\u89C6\u56FE\uFF0C\u6309\u9700 set_note \u548C\u6307\u5B9A groupId\uFF1B\u65B0\u589E\u5173\u7CFB\u8981 add_relation\uFF0C\u5E76\u628A\u5173\u7CFBID\u52A0\u5165\u76EE\u6807\u89C6\u56FE\u7684\u5B8C\u6574 relationIds \u96C6\u5408\u3002set_view_relations \u66FF\u6362\u5C55\u793A\u96C6\u5408\uFF0C\u987B\u4FDD\u7559\u4ECD\u9700\u663E\u793A\u7684\u5DF2\u6709\u5173\u7CFB\uFF1B\u4E24\u4E2A\u7AEF\u70B9\u5747\u987B\u5728\u8BE5\u89C6\u56FE\u7684 occurrences \u4E2D\u3002
2427
+ - \u7528\u6237\u5E26\u300C\u6B63\u6587\u4F4D\u7F6E\u300D\u5F15\u7528\u660E\u786E\u8981\u6C42\u6DFB\u52A0\u56FE\u8868\u6216\u516C\u5F0F\u65F6\uFF0C\u7528 atlas_read \u6309\u5F15\u7528\u7684 mapId\u3001nodeId \u91CD\u8BFB\uFF0C\u53D6\u5F97\u6700\u65B0 fingerprint\u3002\u5C06\u5F15\u7528\u91CC\u7684 anchor \u5BF9\u8C61\u539F\u6837\u4F20\u7ED9 atlas_apply \u7684\u552F\u4E00\u53D8\u66F4\u9879 {op:"insert_note_content",nodeId,anchor,kind,markdown}\u3002kind \u4E3A inline_formula\u3001display_formula \u6216 plot\uFF0Cmarkdown \u53EA\u542B\u4E00\u9879\u5B8C\u6574\u5185\u5BB9\u3002\u884C\u5185\u516C\u5F0F\u4F18\u5148\u7528 \\(\u2026\\)\uFF0C\u72EC\u7ACB\u516C\u5F0F\u7528\u72EC\u7ACB\u5757\uFF0C\u56FE\u8868\u7528\u5E26\u65B0\u4E14\u552F\u4E00 ID \u7684 dsh-plot \u56F4\u680F\u3002\u6BB5\u843D\u6587\u5B57\u5B9A\u4F4D\u65F6\uFF0C\u63D2\u4EF6\u5C06\u884C\u5185\u516C\u5F0F\u63D2\u5230\u70B9\u51FB\u5904\uFF0C\u5C06\u72EC\u7ACB\u516C\u5F0F\u6216\u56FE\u8868\u653E\u5728\u8BE5\u6BB5\u540E\u3002\u7A7A\u767D\u5B9A\u4F4D\uFF08anchor.kind \u4E3A gap\uFF09\u65F6\uFF0C\u63D2\u4EF6\u5C06\u8BF7\u6C42\u5185\u5BB9\u653E\u5728\u9009\u4E2D\u7684\u5757\u95F4\u6216\u6B63\u6587\u9996\u5C3E\u3002
2428
+ - \u5B9A\u4F4D\u63D2\u5165\u5931\u8D25\u65F6\u4FDD\u7559\u73B0\u6709\u7B14\u8BB0\u3002\u4F4D\u7F6E\u53D8\u66F4\u6216\u4E0D\u552F\u4E00\u65F6\u8BF7\u7528\u6237\u91CD\u65B0\u53F3\u952E\u9009\u70B9\u3002\u9047\u5730\u56FE\u7248\u672C\u51B2\u7A81\u53EF\u91CD\u8BFB\u5E76\u7528\u539F anchor \u91CD\u65B0\u6838\u9A8C\u3002\u5B9A\u4F4D\u9519\u8BEF\u4E0D\u80FD\u7528 set_note \u7ED5\u8FC7\uFF0C\u4E0D\u80FD\u6309\u540C\u540D\u6216\u53EF\u8BFB\u5FEB\u7167\u731C\u4F4D\u7F6E\u3002\u4EC5\u6536\u5230\u5F15\u7528\u6216\u7528\u6237\u53EA\u63D0\u95EE\u65F6\u4E0D\u5199\u5165\u3002
2429
+ - \u6269\u5C55\u5DF2\u62E5\u6324\u7684\u89C6\u56FE\u65F6\uFF0C\u4F18\u5148\u8865\u5230\u5408\u9002\u8282\u70B9\u7684\u8BE6\u60C5\u6216\u5B50\u56FE\uFF0C\u5DF2\u6709\u7ED3\u6784\u7684\u91CD\u7EC4\u4F9D\u7528\u6237\u9700\u6C42\u6267\u884C\u3002
2430
+ - \u6269\u5C55\u5B50\u56FE\u5148\u67E5\u8282\u70B9 childViewId\uFF1B\u6CA1\u6709\u65F6 add_view \u5E76 set_child_view\uFF0C\u8BBE\u7F6E\u6B63\u786E parentViewId \u548C centerNodeId\uFF0C\u5173\u8054\u4E24\u7AEF\u4E00\u81F4\u3002add_node \u4E0D\u63A5\u6536 childViewId\uFF0C\u4FEE\u6539\u65F6\u901A\u8FC7 set_child_view \u5173\u8054\u3002\u4E00\u6B21 changes \u53EF\u7EC4\u5408\u76F8\u5173\u64CD\u4F5C\uFF0C\u6700\u7EC8\u5019\u9009\u5FC5\u987B\u6574\u4F53\u5408\u6CD5\u3002
2431
+ - \u8C03\u6574\u5206\u7EC4\u5F52\u5C5E\u4F7F\u7528 put_occurrence\uFF0C\u79FB\u9664\u5206\u7EC4\u524D\u663E\u5F0F\u5B89\u6392\u539F\u6210\u5458\u53BB\u5411\u3002\u53EA\u5728\u67D0\u89C6\u56FE\u79FB\u9664\u8282\u70B9\u7528 remove_occurrence\uFF0C\u4FDD\u7559\u5168\u56FE\u5BF9\u8C61\u53CA\u5176\u4ED6\u89C6\u56FE\uFF1B\u5168\u56FE delete_node \u4F1A\u5F71\u54CD\u6240\u6709\u51FA\u73B0\u4F4D\u7F6E\u3001\u5173\u7CFB\u548C\u6B63\u6587\uFF0C\u6709\u5B50\u56FE\u65F6\u5148\u660E\u786E\u5904\u7406\u5173\u8054\u3002delete_view \u4E5F\u987B\u5904\u7406\u5B50\u89C6\u56FE\u7236\u7EA7\u548C\u8282\u70B9\u5165\u53E3\uFF0C\u4E0D\u80FD\u6697\u4E2D\u7EA7\u8054\u5220\u9664\u5171\u4EAB\u5185\u5BB9\u3002
2432
+ - \u5206\u533A\u53EF\u8C03\u6574\u5206\u7EC4\u5185\u5BB9\u3001\u5F52\u5C5E\u548C\u73B0\u6709 category\uFF1B\u7CBE\u786E\u6392\u5E03\u3001\u80CC\u666F\u5C3A\u5BF8\u4E0E\u5BF9\u9F50\u7B49\u672A\u5F00\u653E\u5DE5\u5177\u7684\u64CD\u4F5C\uFF0C\u8BF4\u660E\u5F53\u524D\u80FD\u529B\u8FB9\u754C\uFF0C\u4E0D\u7528\u91CD\u5EFA\u5BF9\u8C61\u6216\u751F\u6210\u5750\u6807\u5192\u5145\u5B8C\u6210\u3002
2433
+ - \u5220\u9664\u6216\u79FB\u9664\u6B63\u6587\u3001\u5173\u7CFB\u3001\u5206\u7EC4\u3001\u51FA\u73B0\u4F4D\u7F6E\u3001\u89C6\u56FE\u7B49\u5148 atlas_preview \u6838\u5BF9 removals\uFF0C\u518D\u4EE5\u540C\u4E00\u7248\u672C\u3001\u5B8C\u5168\u76F8\u540C\u7684 changes \u548C previewToken \u8C03\u7528 atlas_apply\u3002\u7528\u6237\u6388\u6743\u7531\u5BBF\u4E3B\u786E\u8BA4\uFF0C\u4E0D\u81EA\u586B confirmed\uFF0C\u4E0D\u4EE5\u5BF9\u8BDD\u6587\u5B57\u66FF\u4EE3\u5BBF\u4E3B\u6388\u6743\uFF1B\u9884\u89C8\u672C\u8EAB\u4E0D\u4EE3\u8868\u5DF2\u4FDD\u5B58\u3002
2434
+
2435
+ ## \u5B57\u6BB5\u901F\u67E5
2436
+ - ID \u4E3A\u975E\u7A7A\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u6216\u77ED\u6A2A\u7EBF\u7EC4\u5408\uFF0C\u540C\u7C7B\u5BF9\u8C61\u5185\u552F\u4E00\uFF1B\u6539\u6807\u9898\u4E0D\u6539\u8EAB\u4EFD\u3002
2437
+ - Node\uFF1Aid/title/summary/category/icon\uFF1B\u65B0\u5EFA content \u4E2D\u53EF\u9009 childViewId\u3002category\uFF1Ablue/sage/plum/gold/terra\uFF1Bicon\uFF1Abook/atom/layers/branch/target/spark/flask/check/alert/formula/link/grid/idea/arrows\u3002
2438
+ - View\uFF1Aid/title/parentViewId/groups/occurrences/relationIds\uFF0C\u53EF\u9009 centerNodeId\uFF1B\u6839 parentViewId \u4E3A null\uFF0C\u5176\u4F59\u7236\u7EA7\u6700\u7EC8\u5230\u6839\u4E14\u65E0\u73AF\u3002Group\uFF1Aid/title/number/category\uFF1B\u5206\u7EC4\u6570\u7EC4\u987A\u5E8F\u8868\u8FBE\u5206\u533A\u987A\u5E8F\u3002Occurrence\uFF1AnodeId\uFF0C\u53EF\u9009 groupId\uFF1B\u540C\u4E00\u89C6\u56FE\u4E0D\u91CD\u590D\u8282\u70B9\u3002
2439
+ - Relation\uFF1Aid/fromNodeId/toNodeId/type\uFF0C\u53EF\u9009 label\uFF1Btype \u4E3A dependency/supplement\uFF0C\u5173\u7CFB\u5141\u8BB8\u6210\u73AF\u3002\u5177\u4F53 changes \u7684 op \u548C\u53C2\u6570\u7ED3\u6784\u4EE5\u5B9E\u9645\u5DE5\u5177 schema \u4E3A\u51C6\uFF0C\u4E0D\u731C\u6D4B\u4E0D\u5B58\u5728\u7684\u64CD\u4F5C\u3002
2440
+
2441
+ ## \u4FDD\u5B58\u4E0E\u53CD\u9988
2442
+ - \u65B0\u5EFA\u6216\u65B0\u589E\u8282\u70B9\u524D\uFF0C\u590D\u6838\u6BCF\u4E2A\u65B0\u5EFA\u6216\u6269\u5C55\u89C6\u56FE\u7684 occurrences \u6570\u91CF\uFF0C\u5E76\u68C0\u67E5\u62C6\u5206\u540E\u5404\u89C6\u56FE\u7684\u5173\u7CFB\u7AEF\u70B9\u4ECD\u5728\u8BE5\u89C6\u56FE\u5185\u3002
2443
+ - \u53EA\u7528\u5B9E\u9645\u6CE8\u518C\u7684 atlas_list/read/create/preview/apply \u7EF4\u62A4\u5730\u56FE\uFF0Catlas_cleanup_create \u4EC5\u5904\u7406\u7528\u6237\u660E\u786E\u8981\u6C42\u7684\u672A\u5B8C\u6210\u521B\u5EFA\u6E05\u7406\u3002\u5DE5\u5177\u4E0D\u53EF\u7528\u65F6\u8BF4\u660E\u672A\u4FDD\u5B58\uFF0C\u53EF\u7ED9\u5185\u5BB9\u65B9\u6848\uFF1B\u4E0D\u7ED5\u8FC7\u63D2\u4EF6\u7528\u901A\u7528\u6587\u4EF6\u5DE5\u5177\u5199\u5730\u56FE\uFF0C\u4E0D\u751F\u6210 HTML/CSS/SVG \u6A21\u677F\u3001\u5750\u6807\u6216\u6062\u590D\u8D44\u6599\uFF0C\u4E0D\u8981\u6C42\u8BFB\u53D6\u754C\u9762\u539F\u578B\u3002
2444
+ - expectedFingerprint \u539F\u6837\u4F7F\u7528\u672C\u6B21\u8BFB\u53D6\u7ED3\u679C\u3002version_conflict \u6216 cursor_expired \u65F6\u91CD\u65B0\u8BFB\u53D6\u5E76\u8BC4\u4F30\uFF1B\u53D1\u751F\u6B67\u4E49\u518D\u8BE2\u95EE\uFF0C\u4E0D\u76F2\u76EE\u8986\u76D6\u3002operationId \u5728\u5B8C\u5168\u76F8\u540C\u8BF7\u6C42\u91CD\u8BD5\u65F6\u4FDD\u6301\u4E0D\u53D8\uFF0C\u53C2\u6570\u6216\u7248\u672C\u6539\u53D8\u4F7F\u7528\u65B0ID\uFF1B\u4E0D\u8981\u56E0\u54CD\u5E94\u4E0D\u786E\u5B9A\u5C31\u7528\u65B0ID\u91CD\u590D\u521B\u5EFA\u3002
2445
+ - invalid_data \u6309\u8BCA\u65AD\u4FEE\u6B63\u5019\u9009\uFF1Bpermission_denied/approval_required \u5982\u5B9E\u62A5\u544A\uFF0C\u4E0D\u6362\u5DE5\u5177\u7ED5\u8FC7\u9650\u5236\u3002failed_rolled_back \u8868\u793A\u672C\u6B21\u672A\u4FDD\u5B58\uFF1Brecovery_required \u8868\u793A\u505C\u6B62\u7EE7\u7EED\u5199\u5165\uFF0C\u4FDD\u7559\u5DE5\u5177\u8BCA\u65AD\uFF0C\u4EA4\u7528\u6237\u786E\u8BA4\u539F\u64CD\u4F5C\u5DF2\u7EC8\u6B62\u540E\u5904\u7406\uFF0C\u4E0D\u80FD\u81EA\u52A8\u6267\u884C\u6062\u590D\u547D\u4EE4\u3002
2446
+ - \u521B\u5EFA\u5931\u8D25\u7684\u56DE\u9000\u548C\u5360\u4F4D\u6E05\u7406\u7531\u63D2\u4EF6\u8D1F\u8D23\uFF1B\u4E0D\u8981\u81EA\u884C\u626B\u63CF\u6216\u5220\u9664\u5730\u56FE\u76EE\u5F55\u53CA\u4E8B\u52A1\u6587\u4EF6\u3002atlas_list \u7684 incompleteCreates \u662F\u672A\u5B8C\u6210\u521B\u5EFA\u8BB0\u5F55\uFF0C\u4E0D\u662F\u53EF\u8BFB\u53D6\u5730\u56FE\u3002\u7528\u6237\u660E\u786E\u8981\u6C42\u6E05\u7406\u65F6\uFF0C\u4ECE\u8BE5\u5217\u8868\u786E\u5B9A mapId/operationId\uFF0C\u8C03\u7528 atlas_cleanup_create \u5E76\u7531\u5BBF\u4E3B\u6388\u6743\uFF1B\u4E0D\u4F7F\u7528\u5185\u5BB9\u5220\u9664\u5DE5\u5177\uFF0C\u4E0D\u5728\u65B0\u5EFA\u6210\u529F\u540E\u987A\u4FBF\u6E05\u7406\u5176\u4ED6\u8BB0\u5F55\u3002\u6E05\u7406\u4F1A\u4F5C\u5E9F\u539F\u521B\u5EFA\u8BF7\u6C42\uFF0Ccreate_discarded \u65F6\u505C\u6B62\u91CD\u8BD5\u8BE5ID\uFF0C\u7528\u6237\u91CD\u65B0\u8981\u6C42\u5EFA\u56FE\u540E\u624D\u4F7F\u7528\u65B0ID\u521B\u5EFA\u3002
2447
+ - \u4EE5\u5DE5\u5177\u5B9E\u9645\u7ED3\u679C\u8BF4\u660E\u72B6\u6001\u3002\u6210\u529F\u7B80\u8FF0\u5730\u56FE\u540D\u79F0\u3001mapId\u548C\u672C\u6B21\u53D8\u5316\uFF1B\u5931\u8D25\u3001\u9884\u89C8\u6216\u5206\u6279\u672A\u5B8C\u6210\u65F6\u51C6\u786E\u8BF4\u660E\u3002\u4FDD\u5B58\u6210\u529F\u540E\u63D2\u4EF6\u8D1F\u8D23\u5237\u65B0\u548C\u6253\u5F00\u76EE\u6807\u56FE\u3002\u88AB\u95EE\u53CA\u9A8C\u6536\u65F6\uFF0Catlas \u5DE5\u5177\u53EF\u6838\u5BF9\u7ED3\u6784\u3001\u6B63\u6587\u548C\u63D0\u4EA4\u7ED3\u679C\uFF0C\u4FA7\u680F\u4EA4\u4E92\u3001\u81EA\u52A8\u4FDD\u5B58\u53CA\u79BB\u7EBF\u5448\u73B0\u4EE5\u5B9E\u9645\u64CD\u4F5C\u89C2\u5BDF\u4E3A\u51C6\u3002`;
2448
+
2449
+ // src/server/prompts/register.ts
2450
+ function registerAuthoring(ctx) {
2451
+ ctx.skills.register({ name: "mindmap", description: mindmapDescription, source: "bundled", content: mindmapAuthoring });
2452
+ }
2453
+
2454
+ // src/server/purge-map.ts
2455
+ import { randomUUID as randomUUID5 } from "node:crypto";
2456
+ import { z as z10 } from "zod";
2457
+ var manifestSchema = z10.strictObject({
2458
+ mapId: z10.string(),
2459
+ state: z10.enum(["deleting", "completed"]),
2460
+ files: z10.array(z10.strictObject({ path: z10.string(), version: z10.string().min(1) })).min(1).refine((files) => files.some((file) => file.path === "map.json") && new Set(files.map((file) => file.path)).size === files.length, "\u5220\u9664\u6E05\u5355\u5FC5\u987B\u5305\u542B\u7ED3\u6784\u6587\u4EF6\u4E14\u8DEF\u5F84\u552F\u4E00")
2461
+ });
2462
+ var MANIFEST = ".transactions/purge.json";
2463
+ async function purgeMap(ctx, scope, id, policy, signal) {
2464
+ const port = createHostFiles(ctx, scope, signal, policy);
2465
+ const metadata = transactionPort(ctx, scope, id, policy);
2466
+ if (!await port.absent(mapPath(id, ".transactions/active.json"))) throw new AtlasError("recovery_required", "\u5B58\u5728\u5F85\u6062\u590D\u5185\u5BB9\u64CD\u4F5C\uFF0C\u8BF7\u5148\u6062\u590D\u540E\u518D\u6C38\u4E45\u5220\u9664");
2467
+ const lockText = JSON.stringify({ kind: "purge", mapId: id, owner: randomUUID5() });
2468
+ let claimed = false;
2469
+ let stored = await metadata.read(MANIFEST);
2470
+ let manifest;
2471
+ if (stored) {
2472
+ manifest = manifestSchema.parse(JSON.parse(stored.text));
2473
+ if (manifest.mapId !== id) throw new AtlasError("invalid_data", "\u5220\u9664\u6E05\u5355\u8EAB\u4EFD\u4E0D\u5339\u914D");
2474
+ } else {
2475
+ const snapshot = await readSnapshot(port, id);
2476
+ const prefix = mapPath(id, "map.json").slice(0, -"map.json".length);
2477
+ manifest = { mapId: id, state: "deleting", files: snapshot.files.map((file) => ({ path: file.path.slice(prefix.length), version: file.version })).sort((a, b) => Number(a.path === "map.json") - Number(b.path === "map.json")) };
2478
+ }
2479
+ for (const file of manifest.files) {
2480
+ if (file.path !== localPath(file.path) || /(^|\/)(exports|\.transactions)(\/|$)/.test(file.path) || !["map.json", "layout.json"].includes(file.path) && !file.path.endsWith(".md") && !file.path.startsWith("assets/")) throw new AtlasError("invalid_data", "\u5220\u9664\u6E05\u5355\u542B\u975E\u5185\u5BB9\u6587\u4EF6\uFF0C\u62D2\u7EDD\u6267\u884C");
2481
+ }
2482
+ try {
2483
+ await metadata.put(".transactions/active.json", lockText, null);
2484
+ claimed = true;
2485
+ if (!stored) {
2486
+ await metadata.put(MANIFEST, JSON.stringify(manifest), null);
2487
+ stored = await metadata.read(MANIFEST);
2488
+ }
2489
+ if (manifest.state === "completed") {
2490
+ for (const file of manifest.files) if (!await port.absent(mapPath(id, file.path))) throw new AtlasError("version_conflict", "\u5DF2\u5220\u9664\u5730\u56FE\u51FA\u73B0\u65B0\u5185\u5BB9\uFF0C\u4FDD\u7559\u65B0\u6587\u4EF6\u5E76\u505C\u6B62");
2491
+ return;
2492
+ }
2493
+ const root = await ctx.fs.resolve(scope.workspaceRoot, { signal });
2494
+ const map = await ctx.fs.resolve(mapPath(id, "."), { cwd: scope.workspaceRoot, signal });
2495
+ if (!ctx.fs.contains(root, map)) throw new AtlasError("path_outside_map", "\u5220\u9664\u76EE\u6807\u8D8A\u8FC7\u5DE5\u4F5C\u533A");
2496
+ const targetFor = async (file) => {
2497
+ const relative = mapPath(id, file.path);
2498
+ const target = await ctx.fs.resolve(relative, { cwd: scope.workspaceRoot, signal });
2499
+ if (!ctx.fs.contains(map, target) || target.targetKey === map.targetKey) throw new AtlasError("path_outside_map", "\u5220\u9664\u76EE\u6807\u8D8A\u8FC7\u5730\u56FE\u8FB9\u754C");
2500
+ const entry = await ctx.fs.lstat(relative, { cwd: scope.workspaceRoot }, signal);
2501
+ if (entry && entry.type !== "file") throw new AtlasError("path_outside_map", "\u62D2\u7EDD\u5220\u9664\u7B26\u53F7\u94FE\u63A5\u6216\u975E\u666E\u901A\u6587\u4EF6");
2502
+ const info = await ctx.fs.stat(target, signal);
2503
+ if (info && String(info.version) !== file.version) throw new AtlasError("version_conflict", `\u6587\u4EF6\u5DF2\u53D8\u5316\uFF0C\u672A\u8986\u76D6\uFF1A${file.path}`);
2504
+ return { target, info };
2505
+ };
2506
+ for (const file of manifest.files) await targetFor(file);
2507
+ for (const file of manifest.files) {
2508
+ signal.throwIfAborted();
2509
+ const { target, info } = await targetFor(file);
2510
+ if (info) await ctx.fs.deleteFile(target, { version: info.version }, signal, policy);
2511
+ }
2512
+ for (const file of manifest.files) if (!await port.absent(mapPath(id, file.path))) throw new AtlasError("version_conflict", "\u5220\u9664\u671F\u95F4\u51FA\u73B0\u65B0\u5185\u5BB9\uFF0C\u4FDD\u7559\u65B0\u6587\u4EF6\u5E76\u505C\u6B62");
2513
+ await metadata.put(MANIFEST, JSON.stringify({ ...manifest, state: "completed" }), stored.version);
2514
+ } finally {
2515
+ const lock = claimed ? await metadata.read(".transactions/active.json") : null;
2516
+ if (lock && lock.text === lockText) await metadata.remove(".transactions/active.json", lock.version);
2517
+ }
2518
+ }
2519
+
2520
+ // src/server/map-service.ts
2521
+ import { z as z11 } from "zod";
2522
+ import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
2523
+
2524
+ // src/shared/library-order.ts
2525
+ function stripIdsFromOrders(library, excluded) {
2526
+ const rootMapOrder = library.rootMapOrder?.filter((id) => !excluded.has(id));
2527
+ let folderMapOrders;
2528
+ if (library.folderMapOrders) {
2529
+ const entries = [];
2530
+ for (const [folderId, list] of Object.entries(library.folderMapOrders)) {
2531
+ const next = list.filter((id) => !excluded.has(id));
2532
+ if (next.length) entries.push([folderId, next]);
2533
+ }
2534
+ if (entries.length) folderMapOrders = Object.fromEntries(entries);
2535
+ }
2536
+ return {
2537
+ ...rootMapOrder?.length ? { rootMapOrder } : {},
2538
+ ...folderMapOrders ? { folderMapOrders } : {}
2539
+ };
2540
+ }
2541
+ function prunePurgedFromOrders(library, purgedIds) {
2542
+ return stripIdsFromOrders(library, purgedIds);
2543
+ }
2544
+
2545
+ // src/server/map-service.ts
2546
+ var requestSchema = z11.discriminatedUnion("op", [
2547
+ commitEditSchema,
2548
+ editStatusSchema,
2549
+ z11.strictObject({ op: z11.literal("list") }),
2550
+ z11.strictObject({ op: z11.literal("cleanupCreate"), mapId: idSchema, operationId: idSchema, expectedWorkspaceKey: z11.string().min(1) }),
2551
+ z11.strictObject({ op: z11.literal("purge"), mapIds: z11.array(idSchema).min(1), version: z11.string().nullable(), expectedWorkspaceKey: z11.string().min(1) }),
2552
+ z11.strictObject({ op: z11.literal("rename"), mapId: idSchema, title: z11.string().trim().min(1).max(120), previousTitle: z11.string(), expectedWorkspaceKey: z11.string().min(1) }),
2553
+ z11.strictObject({ op: z11.literal("create"), title: z11.string().trim().min(1).max(120), expectedWorkspaceKey: z11.string().min(1) }),
2554
+ z11.strictObject({ op: z11.literal("saveLibrary"), data: librarySchema, version: z11.string().nullable(), expectedWorkspaceKey: z11.string().min(1) }),
2555
+ z11.strictObject({
2556
+ op: z11.literal("read"),
2557
+ mapId: idSchema,
2558
+ expectedWorkspaceKey: z11.string().min(1).optional()
2559
+ }),
2560
+ z11.strictObject({
2561
+ op: z11.literal("saveLayout"),
2562
+ mapId: idSchema,
2563
+ expectedFingerprint: z11.string().min(1),
2564
+ expectedWorkspaceKey: z11.string().min(1),
2565
+ layout: layoutSchema,
2566
+ manual: z11.boolean().optional()
2567
+ })
2568
+ ]);
2569
+ var _request_dec, _a, _init;
2570
+ var MapService = class extends (_a = TypertRemoteService, _request_dec = [Remote], _a) {
2571
+ constructor(ctx) {
2572
+ super(ctx, "dshAtlas");
2573
+ __runInitializers(_init, 5, this);
2574
+ }
2575
+ async request(workspaceFileScope, payload, signal) {
2576
+ let operationId;
2577
+ try {
2578
+ if (new TextEncoder().encode(payload).length > 24 * 1024 * 1024) throw new AtlasError("resource_too_large", "\u8BF7\u6C42\u8D85\u8FC7 24 MiB");
2579
+ const req = requestSchema.parse(JSON.parse(payload));
2580
+ operationId = "operationId" in req ? req.operationId : void 0;
2581
+ if (req.op !== "list" && req.expectedWorkspaceKey !== void 0 && req.expectedWorkspaceKey !== workspaceFileScope.workspaceRoot)
2582
+ throw new AtlasError(
2583
+ "workspace_changed",
2584
+ "\u6765\u6E90\u4F1A\u8BDD\u7684\u5DE5\u4F5C\u533A\u5DF2\u53D8\u5316\uFF0C\u62D2\u7EDD\u8BFB\u53D6\u6216\u4FDD\u5B58\u5230\u53E6\u4E00\u4E2A\u5DE5\u4F5C\u533A"
2585
+ );
2586
+ const key = `${workspaceFileScope.workspaceRoot}\0${"mapId" in req ? req.mapId : ""}`;
2587
+ const run = async () => {
2588
+ signal.throwIfAborted();
2589
+ const writes = req.op === "commitEdit" || req.op === "cleanupCreate" || req.op === "purge" || req.op === "rename" || req.op === "create" || req.op === "saveLibrary" || req.op === "saveLayout";
2590
+ const session = writes ? this.ctx.sessions.get(workspaceFileScope.sessionId) : void 0;
2591
+ if (writes && !session) throw new AtlasError("session_unavailable", "\u6765\u6E90\u4F1A\u8BDD\u672A\u52A0\u8F7D\uFF0C\u65E0\u6CD5\u4FDD\u5B58");
2592
+ const policy = writes ? this.ctx.sandboxPolicy.resolve({ session }) : void 0;
2593
+ if (policy?.mode === "read-only") throw new AtlasError("permission_denied", "\u5F53\u524D\u4F1A\u8BDD\u4E3A\u53EA\u8BFB\uFF0C\u5E03\u5C40\u4FDD\u7559\u5728\u5185\u5B58\uFF1B\u5207\u6362\u5230\u5141\u8BB8\u5DE5\u4F5C\u533A\u5199\u5165\u7684\u4F1A\u8BDD\u540E\u53EF\u91CD\u8BD5");
2594
+ if (policy && policy.workspaceRoot !== workspaceFileScope.workspaceRoot)
2595
+ throw new AtlasError("workspace_changed", "\u4F1A\u8BDD\u5199\u5165\u5DE5\u4F5C\u533A\u5DF2\u53D8\u5316");
2596
+ const port = createHostFiles(this.ctx, workspaceFileScope, signal, policy);
2597
+ const library = libraryFiles(this.ctx, workspaceFileScope, signal, policy);
2598
+ if (req.op === "cleanupCreate") return cleanupCreate(this.ctx, workspaceFileScope, req.mapId, req.operationId, policy, signal);
2599
+ if (req.op === "purge") {
2600
+ let current = await library.read();
2601
+ if (current.version !== req.version) throw new AtlasError("version_conflict", "\u76EE\u5F55\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8F7D\u5165\u540E\u518D\u5220\u9664");
2602
+ const ids = [...new Set(req.mapIds)];
2603
+ if (ids.some((id) => !current.data.deletedMapIds?.includes(id))) throw new AtlasError("invalid_data", "\u53EA\u5141\u8BB8\u6C38\u4E45\u5220\u9664\u5F53\u524D\u56DE\u6536\u7AD9\u4E2D\u7684\u5BFC\u56FE");
2604
+ const titles = { ...current.data.deletedMapTitles };
2605
+ for (const id of ids) if (!titles[id]) {
2606
+ try {
2607
+ titles[id] = (await readSnapshot(port, id)).map.title;
2608
+ } catch {
2609
+ }
2610
+ }
2611
+ current = await library.save({ ...current.data, deletedMapTitles: titles, purgingMapIds: [.../* @__PURE__ */ new Set([...current.data.purgingMapIds ?? [], ...ids])] }, current.version);
2612
+ const deletedIds = [];
2613
+ const failures = [];
2614
+ for (const id of ids) {
2615
+ try {
2616
+ await serializeMap(`${workspaceFileScope.workspaceRoot}\0${id}`, () => purgeMap(this.ctx, workspaceFileScope, id, policy, signal));
2617
+ deletedIds.push(id);
2618
+ } catch (e) {
2619
+ failures.push({ id, message: String(e) });
2620
+ if (signal.aborted) break;
2621
+ }
2622
+ }
2623
+ const purged = /* @__PURE__ */ new Set([...current.data.purgedMapIds ?? [], ...deletedIds]);
2624
+ const orders = prunePurgedFromOrders(current.data, purged);
2625
+ const { rootMapOrder: _rootOrder, folderMapOrders: _folderOrders, ...baseLibrary } = current.data;
2626
+ const state = deletedIds.length ? await library.save({
2627
+ ...baseLibrary,
2628
+ ...orders,
2629
+ purgedMapIds: [...purged],
2630
+ deletedMapIds: current.data.deletedMapIds?.filter((id) => !purged.has(id)),
2631
+ purgingMapIds: current.data.purgingMapIds?.filter((id) => !purged.has(id)),
2632
+ deletedMapTitles: Object.fromEntries(Object.entries(current.data.deletedMapTitles ?? {}).filter(([id]) => !purged.has(id))),
2633
+ mapFolders: Object.fromEntries(Object.entries(current.data.mapFolders).filter(([id]) => !purged.has(id)))
2634
+ }, current.version) : current;
2635
+ return { deletedIds, failures, library: state };
2636
+ }
2637
+ if (req.op === "create") return library.create(req.title);
2638
+ if (req.op === "saveLibrary") {
2639
+ const previous = await library.read();
2640
+ if ((previous.data.purgingMapIds ?? []).some((id) => !req.data.deletedMapIds?.includes(id) || !req.data.purgingMapIds?.includes(id)) || (previous.data.purgedMapIds ?? []).some((id) => !req.data.purgedMapIds?.includes(id))) throw new AtlasError("purge_pending", "\u6C38\u4E45\u5220\u9664\u5DF2\u5F00\u59CB\uFF0C\u4E0D\u80FD\u8FD8\u539F\u8BE5\u5BFC\u56FE\uFF1B\u8BF7\u5728\u56DE\u6536\u7AD9\u7EE7\u7EED\u5220\u9664");
2641
+ return library.save(req.data, req.version);
2642
+ }
2643
+ if (req.op === "list") {
2644
+ let state;
2645
+ let libraryError;
2646
+ try {
2647
+ state = await library.read();
2648
+ } catch (e) {
2649
+ libraryError = e;
2650
+ }
2651
+ const listing = await listMapHeaders(port, /* @__PURE__ */ new Set([...state?.data.purgedMapIds ?? [], ...state?.data.purgingMapIds ?? []]));
2652
+ listing.library = state;
2653
+ if (libraryError) listing.diagnostics.push({ path: "library.json", code: errorCode(libraryError), message: String(libraryError) });
2654
+ return listing;
2655
+ }
2656
+ const currentLibrary = (await library.read()).data;
2657
+ if (currentLibrary.deletedMapIds?.includes(req.mapId) || currentLibrary.purgedMapIds?.includes(req.mapId)) throw new AtlasError("map_deleted", "\u6B64\u5BFC\u56FE\u5DF2\u5728\u56DE\u6536\u7AD9\uFF0C\u8BF7\u5148\u6062\u590D");
2658
+ if (req.op === "editStatus") return editStatus(this.ctx, workspaceFileScope, req, signal);
2659
+ if (req.op === "commitEdit") return commitEdit(this.ctx, workspaceFileScope, req, policy, signal);
2660
+ if (req.op === "rename") {
2661
+ const snapshot = await readSnapshot(port, req.mapId);
2662
+ if (snapshot.map.title !== req.previousTitle) throw new AtlasError("version_conflict", "\u5BFC\u56FE\u540D\u79F0\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5");
2663
+ const file = snapshot.files.find((file2) => file2.path === `dsh-knowledge-maps/${req.mapId}/map.json`);
2664
+ await library.rename(snapshot.map, req.title, file.version);
2665
+ return null;
2666
+ }
2667
+ return req.op === "read" ? readSnapshot(port, req.mapId, true) : saveLayout(port, req.mapId, req.expectedFingerprint, req.layout, req.manual);
2668
+ };
2669
+ return JSON.stringify({ ok: true, value: await (req.op === "list" ? run() : serializeMap(key, run)) });
2670
+ } catch (e) {
2671
+ signal.throwIfAborted();
2672
+ return JSON.stringify({
2673
+ ok: false,
2674
+ operationId,
2675
+ commitState: errorCode(e) === "failed_rolled_back" ? "rolled_back" : ["verification_required", "permission_denied", "invalid_data", "resource_too_large", "workspace_changed", "session_unavailable"].includes(errorCode(e)) ? "not_applied" : "unknown",
2676
+ code: errorCode(e),
2677
+ message: e instanceof Error ? e.message : String(e),
2678
+ diagnostics: typeof e === "object" && e !== null && "diagnostics" in e ? e.diagnostics : []
2679
+ });
2680
+ }
2681
+ }
2682
+ };
2683
+ _init = __decoratorStart(_a);
2684
+ __decorateElement(_init, 1, "request", _request_dec, MapService);
2685
+ __decoratorMetadata(_init, MapService);
2686
+
2687
+ // src/index.ts
2688
+ var name = "dsh-mindmap";
2689
+ var inject = ["fs", "workspaceFiles", "typert", "sessions", "sandboxPolicy"];
2690
+ function apply(ctx) {
2691
+ new MapService(ctx);
2692
+ ctx.inject(["tools", "skills", "approval"], (api) => {
2693
+ registerTools(api);
2694
+ registerAuthoring(api);
2695
+ });
2696
+ }
2697
+ export {
2698
+ apply,
2699
+ inject,
2700
+ name
2701
+ };