dsh-coexist-cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,319 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ runCheck,
4
+ runPlan,
5
+ runApply,
6
+ runRollback,
7
+ runReport,
8
+ runList,
9
+ runAudit,
10
+ runBackups,
11
+ runPrefer,
12
+ } from '../src/commands.js'
13
+ import {
14
+ renderGraph,
15
+ renderPlan,
16
+ renderApply,
17
+ renderRollback,
18
+ renderReport,
19
+ renderList,
20
+ renderAudit,
21
+ renderBackups,
22
+ renderInstall,
23
+ renderUninstall,
24
+ renderMatrix,
25
+ renderDesktopPlan,
26
+ renderDesktopInstall,
27
+ renderDesktopRestore,
28
+ renderDesktopStatus,
29
+ renderDesktopLog,
30
+ } from '../src/report.js'
31
+ import { installPlugin, uninstallPlugin, buildMatrix } from '../src/installer.js'
32
+ import { freePort } from '../src/ports.js'
33
+ import { fileURLToPath } from 'node:url'
34
+ import { parseRunArgs, runDsh, RUN_HELP } from '../src/launcher.js'
35
+ import {
36
+ parseDesktopArgs,
37
+ installDesktop,
38
+ restoreDesktop,
39
+ desktopStatus,
40
+ desktopLog,
41
+ DESKTOP_HELP,
42
+ } from '../src/desktop.js'
43
+
44
+ const HELP = `dsh-coexist <check|plan|apply|rollback|report|list|audit|backups|prefer|free-port|run|desktop|install|uninstall|matrix> [options]
45
+
46
+ check scan the profile and report coexistence conflicts (default)
47
+ plan print the repair plan without writing anything
48
+ apply apply the plan (requires --yes)
49
+ rollback restore the latest backup, or one selected with --id
50
+ report read the runtime report written by the plugin
51
+ list list installed bundles and detected resources
52
+ audit read the local audit log
53
+ backups list backup ids
54
+ prefer move a bundle to the front so it keeps the original name on conflicts
55
+ free-port show or kill the process listening on a port (--yes to kill)
56
+ run boot DSH with the coexist preload (see: dsh-coexist run --help)
57
+ desktop install/restore the DSH desktop shortcut wrapper
58
+ install install a plugin into the profile (auto version check + rollback)
59
+ uninstall remove a plugin from the profile
60
+ matrix show host/plugin version compatibility for every installed plugin
61
+
62
+ Options:
63
+ --home <dir> DSH_HOME (default: $DSH_HOME or ~/.dsh)
64
+ --profile <name> profile name (default: desktop when it exists, otherwise web)
65
+ --json print JSON
66
+ --yes apply without the dry-run confirmation
67
+ --no-port-scan skip probing declared ports
68
+ --no-log-scan skip scanning DSH logs for historical errors
69
+ --no-source-scan skip scanning plugin sources for command/provider/slot/lock conflicts
70
+ --log <file> scan a specific log file
71
+ --allow-peer-override write controlled peer overrides (requires reinstall)
72
+ --app <file> path to the DSH desktop executable (auto-detected by default)
73
+ --dsh-version <v> override the detected DSH version
74
+ --self install the bundled dsh-coexist-plugin
75
+ --force install even if the version check fails
76
+ --dry-run for install: check only, write nothing
77
+ --plan <id> apply a saved plan (default: latest)
78
+ --id <id> rollback a specific backup id
79
+ --limit <n> audit entries to show (default 20)
80
+ --dump-config also run DSH --dump-config as a preflight
81
+ --reinstall after rollback, reinstall dependencies from the restored lockfile
82
+ --purge for uninstall: also remove ~/.dsh/coexist (backups, reports, config)
83
+ --no-diff skip the plan file preview
84
+ -h, --help show this help
85
+ `
86
+
87
+ function parseArgs(argv) {
88
+ const options = { command: 'check', positional: [] }
89
+ let commandSet = false
90
+
91
+ for (let index = 0; index < argv.length; index += 1) {
92
+ const arg = argv[index]
93
+ if (arg === '--home') options.home = argv[++index]
94
+ else if (arg === '--profile') options.profile = argv[++index]
95
+ else if (arg === '--json') options.json = true
96
+ else if (arg === '--yes') options.yes = true
97
+ else if (arg === '--no-port-scan') options.scanPorts = false
98
+ else if (arg === '--no-log-scan') options.scanLogs = false
99
+ else if (arg === '--no-source-scan') options.scanSources = false
100
+ else if (arg === '--log') options.logFile = argv[++index]
101
+ else if (arg === '--allow-peer-override') options.allowPeerOverride = true
102
+ else if (arg === '--app') options.app = argv[++index]
103
+ else if (arg === '--dsh-version') options.dshVersion = argv[++index]
104
+ else if (arg === '--self') options.self = true
105
+ else if (arg === '--force') options.force = true
106
+ else if (arg === '--dry-run') options.dryRun = true
107
+ else if (arg === '--plan') options.planId = argv[++index]
108
+ else if (arg === '--id') options.id = argv[++index]
109
+ else if (arg === '--limit') options.limit = Number(argv[++index])
110
+ else if (arg === '--dump-config') options.dumpConfig = true
111
+ else if (arg === '--reinstall') options.reinstall = true
112
+ else if (arg === '--purge') options.purge = true
113
+ else if (arg === '--no-diff') options.diff = false
114
+ else if (arg === '--help' || arg === '-h') options.help = true
115
+ else if (!arg.startsWith('-') && !commandSet) {
116
+ options.command = arg
117
+ commandSet = true
118
+ } else if (!arg.startsWith('-')) options.positional.push(arg)
119
+ }
120
+
121
+ return options
122
+ }
123
+
124
+ async function main() {
125
+ if (process.argv[2] === 'run') {
126
+ const runOptions = parseRunArgs(process.argv.slice(3))
127
+ if (runOptions.help) {
128
+ console.log(RUN_HELP)
129
+ return
130
+ }
131
+ const code = await runDsh(runOptions)
132
+ if (typeof code === 'number' && code !== 0) process.exitCode = code
133
+ return
134
+ }
135
+
136
+ if (process.argv[2] === 'desktop') {
137
+ const desktopOptions = parseDesktopArgs(process.argv.slice(3))
138
+ if (desktopOptions.help) {
139
+ console.log(DESKTOP_HELP)
140
+ return
141
+ }
142
+
143
+ if (desktopOptions.action === 'install') {
144
+ const result = await installDesktop(desktopOptions)
145
+ if (!result.applied) {
146
+ console.log(renderDesktopPlan(result))
147
+ if (result.needsConfirm) {
148
+ console.log('')
149
+ console.log('Dry run only. Re-run with --yes to apply.')
150
+ }
151
+ return
152
+ }
153
+ console.log(renderDesktopInstall(result))
154
+ return
155
+ }
156
+
157
+ if (desktopOptions.action === 'restore') {
158
+ console.log(renderDesktopRestore(await restoreDesktop(desktopOptions)))
159
+ return
160
+ }
161
+
162
+ if (desktopOptions.action === 'status') {
163
+ console.log(renderDesktopStatus(await desktopStatus(desktopOptions)))
164
+ return
165
+ }
166
+
167
+ if (desktopOptions.action === 'log') {
168
+ console.log(renderDesktopLog(await desktopLog(desktopOptions)))
169
+ return
170
+ }
171
+
172
+ console.error(`Unknown desktop action: ${desktopOptions.action}`)
173
+ console.log(DESKTOP_HELP)
174
+ process.exitCode = 1
175
+ return
176
+ }
177
+
178
+ const options = parseArgs(process.argv.slice(2))
179
+
180
+ if (options.help) {
181
+ console.log(HELP)
182
+ return
183
+ }
184
+
185
+ if (options.command === 'check') {
186
+ const { graph } = await runCheck(options)
187
+ console.log(options.json ? JSON.stringify(graph, null, 2) : renderGraph(graph))
188
+ return
189
+ }
190
+
191
+ if (options.command === 'plan') {
192
+ const { plan } = await runPlan(options)
193
+ console.log(options.json ? JSON.stringify(plan, null, 2) : renderPlan(plan))
194
+ return
195
+ }
196
+
197
+ if (options.command === 'apply') {
198
+ const result = await runApply(options)
199
+ if (result.needsConfirm) {
200
+ console.log(renderPlan(result.plan))
201
+ console.log('')
202
+ console.log('Dry run only. Re-run with --yes to apply.')
203
+ return
204
+ }
205
+ console.log(options.json ? JSON.stringify(result, null, 2) : renderApply(result))
206
+ return
207
+ }
208
+
209
+ if (options.command === 'rollback') {
210
+ const result = await runRollback(options)
211
+ console.log(options.json ? JSON.stringify(result, null, 2) : renderRollback(result))
212
+ return
213
+ }
214
+
215
+ if (options.command === 'report') {
216
+ const result = await runReport(options)
217
+ console.log(options.json ? JSON.stringify(result, null, 2) : renderReport(result))
218
+ return
219
+ }
220
+
221
+ if (options.command === 'list') {
222
+ const result = await runList(options)
223
+ console.log(options.json ? JSON.stringify(result, null, 2) : renderList(result))
224
+ return
225
+ }
226
+
227
+ if (options.command === 'audit') {
228
+ const result = await runAudit(options)
229
+ console.log(options.json ? JSON.stringify(result, null, 2) : renderAudit(result))
230
+ return
231
+ }
232
+
233
+ if (options.command === 'backups') {
234
+ const result = await runBackups(options)
235
+ console.log(options.json ? JSON.stringify(result, null, 2) : renderBackups(result))
236
+ return
237
+ }
238
+
239
+ if (options.command === 'prefer') {
240
+ const result = await runPrefer({ ...options, plugin: options.positional[0] })
241
+ if (options.json) {
242
+ console.log(JSON.stringify(result, null, 2))
243
+ } else if (!result.ok) {
244
+ console.log(`Prefer failed: ${result.error}`)
245
+ } else if (!result.changed) {
246
+ console.log(`${result.plugin} is already first.`)
247
+ } else {
248
+ console.log(`Moved ${result.plugin} to the front. Restart DSH to apply.`)
249
+ console.log(`Backup: ${result.backup}`)
250
+ }
251
+ if (!result.ok) process.exitCode = 1
252
+ return
253
+ }
254
+
255
+ if (options.command === 'free-port') {
256
+ const port = Number(options.positional[0])
257
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) {
258
+ console.error('Usage: dsh-coexist free-port <port> [--yes]')
259
+ process.exitCode = 1
260
+ return
261
+ }
262
+ const result = await freePort(port, { yes: options.yes })
263
+ if (options.json) {
264
+ console.log(JSON.stringify(result, null, 2))
265
+ } else if (!result.ok) {
266
+ console.log(`Cannot inspect port ${port}: ${result.error}`)
267
+ } else if (result.pids.length === 0) {
268
+ console.log(`Port ${port} is free.`)
269
+ } else if (result.killed.length > 0) {
270
+ console.log(`Killed ${result.killed.length} process(es) on port ${port}: ${result.killed.join(', ')}`)
271
+ } else {
272
+ console.log(`Port ${port} is held by PID(s): ${result.pids.join(', ')}`)
273
+ console.log('Re-run with --yes to kill them.')
274
+ }
275
+ return
276
+ }
277
+
278
+ if (options.command === 'install') {
279
+ const spec = options.self
280
+ ? fileURLToPath(new URL('../../plugin', import.meta.url))
281
+ : options.positional[0]
282
+ if (!spec) {
283
+ console.error('Usage: dsh-coexist install <package|path> [--self]')
284
+ process.exitCode = 1
285
+ return
286
+ }
287
+ const result = await installPlugin({ ...options, spec })
288
+ console.log(options.json ? JSON.stringify(result, null, 2) : renderInstall(result))
289
+ if (!result.ok && !result.dryRun) process.exitCode = 1
290
+ return
291
+ }
292
+
293
+ if (options.command === 'uninstall') {
294
+ const spec = options.positional[0]
295
+ if (!spec) {
296
+ console.error('Usage: dsh-coexist uninstall <package>')
297
+ process.exitCode = 1
298
+ return
299
+ }
300
+ const result = await uninstallPlugin({ ...options, spec })
301
+ console.log(options.json ? JSON.stringify(result, null, 2) : renderUninstall(result))
302
+ return
303
+ }
304
+
305
+ if (options.command === 'matrix') {
306
+ const result = await buildMatrix(options)
307
+ console.log(options.json ? JSON.stringify(result, null, 2) : renderMatrix(result))
308
+ return
309
+ }
310
+
311
+ console.error(`Unknown command: ${options.command}`)
312
+ console.log(HELP)
313
+ process.exitCode = 1
314
+ }
315
+
316
+ main().catch((err) => {
317
+ console.error(err.stack ?? err.message)
318
+ process.exitCode = 1
319
+ })
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
2
  "name": "dsh-coexist-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Pre-boot conflict scanner and repair planner for DeepSeek Harness profiles.",
5
+ "type": "module",
6
+ "bin": {
7
+ "dsh-coexist": "bin/dsh-coexist.js"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src",
12
+ "preload.mjs"
13
+ ],
14
+ "keywords": [
15
+ "dsh-plugin",
16
+ "deepseek-harness",
17
+ "compatibility",
18
+ "coexistence"
19
+ ],
20
+ "license": "MIT",
21
+ "dependencies": {
22
+ "yaml": "^2.8.0"
23
+ },
24
+ "engines": {
25
+ "node": "^22.19.0 || >=24.0.0"
26
+ }
27
+ }
package/preload.mjs ADDED
@@ -0,0 +1,74 @@
1
+ import { appendFileSync, mkdirSync } from 'node:fs'
2
+ import { createRequire } from 'node:module'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import { pathToFileURL } from 'node:url'
6
+ import { installPrototypePatch } from './src/preload/patch.js'
7
+
8
+ const logFile =
9
+ process.env.DSH_COEXIST_LOG ??
10
+ path.join(os.homedir(), '.dsh', 'coexist', 'desktop', 'preload.log')
11
+
12
+ function logLine(message) {
13
+ try {
14
+ mkdirSync(path.dirname(logFile), { recursive: true })
15
+ appendFileSync(logFile, `[${new Date().toISOString()}] ${message}\n`)
16
+ } catch {
17
+ // Logging must never break the host.
18
+ }
19
+ }
20
+
21
+ logLine(
22
+ `preload start argv=${JSON.stringify(process.argv)} ` +
23
+ `electronRunAsNode=${process.env.ELECTRON_RUN_AS_NODE ?? ''} ` +
24
+ `nodeOptions=${process.env.NODE_OPTIONS ? 'yes' : 'no'}`,
25
+ )
26
+
27
+ const watch = (process.env.DSH_COEXIST_WATCH ?? '')
28
+ .split(',')
29
+ .map((name) => name.trim())
30
+ .filter(Boolean)
31
+
32
+ let toolsPath = process.env.DSH_COEXIST_TOOLS_PATH
33
+ if (!toolsPath) {
34
+ try {
35
+ toolsPath = createRequire(process.argv[1] ?? process.cwd()).resolve('@deepseek-ai/dsh-tools')
36
+ } catch {
37
+ // Keep looking below; the caller may set DSH_COEXIST_TOOLS_PATH.
38
+ }
39
+ }
40
+
41
+ if (!toolsPath) {
42
+ logLine('preload failed: cannot resolve @deepseek-ai/dsh-tools')
43
+ console.warn('[coexist] cannot resolve @deepseek-ai/dsh-tools; preload skipped')
44
+ } else {
45
+ try {
46
+ logLine(`preload tools=${toolsPath}`)
47
+ const requireFromDsh = createRequire(toolsPath)
48
+ const mod = await import(pathToFileURL(toolsPath).href)
49
+ const ToolsService = [mod.ToolsService, mod.ToolRuntime, mod.default].find(
50
+ (candidate) => typeof candidate?.prototype?.register === 'function',
51
+ )
52
+ if (!ToolsService) {
53
+ throw new Error('no tool registry class with register() found')
54
+ }
55
+
56
+ let scopeOf
57
+ try {
58
+ const scopePath = requireFromDsh.resolve('@deepseek-ai/dsh-scope')
59
+ ;({ scopeOf } = await import(pathToFileURL(scopePath).href))
60
+ } catch {
61
+ // Scope isolation falls back to a single global bucket.
62
+ }
63
+
64
+ installPrototypePatch(ToolsService, {
65
+ watch,
66
+ auto: watch.length === 0,
67
+ scopeOf,
68
+ logFile,
69
+ })
70
+ } catch (err) {
71
+ logLine(`preload failed: ${err.stack ?? err.message}`)
72
+ console.warn(`[coexist] preload failed: ${err.message}`)
73
+ }
74
+ }
package/src/apply.js ADDED
@@ -0,0 +1,255 @@
1
+ import fs from 'node:fs/promises'
2
+ import path from 'node:path'
3
+ import YAML from 'yaml'
4
+ import { createBackup } from './backup.js'
5
+ import { auditFile } from './paths.js'
6
+
7
+ async function atomicWrite(file, content) {
8
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`
9
+ await fs.writeFile(tmp, content, 'utf8')
10
+ try {
11
+ await fs.rename(tmp, file)
12
+ } catch (err) {
13
+ if (err.code === 'EEXIST' || err.code === 'EPERM') {
14
+ await fs.rm(file, { force: true })
15
+ await fs.rename(tmp, file)
16
+ return
17
+ }
18
+ await fs.rm(tmp, { force: true })
19
+ throw err
20
+ }
21
+ }
22
+
23
+ async function pathExists(file) {
24
+ try {
25
+ await fs.access(file)
26
+ return true
27
+ } catch {
28
+ return false
29
+ }
30
+ }
31
+
32
+ export function renameNthLoaderId(text, oldId, newId, occurrence = 1) {
33
+ const eol = text.includes('\r\n') ? '\r\n' : '\n'
34
+ const lines = text.split(/\r?\n/)
35
+ let count = 0
36
+
37
+ for (let index = 0; index < lines.length; index += 1) {
38
+ const match = lines[index].match(/^(\s*-\s+id:\s*)(["']?)([^"'\s#]+)\2(\s*(?:#.*)?)$/)
39
+ if (!match || match[3] !== oldId) continue
40
+ count += 1
41
+ if (count !== occurrence) continue
42
+ lines[index] = `${match[1]}${match[2]}${newId}${match[2]}${match[4]}`
43
+ return { ok: true, text: lines.join(eol) }
44
+ }
45
+
46
+ return { ok: false, text }
47
+ }
48
+
49
+ /** 在指定 id 的 patch 行块内把 port: oldPort 改成 newPort,保留缩进与注释。 */
50
+ export function replacePortInRow(text, id, oldPort, newPort) {
51
+ const eol = text.includes('\r\n') ? '\r\n' : '\n'
52
+ const lines = text.split(/\r?\n/)
53
+ const idRe = /^(\s*-\s+id:\s*)(["']?)([^"'\s#]+)\2(\s*(?:#.*)?)$/
54
+
55
+ let start = -1
56
+ for (let index = 0; index < lines.length; index += 1) {
57
+ const match = lines[index].match(idRe)
58
+ if (match && match[3] === id) {
59
+ start = index
60
+ break
61
+ }
62
+ }
63
+ if (start === -1) return { ok: false, text }
64
+
65
+ const startIndent = (lines[start].match(/^\s*/) ?? [''])[0].length
66
+ let end = lines.length
67
+ for (let index = start + 1; index < lines.length; index += 1) {
68
+ const dash = lines[index].match(/^(\s*)-\s/)
69
+ if (dash && dash[1].length <= startIndent) {
70
+ end = index
71
+ break
72
+ }
73
+ }
74
+
75
+ const portRe = new RegExp(`(\\bport:\\s*)${oldPort}\\b`)
76
+ for (let index = start; index < end; index += 1) {
77
+ if (!portRe.test(lines[index])) continue
78
+ lines[index] = lines[index].replace(portRe, `$1${newPort}`)
79
+ return { ok: true, text: lines.join(eol) }
80
+ }
81
+
82
+ return { ok: false, text }
83
+ }
84
+
85
+ export async function applyPlan({ home, graph, plan }) {
86
+ const files = new Set()
87
+ for (const action of plan.actions) {
88
+ if (
89
+ action.kind === 'rename-loader-id' ||
90
+ action.kind === 'dedupe-bundles' ||
91
+ action.kind === 'change-port' ||
92
+ action.kind === 'append-patch' ||
93
+ action.kind === 'peer-override' ||
94
+ action.kind === 'disable-loader-row' ||
95
+ action.kind === 'clone-loader-row'
96
+ ) {
97
+ files.add(action.file)
98
+ }
99
+ }
100
+
101
+ if (files.size === 0) {
102
+ return { applied: [], backup: null }
103
+ }
104
+
105
+ const backup = await createBackup(home, [...files])
106
+ const applied = []
107
+
108
+ const renamesByFile = new Map()
109
+ for (const action of plan.actions) {
110
+ if (action.kind !== 'rename-loader-id') continue
111
+ const list = renamesByFile.get(action.file) ?? []
112
+ list.push(action)
113
+ renamesByFile.set(action.file, list)
114
+ }
115
+
116
+ for (const [file, actions] of renamesByFile) {
117
+ let text = await fs.readFile(file, 'utf8')
118
+ const descending = [...actions].sort((a, b) => b.occurrence - a.occurrence)
119
+
120
+ for (const action of descending) {
121
+ const result = renameNthLoaderId(text, action.oldId, action.newId, action.occurrence)
122
+ if (!result.ok) {
123
+ throw new Error(
124
+ `Loader id "${action.oldId}" occurrence ${action.occurrence} not found in ${file}`,
125
+ )
126
+ }
127
+ text = result.text
128
+ applied.push({ ...action, file })
129
+ }
130
+
131
+ await atomicWrite(file, text)
132
+ }
133
+
134
+ const portActionsByFile = new Map()
135
+ for (const action of plan.actions) {
136
+ if (action.kind !== 'change-port') continue
137
+ const list = portActionsByFile.get(action.file) ?? []
138
+ list.push(action)
139
+ portActionsByFile.set(action.file, list)
140
+ }
141
+
142
+ for (const [file, actions] of portActionsByFile) {
143
+ let text = await fs.readFile(file, 'utf8')
144
+ for (const action of actions) {
145
+ const result = replacePortInRow(text, action.id, action.oldPort, action.newPort)
146
+ if (!result.ok) {
147
+ throw new Error(
148
+ `Port ${action.oldPort} for "${action.id}" not found in ${file}`,
149
+ )
150
+ }
151
+ text = result.text
152
+ applied.push({ ...action, file })
153
+ }
154
+ await atomicWrite(file, text)
155
+ }
156
+
157
+ const appendActionsByFile = new Map()
158
+ for (const action of plan.actions) {
159
+ if (
160
+ action.kind !== 'append-patch' &&
161
+ action.kind !== 'disable-loader-row' &&
162
+ action.kind !== 'clone-loader-row'
163
+ ) {
164
+ continue
165
+ }
166
+ const list = appendActionsByFile.get(action.file) ?? []
167
+ list.push(action)
168
+ appendActionsByFile.set(action.file, list)
169
+ }
170
+
171
+ for (const [file, actions] of appendActionsByFile) {
172
+ let existing = ''
173
+ try {
174
+ existing = await fs.readFile(file, 'utf8')
175
+ } catch (error) {
176
+ if (error.code !== 'ENOENT') throw error
177
+ }
178
+ const body = actions
179
+ .map((action) => {
180
+ let yaml
181
+ let label
182
+ if (action.kind === 'disable-loader-row') {
183
+ yaml = YAML.stringify([{ replace: [{ id: action.oldId, disabled: true }] }])
184
+ label = `disable loader row ${action.oldId}`
185
+ } else if (action.kind === 'clone-loader-row') {
186
+ const row = {
187
+ id: action.newId,
188
+ ...(action.name ? { name: action.name } : {}),
189
+ ...(action.config !== undefined ? { config: action.config } : {}),
190
+ ...(action.disabled !== undefined ? { disabled: action.disabled } : {}),
191
+ }
192
+ yaml = YAML.stringify([{ insert: [row] }])
193
+ label = `clone loader row ${action.oldId} -> ${action.newId}`
194
+ } else {
195
+ yaml = action.yaml
196
+ label = `${action.reason} ${action.targetId}`
197
+ }
198
+ return `# dsh-coexist: ${label}\n${yaml.trimEnd()}`
199
+ })
200
+ .join('\n\n')
201
+ const next = `${existing.trimEnd()}${existing.trim() ? '\n\n' : ''}${body}\n`
202
+ await atomicWrite(file, next)
203
+ for (const action of actions) applied.push({ ...action, file })
204
+ }
205
+
206
+ const peerActionsByFile = new Map()
207
+ for (const action of plan.actions) {
208
+ if (action.kind !== 'peer-override') continue
209
+ const list = peerActionsByFile.get(action.file) ?? []
210
+ list.push(action)
211
+ peerActionsByFile.set(action.file, list)
212
+ }
213
+
214
+ for (const [file, actions] of peerActionsByFile) {
215
+ const dir = path.dirname(file)
216
+ const usePnpm =
217
+ (await pathExists(path.join(dir, 'pnpm-lock.yaml'))) ||
218
+ (await pathExists(path.join(dir, 'pnpm-workspace.yaml')))
219
+ const packageJson = JSON.parse(await fs.readFile(file, 'utf8'))
220
+ const target = usePnpm ? (packageJson.pnpm ??= {}) : packageJson
221
+ target.overrides ??= {}
222
+
223
+ for (const action of actions) {
224
+ target.overrides[action.dep] = action.version
225
+ applied.push({ ...action, file, manager: usePnpm ? 'pnpm' : 'npm' })
226
+ }
227
+
228
+ await atomicWrite(file, `${JSON.stringify(packageJson, null, 2)}\n`)
229
+ }
230
+
231
+ for (const action of plan.actions) {
232
+ if (action.kind !== 'dedupe-bundles') continue
233
+ const packageJson = JSON.parse(await fs.readFile(action.file, 'utf8'))
234
+ const bundles = packageJson?.dsh?.profile?.bundles
235
+ if (!Array.isArray(bundles)) continue
236
+
237
+ const seen = new Set()
238
+ packageJson.dsh.profile.bundles = bundles.filter((bundle) => {
239
+ if (seen.has(bundle)) return false
240
+ seen.add(bundle)
241
+ return true
242
+ })
243
+
244
+ await atomicWrite(action.file, `${JSON.stringify(packageJson, null, 2)}\n`)
245
+ applied.push({ ...action, file: action.file })
246
+ }
247
+
248
+ await fs.mkdir(path.dirname(auditFile(home)), { recursive: true })
249
+ await fs.appendFile(
250
+ auditFile(home),
251
+ `${JSON.stringify({ at: new Date().toISOString(), applied, backup: backup.dir })}\n`,
252
+ )
253
+
254
+ return { applied, backup: backup.dir }
255
+ }