dsh-mindmap 0.12.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -7,6 +7,9 @@
7
7
  // - 根节点标题 = 文档名(决策 2):renameRoot 触发文件重命名,撞名报错不覆盖;
8
8
  // 文件被外部改名时根标题由 client 从路径推导,天然跟随。
9
9
  // - 四工具都带 path/name 参数(决策 3:多脑图并存,作用于指定那颗)。
10
+ // - 036 默认落点:用户没指定目录的随手创建进 `.mindmaps/` 脑图收件箱,
11
+ // 名字 `YYYYMMDD-HHmmss-中文描述.md`——时间戳由 host 读表(模型不猜时间),
12
+ // 描述由 AI 给。收件箱按需创建、不进 .gitignore,同秒撞名加 -2/-3 不覆盖。
10
13
  // - 结果 JSON {ok, op, path, rootTitle, content, renamedFrom?}:content 全文
11
14
  // 供模型续编辑,client 用同一份重放面板(工具结果即实时通道,002 第二节)。
12
15
  // - requireApproval 配置(决策 6):默认 true;approvalMode 默认按「当前会话 + 当前文件」
@@ -15,7 +18,7 @@
15
18
  // 015 起经 settings namespace 可运行时切换。
16
19
  // - 依赖:仅 @deepseek-ai/schemastery(settings schema;发布包正常解析,
17
20
  // link 开发需先 npm i)。工具参数 schema 仍手写 JSON Schema(003 偏差 1)。
18
- import { access, open, opendir, realpath, rename, stat, unlink, writeFile } from 'node:fs/promises'
21
+ import { access, mkdir, open, opendir, realpath, rename, stat, unlink, writeFile } from 'node:fs/promises'
19
22
  import { createHash, randomUUID } from 'node:crypto'
20
23
  import { dirname, isAbsolute, join, relative, resolve as resolvePath, sep } from 'node:path'
21
24
  import Schema from '@deepseek-ai/schemastery'
@@ -58,13 +61,20 @@ const BROAD_REWRITE_MIN_BYTES = 16 * 1024
58
61
  // 比例判定只对足够大的文档生效:几百字节的脑图整体改写不算「大范围重写」,
59
62
  // 否则小文档的每次更新都会被升级成高风险确认,会话授权形同虚设。
60
63
  const BROAD_REWRITE_RATIO_MIN_BYTES = 4 * 1024
64
+ // 036 默认脑图收件箱:用户没指定目录时的落点。目录只在第一次需要时按需创建,
65
+ // 也不自动进 .gitignore——脑图仍是普通 Markdown,用户可以审阅、diff、提交。
66
+ export const DEFAULT_MINDMAP_DIR = '.mindmaps'
67
+ // 描述只占默认名的一段,上限留足时间戳(15)与连接符的余量后仍远低于 MAX_NAME_CHARS。
68
+ const MAX_DESCRIPTION_CHARS = 24
69
+ // 同一秒同名(默认命名)时的后缀尝试次数上限。
70
+ const MAX_CREATE_ATTEMPTS = 50
61
71
 
62
72
  const GUIDANCE = `## Mindmap editing (dsh-mindmap)
63
73
 
64
74
  A mindmap is a plain markdown file in the session working directory. The right-side panel renders it live; the filename (without .md) is the root node title. These files are ordinary documents: the user reviews and commits them with git themselves.
65
75
 
66
76
  Tools:
67
- - mindmap_create(name, directory?): create <name>.md in the working directory or the selected relative directory (fails if it exists) and show it in the panel.
77
+ - mindmap_create(name? | description, directory?): create a mindmap and show it in the panel (fails if the file already exists). Give \`name\` when the user named the mindmap; otherwise give a short \`description\` and the host names the file \`YYYYMMDD-HHmmss-<description>.md\`. Give \`directory\` only when the user picked a location.
68
78
  - mindmap_open(path): open an existing .md as a mindmap in the panel.
69
79
  - mindmap_get(path): read the current markdown content.
70
80
  - mindmap_update(path, content, renameRoot?, expectedRevision?): write the FULL updated markdown. Pass the revision returned by mindmap_get/open when editing; a mismatch stops the write instead of overwriting newer changes. renameRoot renames the file to match a new root title (fails on name collision); use it only when the user asks to rename the root node.
@@ -72,6 +82,9 @@ Tools:
72
82
  Markdown mapping (the panel's parser): headings nest by level (H1 are root children, H2 under the previous H1, ...); list items are child nodes nested by 2-space indentation; a list item with no text after the marker renders as a placeholder node (both "-" and "- " work; no trailing space is required) — use placeholders for planned-but-unwritten nodes; a fenced code block becomes a leaf node titled "[lang] first line"; plain paragraphs become their own text/Markdown block nodes under the nearest heading.
73
83
 
74
84
  Behavior rules:
85
+ - Where new files go: for casual requests ("创建一个脑图", "把刚才的讨论整理成脑图", "盘点一下这个问题") omit \`directory\` — the host files them in \`${DEFAULT_MINDMAP_DIR}/\`, the mindmap inbox, created on first use. That is the only location the plugin ever chooses on its own: when the user names a directory (or right-clicks one in the tree), pass that \`directory\` and leave their placement alone.
86
+ - Never write a date or time into a mindmap filename yourself. Pass a bare \`description\` (e.g. 项目盘点) and the host stamps the real current time, then takes the first free name (\`-2\`, \`-3\`, …) so an existing file is never overwritten. The path the user confirms is the path it writes; if another create claims that name while the confirmation is pending, the host steps to the next free suffix and reports the final path in the tool result — relay that path to the user rather than assuming the one they confirmed.
87
+ - Because the root node title is the filename, a default-created mindmap shows its timestamp as the root title (e.g. 20260918-155230-项目盘点). Rename it with renameRoot only when the user asks; do not restructure the document to hide the stamp.
75
88
  - When the user asks to create a mindmap, call mindmap_create. When the user asks to open, view, show, or switch to an existing mindmap, call mindmap_open (do not use mindmap_get alone). Both operations bring that document to the visible mindmap panel automatically.
76
89
  - Always mindmap_get before editing, then send the complete updated document and the returned revision as expectedRevision to mindmap_update. If the tool reports a revision conflict, stop and ask the user whether to reload or merge; never overwrite newer text silently. Every call must carry the FULL document, never a fragment.
77
90
  - Update step by step: whenever the request involves several parts, call mindmap_update as soon as each part is ready — several small updates beat one giant update at the end. The panel plays a growth animation on newly added/changed nodes, so step-by-step updates make the tree visibly grow while you work. Do not call mindmap_update twice in a row with identical content.
@@ -262,6 +275,61 @@ function sanitizeStem(input) {
262
275
  return stem
263
276
  }
264
277
 
278
+ /** 本地时间 → `YYYYMMDD-HHmmss`。时间只由 host 读表,绝不交给模型猜。 */
279
+ function timestampStamp(date) {
280
+ const pad = (value, width = 2) => String(value).padStart(width, '0')
281
+ return `${pad(date.getFullYear(), 4)}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`
282
+ }
283
+
284
+ /**
285
+ * AI 描述 → 默认名的描述段:折叠空白、按 sanitizeStem 同款安全规则拒绝越界字符、
286
+ * 截断到 MAX_DESCRIPTION_CHARS。清理后为空(含只剩点号)一律拒绝,不静默造怪文件名。
287
+ */
288
+ function sanitizeDescription(input) {
289
+ const raw = String(input ?? '').replace(/\s+/g, ' ').trim().replace(/\.+$/, '')
290
+ if (!raw) throw new Error('mindmap description must not be empty.')
291
+ if (/[\\/:*?"<>|]/.test(raw)) throw new Error(`Invalid mindmap description ${JSON.stringify(input)}: path separators and :*?"<>| are not allowed.`)
292
+ // eslint-disable-next-line no-control-regex
293
+ if (/[\u0000-\u001f]/.test(raw)) throw new Error('Invalid mindmap description: control characters are not allowed.')
294
+ const chars = [...raw]
295
+ return chars.length > MAX_DESCRIPTION_CHARS ? chars.slice(0, MAX_DESCRIPTION_CHARS).join('') : raw
296
+ }
297
+
298
+ /** 默认脑图主干:`YYYYMMDD-HHmmss-中文描述`(例 20260918-155230-项目盘点)。 */
299
+ function defaultStem(date, description) {
300
+ return `${timestampStamp(date)}-${sanitizeDescription(description)}`
301
+ }
302
+
303
+ /** create 参数里的显式目录(去空白);缺省 = 走默认收件箱。 */
304
+ function explicitDirectory(args) {
305
+ return typeof args?.directory === 'string' && args.directory.trim() ? args.directory.trim() : ''
306
+ }
307
+
308
+ /**
309
+ * 一次 create 的路径计划——纯计算,不落盘,因此可以安全地在审批钩子里调用。
310
+ * 主干与目录在此定死,`execute` 复用同一份(含同一时间戳),避免两处二次取时间
311
+ * 算出不同文件名,让审批确认的路径和真正写入的路径脱节。
312
+ * @returns {{stem: string, relative: string, defaultDir: boolean, autoNamed: boolean}}
313
+ * `defaultDir` = 落点由插件决定(需要时现建收件箱);`autoNamed` = 主干由 host
314
+ * 生成,撞名可以加后缀。两者互相独立:只给名字不给目录时进收件箱,但那是用户的
315
+ * 命名意图,撞名了不能替他改名。
316
+ */
317
+ function planCreatePaths(cwd, args, now = new Date()) {
318
+ if (!cwd) throw new Error('The session has no working directory; cannot create a mindmap.')
319
+ const directory = explicitDirectory(args)
320
+ const explicitName = typeof args?.name === 'string' ? args.name.trim() : ''
321
+ if (!explicitName && (typeof args?.description !== 'string' || !args.description.trim())) {
322
+ throw new Error('mindmap_create needs either `name` (an explicit title) or `description` (a short phrase such as 项目盘点); the host supplies the timestamp.')
323
+ }
324
+ const stem = explicitName ? sanitizeStem(explicitName) : defaultStem(now, args?.description)
325
+ return {
326
+ stem,
327
+ relative: join(directory || DEFAULT_MINDMAP_DIR, `${stem}.md`),
328
+ defaultDir: !directory,
329
+ autoNamed: !explicitName,
330
+ }
331
+ }
332
+
265
333
  /**
266
334
  * 解析脑图文件路径:相对路径以会话 cwd 为基;结果必须落在 cwd 内(决策 1),
267
335
  * 且必须以 .md 结尾。cwd 是文件授权边界,缺失时必须失败关闭。
@@ -290,6 +358,113 @@ async function pathExists(p) {
290
358
  }
291
359
  }
292
360
 
361
+ /**
362
+ * 默认收件箱目录按需创建(036):不在插件初始化时预生成,第一次需要时才落盘,
363
+ * 已存在则直接复用(不重复 mkdir,免得碰用户目录的 mtime)。
364
+ * 三条失败关闭:符号链接越界、同名普通文件占位、真建不出来(权限/只读盘)。
365
+ * @returns 绝对目录路径。
366
+ */
367
+ async function ensureDefaultDirectory(cwd) {
368
+ const dir = resolvePath(cwd, DEFAULT_MINDMAP_DIR)
369
+ const rel = relative(cwd, dir)
370
+ if (escapesBase(rel) || !(await resolvesInsideBase(dir, cwd))) {
371
+ throw new Error(`Mindmap directory must stay inside the session working directory (${cwd}).`)
372
+ }
373
+ let info = await stat(dir).catch(() => null)
374
+ if (!info) {
375
+ const failure = await mkdir(dir, { recursive: true }).then(() => null, (error) => error)
376
+ info = await stat(dir).catch(() => null)
377
+ if (!info) {
378
+ // 并发创建下另一个调用可能刚建好(所以 stat 得到了结果);这里仍拿不到,
379
+ // 才是真失败——把 mkdir 的原始错误码带出去,别只报一句"建不出来"。
380
+ throw new Error(`Cannot create the default mindmap directory ${JSON.stringify(dir)}: ${String(failure?.message ?? 'it vanished right after creation')}`)
381
+ }
382
+ }
383
+ if (!info.isDirectory()) {
384
+ throw new Error(`Cannot create the default mindmap directory: ${JSON.stringify(dir)} exists and is not a directory.`)
385
+ }
386
+ return dir
387
+ }
388
+
389
+ /**
390
+ * 默认命名的候选主干:第 1 次原名,之后依次 `-2`、`-3`。
391
+ * 后缀规则的唯一出口,挑名字和写文件都走它,避免两处算法各写一遍就漂。
392
+ */
393
+ function stemForAttempt(stem, attempt) {
394
+ return attempt > 1 ? `${stem}-${attempt}` : stem
395
+ }
396
+
397
+ /**
398
+ * 收件箱里第一个没被占用的候选序号(纯探测,不建文件)。必须由**审批钩子**先跑一遍:
399
+ * 确认框里报出的路径若已被上一个同秒创建占用,用户点的就不是真正会写的那条,会话授权
400
+ * 也会登记到错文件上(036 并发一致性)。显式 `name` 不走这里——用户的命名意图优先,
401
+ * 撞名不能替他改名。
402
+ * @returns 候选序号(1 = 原名)。
403
+ */
404
+ async function firstFreeAttempt(directory, stem, maxAttempts = MAX_CREATE_ATTEMPTS) {
405
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
406
+ if (!(await pathExists(join(directory, `${stemForAttempt(stem, attempt)}.md`)))) return attempt
407
+ }
408
+ throw new Error(`Too many mindmaps already share ${JSON.stringify(stem)} in this second; give the description more detail.`)
409
+ }
410
+
411
+ /**
412
+ * 写入瞬间的路径复核(P1):审批只代表"用户同意往这条路径写",不是路径安全的
413
+ * 长期保证——等待确认期间目录可能被改名、原位换成指向 cwd 外的符号链接。审批
414
+ * 阶段的校验结论不能顶替落盘前的校验,每条候选都用当前文件系统状态重新解析。
415
+ * @returns 重解析后的绝对路径(写盘用这一份,不用审批阶段缓存的)。
416
+ */
417
+ async function resolveWriteTimeTarget(cwd, relativeTarget) {
418
+ try {
419
+ return await resolveMindmapPath(cwd, relativeTarget)
420
+ } catch (error) {
421
+ const detail = error instanceof Error ? error.message : String(error)
422
+ throw new Error(`Refusing to create the mindmap at ${JSON.stringify(relativeTarget)}: ${detail} The target directory may have changed while the write was being confirmed; start the create again.`)
423
+ }
424
+ }
425
+
426
+ /**
427
+ * 原子新建空脑图:`wx` 不存在才创建,挡掉已存在与同名目录,无 TOCTOU 窗口。
428
+ * 首选候选 `plan.relative`(= `stem` 第 `attempt` 号)——就是审批确认过的那条,
429
+ * 绝大多数情况一次即中。默认命名只有在极窄的竞态窗口里(探测到写盘之间被别人
430
+ * 抢注)才往后挪 -2、-3:覆盖别人的文件永远不可能发生,而挪了名之后授权由
431
+ * `actualCreates` 跟着纠正,工具结果里的 `path` 也始终是真正落盘的那条。
432
+ * 显式 `name` 只试一次、不改名。
433
+ * 每条候选落盘前都过 `resolveWriteTimeTarget`(P1):审批报的路径在确认期间被
434
+ * 换成越界符号链接时,这里拒写,绝不把文件建到工作区外面。
435
+ * @param {{relative: string, stem: string, attempt: number, autoNamed: boolean}} plan
436
+ * @returns 实际创建出来的绝对路径。
437
+ */
438
+ async function createMindmapFile(cwd, plan) {
439
+ const { stem, attempt, autoNamed } = plan
440
+ const relDirectory = dirname(plan.relative)
441
+ const planned = join(cwd, plan.relative)
442
+ const targetFor = (index) => resolveWriteTimeTarget(cwd, join(relDirectory, `${stemForAttempt(stem, index)}.md`))
443
+ if (!autoNamed) {
444
+ // 显式命名只试这一条:命名意图优先,撞名就报错让他去开那份旧的。
445
+ try {
446
+ const target = await targetFor(attempt)
447
+ await writeFile(target, '', { encoding: 'utf8', flag: 'wx' })
448
+ return target
449
+ } catch (error) {
450
+ if (error?.code === 'EEXIST' || error?.code === 'EISDIR') {
451
+ throw new Error(`Mindmap already exists: ${JSON.stringify(planned)}. Open it with mindmap_open instead.`)
452
+ }
453
+ throw error
454
+ }
455
+ }
456
+ for (let index = attempt; index <= MAX_CREATE_ATTEMPTS; index += 1) {
457
+ try {
458
+ const candidate = await targetFor(index)
459
+ await writeFile(candidate, '', { encoding: 'utf8', flag: 'wx' })
460
+ return candidate
461
+ } catch (error) {
462
+ if (error?.code !== 'EEXIST' && error?.code !== 'EISDIR') throw error
463
+ }
464
+ }
465
+ throw new Error(`Cannot create mindmap ${JSON.stringify(planned)}: every nearby suffix is already taken, give the description more detail.`)
466
+ }
467
+
293
468
  /**
294
469
  * 两个路径是否指向同一个文件(dev + inode 比较)。大小写不敏感 FS(macOS/
295
470
  * Windows)上仅大小写不同的路径命中同一文件——case-only 改名时据此区分
@@ -422,6 +597,9 @@ export function apply(ctx, config = {}) {
422
597
  // 自然释放,不把授权带到别的会话。
423
598
  let approvedTargets = new WeakMap()
424
599
  const pendingApprovals = new WeakMap()
600
+ // 实际写盘路径:默认命名在「审批到写盘」之间被别人抢注时会挪到下一个空闲后缀,
601
+ // 授权必须跟着记真实路径,不能把审批阶段的旧候选登记成本次会话的授权目标。
602
+ const actualCreates = new WeakMap()
425
603
  let lastMode
426
604
  const readApprovalMode = () => {
427
605
  const value = activeConfig()
@@ -458,23 +636,44 @@ export function apply(ctx, config = {}) {
458
636
  const id = exec?.agent?.id
459
637
  return id && ctx.sessions?.get ? ctx.sessions.get(id) ?? null : null
460
638
  }
639
+ // 036:一次 create 的路径计划只算一遍,审批钩子与 execute 共用(含同一个时间戳)。
640
+ // WeakMap 以 exec 为键,和 pendingApprovals 一样依赖「整个工具生命周期内 exec
641
+ // 对象稳定」这一宿主契约;取不到缓存时 execute 自行重算,最多多要一次确认,
642
+ // 不会把审批过的路径和写盘的路径搞混。
643
+ const createPlans = new WeakMap()
644
+ /**
645
+ * 定稿一次 create 的落盘路径:纯计划 → 权威路径校验(越界与符号链接在这里拒)→
646
+ * 默认命名避开已占用的名字 → 重算并再校验一次。顺序不能换:先校验才敢探测,
647
+ * 否则 `.mindmaps` 是指向外部的符号链接时,探测会把外面的目录当成候选清单读。
648
+ * 也不在这里建目录——用户可能当场拒绝,不能凭一次确认之前先落一只空目录。
649
+ */
650
+ const plannedCreate = async (exec, cwd, args) => {
651
+ const cached = createPlans.get(exec)
652
+ if (cached && cached.args === args) return cached.plan
653
+ const base = planCreatePaths(cwd, args ?? {})
654
+ const first = await resolveMindmapPath(cwd, base.relative)
655
+ // 顺序不能换:先过权威路径校验才敢探测。`.mindmaps` 若是指向外部的符号链接,
656
+ // 上面这一步已经拒了,不会把别人的目录当成候选清单来读。
657
+ const attempt = base.autoNamed ? await firstFreeAttempt(dirname(first), base.stem) : 1
658
+ const path = attempt === 1 ? first : await resolveMindmapPath(cwd, join(dirname(base.relative), `${stemForAttempt(base.stem, attempt)}.md`))
659
+ const plan = { ...base, attempt, path }
660
+ createPlans.set(exec, { args, plan })
661
+ return plan
662
+ }
461
663
  const targetOf = async (exec) => {
462
664
  const args = exec.arguments ?? {}
463
665
  const cwd = sessionCwd(exec, ctx.sessions)
464
- let raw
465
666
  if (exec.name === 'mindmap_create') {
466
667
  try {
467
- const stem = sanitizeStem(args.name)
468
- const directory = typeof args.directory === 'string' && args.directory.trim() ? args.directory.trim() : ''
469
- raw = join(directory, `${stem}.md`)
668
+ // 审批目标 = 校验过、且已避开占用名字的最终绝对路径:确认的就是真正会写的那条。
669
+ return (await plannedCreate(exec, cwd, args)).path
470
670
  } catch {
471
671
  // Let the tool return its normal argument error; approval lookup must
472
672
  // never turn malformed input into a hook-level exception.
473
- raw = typeof args.name === 'string' ? args.name.trim() : '?'
673
+ return `mindmap_create:${typeof args.name === 'string' ? args.name.trim() : '?'}`
474
674
  }
475
- } else {
476
- raw = typeof args.path === 'string' ? args.path.trim() : ''
477
675
  }
676
+ const raw = typeof args.path === 'string' ? args.path.trim() : ''
478
677
  if (cwd && raw) {
479
678
  try { return await resolveMindmapPath(cwd, raw) } catch { /* 工具本身负责报告参数错误 */ }
480
679
  }
@@ -515,9 +714,10 @@ export function apply(ctx, config = {}) {
515
714
  if (mode === 'session' && !highRisk && state?.paths.has(target)) return decision
516
715
  if (mode === 'session' && !highRisk && state) pendingApprovals.set(exec, { session, target, state, generation: state.generation })
517
716
  if (exec.name === 'mindmap_create') {
717
+ const title = String(target).split(/[\\/]/).pop()?.replace(/\.md$/i, '') ?? '?'
518
718
  return {
519
719
  kind: 'ask',
520
- reason: `Create mindmap ${JSON.stringify(String(args.name ?? '?'))} at ${JSON.stringify(target)}. ${mode === 'per-operation' ? 'Confirm this write.' : 'Confirm once for this document in the current session.'}`,
720
+ reason: `Create mindmap ${JSON.stringify(title)} at ${JSON.stringify(target)}. ${mode === 'per-operation' ? 'Confirm this write.' : 'Confirm once for this document in the current session.'}`,
521
721
  }
522
722
  }
523
723
  const renameNote = rename ? `, rename root to "${args.renameRoot}"` : ''
@@ -539,38 +739,36 @@ export function apply(ctx, config = {}) {
539
739
  if (readApprovalMode() !== 'session') return
540
740
  // 撤销或策略切换之后,尚未结束的旧调用不能重新恢复授权。
541
741
  if (approvedTargets.get(pending.session) !== pending.state || pending.state.generation !== pending.generation) return
542
- pending.state.paths.add(pending.target)
742
+ // 审批后被抢注、实际写到了 -2 的情形:授权记真实路径,不记用户没见过的那条。
743
+ const actual = actualCreates.get(exec)
744
+ if (actual) actualCreates.delete(exec)
745
+ pending.state.paths.add(actual ?? pending.target)
543
746
  })
544
747
 
545
748
  ctx.tools.register(defineTool({
546
749
  name: 'mindmap_create',
547
- description: 'Create a new mindmap markdown file <name>.md in the session working directory or an optional relative directory and show it in the mindmap panel. Fails if the file already exists. The filename becomes the root node title.',
750
+ description: `Create a new mindmap markdown file and show it in the mindmap panel. Fails if the file already exists. The filename becomes the root node title. Pass \`name\` when the user gave an explicit title, otherwise pass \`description\` and the file is auto-named YYYYMMDD-HHmmss-<description>.md inside the default mindmap inbox (${DEFAULT_MINDMAP_DIR}/) — the host picks the next free -2/-3 suffix when that name is already taken, so nothing is ever overwritten. Only pass \`directory\` when the user chose a location.`,
548
751
  parameters: {
549
752
  type: 'object',
550
753
  properties: {
551
- name: { type: 'string', description: 'Mindmap document name (without .md). Becomes the filename and the root node title.' },
552
- directory: { type: 'string', description: 'Optional directory relative to the session working directory. Use this when creating from a directory tree.' },
754
+ name: { type: 'string', description: 'Explicit mindmap document name (without .md). Becomes the filename and the root node title; a name collision is reported instead of auto-renaming. Omit it for a quick capture and pass `description` instead.' },
755
+ description: { type: 'string', description: `Short phrase for the auto-generated filename when \`name\` is omitted (e.g. 项目盘点). Cleaned and truncated to ${MAX_DESCRIPTION_CHARS} characters. Never put a date or time here — the host stamps the real current time.` },
756
+ directory: { type: 'string', description: `Directory relative to the session working directory, only when the user picked one (it must already exist). Omit it to file the mindmap in the default inbox ${DEFAULT_MINDMAP_DIR}/, which is created on first use.` },
553
757
  },
554
- required: ['name'],
758
+ required: [],
555
759
  },
556
760
  output: { schema: { type: 'string' }, render: (_args, value) => textOut(value) },
557
761
  timeoutMs: TOOL_TIMEOUT_MS,
558
762
  async execute(args, exec) {
559
763
  const cwd = sessionCwd(exec, ctx.sessions)
560
- if (!cwd) throw new Error('The session has no working directory; cannot create a mindmap.')
561
- const stem = sanitizeStem(args?.name)
562
- const directory = typeof args?.directory === 'string' && args.directory.trim() ? args.directory.trim() : ''
563
- const path = await resolveMindmapPath(cwd, join(directory, `${stem}.md`))
564
- // wx = 不存在才创建:原子拒绝已存在(含并发竞态)与同名目录,无 TOCTOU 窗口。
565
- try {
566
- await writeFile(path, '', { encoding: 'utf8', flag: 'wx' })
567
- } catch (error) {
568
- if (error && (error.code === 'EEXIST' || error.code === 'EISDIR')) {
569
- throw new Error(`Mindmap already exists: ${JSON.stringify(path)}. Open it with mindmap_open instead.`)
570
- }
571
- throw error
572
- }
573
- return buildResult('create', path, { content: '', created: true, revision: revisionOfContent('') })
764
+ const plan = await plannedCreate(exec, cwd, args)
765
+ // 默认收件箱按需建;显式目录沿用既有边界(不代建,越界与不存在都直接失败)。
766
+ if (plan.defaultDir) await ensureDefaultDirectory(cwd)
767
+ // 审批阶段的 plan 只能当作「确认过哪条路径」的备忘,写盘前由 createMindmapFile
768
+ // 重新解析校验,确认期间目录被掉包不会把文件写到工作区外。
769
+ const created = await createMindmapFile(cwd, plan)
770
+ actualCreates.set(exec, created)
771
+ return buildResult('create', created, { content: '', created: true, revision: revisionOfContent('') })
574
772
  },
575
773
  }))
576
774
 
@@ -743,9 +941,20 @@ export const internals = Object.freeze({
743
941
  normalizeApprovalMode,
744
942
  MAX_CONTENT_BYTES,
745
943
  MAX_READ_BYTES,
944
+ DEFAULT_MINDMAP_DIR,
945
+ MAX_DESCRIPTION_CHARS,
746
946
  readMindmap,
747
947
  writeMindmap,
748
948
  sanitizeStem,
949
+ sanitizeDescription,
950
+ timestampStamp,
951
+ defaultStem,
952
+ stemForAttempt,
953
+ firstFreeAttempt,
954
+ planCreatePaths,
955
+ ensureDefaultDirectory,
956
+ createMindmapFile,
957
+ resolveWriteTimeTarget,
749
958
  resolveMindmapPath,
750
959
  sessionCwd,
751
960
  sessionCwdOf,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mindmap",
3
- "version": "0.12.0",
3
+ "version": "0.13.1",
4
4
  "description": "Mindmap plugin for DeepSeek Harness: a plain markdown file in the working directory IS the mindmap; the chat edits it step by step and the right-side panel follows live.",
5
5
  "repository": {
6
6
  "type": "git",