dsh-relocate 0.0.0-stage → 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dsh-relocate contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.en.md ADDED
@@ -0,0 +1,68 @@
1
+ # dsh-relocate
2
+
3
+ Move a directory to another drive and leave a junction at the original path, so
4
+ programs that hard-code the old location keep working while the data lives
5
+ elsewhere.
6
+
7
+ Built for the everyday "my `C:\` keeps filling up" problem: `C:\Users\me\.dsh`
8
+ stays a valid path, but the bytes sit on `D:\`.
9
+
10
+ ## Install
11
+
12
+ In DSH: **Settings → Plugins → Add plugin**, enter
13
+
14
+ ```
15
+ dsh-relocate@1.0.1
16
+ ```
17
+
18
+ The bundle registers two Agent tools; no build step and no dependencies.
19
+
20
+ ## Tools
21
+
22
+ | Tool | Effect |
23
+ |---|---|
24
+ | `storage_audit` | Read-only. Lists known DSH data roots (real path, link kind, size, file count) and the free space of the volumes that actually hold them. |
25
+ | `storage_relocate` | Plans first; with `confirm: true` it copies, renames, links, and verifies. Existing targets are never overwritten, the original is kept as `<path>.old-<timestamp>`, and a failed step rolls back. |
26
+
27
+ ## Safety
28
+
29
+ - `$DSH_HOME`, the active profile, and the installation directory are refused
30
+ while the Host is running — their files are open, so they must be moved from a
31
+ terminal with DSH stopped.
32
+ - Copy failures leave the original untouched and remove the partial copy.
33
+ - Link creation failures restore the original directory.
34
+
35
+ ## Limits
36
+
37
+ - A directory held open by a running process cannot be moved (`EPERM`/`EBUSY`).
38
+ - Junctions are a Windows capability; other platforms fall back to a symlink.
39
+ - No "move back" button: delete the link and rename `.old-*` yourself.
40
+
41
+ ## Manual use
42
+
43
+ ```
44
+ storage_audit
45
+
46
+ storage_relocate
47
+ source: C:\Users\me\AppData\Roaming\@deepseek-ai
48
+ target: D:\workspaces\dsh\desktop-userdata
49
+
50
+ # then, after checking the plan
51
+ storage_relocate
52
+ source: C:\Users\me\AppData\Roaming\@deepseek-ai
53
+ target: D:\workspaces\dsh\desktop-userdata
54
+ confirm: true
55
+ ```
56
+
57
+ ## Changelog
58
+
59
+ - 1.0.1 — Chinese documentation; audit now measures through links and resolves the real volume.
60
+ - 1.0.0 — first release.
61
+
62
+ ## License
63
+
64
+ MIT
65
+
66
+ ---
67
+
68
+ 中文文档:[README.md](README.md)
package/README.md CHANGED
@@ -1,3 +1,85 @@
1
- # Temporary Holding Version
1
+ # dsh-relocate 目录搬家
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 把占用 C 盘的数据目录搬到其他盘,并在原路径留下**目录联接(junction)**,让所有写死旧路径的程序照常工作——旧路径还能读写,字节实际落在新盘。
4
+
5
+ 专治:“我的 C 盘又红了,但这个软件只会往 `C:\Users\...` 里写。”
6
+
7
+ ## 安装
8
+
9
+ 在 DSH 里:**设置 → 插件 → 添加插件**,填
10
+
11
+ ```
12
+ dsh-relocate@1.0.1
13
+ ```
14
+
15
+ 或直接对助手说「安装 dsh-relocate 插件」。
16
+
17
+ 装好后会多出两个工具:`storage_audit`、`storage_relocate`。
18
+
19
+ ## 两个工具
20
+
21
+ | 工具 | 性质 | 作用 |
22
+ |---|---|---|
23
+ | `storage_audit` | **只读** | 列出 DSH 各数据目录:真实位置、是否已是联接、占用体积、文件数,以及相关磁盘剩余空间 |
24
+ | `storage_relocate` | **会改动** | 迁移:默认只出计划;带 `confirm: true` 才真正执行 |
25
+
26
+ ## 怎么用
27
+
28
+ 先看清楚现状:
29
+
30
+ ```
31
+ 用 storage_audit 看看我的 C 盘数据都在哪
32
+ ```
33
+
34
+ 再迁移一个目录,先看计划:
35
+
36
+ ```
37
+ 把 C:\Users\me\AppData\Local\SomeApp\cache 搬到 D:\data\SomeApp-cache
38
+ ```
39
+
40
+ 确认无误后执行:
41
+
42
+ ```
43
+ 同上,confirm: true
44
+ ```
45
+
46
+ 工具会依次:**复制 → 原目录改名为 `<原路径>.old-<时间戳>` → 在原位置建联接 → 校验联接**。
47
+
48
+ ## 安全设计
49
+
50
+ - **不覆盖**:目标已存在直接拒绝;
51
+ - **不越界**:目标不能在源目录内部;
52
+ - **保护运行中的 DSH**:`$DSH_HOME`、当前 profile、安装目录一律拒绝,并提示先退出 DSH、在终端里迁移;
53
+ - **失败即回滚**:复制失败会删除自己创建的部分副本;改名或建联接失败会恢复原目录;
54
+ - **默认保留旧副本**(`keepOld: true`),出问题把 `.old-*` 改回原名即可。
55
+
56
+ ## 已知限制
57
+
58
+ - 被进程占用的目录无法复制(Windows 报 `EPERM`/`EBUSY`),请先关闭对应程序;
59
+ - 目录联接是 Windows 能力,其他平台退化为符号链接;
60
+ - 没有“搬回来”按钮:需要时删除联接、把 `.old-*` 改回原名;
61
+ - 工具只报告剩余空间,不会替你判断目标盘够不够。
62
+
63
+ ## 常见问题
64
+
65
+ **Q:DSH 自己的 `.dsh` 目录能搬吗?**
66
+ 不能,在 DSH 运行时文件是打开的。要先退出 DSH,在终端里用脚本迁移,然后从新位置启动。本仓库的姊妹插件 `dsh-memory` 就是这种迁移之后继续工作的例子。
67
+
68
+ **Q:搬完程序找不到数据?**
69
+ 检查原路径是不是联接:`storage_audit` 会显示 `[junction] -> 目标路径`。如果显示普通目录,说明迁移没完成。
70
+
71
+ **Q:会不会把数据弄丢?**
72
+ 复制成功之前不会动原目录;复制成功后才改名并建联接;失败会回滚。默认还会保留一份 `.old-*`。
73
+
74
+ ## 版本
75
+
76
+ - 1.0.1 — 增加中文文档,修正审计对联接目录的统计与卷信息解析
77
+ - 1.0.0 — 首次发布
78
+
79
+ ## License
80
+
81
+ MIT
82
+
83
+ ---
84
+
85
+ English documentation: [README.en.md](README.en.md)
@@ -0,0 +1,4 @@
1
+ - insert:
2
+ - id: dsh-relocate
3
+ name: 'dsh-relocate'
4
+ config: {}
package/docs/DETAIL.md ADDED
@@ -0,0 +1,56 @@
1
+ # 目录搬家
2
+
3
+ 解决「C 盘被某个程序塞满,但它写死了路径」这个常见问题。
4
+
5
+ 原理只有一句话:**数据搬到别的盘,原路径留一个目录联接(junction)**。旧路径继续可读写,实际字节落在新盘。
6
+
7
+ ## 两个工具
8
+
9
+ | 工具 | 性质 | 作用 |
10
+ |---|---|---|
11
+ | `storage_audit` | 只读 | 列出 DSH 各数据目录的真实位置、是否已是联接、占用大小,以及相关磁盘剩余空间 |
12
+ | `storage_relocate` | 会改动 | 预约迁移:默认只出计划;`confirm: true` 才执行 |
13
+
14
+ ## 迁移步骤
15
+
16
+ 1. `storage_audit` 先看清楚现状;
17
+ 2. `storage_relocate { source, target }` 不带 `confirm` —— 只报告体积和计划;
18
+ 3. 确认无误后带 `confirm: true`:
19
+ - 复制到目标;
20
+ - 原目录改名为 `<原路径>.old-<时间戳>`;
21
+ - 在原名建目录联接;
22
+ - 验证联接成功。
23
+ 4. 验证程序一切正常后,删除 `.old-*` 备份。
24
+
25
+ ## 安全设计
26
+
27
+ - **不覆盖**:目标已存在直接拒绝;
28
+ - **不越界**:目标不能在源目录内部;
29
+ - **保护运行中的 DSH**:`$DSH_HOME`、当前 profile、安装目录一律拒绝,提示先退出再迁移;
30
+ - **失败即回滚**:复制失败删除自己创建的部分副本;改名或建联接失败恢复原目录;
31
+ - **默认保留旧副本**:`keepOld: true`,出问题可直接改名还原。
32
+
33
+ ## 已知限制
34
+
35
+ - 被进程占用的文件无法复制(Windows 会报 EPERM/EBUSY);请先关闭对应程序;
36
+ - 目录联接是 Windows 能力,其他平台退化为符号链接;
37
+ - 不提供「搬回来」按钮:需要时手动删除联接、把 `.old-*` 改回原名;
38
+ - 迁移前请确认目标盘有足够空间,工具只报告剩余空间,不会替你判断。
39
+
40
+ ## 典型用法
41
+
42
+ ```text
43
+ storage_audit
44
+
45
+ storage_relocate
46
+ source: C:\Users\me\AppData\Roaming\@deepseek-ai
47
+ target: D:\workspaces\dsh\desktop-userdata
48
+
49
+ # 确认后
50
+ storage_relocate
51
+ source: C:\Users\me\AppData\Roaming\@deepseek-ai
52
+ target: D:\workspaces\dsh\desktop-userdata
53
+ confirm: true
54
+ ```
55
+
56
+ `$DSH_HOME` 本身(含会话、profile、插件)不能在运行中搬:先在终端做一次,之后 DSH 从新位置启动。
package/icon.svg ADDED
@@ -0,0 +1,13 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="Directory relocation">
2
+ <defs>
3
+ <linearGradient id="rg" x1="0" y1="0" x2="1" y2="1">
4
+ <stop offset="0" stop-color="#0ea5e9"/>
5
+ <stop offset="1" stop-color="#14b8a6"/>
6
+ </linearGradient>
7
+ </defs>
8
+ <rect x="4" y="4" width="56" height="56" rx="14" fill="url(#rg)"/>
9
+ <path d="M13 24h16v6h-16z" fill="none" stroke="#ffffff" stroke-width="2.4" stroke-linejoin="round"/>
10
+ <path d="M12 18h13l3 4h13v20H12z" fill="none" stroke="#ffffff" stroke-width="2.4" stroke-linejoin="round"/>
11
+ <path d="M34 38h14" fill="none" stroke="#ffffff" stroke-width="2.6" stroke-linecap="round"/>
12
+ <path d="M44 33l5 5-5 5" fill="none" stroke="#ffffff" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"/>
13
+ </svg>
package/index.js ADDED
@@ -0,0 +1,466 @@
1
+ /**
2
+ * dsh-relocate — move a directory to another drive and leave a junction behind.
3
+ *
4
+ * Many applications hard-code `C:\Users\<name>\...`. When that drive fills up,
5
+ * the usual answer is a copy plus a junction: the original path keeps working
6
+ * (every read and write follows the link), while the bytes live on another
7
+ * drive. This plugin exposes that operation as two Agent tools:
8
+ *
9
+ * storage_audit read-only: what is where, how large, and what is free
10
+ * storage_relocate dry-run by default; moves a directory and links it back
11
+ *
12
+ * Safety rules the tools enforce:
13
+ * - the DSH home and the active profile are never relocated while running;
14
+ * - an existing target is never overwritten;
15
+ * - the original directory is kept as `<path>.old-<timestamp>` for rollback;
16
+ * - a failed copy leaves the original untouched and removes its own partial copy;
17
+ * - platform-specific link creation (junction on Windows, symlink elsewhere).
18
+ *
19
+ * @module @local/dsh-relocate
20
+ */
21
+
22
+ import fs from 'node:fs'
23
+ import fsp from 'node:fs/promises'
24
+ import { homedir } from 'node:os'
25
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'
26
+
27
+ export const name = 'dsh-relocate'
28
+
29
+ /** The tool registry is the only service needed; everything else is filesystem work. */
30
+ export const inject = ['tools']
31
+
32
+ const MB = 1024 * 1024
33
+
34
+ function textResult(text) {
35
+ return [{ type: 'text', text }]
36
+ }
37
+
38
+ function human(bytes) {
39
+ if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'
40
+ if (bytes < 1024) return `${bytes} B`
41
+ if (bytes < MB) return `${(bytes / 1024).toFixed(1)} KB`
42
+ if (bytes < 1024 * MB) return `${(bytes / MB).toFixed(1)} MB`
43
+ return `${(bytes / (1024 * MB)).toFixed(2)} GB`
44
+ }
45
+
46
+ function isDirectory(path) {
47
+ try {
48
+ return fs.statSync(path).isDirectory()
49
+ } catch {
50
+ return false
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Describe one path: link kind, target, size, file count.
56
+ *
57
+ * A link is measured through its target on purpose: the question the audit
58
+ * answers is "how much space does this data occupy", not "how much does the
59
+ * link itself weigh".
60
+ */
61
+ async function describe(path) {
62
+ let info
63
+ try {
64
+ info = await fsp.lstat(path)
65
+ } catch (error) {
66
+ return { path, exists: false, error: error.code ?? 'EXISTS_CHECK_FAILED' }
67
+ }
68
+ const linkTarget = info.isSymbolicLink() ? (fs.readlinkSync(path, { encoding: 'utf8' })) : null
69
+ let kind = 'directory'
70
+ if (info.isSymbolicLink()) {
71
+ kind = linkTarget && linkTarget.toLowerCase().includes('\\') ? 'junction' : 'symlink'
72
+ }
73
+ const measured = linkTarget && isDirectory(linkTarget)
74
+ ? await measure(linkTarget)
75
+ : info.isSymbolicLink() ? { bytes: 0, files: 0 } : await measure(path)
76
+ return {
77
+ path,
78
+ exists: true,
79
+ kind,
80
+ linkTarget,
81
+ measuredPath: linkTarget && isDirectory(linkTarget) ? linkTarget : path,
82
+ bytes: measured.bytes,
83
+ files: measured.files,
84
+ }
85
+ }
86
+
87
+ /** Sum file sizes under `dir` without following links (so a junction is not re-counted). */
88
+ async function measure(dir) {
89
+ let bytes = 0
90
+ let files = 0
91
+ let entries
92
+ try {
93
+ entries = await fsp.readdir(dir, { withFileTypes: true })
94
+ } catch {
95
+ return { bytes, files }
96
+ }
97
+ for (const entry of entries) {
98
+ const full = join(dir, entry.name)
99
+ if (entry.isSymbolicLink()) continue
100
+ if (entry.isDirectory()) {
101
+ const nested = await measure(full)
102
+ bytes += nested.bytes
103
+ files += nested.files
104
+ continue
105
+ }
106
+ if (entry.isFile()) {
107
+ try {
108
+ const stat = await fsp.stat(full)
109
+ bytes += stat.size
110
+ files += 1
111
+ } catch {
112
+ // Unreadable file: skip it rather than fail the whole measurement.
113
+ }
114
+ }
115
+ }
116
+ return { bytes, files }
117
+ }
118
+
119
+ /** Free and total bytes for the volume holding `path`. */
120
+ function volumeOf(path) {
121
+ try {
122
+ const stat = fs.statfsSync(path)
123
+ return {
124
+ totalBytes: Number(stat.bsize) * Number(stat.blocks),
125
+ freeBytes: Number(stat.bsize) * Number(stat.bavail),
126
+ }
127
+ } catch {
128
+ return null
129
+ }
130
+ }
131
+
132
+ /** Curated DSH data roots, resolved from the live environment. */
133
+ function knownRoots(configured) {
134
+ if (Array.isArray(configured) && configured.length > 0) {
135
+ return configured.map((entry) => ({ name: String(entry.name ?? basename(String(entry.path))), path: resolve(String(entry.path)) }))
136
+ }
137
+ const home = process.env.DSH_HOME?.trim()
138
+ ? resolve(process.env.DSH_HOME.trim())
139
+ : join(homedir(), '.dsh')
140
+ const appData = process.env.APPDATA
141
+ const localAppData = process.env.LOCALAPPDATA
142
+ const roots = [
143
+ { name: 'DSH home (sessions, profiles, plugins)', path: home },
144
+ { name: 'Default workspace data (junction target)', path: join(home, 'im') },
145
+ ]
146
+ if (appData) roots.push({ name: 'Desktop app data', path: join(appData, '@deepseek-ai') })
147
+ if (localAppData) roots.push({ name: 'Updater cache', path: join(localAppData, '@deepseek-aidsh-desktop-updater') })
148
+ return roots
149
+ }
150
+
151
+ /** Paths that must never be relocated while this Host is running. */
152
+ function protectedPaths() {
153
+ const list = []
154
+ const home = process.env.DSH_HOME?.trim()
155
+ ? resolve(process.env.DSH_HOME.trim())
156
+ : join(homedir(), '.dsh')
157
+ list.push(resolve(home))
158
+ if (process.env.DSH_PROFILE_DIR) list.push(resolve(process.env.DSH_PROFILE_DIR))
159
+ if (process.env.DSH_INSTALL_DIR) list.push(resolve(process.env.DSH_INSTALL_DIR))
160
+ return list
161
+ }
162
+
163
+ function overlapsProtected(source) {
164
+ const sourcePath = resolve(source)
165
+ for (const guarded of protectedPaths()) {
166
+ if (sourcePath === guarded) return guarded
167
+ const prefix = guarded.endsWith('\\') || guarded.endsWith('/') ? guarded : `${guarded}${'\\'}`
168
+ if (sourcePath.startsWith(prefix)) return guarded
169
+ }
170
+ return null
171
+ }
172
+
173
+ export function apply(ctx, rawConfig = {}) {
174
+ const config = { ...rawConfig }
175
+ const roots = () => knownRoots(config.roots)
176
+
177
+ const auditTool = {
178
+ name: 'storage_audit',
179
+ description:
180
+ 'Report where DeepSeek Harness data actually lives: each known data root, whether it is a '
181
+ + 'junction pointing elsewhere, how much space it occupies, and the free space of the '
182
+ + 'volumes involved. Read-only; use it before deciding to relocate anything.',
183
+ parameters: {
184
+ type: 'object',
185
+ additionalProperties: false,
186
+ properties: {
187
+ paths: {
188
+ type: 'array',
189
+ description: 'Optional extra absolute directories to report on.',
190
+ items: { type: 'string' },
191
+ },
192
+ },
193
+ },
194
+ output: {
195
+ schema: {
196
+ type: 'object',
197
+ additionalProperties: false,
198
+ required: ['roots', 'volumes'],
199
+ properties: {
200
+ roots: {
201
+ type: 'array',
202
+ items: {
203
+ type: 'object',
204
+ additionalProperties: false,
205
+ required: ['name', 'path', 'exists', 'kind', 'bytes', 'files'],
206
+ properties: {
207
+ name: { type: 'string' },
208
+ path: { type: 'string' },
209
+ exists: { type: 'boolean' },
210
+ kind: { type: 'string' },
211
+ linkTarget: { type: 'string' },
212
+ bytes: { type: 'number' },
213
+ files: { type: 'number' },
214
+ },
215
+ },
216
+ },
217
+ volumes: {
218
+ type: 'array',
219
+ items: {
220
+ type: 'object',
221
+ additionalProperties: false,
222
+ required: ['name', 'path', 'freeBytes', 'totalBytes'],
223
+ properties: {
224
+ name: { type: 'string' },
225
+ path: { type: 'string' },
226
+ freeBytes: { type: 'number' },
227
+ totalBytes: { type: 'number' },
228
+ },
229
+ },
230
+ },
231
+ },
232
+ },
233
+ render: (_args, value) => {
234
+ const lines = value.roots.map((entry) => {
235
+ if (!entry.exists) return `- ${entry.name}: ${entry.path} (missing)`
236
+ const where = entry.linkTarget ? ` -> ${entry.linkTarget}` : ''
237
+ return `- ${entry.name}: ${entry.path} [${entry.kind}]${where} ${human(entry.bytes)} / ${entry.files} files`
238
+ })
239
+ const volumes = value.volumes.map((v) => `- ${v.name}: ${human(v.freeBytes)} free of ${human(v.totalBytes)}`)
240
+ return textResult(['Data roots:', ...lines, '', 'Volumes:', ...volumes].join('\n'))
241
+ },
242
+ },
243
+ async execute(args) {
244
+ const extras = Array.isArray(args?.paths) ? args.paths.filter((p) => typeof p === 'string' && isAbsolute(p)) : []
245
+ const targets = [...roots(), ...extras.map((p) => ({ name: basename(p), path: resolve(p) }))]
246
+ const entries = []
247
+ const volumes = []
248
+ const seenVolume = new Set()
249
+ for (const target of targets) {
250
+ const info = await describe(target.path)
251
+ entries.push({
252
+ name: target.name,
253
+ path: target.path,
254
+ exists: info.exists,
255
+ kind: info.kind ?? 'missing',
256
+ ...(info.linkTarget ? { linkTarget: info.linkTarget } : {}),
257
+ bytes: info.bytes ?? 0,
258
+ files: info.files ?? 0,
259
+ })
260
+ // Report the volume that actually holds the bytes, not the one the
261
+ // old path strings still mention: resolve the link/junction chain first,
262
+ // then read that volume's free space.
263
+ const realPath = info.measuredPath ?? target.path
264
+ const resolved = await fsp.realpath(realPath).catch(() => realPath)
265
+ const volumeStats = volumeOf(dirname(resolved))
266
+ if (!volumeStats) continue
267
+ const drive = /^[A-Za-z]:/.exec(resolved)?.[0]?.toUpperCase()
268
+ const key = drive ?? dirname(resolved)
269
+ if (seenVolume.has(key)) continue
270
+ seenVolume.add(key)
271
+ volumes.push({ name: drive ? drive.replace(':', '') : key, path: resolved, ...volumeStats })
272
+ }
273
+ return { roots: entries, volumes }
274
+ },
275
+ }
276
+
277
+ const relocateTool = {
278
+ name: 'storage_relocate',
279
+ description:
280
+ 'Move an existing directory to another drive and leave a link at the original path, so every '
281
+ + 'program that hard-codes the old path keeps working while the bytes live on the new drive. '
282
+ + 'Runs as a plan only unless confirm is true. The original directory is preserved as '
283
+ + '`<path>.old-<timestamp>` for rollback, and an existing target is never overwritten. '
284
+ + 'A directory that is open by a running process cannot be moved: close the program and retry.',
285
+ parameters: {
286
+ type: 'object',
287
+ additionalProperties: false,
288
+ required: ['source', 'target'],
289
+ properties: {
290
+ source: {
291
+ type: 'string',
292
+ description: 'Absolute directory to relocate, for example C:\\Users\\me\\AppData\\Roaming\\@deepseek-ai.',
293
+ },
294
+ target: {
295
+ type: 'string',
296
+ description: 'Absolute destination directory that will hold the data.',
297
+ },
298
+ confirm: {
299
+ type: 'boolean',
300
+ description: 'Must be true to perform the move; false only reports the plan.',
301
+ },
302
+ keepOld: {
303
+ type: 'boolean',
304
+ description: 'Keep <source>.old-<timestamp> after success; defaults to true for rollback.',
305
+ },
306
+ },
307
+ },
308
+ output: {
309
+ schema: {
310
+ type: 'object',
311
+ additionalProperties: false,
312
+ required: ['source', 'target', 'planned', 'performed'],
313
+ properties: {
314
+ source: { type: 'string' },
315
+ target: { type: 'string' },
316
+ planned: { type: 'boolean' },
317
+ performed: { type: 'boolean' },
318
+ bytes: { type: 'number' },
319
+ files: { type: 'number' },
320
+ linkKind: { type: 'string' },
321
+ rollbackDir: { type: 'string' },
322
+ warning: { type: 'string' },
323
+ },
324
+ },
325
+ render: (_args, value) => {
326
+ if (!value.performed) {
327
+ return textResult([
328
+ `Plan only (confirm was false): ${value.source} -> ${value.target}`,
329
+ `Payload: ${human(value.bytes)} / ${value.files} files.`,
330
+ value.warning ? `Note: ${value.warning}` : '',
331
+ 'Re-run with confirm: true to perform the move.',
332
+ ].filter(Boolean).join('\n'))
333
+ }
334
+ return textResult([
335
+ `Relocated ${value.source} -> ${value.target}`,
336
+ `Payload: ${human(value.bytes)} / ${value.files} files; link: ${value.linkKind}.`,
337
+ value.rollbackDir ? `Rollback copy kept at ${value.rollbackDir}.` : 'Original copy removed.',
338
+ value.warning ? `Note: ${value.warning}` : '',
339
+ ].filter(Boolean).join('\n'))
340
+ },
341
+ },
342
+ async execute(args, exec) {
343
+ const source = resolve(String(args.source))
344
+ const target = resolve(String(args.target))
345
+ const confirm = args.confirm === true
346
+ const keepOld = args.keepOld !== false
347
+
348
+ if (!isAbsolute(String(args.source)) || !isAbsolute(String(args.target))) {
349
+ throw new Error('source and target must be absolute paths')
350
+ }
351
+ if (!isDirectory(source)) throw new Error(`source is not an existing directory: ${source}`)
352
+ const info = await fsp.lstat(source)
353
+ if (info.isSymbolicLink()) throw new Error(`source is already linked to ${fs.readlinkSync(source)}; nothing to do`)
354
+ if (resolve(target).startsWith(`${source}${'\\'}`) || resolve(target).startsWith(`${source}/`)) {
355
+ throw new Error('target must not be inside source')
356
+ }
357
+ if (isDirectory(target) || fs.existsSync(target)) {
358
+ throw new Error(`target already exists: ${target}`)
359
+ }
360
+ const guarded = overlapsProtected(source)
361
+ if (guarded) {
362
+ throw new Error(
363
+ `refusing to relocate ${source}: it belongs to the running Harness (${guarded}). `
364
+ + 'Quit DSH first and run the migration script from a terminal instead.',
365
+ )
366
+ }
367
+
368
+ const measured = await measure(source)
369
+ const plan = {
370
+ source,
371
+ target,
372
+ planned: true,
373
+ performed: false,
374
+ bytes: measured.bytes,
375
+ files: measured.files,
376
+ }
377
+ if (!confirm) {
378
+ return { ...plan, warning: `target volume has ${human(volumeOf(dirname(target))?.freeBytes ?? 0)} free` }
379
+ }
380
+ if (exec?.signal?.aborted) throw new Error('cancelled before the move started')
381
+
382
+ await fsp.mkdir(dirname(target), { recursive: true })
383
+ let copied = false
384
+ try {
385
+ await fsp.cp(source, target, {
386
+ recursive: true,
387
+ errorOnExist: false,
388
+ force: false,
389
+ preserveTimestamps: true,
390
+ verbatimSymlinks: true,
391
+ })
392
+ copied = true
393
+ } catch (error) {
394
+ if (copied) await fsp.rm(target, { recursive: true, force: true }).catch(() => {})
395
+ throw new Error(
396
+ `copy failed: ${error?.code ?? error?.message}. Nothing was changed. `
397
+ + 'If the directory is open by a running program, close it and retry.',
398
+ )
399
+ }
400
+
401
+ const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 15)
402
+ const rollbackDir = `${source}.old-${stamp}`
403
+ try {
404
+ await fsp.rename(source, rollbackDir)
405
+ } catch (error) {
406
+ await fsp.rm(target, { recursive: true, force: true }).catch(() => {})
407
+ throw new Error(`could not detach the original directory: ${error?.code ?? error?.message}. Nothing was changed.`)
408
+ }
409
+
410
+ const linkKind = process.platform === 'win32' ? 'junction' : 'symlink'
411
+ try {
412
+ await fsp.symlink(target, source, linkKind === 'junction' ? 'junction' : 'dir')
413
+ } catch (error) {
414
+ await fsp.rename(rollbackDir, source).catch(() => {})
415
+ await fsp.rm(target, { recursive: true, force: true }).catch(() => {})
416
+ throw new Error(`could not create the ${linkKind}: ${error?.code ?? error?.message}. Original restored.`)
417
+ }
418
+
419
+ const created = await fsp.lstat(source)
420
+ if (!created.isSymbolicLink()) throw new Error('link verification failed; original kept in ' + rollbackDir)
421
+
422
+ if (!keepOld) {
423
+ await fsp.rm(rollbackDir, { recursive: true, force: true }).catch(() => {})
424
+ }
425
+
426
+ return {
427
+ source,
428
+ target,
429
+ planned: true,
430
+ performed: true,
431
+ bytes: measured.bytes,
432
+ files: measured.files,
433
+ linkKind,
434
+ ...(keepOld ? { rollbackDir } : {}),
435
+ }
436
+ },
437
+ presentCall(args) {
438
+ return { card: 'generic', title: 'Relocate a directory', kind: 'other', rawInput: args }
439
+ },
440
+ }
441
+
442
+ const disposers = [
443
+ ctx.tools.register(auditTool),
444
+ ctx.tools.register(relocateTool),
445
+ ]
446
+
447
+ return ctx.effect(() => () => {
448
+ for (const dispose of disposers) {
449
+ try {
450
+ dispose?.()
451
+ } catch {
452
+ // Teardown must not throw.
453
+ }
454
+ }
455
+ })
456
+ }
457
+
458
+ /** Exported for tests: resolve the curated root list without a Cordis context. */
459
+ export function defaultRoots() {
460
+ return knownRoots(undefined)
461
+ }
462
+
463
+ /** Exported for tests: whether a path belongs to the running Harness. */
464
+ export function isProtectedPath(path) {
465
+ return overlapsProtected(path) !== null
466
+ }
package/locale/en.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Directory relocation",
4
+ "description": "Move a data directory off the system drive and leave a junction at the original path, so programs that hard-code the old location keep working. It ships a read-only storage audit and a relocation tool that plans first, then copies, renames, links, and keeps a rollback copy.",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "目录搬家",
4
+ "description": "把占用 C 盘的数据目录搬到其他盘,并在原路径留下目录联接,让所有写死旧路径的程序照常工作。提供存储审计与迁移两个工具:审计只读,迁移默认只出计划,确认后才复制、改名、建联接,并保留可回滚的旧副本。",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "dsh-relocate",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "Move a directory to another drive and leave a junction at the original path, so programs that hard-code C:\\ keep working while the data lives elsewhere. 把占用 C 盘的数据目录搬到其他盘,原路径留目录联接。",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "keywords": [
8
+ "dsh",
9
+ "dsh-plugin",
10
+ "deepseek-harness",
11
+ "disk-space",
12
+ "junction",
13
+ "symlink",
14
+ "migration"
15
+ ],
16
+ "exports": {
17
+ ".": "./index.js",
18
+ "./locale/*.json": "./locale/*.json",
19
+ "./icon": "./icon.svg"
20
+ },
21
+ "files": [
22
+ "index.js",
23
+ "cordis.patch.yml",
24
+ "locale/*.json",
25
+ "docs",
26
+ "icon.svg",
27
+ "README.md",
28
+ "README.en.md",
29
+ "LICENSE"
30
+ ],
31
+ "engines": {
32
+ "node": ">=22.16"
33
+ },
34
+ "dsh": {
35
+ "bundle": {
36
+ "patch": "./cordis.patch.yml"
37
+ }
38
+ }
39
+ }