@twinsearth/dsh-fang 3.1.6 → 3.1.8

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twinsearth/dsh-fang",
3
- "version": "3.1.6",
3
+ "version": "3.1.8",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "dsh-Fang (瓮城) — mother/fork plugin development environment for DeepSeek Harness: one readonly mother, a disposable child dsh-Web per task.",
@@ -176,6 +176,47 @@ export function isLink(p) {
176
176
  }
177
177
  }
178
178
 
179
+ /**
180
+ * Copy a tree with hardlinked files: directories are recreated, ordinary files are
181
+ * hardlinked (same volume only; falls back to a copy), and links are recreated as links
182
+ * rather than traversed. Used when the essence runtime's touched packages must be
183
+ * materialized into the essence module tree without duplicating file bytes and without
184
+ * junction cycles (the runtime mirror would otherwise point back at the essence tree).
185
+ * @param {string} from Source directory.
186
+ * @param {string} to Destination directory (created; expected to be empty/new).
187
+ * @returns {string} The destination.
188
+ */
189
+ export function hardlinkTree(from, to) {
190
+ let names
191
+ try { names = fs.readdirSync(from) } catch {
192
+ ensureDir(to)
193
+ return to
194
+ }
195
+ ensureDir(to)
196
+ for (const name of names) {
197
+ const src = path.join(from, name)
198
+ const dst = path.join(to, name)
199
+ let st
200
+ try { st = fs.lstatSync(src) } catch { continue }
201
+ if (st.isSymbolicLink()) {
202
+ let target = ''
203
+ try { target = fs.readlinkSync(src) } catch { continue }
204
+ try {
205
+ const absolute = path.isAbsolute(target) ? target : path.resolve(from, target)
206
+ const stTarget = fs.lstatSync(absolute)
207
+ if (stTarget.isDirectory()) fs.symlinkSync(absolute, dst, 'junction')
208
+ else fs.copyFileSync(absolute, dst)
209
+ } catch { /* an unmirrorable link is skipped */ }
210
+ continue
211
+ }
212
+ if (st.isDirectory()) { hardlinkTree(src, dst); continue }
213
+ try { fs.linkSync(src, dst) } catch {
214
+ try { fs.copyFileSync(src, dst) } catch { /* skip */ }
215
+ }
216
+ }
217
+ return to
218
+ }
219
+
179
220
  /** Create (or replace) a Windows junction / POSIX dir symlink. */
180
221
  export function makeJunction(target, linkPath) {
181
222
  ensureDir(path.dirname(linkPath))
@@ -184,6 +225,78 @@ export function makeJunction(target, linkPath) {
184
225
  return linkPath
185
226
  }
186
227
 
228
+ /**
229
+ * Replace `dest` with a real directory that mirrors `source`'s top-level entries:
230
+ * directories become junctions to their real targets, plain root files are copied.
231
+ * Package contents are never copied, so the module tree stays shared — but every
232
+ * entry is its own link. That is what DSH's profile-scope resolver needs: an
233
+ * importer below a linked root gets the installation's `@deepseek-ai/*` packages
234
+ * supplied (subject to the peer declaration), while a single whole-node_modules
235
+ * junction leaves the importer outside every known scope. Measured consequence of
236
+ * the whole-tree link: plugins that lazily `import('@deepseek-ai/dsh-tools')` in a
237
+ * fork fall back to their offline shim — w2m's shim stamps `required: false` into a
238
+ * property schema, and the provider rejects every request with
239
+ * `Invalid schema for function 'w2m_report'` (v3.1.7 report).
240
+ * Junction-safe: a reparse point in `dest` is unlinked, never entered; link targets
241
+ * are resolved with realpath first so a link-to-link (pnpm) also lands on a dir.
242
+ * @param {string} source Directory whose entries are mirrored (the module tree).
243
+ * @param {string} dest Directory to replace with the mirror.
244
+ * @returns {{ok:boolean, links:string[], files:string[], error?:string}}
245
+ */
246
+ export function mirrorModuleTree(source, dest) {
247
+ const src = path.resolve(String(source ?? ''))
248
+ if (!exists(src)) return { ok: false, links: [], files: [], error: 'source-missing' }
249
+ let srcStat
250
+ try { srcStat = fs.lstatSync(src) } catch { return { ok: false, links: [], files: [], error: 'source-unreadable' } }
251
+ if (!srcStat.isDirectory() && !srcStat.isSymbolicLink()) return { ok: false, links: [], files: [], error: 'source-not-directory' }
252
+ removeTree(dest)
253
+ ensureDir(dest)
254
+ const links = []
255
+ const files = []
256
+ let names = []
257
+ try { names = fs.readdirSync(src) } catch { names = [] }
258
+ for (const name of names) {
259
+ const from = path.join(src, name)
260
+ const to = path.join(dest, name)
261
+ let real = from
262
+ try {
263
+ if (fs.lstatSync(from).isSymbolicLink()) real = fs.realpathSync(from)
264
+ } catch { continue }
265
+ let targetStat
266
+ try { targetStat = fs.statSync(real) } catch { continue }
267
+ if (targetStat.isDirectory()) {
268
+ try {
269
+ fs.symlinkSync(path.resolve(real), to, 'junction')
270
+ links.push(name)
271
+ } catch { /* an unmirrorable entry is skipped; the remaining tree still boots */ }
272
+ continue
273
+ }
274
+ try {
275
+ fs.copyFileSync(from, to)
276
+ files.push(name)
277
+ } catch { /* ignore */ }
278
+ }
279
+ return { ok: true, links, files }
280
+ }
281
+
282
+ /**
283
+ * Repair a profile `node_modules` that is still a whole-tree junction (v3.1.6 and
284
+ * older) into the per-entry mirror form. A real directory is left untouched.
285
+ * @param {string} modulesPath The profile's node_modules path.
286
+ * @returns {{ok:boolean, changed:boolean, links?:string[], files?:string[], source?:string, error?:string}}
287
+ */
288
+ export function ensureModuleMirror(modulesPath) {
289
+ const p = String(modulesPath ?? '')
290
+ if (!p || !exists(p)) return { ok: false, changed: false, error: 'node-modules-missing' }
291
+ let st
292
+ try { st = fs.lstatSync(p) } catch { return { ok: false, changed: false, error: 'node-modules-unreadable' } }
293
+ if (!st.isSymbolicLink()) return { ok: true, changed: false, links: [], files: [] }
294
+ let source
295
+ try { source = fs.realpathSync(p) } catch { return { ok: false, changed: false, error: 'node-modules-target-missing' } }
296
+ const mirrored = mirrorModuleTree(source, p)
297
+ return { ...mirrored, changed: true, source }
298
+ }
299
+
187
300
  /**
188
301
  * Remove a file or directory tree. Junction-safe: a reparse point is unlinked,
189
302
  * its target is never entered. This is the ONLY removal path plugins may use on
@@ -128,7 +128,7 @@ export const AUDIT = {
128
128
  RUNTIME_ERROR: 'runtime-error',
129
129
  }
130
130
 
131
- export const FANG_VERSION = '3.1.6'
131
+ export const FANG_VERSION = '3.1.8'
132
132
 
133
133
  /**
134
134
  * @typedef {object} ForkInfo
@@ -1144,13 +1144,30 @@ export class EssenceManager {
1144
1144
 
1145
1145
  /**
1146
1146
  * 物化 merged/profile:镜像骨架 + 合并后的 patch/package/settings + 原身凭据(镜像凭据剔除)。
1147
+ * v3.1.8:保留已有 merged/profile/node_modules(元主模块树可能是 GB 级、且可能已包含运行态
1148
+ * 捕获回来的插件变更,重建成本高);overlay 里的 pnpm 锁/设置文件一并投影到 merged,供
1149
+ * 运行态复用时保持可复现的依赖图。
1147
1150
  */
1148
1151
  materializeMerged(root, mirror, overlay, result) {
1149
1152
  const mergedRoot = path.join(root, 'merged')
1150
1153
  const mergedProfile = path.join(mergedRoot, 'profile')
1154
+ const preservedModules = path.join(root, '.modules-preserve')
1155
+ let hadModules = false
1156
+ if (exists(preservedModules)) removeTree(preservedModules)
1157
+ if (exists(path.join(mergedProfile, 'node_modules'))) {
1158
+ try {
1159
+ fs.renameSync(path.join(mergedProfile, 'node_modules'), preservedModules)
1160
+ hadModules = true
1161
+ } catch { hadModules = false }
1162
+ }
1151
1163
  if (exists(mergedRoot)) removeTree(mergedRoot)
1152
1164
  ensureDir(mergedProfile)
1153
1165
  copyTree(mirror.root, mergedProfile)
1166
+ if (hadModules) {
1167
+ const freshModules = path.join(mergedProfile, 'node_modules')
1168
+ if (exists(freshModules)) removeTree(freshModules)
1169
+ fs.renameSync(preservedModules, freshModules)
1170
+ }
1154
1171
  fs.writeFileSync(path.join(mergedProfile, 'cordis.patch.yml'), serializePatchEntries(result.mergedPatchEntries), 'utf8')
1155
1172
  writeJsonAtomic(path.join(mergedProfile, 'package.json'), result.mergedPackageJson)
1156
1173
  const settingsDir = path.join(mergedProfile, 'settings')
@@ -1158,6 +1175,12 @@ export class EssenceManager {
1158
1175
  for (const [name, value] of Object.entries(result.mergedSettings)) {
1159
1176
  fs.writeFileSync(path.join(settingsDir, `${name}.yaml`), `${JSON.stringify(value, null, 2)}\n`, 'utf8')
1160
1177
  }
1178
+ // v3.1.8:overlay 里保管的 pnpm 依赖图文件(运行态插件变更捕获)投影到 merged profile。
1179
+ for (const name of ['pnpm-lock.yaml', 'pnpm-workspace.yaml', '.npmrc']) {
1180
+ const source = path.join(root, 'overlay', name)
1181
+ if (!exists(source)) continue
1182
+ try { fs.copyFileSync(source, path.join(mergedProfile, name)) } catch { /* 单个文件失败不阻塞物化 */ }
1183
+ }
1161
1184
  // v3.0.5/B8:凭据永不进入 merged/profile —— 派生 profile 不携带任何 credentials
1162
1185
  const mergedCredentials = path.join(mergedProfile, 'credentials')
1163
1186
  if (exists(mergedCredentials)) removeTree(mergedCredentials)
@@ -0,0 +1,184 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ // dsh-Fang lib — pnpm settings for the essence runtime profile.
4
+ //
5
+ // DSH 0.2.2-rc.1 bundles pnpm 11, and pnpm 11 no longer reads non-auth settings
6
+ // (`store-dir`, `package-import-method`, …) from a project `.npmrc`: only auth and
7
+ // network keys are read from that file, the rest moved to `pnpm-workspace.yaml`
8
+ // (camelCase). Fang used to write only `.npmrc`, so every pnpm operation inside an
9
+ // essence runtime picked the per-drive default store (`D:\.pnpm-store\v11` on a D:
10
+ // project) while the module tree recorded the mother's C: store, and pnpm failed with
11
+ // [ERR_PNPM_UNEXPECTED_STORE] Unexpected store location ...
12
+ // Before removing/updating any plugin (v3.1.8 report).
13
+ //
14
+ // This module writes the settings in the form pnpm 11 actually reads, keeps the legacy
15
+ // `.npmrc` for older pnpm/npm, and aligns the modules manifest so pnpm's compatibility
16
+ // check accepts the shared module tree: the store must match and the virtual store must
17
+ // be this project's own `node_modules/.pnpm` (the copied manifest still named the
18
+ // mother's virtual store).
19
+ import fs from 'node:fs'
20
+ import path from 'node:path'
21
+
22
+ /** The project settings file pnpm 11 reads (non-auth settings). */
23
+ export const PNPM_WORKSPACE_FILE = 'pnpm-workspace.yaml'
24
+ /** Legacy npm/pnpm config file; still written for older toolchains. */
25
+ export const NPMRC_FILE = '.npmrc'
26
+ /** The modules manifest pnpm writes into `node_modules`. */
27
+ export const MODULES_MANIFEST_FILE = '.modules.yaml'
28
+
29
+ function readText(file, fallback = '') {
30
+ try { return fs.readFileSync(file, 'utf8') } catch { return fallback }
31
+ }
32
+
33
+ function readJson(file, fallback = null) {
34
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return fallback }
35
+ }
36
+
37
+ function writeText(file, text) {
38
+ fs.mkdirSync(path.dirname(file), { recursive: true })
39
+ fs.writeFileSync(file, text, 'utf8')
40
+ }
41
+
42
+ /**
43
+ * Read the store + virtual store recorded for a module tree.
44
+ * @param {string} modulesDir `node_modules` directory (its `.modules.yaml` is read).
45
+ * @returns {{storeDir:string, virtualStoreDir:string|null, layoutVersion:number|null, file:string}|null}
46
+ */
47
+ export function readModulesManifest(modulesDir) {
48
+ const file = path.join(String(modulesDir ?? ''), MODULES_MANIFEST_FILE)
49
+ const manifest = readJson(file, null)
50
+ if (!manifest || typeof manifest !== 'object') return null
51
+ return {
52
+ storeDir: typeof manifest.storeDir === 'string' ? manifest.storeDir : '',
53
+ virtualStoreDir: typeof manifest.virtualStoreDir === 'string' ? manifest.virtualStoreDir : null,
54
+ layoutVersion: Number.isFinite(manifest.layoutVersion) ? manifest.layoutVersion : null,
55
+ file,
56
+ }
57
+ }
58
+
59
+ /**
60
+ * The linker an existing module tree was laid out with, from the profile that owns it.
61
+ * DSH's desktop profile declares `nodeLinker: hoisted`; a runtime profile cloned from it
62
+ * must keep the same linker or pnpm would want to rebuild the modules directory.
63
+ * @param {string} profileDir Profile directory whose pnpm-workspace.yaml is read.
64
+ * @param {string} [fallback='hoisted'] Value used when the file has no nodeLinker.
65
+ * @returns {string}
66
+ */
67
+ export function readNodeLinker(profileDir, fallback = 'hoisted') {
68
+ const text = readText(path.join(String(profileDir ?? ''), PNPM_WORKSPACE_FILE))
69
+ const match = /^nodeLinker:\s*([A-Za-z-]+)\s*$/m.exec(text)
70
+ return match ? match[1] : fallback
71
+ }
72
+
73
+ /**
74
+ * Upsert top-level keys in a pnpm settings YAML file, preserving every other line
75
+ * (settings, comments, order). The values written here are machine paths and simple
76
+ * scalars, so a line-oriented upsert is enough and keeps the file readable.
77
+ * @param {string} file pnpm-workspace.yaml path.
78
+ * @param {Record<string,string>} settings Keys to write (camelCase).
79
+ * @returns {string[]} Keys written.
80
+ */
81
+ export function upsertPnpmWorkspaceSettings(file, settings = {}) {
82
+ const entries = Object.entries(settings).filter(([, value]) => typeof value === 'string' && value !== '')
83
+ if (entries.length === 0) return []
84
+ const keys = new Set(entries.map(([key]) => key))
85
+ const original = readText(file)
86
+ const kept = original.split(/\r?\n/).filter((line) => {
87
+ const match = /^([A-Za-z][A-Za-z0-9_]*):/.exec(line)
88
+ return !(match && keys.has(match[1]))
89
+ })
90
+ const trimmed = kept.join('\n').replace(/[ \t]+$/gm, '').replace(/^\n+|\n+$/g, '')
91
+ const appended = entries.map(([key, value]) => `${key}: ${value}`).join('\n')
92
+ writeText(file, `${trimmed ? `${trimmed}\n` : ''}${appended}\n`)
93
+ return entries.map(([key]) => key)
94
+ }
95
+
96
+ /**
97
+ * Upsert legacy `.npmrc` keys. pnpm 11 ignores these, but npm and older pnpm honor
98
+ * them and the runtime profile may outlive a DSH downgrade.
99
+ * @param {string} profileDir Profile directory.
100
+ * @param {{storeDir:string, packageImportMethod:string}} options
101
+ * @returns {string[]}
102
+ */
103
+ export function upsertNpmrc(profileDir, { storeDir, packageImportMethod = 'copy' } = {}) {
104
+ const file = path.join(String(profileDir ?? ''), NPMRC_FILE)
105
+ const pairs = [
106
+ ['store-dir', storeDir],
107
+ ['package-import-method', packageImportMethod],
108
+ ].filter(([, value]) => typeof value === 'string' && value !== '')
109
+ if (pairs.length === 0) return []
110
+ const written = []
111
+ let text = readText(file)
112
+ for (const [key, value] of pairs) {
113
+ const re = new RegExp(`^${key}=.*$`, 'm')
114
+ if (re.test(text)) text = text.replace(re, `${key}=${value}`)
115
+ else text = `${text && !text.endsWith('\n') ? `${text}\n` : text}${key}=${value}\n`
116
+ written.push(key)
117
+ }
118
+ writeText(file, text.replace(/^\n+/, ''))
119
+ return written
120
+ }
121
+
122
+ /**
123
+ * Align a modules manifest with the store and virtual store pnpm will compute for this
124
+ * project. pnpm's `checkCompatibility` refuses a modules directory whose recorded store
125
+ * differs from the chosen store, or whose recorded `virtualStoreDir` differs from the
126
+ * project's own — the runtime tree was copied from the mother, so it names the mother's
127
+ * virtual store. Both become this project's values; the rest of the manifest is kept.
128
+ * @param {string} modulesDir `node_modules` directory.
129
+ * @param {{storeDir:string, virtualStoreDir:string}} options
130
+ * @returns {{changed:boolean, storeDir?:string, virtualStoreDir?:string, error?:string}}
131
+ */
132
+ export function patchModulesManifest(modulesDir, { storeDir, virtualStoreDir } = {}) {
133
+ const manifest = readModulesManifest(modulesDir)
134
+ if (!manifest) return { changed: false, error: 'modules-manifest-missing' }
135
+ if (!storeDir || !virtualStoreDir) return { changed: false, error: 'store-or-virtual-store-missing' }
136
+ const raw = readJson(manifest.file, null)
137
+ if (!raw) return { changed: false, error: 'modules-manifest-unreadable' }
138
+ const sameStore = raw.storeDir === storeDir
139
+ const sameVirtual = raw.virtualStoreDir === virtualStoreDir
140
+ if (sameStore && sameVirtual) return { changed: false, storeDir, virtualStoreDir }
141
+ raw.storeDir = storeDir
142
+ raw.virtualStoreDir = virtualStoreDir
143
+ writeText(manifest.file, `${JSON.stringify(raw, null, 2)}\n`)
144
+ return { changed: true, storeDir, virtualStoreDir }
145
+ }
146
+
147
+ /**
148
+ * Make an essence runtime profile's pnpm operations work off the shared module tree.
149
+ *
150
+ * Writes the settings pnpm 11 reads (`pnpm-workspace.yaml`), refreshes the legacy
151
+ * `.npmrc`, and aligns `node_modules/.modules.yaml` with the store and this project's
152
+ * virtual store. The store location is taken from the module tree's own manifest, so the
153
+ * chosen store always matches what the installed packages were linked from.
154
+ * @param {{profileDir:string, modulesDir:string, sourceModulesDir?:string, nodeLinker?:string}} options
155
+ * @returns {{ok:boolean, storeDir?:string, virtualStoreDir?:string, nodeLinker?:string, settings?:string[], npmrc?:string[], manifest?:object, error?:string}}
156
+ */
157
+ export function ensureEssenceRuntimePnpmConfig({ profileDir, modulesDir, sourceModulesDir = '', nodeLinker = 'hoisted' } = {}) {
158
+ const profile = String(profileDir ?? '')
159
+ const modules = String(modulesDir ?? '')
160
+ if (!profile || !modules) return { ok: false, error: 'profile-or-modules-missing' }
161
+ const source = String(sourceModulesDir ?? '') || modules
162
+ const manifest = readModulesManifest(source) ?? readModulesManifest(modules)
163
+ if (!manifest) return { ok: false, error: 'modules-manifest-missing' }
164
+ const storeDir = manifest.storeDir
165
+ if (!storeDir) return { ok: false, error: 'store-dir-unknown' }
166
+ const virtualStoreDir = path.join(modules, '.pnpm')
167
+ const settings = upsertPnpmWorkspaceSettings(path.join(profile, PNPM_WORKSPACE_FILE), {
168
+ nodeLinker,
169
+ storeDir,
170
+ packageImportMethod: 'copy',
171
+ })
172
+ const npmrc = upsertNpmrc(profile, { storeDir, packageImportMethod: 'copy' })
173
+ const patched = patchModulesManifest(modules, { storeDir, virtualStoreDir })
174
+ return {
175
+ ok: patched.error === undefined,
176
+ storeDir,
177
+ virtualStoreDir,
178
+ nodeLinker,
179
+ settings,
180
+ npmrc,
181
+ manifest: patched,
182
+ ...(patched.error === undefined ? {} : { error: patched.error }),
183
+ }
184
+ }
@@ -0,0 +1,307 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ // dsh-Fang lib — capture the essence runtime's plugin changes back into the essence.
4
+ //
5
+ // The essence runtime (`profiles/essence-runtime`) is a config instance: the user opens
6
+ // it, installs/updates/removes plugins through the DSH plugin manager, and expects the
7
+ // 元宝 to keep those changes. The runtime profile is cloned from the essence `merged`
8
+ // profile on every open, so without capture the next open would replay the old config and
9
+ // silently drop the work (v3.1.7 known boundary; implemented here in v3.1.8).
10
+ //
11
+ // What is captured:
12
+ // * `package.json`: dependencies + `dsh.profile.bundles` (+ name/private/type),
13
+ // * `cordis.patch.yml`: entries that differ from the merged profile (enable/disable),
14
+ // * the pnpm dependency-graph files (`pnpm-lock.yaml`, `pnpm-workspace.yaml`, `.npmrc`),
15
+ // * the touched module directories: packages pnpm re-materialized in the runtime
16
+ // `node_modules` are hardlink-copied into the essence module tree so derived forks see
17
+ // the same plugin set.
18
+ //
19
+ // Capture is cheap when nothing changed: a signature over package.json + cordis.patch.yml
20
+ // + the node_modules manifest mtime is stored in the runtime profile and compared first.
21
+ import fs from 'node:fs'
22
+ import path from 'node:path'
23
+
24
+ import { ensureDir, exists, hardlinkTree, readJson, removeTree, writeJsonAtomic } from '../kernel/index.mjs'
25
+ import { parsePatchEntries } from './essence.mjs'
26
+
27
+ /** Files the pnpm dependency graph needs and the runtime may have rewritten. */
28
+ export const CAPTURED_AUX_FILES = Object.freeze(['pnpm-lock.yaml', 'pnpm-workspace.yaml', '.npmrc'])
29
+ /** Marker written inside the runtime profile after a successful capture. */
30
+ export const CAPTURE_MARKER_FILE = '.fang-runtime-capture.json'
31
+ /** Top-level/scope entries that are pnpm bookkeeping, never package directories. */
32
+ const INTERNAL_MODULE_NAMES = new Set(['.pnpm', '.bin', '.modules.yaml', '.ignored', '.pnpm-workspace-state-v1.json'])
33
+
34
+ function readText(file) {
35
+ try { return fs.readFileSync(file, 'utf8') } catch { return '' }
36
+ }
37
+
38
+ function readPackageJson(profileDir) {
39
+ const value = readJson(path.join(String(profileDir ?? ''), 'package.json'), null)
40
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : null
41
+ }
42
+
43
+ /** Stable JSON (sorted object keys) for structural comparisons. */
44
+ export function stableStringify(value) {
45
+ if (Array.isArray(value)) return `[${value.map((entry) => stableStringify(entry)).join(',')}]`
46
+ if (value && typeof value === 'object') {
47
+ const keys = Object.keys(value).sort()
48
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`
49
+ }
50
+ return JSON.stringify(value)
51
+ }
52
+
53
+ /** The profile package fields the essence overlay carries (mirrors EssenceManager.selectProfilePackage). */
54
+ export function pickProfilePackage(profilePkg) {
55
+ const picked = {}
56
+ for (const key of ['name', 'private', 'type']) {
57
+ if (profilePkg?.[key] !== undefined) picked[key] = profilePkg[key]
58
+ }
59
+ const dsh = profilePkg?.dsh
60
+ if (dsh && typeof dsh === 'object' && Object.keys(dsh).length > 0) picked.dsh = dsh
61
+ const deps = profilePkg?.dependencies
62
+ if (deps && typeof deps === 'object' && Object.keys(deps).length > 0) picked.dependencies = deps
63
+ return picked
64
+ }
65
+
66
+ /**
67
+ * Patch entries the runtime changed or added relative to the merged profile, plus merged
68
+ * ids the runtime no longer carries (the plugin manager removed the row; a disabled marker
69
+ * keeps the mirror-provided row from coming back).
70
+ * @param {Array<Record<string,unknown>>} mergedEntries
71
+ * @param {Array<Record<string,unknown>>} runtimeEntries
72
+ * @returns {{changed:Array<Record<string,unknown>>, removedIds:string[]}}
73
+ */
74
+ export function diffPatchEntries(mergedEntries = [], runtimeEntries = []) {
75
+ const mergedById = new Map((mergedEntries ?? []).map((entry) => [String(entry?.id ?? ''), entry]))
76
+ const runtimeById = new Map((runtimeEntries ?? []).map((entry) => [String(entry?.id ?? ''), entry]))
77
+ const changed = []
78
+ for (const [id, entry] of runtimeById) {
79
+ const previous = mergedById.get(id)
80
+ if (previous === undefined || stableStringify(previous) !== stableStringify(entry)) changed.push(entry)
81
+ }
82
+ const removedIds = [...mergedById.keys()].filter((id) => !runtimeById.has(id))
83
+ return { changed, removedIds }
84
+ }
85
+
86
+ /** Merge captured patch changes into the overlay entry list (by id; keep order stable). */
87
+ export function mergeOverlayPatchEntries(overlayEntries = [], { changed = [], removedIds = [] } = {}, mergedEntries = []) {
88
+ const byId = new Map((overlayEntries ?? []).map((entry) => [String(entry?.id ?? ''), entry]))
89
+ const mergedById = new Map((mergedEntries ?? []).map((entry) => [String(entry?.id ?? ''), entry]))
90
+ for (const entry of changed) byId.set(String(entry?.id ?? ''), entry)
91
+ for (const id of removedIds) {
92
+ const previous = byId.get(id) ?? mergedById.get(id)
93
+ byId.set(id, { ...(previous && typeof previous === 'object' ? previous : { id }), disabled: true })
94
+ }
95
+ return [...byId.values()]
96
+ }
97
+
98
+ function isRealDirectory(entryPath) {
99
+ try {
100
+ const stat = fs.lstatSync(entryPath)
101
+ return stat.isDirectory() && !stat.isSymbolicLink()
102
+ } catch {
103
+ return false
104
+ }
105
+ }
106
+
107
+ function packageVersion(entryDir) {
108
+ return String(readJson(path.join(entryDir, 'package.json'), null)?.version ?? '')
109
+ }
110
+
111
+ /** Module entries under `node_modules`, scope entries expanded; link entries are reported as untouched. */
112
+ function listModuleEntries(modulesDir) {
113
+ const entries = []
114
+ let top = []
115
+ try { top = fs.readdirSync(modulesDir, { withFileTypes: true }) } catch { return entries }
116
+ for (const entry of top) {
117
+ const name = entry.name
118
+ if (INTERNAL_MODULE_NAMES.has(name) || name.startsWith('.')) continue
119
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue
120
+ const absolute = path.join(modulesDir, name)
121
+ if (name.startsWith('@')) {
122
+ // A mirrored scope is a single junction; its children were not touched by pnpm.
123
+ const scopeIsLink = !isRealDirectory(absolute)
124
+ let children = []
125
+ try { children = fs.readdirSync(absolute, { withFileTypes: true }) } catch { children = [] }
126
+ for (const child of children) {
127
+ if (!child.isDirectory() && !child.isSymbolicLink()) continue
128
+ entries.push({ rel: `${name}/${child.name}`, absolute: path.join(absolute, child.name), link: scopeIsLink || child.isSymbolicLink() })
129
+ }
130
+ continue
131
+ }
132
+ entries.push({ rel: name, absolute, link: !isRealDirectory(absolute) })
133
+ }
134
+ return entries
135
+ }
136
+
137
+ /**
138
+ * Decide which runtime module entries must travel into the essence tree.
139
+ * Junction entries are untouched mirror entries (pnpm never rewrote them) and are skipped.
140
+ * Real directories are the packages pnpm re-materialized in the runtime; only those whose
141
+ * version differs from the essence copy (or that the essence does not have) are copied.
142
+ * Entries the runtime no longer carries are removed from the essence tree.
143
+ * @param {string} runtimeModules
144
+ * @param {string} essenceModules
145
+ * @returns {{copy:Array<{rel:string, from:string}>, remove:string[], untouched:string[]}}
146
+ */
147
+ export function planRuntimeModuleChanges(runtimeModules, essenceModules) {
148
+ const copy = []
149
+ const remove = []
150
+ const untouched = []
151
+ const runtimeEntries = listModuleEntries(runtimeModules)
152
+ const runtimeByRel = new Map(runtimeEntries.map((entry) => [entry.rel, entry]))
153
+ for (const entry of runtimeEntries) {
154
+ if (entry.link === true || !isRealDirectory(entry.absolute)) { untouched.push(entry.rel); continue }
155
+ const destination = path.join(essenceModules, entry.rel)
156
+ if (!exists(destination)) { copy.push({ rel: entry.rel, from: entry.absolute }); continue }
157
+ const runtimeVersion = packageVersion(entry.absolute)
158
+ const essenceVersion = packageVersion(destination)
159
+ if (runtimeVersion !== essenceVersion) copy.push({ rel: entry.rel, from: entry.absolute })
160
+ else untouched.push(entry.rel)
161
+ }
162
+ const essenceEntries = listModuleEntries(essenceModules)
163
+ for (const entry of essenceEntries) {
164
+ if (!runtimeByRel.has(entry.rel)) remove.push(entry.rel)
165
+ }
166
+ return { copy, remove, untouched }
167
+ }
168
+
169
+ /** Hardlink-copy one planned entry into place, replacing the essence copy atomically enough. */
170
+ function materializeModuleEntry(essenceModules, { rel, from }) {
171
+ const destination = path.join(essenceModules, rel)
172
+ const staging = path.join(essenceModules, `.fang-sync-${rel.replace(/[\\/]/g, '_')}`)
173
+ removeTree(staging)
174
+ ensureDir(path.dirname(destination))
175
+ hardlinkTree(from, staging)
176
+ removeTree(destination)
177
+ fs.renameSync(staging, destination)
178
+ }
179
+
180
+ /**
181
+ * Execute a module plan; returns counts plus the entries it could not copy.
182
+ * @param {string} runtimeModules
183
+ * @param {string} essenceModules
184
+ * @param {ReturnType<typeof planRuntimeModuleChanges>} [plan]
185
+ */
186
+ export function reconcileRuntimeModules(runtimeModules, essenceModules, plan = planRuntimeModuleChanges(runtimeModules, essenceModules)) {
187
+ const copied = []
188
+ const removed = []
189
+ const failed = []
190
+ for (const entry of plan.copy) {
191
+ try { materializeModuleEntry(essenceModules, entry); copied.push(entry.rel) } catch (error) {
192
+ failed.push({ rel: entry.rel, error: String(error?.message ?? error) })
193
+ }
194
+ }
195
+ for (const rel of plan.remove) {
196
+ try { removeTree(path.join(essenceModules, rel)); removed.push(rel) } catch { /* best effort */ }
197
+ }
198
+ // Drop scopes emptied by the removals.
199
+ let scopes = []
200
+ try { scopes = fs.readdirSync(essenceModules, { withFileTypes: true }).filter((entry) => entry.name.startsWith('@')).map((entry) => entry.name) } catch { scopes = [] }
201
+ for (const scope of scopes) {
202
+ const scopePath = path.join(essenceModules, scope)
203
+ try { if (fs.readdirSync(scopePath).length === 0) removeTree(scopePath) } catch { /* ignore */ }
204
+ }
205
+ return { copied, removed, failed, untouched: plan.untouched }
206
+ }
207
+
208
+ /** Signature of the runtime profile's plugin configuration; cheap no-op detection. */
209
+ export function runtimeCaptureSignature(runtimeProfileDir) {
210
+ const packageText = readText(path.join(String(runtimeProfileDir ?? ''), 'package.json'))
211
+ const patchText = readText(path.join(String(runtimeProfileDir ?? ''), 'cordis.patch.yml'))
212
+ let modulesMtime = 0
213
+ try { modulesMtime = fs.statSync(path.join(String(runtimeProfileDir ?? ''), 'node_modules', '.modules.yaml')).mtimeMs } catch { modulesMtime = 0 }
214
+ return `${packageText.length}:${patchText.length}:${modulesMtime}`
215
+ }
216
+
217
+ function readCaptureMarker(runtimeProfileDir) {
218
+ return readJson(path.join(String(runtimeProfileDir ?? ''), CAPTURE_MARKER_FILE), null)
219
+ }
220
+
221
+ function writeCaptureMarker(runtimeProfileDir, marker) {
222
+ try { writeJsonAtomic(path.join(String(runtimeProfileDir ?? ''), CAPTURE_MARKER_FILE), marker) } catch { /* marker is an optimization only */ }
223
+ }
224
+
225
+ /**
226
+ * Capture the runtime profile's plugin work into the essence and recompute its merged
227
+ * profile. Safe to call when nothing changed (signature check) or when the runtime
228
+ * profile does not exist yet (no-op).
229
+ * @param {{essenceManager:object, essenceId:string, runtimeProfileDir:string, logger?:object}} options
230
+ * @returns {{ok:boolean, captured:boolean, packageChanged?:boolean, patchChanged?:number, modules?:object, error?:string, detail?:string}}
231
+ */
232
+ export function captureRuntimeProfileIntoEssence({ essenceManager, essenceId, runtimeProfileDir, logger = null } = {}) {
233
+ const id = String(essenceId ?? '').trim()
234
+ const profileDir = String(runtimeProfileDir ?? '').trim()
235
+ if (!essenceManager || typeof essenceManager.loadOverlay !== 'function' || typeof essenceManager.recompute !== 'function') {
236
+ return { ok: false, captured: false, error: 'essence-manager-unavailable' }
237
+ }
238
+ if (!id || !profileDir || !exists(profileDir)) return { ok: true, captured: false, skipped: 'runtime-profile-missing' }
239
+ const runtimePkg = readPackageJson(profileDir)
240
+ if (!runtimePkg) return { ok: true, captured: false, skipped: 'runtime-package-missing' }
241
+ const signature = runtimeCaptureSignature(profileDir)
242
+ const previousMarker = readCaptureMarker(profileDir)
243
+ if (previousMarker?.signature === signature) return { ok: true, captured: false, skipped: 'unchanged' }
244
+
245
+ const root = essenceManager.essenceRoot(id)
246
+ const mergedProfile = essenceManager.mergedProfileDir(id)
247
+ const mergedPkg = readPackageJson(mergedProfile) ?? {}
248
+ const runtimePatchText = readText(path.join(profileDir, 'cordis.patch.yml'))
249
+ const mergedPatchText = readText(path.join(mergedProfile, 'cordis.patch.yml'))
250
+ const runtimeEntries = parsePatchEntries(runtimePatchText).entries
251
+ const mergedEntries = parsePatchEntries(mergedPatchText).entries
252
+ const packageChanged = stableStringify(pickProfilePackage(runtimePkg)) !== stableStringify(pickProfilePackage(mergedPkg))
253
+ const { changed, removedIds } = diffPatchEntries(mergedEntries, runtimeEntries)
254
+ const runtimeModules = path.join(profileDir, 'node_modules')
255
+ const essenceModules = path.join(mergedProfile, 'node_modules')
256
+ const modulePlan = planRuntimeModuleChanges(runtimeModules, essenceModules)
257
+ const moduleChanges = modulePlan.copy.length + modulePlan.remove.length
258
+ if (!packageChanged && changed.length === 0 && removedIds.length === 0 && moduleChanges === 0) {
259
+ writeCaptureMarker(profileDir, { at: Date.now(), signature, captured: false })
260
+ return { ok: true, captured: false, skipped: 'no-plugin-changes' }
261
+ }
262
+
263
+ // 1) overlay: package.json (deps + bundles + profile metadata) and changed patch entries
264
+ const overlay = essenceManager.loadOverlay(root)
265
+ if (packageChanged) overlay.packageJson = { ...overlay.packageJson, ...pickProfilePackage(runtimePkg) }
266
+ if (changed.length > 0 || removedIds.length > 0) {
267
+ overlay.patchEntries = mergeOverlayPatchEntries(overlay.patchEntries ?? [], { changed, removedIds }, mergedEntries)
268
+ }
269
+ essenceManager.saveOverlay(root, overlay)
270
+ // 2) pnpm dependency graph files ride with the overlay so every rematerialization keeps them
271
+ const overlayRoot = path.join(root, 'overlay')
272
+ for (const name of CAPTURED_AUX_FILES) {
273
+ const source = path.join(profileDir, name)
274
+ if (!exists(source)) continue
275
+ try { fs.copyFileSync(source, path.join(overlayRoot, name)) } catch { /* single file best effort */ }
276
+ }
277
+ // 3) recompute merged (materializeMerged preserves the existing module tree) …
278
+ try {
279
+ essenceManager.recompute(id)
280
+ } catch (error) {
281
+ return { ok: false, captured: false, error: 'recompute-failed', detail: String(error?.message ?? error) }
282
+ }
283
+ // 4) … then hardlink the touched packages into the essence module tree.
284
+ let modules = { copied: [], removed: [], failed: [], untouched: [] }
285
+ try {
286
+ const essenceModulesAfter = path.join(essenceManager.mergedProfileDir(id), 'node_modules')
287
+ modules = reconcileRuntimeModules(runtimeModules, essenceModulesAfter, modulePlan)
288
+ } catch (error) {
289
+ logger?.warn?.(`[fang] runtime capture module sync failed: ${String(error?.message ?? error)}`)
290
+ modules = { copied: [], removed: [], failed: [{ rel: '*', error: String(error?.message ?? error) }], untouched: [] }
291
+ }
292
+ writeCaptureMarker(profileDir, {
293
+ at: Date.now(),
294
+ signature,
295
+ captured: true,
296
+ packageChanged,
297
+ patchChanged: changed.length + removedIds.length,
298
+ modules: { copied: modules.copied.length, removed: modules.removed.length, failed: modules.failed.length },
299
+ })
300
+ return {
301
+ ok: true,
302
+ captured: true,
303
+ packageChanged,
304
+ patchChanged: changed.length + removedIds.length,
305
+ modules,
306
+ }
307
+ }
@@ -118,7 +118,6 @@ export function apply(ctx, config) {
118
118
  let settledDigests = {}
119
119
  let lastEventAt = null
120
120
  let lastFlushAt = null
121
- let startedAt = null
122
121
  let forcedHighRisk = false
123
122
  let dirty = new Set()
124
123
  let flushQueue = Promise.resolve()
@@ -220,7 +219,6 @@ export function apply(ctx, config) {
220
219
  stop()
221
220
  ensureDir(next)
222
221
  dir = next
223
- startedAt = nowMs()
224
222
  lastEventAt = null
225
223
  lastFlushAt = null
226
224
  forcedHighRisk = false
@@ -238,7 +236,6 @@ export function apply(ctx, config) {
238
236
  dir = ''
239
237
  dirty = new Set()
240
238
  lastEventAt = null
241
- startedAt = null
242
239
  lastFlushAt = null
243
240
  forcedHighRisk = false
244
241
  baselineDigests = {}
@@ -265,7 +262,12 @@ export function apply(ctx, config) {
265
262
  if (!pending.length) {
266
263
  return { state: BUFFER_STATE.SETTLED, dir, lastEventAt, pending: [], highRisk: [], mode, lastFlushAt }
267
264
  }
268
- const quietMs = nowMs() - (lastEventAt ?? startedAt ?? nowMs())
265
+ // A pending change can be observed before any watcher/poller event timestamp exists
266
+ // (the digest fallback in currentDiff() sees it first). Stamping the observation time
267
+ // keeps the quiet window honest: without it, the quiet window has no start bound and
268
+ // state() could report pending-high-risk with a null lastEventAt.
269
+ if (lastEventAt === null) lastEventAt = nowMs()
270
+ const quietMs = nowMs() - lastEventAt
269
271
  const judged =
270
272
  forcedHighRisk || quietMs >= settleMs()
271
273
  ? BUFFER_STATE.PENDING_HIGH_RISK
@@ -31,6 +31,8 @@
31
31
  // `shell: true`; `.mjs`/`.js` entries are launched through node; `.exe` directly.
32
32
  import { spawn as spawnProcess, spawnSync } from 'node:child_process'
33
33
  import { randomBytes } from 'node:crypto'
34
+ import fs from 'node:fs'
35
+ import { createRequire } from 'node:module'
34
36
  import net from 'node:net'
35
37
  import path from 'node:path'
36
38
  import {
@@ -41,10 +43,11 @@ import {
41
43
  bus,
42
44
  copyTree,
43
45
  ensureDir,
46
+ ensureModuleMirror,
44
47
  exists,
45
48
  iso,
46
49
  listFiles,
47
- makeJunction,
50
+ mirrorModuleTree,
48
51
  newId,
49
52
  nowMs,
50
53
  parseWebUrl,
@@ -176,12 +179,19 @@ export function isShellLauncher(cliPath) {
176
179
  * Pure: argv appended to the CLI (CONTRACTS.md §5.1).
177
180
  * v2: with allocatePorts the forker passes the pre-allocated `--port <n>`; the v1 fallback
178
181
  * is still `--port 0` (OS picks a free port).
182
+ * v3.1.7: `patchPaths` are launcher layers (`--patch <path>`) handed to the child before
183
+ * its app args; the headless directory-picker overlay travels this way.
179
184
  * @returns {string[]}
180
185
  */
181
- export function buildSpawnArgs({ profile = 'default', port = 0, noOpen = true } = {}) {
186
+ export function buildSpawnArgs({ profile = 'default', port = 0, noOpen = true, patchPaths = [] } = {}) {
182
187
  const n = Math.floor(Number(port))
183
188
  const p = Number.isInteger(n) && n >= 0 && n <= 65535 ? n : 0
184
- const args = ['--profile', safeProfile(profile), '--port', String(p)]
189
+ const args = ['--profile', safeProfile(profile)]
190
+ for (const entry of Array.isArray(patchPaths) ? patchPaths : []) {
191
+ const patchPath = String(entry ?? '').trim()
192
+ if (patchPath) args.push('--patch', patchPath)
193
+ }
194
+ args.push('--port', String(p))
185
195
  if (noOpen) args.push('--no-open')
186
196
  return args
187
197
  }
@@ -194,11 +204,14 @@ export function buildSpawnArgs({ profile = 'default', port = 0, noOpen = true }
194
204
  * Never touches the filesystem, so it is safe to unit-test without launching anything.
195
205
  * @returns {{command:string, args:string[], shell:boolean, windowsHide:boolean, nodeScript:boolean}}
196
206
  */
197
- export function buildLaunchSpec({ cliPath = '', profile = 'default', port = 0 } = {}) {
207
+ export function buildLaunchSpec({ cliPath = '', profile = 'default', port = 0, patchPaths = [] } = {}) {
198
208
  const entry = String(cliPath ?? '').trim()
199
- const args = buildSpawnArgs({ profile, port })
209
+ const args = buildSpawnArgs({ profile, port, patchPaths })
200
210
  if (isShellLauncher(entry)) {
201
- return { command: entry, args, shell: true, windowsHide: true, nodeScript: false }
211
+ // `shell: true` concatenates argv without escaping (DEP0190); a profile home or overlay
212
+ // path containing whitespace would otherwise split into two child arguments.
213
+ const quoted = args.map((arg) => (/[\s"]/u.test(arg) ? `"${String(arg).replace(/"/g, '\\"')}"` : arg))
214
+ return { command: entry, args: quoted, shell: true, windowsHide: true, nodeScript: false }
202
215
  }
203
216
  if (/\.(mjs|cjs|js)$/i.test(entry)) {
204
217
  return { command: process.execPath, args: [entry, ...args], shell: false, windowsHide: true, nodeScript: true }
@@ -233,6 +246,91 @@ export function buildForkChildEnv(base = process.env, overrides = {}) {
233
246
  return env
234
247
  }
235
248
 
249
+ /**
250
+ * The launch overlay that pins the directory picker to the browser dialog in every
251
+ * fork/ESSENCE-RUNTIME web host.
252
+ *
253
+ * `dsh-host-directory-picker-auto` resolves `native` on win32/darwin whenever the
254
+ * bind is loopback and the launch is not SSH — it has no way to know the host was
255
+ * started headless through `dsh.cmd` (ELECTRON_RUN_AS_NODE, no Electron shell), so
256
+ * the native chooser has no window to open and "选择工作区" fails in the fork Web UI
257
+ * (v3.1.7 report). The documented composition switch is an overlay that disables
258
+ * the auto row and mounts the browse backend + its client surface directly; both
259
+ * package names exist as installation dependencies of the same DSH release.
260
+ */
261
+ export const HEADLESS_PICKER_OVERLAY = [
262
+ '# dsh-Fang v3.1.7: headless web host (dsh.cmd --no-open) has no native chooser window.',
263
+ '# Pin the directory-picker interaction to the browser dialog.',
264
+ '- id: directory-picker',
265
+ ' disabled: true',
266
+ '- insert:',
267
+ ' - id: directory-picker-browse',
268
+ " name: '@deepseek-ai/dsh-host-directory-picker-browse'",
269
+ ' - id: ui-directory-picker-browse',
270
+ " name: '@deepseek-ai/dsh-client-ui-directory-picker-browse'",
271
+ '',
272
+ ].join('\n')
273
+
274
+ /** File name of the headless launch overlay inside the fork/essence-runtime profile. */
275
+ export const HEADLESS_PICKER_OVERLAY_FILE = 'fang-headless.patch.yml'
276
+
277
+ /** Whether this DSH installation carries the browse-picker pair the overlay mounts. */
278
+ export function headlessPickerSupported({ cliPath = '' } = {}) {
279
+ const names = [
280
+ '@deepseek-ai/dsh-host-directory-picker-browse',
281
+ '@deepseek-ai/dsh-client-ui-directory-picker-browse',
282
+ ]
283
+ let require = null
284
+ try { require = createRequire(import.meta.url) } catch { require = null }
285
+ const anchors = []
286
+ // Desktop install: <root>/resources/app.asar/dsh/node_modules (asar-aware fs in the host).
287
+ try { anchors.push(path.join(path.dirname(process.execPath), 'resources', 'app.asar', 'dsh', 'node_modules')) } catch { /* ignore */ }
288
+ // Launcher-derived install root: .../resources/runtime/cli/bin/dsh.cmd → .../resources/app.asar/dsh/node_modules
289
+ const cli = String(cliPath ?? '').trim()
290
+ if (cli) {
291
+ const resources = path.resolve(path.dirname(cli), '..', '..', '..', '..', 'resources')
292
+ anchors.push(path.join(resources, 'app.asar', 'dsh', 'node_modules'))
293
+ }
294
+ for (const name of names) {
295
+ let found = false
296
+ if (require) {
297
+ try { require.resolve(name); found = true } catch { /* not resolvable here */ }
298
+ }
299
+ if (!found) {
300
+ for (const anchor of anchors) {
301
+ try {
302
+ if (fs.existsSync(path.join(anchor, ...name.split('/'), 'package.json'))) { found = true; break }
303
+ } catch { /* ignore */ }
304
+ }
305
+ }
306
+ if (!found) return false
307
+ }
308
+ return true
309
+ }
310
+
311
+ /**
312
+ * Write (or refresh) the headless-picker launch overlay in `profileDir`.
313
+ * `DSH_FANG_HEADLESS_PICKER_PATCH=0` opts out; an installation without the browse
314
+ * pair keeps the DSH default (native) so an unknown-version host is not patched blind.
315
+ * @param {string} profileDir The fork/essence-runtime profile directory.
316
+ * @param {{cliPath?: string, supported?: boolean}} [options] The launcher the fork will
317
+ * be started with; `supported` overrides the installation probe (tests).
318
+ * @returns {string|null} The overlay path to pass as `--patch`, or null.
319
+ */
320
+ export function writeHeadlessPickerOverlay(profileDir, { cliPath = '', supported } = {}) {
321
+ if (String(process.env.DSH_FANG_HEADLESS_PICKER_PATCH ?? '1') === '0') return null
322
+ if (!profileDir || !exists(profileDir)) return null
323
+ const available = typeof supported === 'boolean' ? supported : headlessPickerSupported({ cliPath })
324
+ if (!available) return null
325
+ const file = path.join(profileDir, HEADLESS_PICKER_OVERLAY_FILE)
326
+ try {
327
+ writeFileAtomic(file, HEADLESS_PICKER_OVERLAY)
328
+ return file
329
+ } catch {
330
+ return null
331
+ }
332
+ }
333
+
236
334
  /**
237
335
  * Pure: why did a fork exit? (CONTRACTS.md §5.1)
238
336
  * 0 = normal, 75 = the guard allowed a restart (supervisor contract), else crash.
@@ -708,10 +806,12 @@ export function apply(ctx, config) {
708
806
  const link = path.join(templateDir, 'node_modules')
709
807
  if (source && exists(source)) {
710
808
  try {
711
- makeJunction(source, link)
712
- files.push('node_modules')
809
+ // v3.1.7: per-entry mirror instead of one whole-tree junction — see fsx.mirrorModuleTree.
810
+ const mirrored = mirrorModuleTree(source, link)
811
+ if (mirrored.ok !== true) warnings.push(`node-modules-mirror-failed: ${mirrored.error ?? 'unknown'}`)
812
+ else files.push('node_modules')
713
813
  } catch (e) {
714
- warnings.push(`node-modules-junction-failed: ${msgOf(e)}`)
814
+ warnings.push(`node-modules-mirror-failed: ${msgOf(e)}`)
715
815
  }
716
816
  } else {
717
817
  warnings.push('node-modules-source-missing')
@@ -795,13 +895,21 @@ export function apply(ctx, config) {
795
895
  // 配置文件只读:防误写(DSH_FANG_FORK_PROFILE_RO=0 可关)。
796
896
  const profileReadonly = setProfileConfigReadonly(profileDir, true)
797
897
 
798
- // node_modules junction in the fork profile (always to the mother's module tree).
898
+ // node_modules mirror in the fork profile (always to the mother's module tree).
899
+ // v3.1.7: one junction per top-level entry instead of a whole-tree junction. DSH's
900
+ // profile-scope resolver only supplies installation packages (`@deepseek-ai/*`) to an
901
+ // importer inside the profile tree or below a linked root; a whole-tree junction keeps
902
+ // the importer outside every scope, so lazy host imports fall back to plugin shims
903
+ // (w2m's shim emits `required: false` in a property schema → the provider rejects
904
+ // every request: "Invalid schema for function 'w2m_report'", v3.1.7 report).
799
905
  let nodeModules = null
800
906
  if (exists(nodeModulesSource)) {
801
907
  try {
802
- nodeModules = makeJunction(nodeModulesSource, path.join(profileDir, 'node_modules'))
908
+ const mirrored = mirrorModuleTree(nodeModulesSource, path.join(profileDir, 'node_modules'))
909
+ if (mirrored.ok === true) nodeModules = nodeModulesSource
910
+ else warnings.push(`node-modules-mirror-failed: ${mirrored.error ?? 'unknown'}`)
803
911
  } catch (e) {
804
- warnings.push(`node-modules-junction-failed: ${msgOf(e)}`)
912
+ warnings.push(`node-modules-mirror-failed: ${msgOf(e)}`)
805
913
  }
806
914
  } else if (!cleanTemplate) {
807
915
  // Degraded but still usable: the fork simply has no node_modules link to the mother.
@@ -928,6 +1036,22 @@ export function apply(ctx, config) {
928
1036
  }
929
1037
  try { rec.configLock = applyForkConfigLock(rec.profileDir) } catch { rec.configLock = { ok: false } }
930
1038
  try { rec.profileReadonly = setProfileConfigReadonly(rec.profileDir, true) } catch { rec.profileReadonly = { ok: false } }
1039
+ // v3.1.7: repair a whole-tree `node_modules` junction left by any previous release into
1040
+ // the per-entry mirror. This is what makes the fork host resolve the installation's
1041
+ // `@deepseek-ai/*` packages for profile plugins again; without it every agent request in
1042
+ // the fork is rejected by the provider (w2m offline shim → invalid tool schema).
1043
+ try {
1044
+ const repaired = ensureModuleMirror(path.join(rec.profileDir, 'node_modules'))
1045
+ rec.nodeModulesMirror = {
1046
+ changed: repaired.changed === true,
1047
+ ok: repaired.ok !== false,
1048
+ source: repaired.source ?? null,
1049
+ links: Array.isArray(repaired.links) ? repaired.links.length : 0,
1050
+ error: repaired.error ?? null,
1051
+ }
1052
+ } catch (e) {
1053
+ rec.nodeModulesMirror = { ok: false, changed: false, error: msgOf(e) }
1054
+ }
931
1055
  writeForkMetaOf(rec)
932
1056
  // 广播新 token:首次派生 = 生成,重启 = 刷新;订阅者拿到的是「当前 token」,
933
1057
  // 不是「进程就绪」信号(进程就绪以 fang/fork-started 为准)。
@@ -998,7 +1122,13 @@ export function apply(ctx, config) {
998
1122
  }
999
1123
  pendingSpawns.add(cleanup)
1000
1124
 
1001
- const spec = buildLaunchSpec({ cliPath, profile, port: expectedPort })
1125
+ // v3.1.7: the headless web host (`dsh.cmd --no-open`, ELECTRON_RUN_AS_NODE) has no
1126
+ // window for the native directory chooser; pin the browse interaction through a
1127
+ // launcher overlay so "select workspace" works inside every fork Web UI.
1128
+ const patchPaths = []
1129
+ const headlessOverlay = writeHeadlessPickerOverlay(rec.profileDir, { cliPath })
1130
+ if (headlessOverlay) patchPaths.push(headlessOverlay)
1131
+ const spec = buildLaunchSpec({ cliPath, profile, port: expectedPort, patchPaths })
1002
1132
  const env = buildForkChildEnv(process.env, {
1003
1133
  DSH_HOME: homeDir,
1004
1134
  // Fork identity is injected by the forker (a fork must never be able to call itself mother).
@@ -14,11 +14,13 @@ import path from 'node:path'
14
14
  import {
15
15
  z, roleGate, resolveFangLayout, resolveProfileDir, resolveSessionsLayout,
16
16
  SERVICE, AUDIT, TASK_STATUS, FORK_STATUS, FANG_VERSION, ADAPTER_OP,
17
- exists, ensureDir, readJson, writeJsonAtomic, writeFileAtomic, sha256, removeTree, copyTree, digestTree, makeJunction,
17
+ exists, ensureDir, ensureModuleMirror, readJson, writeJsonAtomic, writeFileAtomic, sha256, removeTree, copyTree, digestTree,
18
18
  newId, iso, nowMs, bus, sleep, parseWebUrl, probeWebUrl,
19
19
  invokeCommercial, commercialConfigSchemaDefaults,
20
20
  } from '../kernel/index.mjs'
21
21
  import { parseWorkspaceIndex, scanSessionDirs, readBoundedEvents, extractSessionTitle, encodeWorkspaceKey } from '../lib/session-format.mjs'
22
+ import { ensureEssenceRuntimePnpmConfig, readNodeLinker } from '../lib/pnpm-store.mjs'
23
+ import { captureRuntimeProfileIntoEssence } from '../lib/runtime-capture.mjs'
22
24
  import { negotiateProtocol } from '../lib/adapter-protocol.mjs'
23
25
  import { describeMotherLink, probeLink, readSharedProfileSummary } from '../lib/mother-link.mjs'
24
26
  import { MirrorManager } from '../lib/mirror.mjs'
@@ -2143,6 +2145,21 @@ export function apply(ctx, config) {
2143
2145
  if (sessionQuota.over) throw new Error(`session-quota-exceeded: ${sessionQuota.used}/${sessionQuota.limit}`)
2144
2146
  const f = forker()
2145
2147
  if (!f || typeof f.provision !== 'function' || typeof f.spawn !== 'function') throw new Error('forker-unavailable')
2148
+ const forkId = runtimeForkId(id)
2149
+ const runtimeProfileDirEarly = path.join(runtimeHomeFor(id), 'profiles', 'essence-runtime')
2150
+ // v3.1.8:上次运行态里的插件安装/更新/卸载先捕获回元宝(overlay + merged + 模块树),
2151
+ // 否则 ensureFresh/provision 会用旧的元宝配置重放,把用户的工作静默丢掉。
2152
+ let capture = null
2153
+ try {
2154
+ const runtimeStatus = f.status?.(forkId) ?? null
2155
+ if (runtimeStatus?.running !== true && exists(runtimeProfileDirEarly)) {
2156
+ capture = captureRuntimeProfileIntoEssence({
2157
+ essenceManager, essenceId: id, runtimeProfileDir: runtimeProfileDirEarly, logger: ctx.logger,
2158
+ })
2159
+ }
2160
+ } catch (error) {
2161
+ capture = { ok: false, captured: false, error: 'capture-threw', detail: String(error?.message ?? error) }
2162
+ }
2146
2163
  await essenceManager.ensureFresh(id)
2147
2164
  const merged = essenceManager.mergedProfileDir(id)
2148
2165
  if (!exists(merged)) throw new Error('merged-profile-missing')
@@ -2161,26 +2178,16 @@ export function apply(ctx, config) {
2161
2178
  }
2162
2179
  // 复制来的模块树记录了母体 store;元主/运行态的 pnpm 必须显式用同一个 store,
2163
2180
  // 否则项目在 D: 盘、模块来自 C: store 时会报 ERR_PNPM_UNEXPECTED_STORE。
2164
- const writeModuleStoreConfig = (profileDir) => {
2165
- try {
2166
- const modulesYaml = fs.readFileSync(path.join(essenceModules, '.modules.yaml'), 'utf8')
2167
- const store = /^storeDir:\s*(.+)$/m.exec(modulesYaml)?.[1]?.trim()
2168
- if (!store) return
2169
- ensureDir(profileDir)
2170
- const file = path.join(profileDir, '.npmrc')
2171
- if (exists(file) && fs.readFileSync(file, 'utf8').includes('store-dir=')) return
2172
- fs.writeFileSync(file, `store-dir=${store}\npackage-import-method=copy\n`, 'utf8')
2173
- } catch { /* missing modules metadata is non-fatal */ }
2174
- }
2175
- writeModuleStoreConfig(merged)
2176
- const forkId = runtimeForkId(id)
2181
+ // v3.1.8:pnpm 11 只从 pnpm-workspace.yaml 读取非鉴权设置(.npmrc 只剩鉴权/网络键),
2182
+ // 且 modules manifest 里记录的 virtual store 仍是母体路径;两处都由
2183
+ // ensureEssenceRuntimePnpmConfig 在运行态 profile 上修正(见下方 spawn 前)。
2177
2184
  // v3.0.9 三区:运行态 home 在 runtimeRoot 下(FANG_HOME 时是 sessions/<essenceId>/home),
2178
2185
  // 原身文件夹只保留配置,项目/会话/任务文件不落原身目录。
2179
2186
  const homeDir = runtimeHomeFor(id)
2180
2187
  assertInside(layout.runtimeRoot, homeDir, 'runtime-home')
2181
2188
  // 运行态 profile 的 node_modules 必须重新指向该元主自己的模块树。
2182
2189
  // makeJunction 对已存在的链接不会替换,所以先安全移除旧 junction(不进入目标)。
2183
- const runtimeProfileDir = path.join(homeDir, 'profiles', 'essence-runtime')
2190
+ const runtimeProfileDir = runtimeProfileDirEarly
2184
2191
  const runtimeModules = path.join(runtimeProfileDir, 'node_modules')
2185
2192
  // 迁移/旧版本可能留下“指向不存在 merged/profile/node_modules”的 junction;
2186
2193
  // fs.existsSync 对 broken junction 返回 false,必须用 lstat 才能发现并清掉。
@@ -2209,18 +2216,28 @@ export function apply(ctx, config) {
2209
2216
  if (!provisioned.ok) throw new Error(String(provisioned.error ?? 'runtime-provision-failed'))
2210
2217
  // 历史版本把生产盘锁写进了 essence-runtime;配置实例必须能管理插件,升级后清掉。
2211
2218
  try { clearForkConfigLock(runtimeProfileDir) } catch { /* best effort */ }
2212
- // provision 若看到旧 junction 可能不替换;这里以 essenceModules 为准做最后自愈。
2213
- if (!exists(runtimeModules)) {
2214
- try {
2215
- const stat = fs.lstatSync(runtimeModules)
2216
- if (stat.isSymbolicLink()) removeTree(runtimeModules)
2217
- } catch { /* ignore */ }
2218
- if (!exists(essenceModules)) throw new Error('runtime-node-modules-source-missing')
2219
- try { makeJunction(essenceModules, runtimeModules) } catch (error) {
2220
- throw new Error(`runtime-node-modules-junction-failed: ${String(error?.message ?? error)}`)
2221
- }
2219
+ // v3.1.7:运行态 profile 的 node_modules 必须是 per-entry mirror(不是整树 junction)。
2220
+ // 整树 junction 会让插件 importer 落在 DSH profile 作用域之外,运行态内 w2m 等插件
2221
+ // 无法解析 @deepseek-ai/*,退回离线 shim,工具 schema 非法 → 模型请求被供应商拒绝。
2222
+ try {
2223
+ const repaired = ensureModuleMirror(runtimeModules)
2224
+ if (repaired.ok === false) throw new Error(repaired.error ?? 'unknown')
2225
+ } catch (error) {
2226
+ throw new Error(`runtime-node-modules-mirror-failed: ${String(error?.message ?? error)}`)
2227
+ }
2228
+ // v3.1.8:让运行态内的 pnpm 真正可用(元宝「插件」页更新/卸载插件走 DSH plugin manager)。
2229
+ // 失败不阻塞实例启动(实例仍可跑会话),但要把原因带回给调用方/面板。
2230
+ let pnpmConfig = null
2231
+ try {
2232
+ pnpmConfig = ensureEssenceRuntimePnpmConfig({
2233
+ profileDir: runtimeProfileDir,
2234
+ modulesDir: runtimeModules,
2235
+ sourceModulesDir: essenceModules,
2236
+ nodeLinker: readNodeLinker(templateDir()),
2237
+ })
2238
+ } catch (error) {
2239
+ pnpmConfig = { ok: false, error: 'pnpm-config-threw', detail: String(error?.message ?? error) }
2222
2240
  }
2223
- writeModuleStoreConfig(runtimeProfileDir)
2224
2241
  // 先导入选中的进行中会话,再拉起实例(实例启动时就能看到它们)。
2225
2242
  const importedSessions = importSessionsInto(homeDir, input?.sessionIds)
2226
2243
  // 注意:forker.spawn 需要显式 homeDir/profile(它不从 provision 记录里猜)。
@@ -2237,15 +2254,27 @@ export function apply(ctx, config) {
2237
2254
  url: started.url, port: started.port, pid: started.pid,
2238
2255
  sandboxHome: homeDir,
2239
2256
  importedSessions,
2257
+ pnpmConfig,
2258
+ capture,
2240
2259
  }
2241
2260
  },
2242
- stopEssenceRuntime: (essenceId) => {
2261
+ stopEssenceRuntime: async (essenceId) => {
2243
2262
  const id = String(essenceId ?? '').trim()
2244
2263
  const f = forker()
2245
2264
  if (!f || typeof f.stop !== 'function') return { ok: false, error: 'forker-unavailable' }
2246
2265
  const forkId = runtimeForkId(id)
2247
2266
  const out = f.stop(forkId)
2248
- return { ok: true, essenceId: id, forkId, stopped: out?.ok !== false }
2267
+ // v3.1.8:停止后把运行态最后一次保存的插件配置捕获回元宝;捕获失败不改变停止结果。
2268
+ let capture = null
2269
+ try {
2270
+ const runtimeProfileDir = path.join(runtimeHomeFor(id), 'profiles', 'essence-runtime')
2271
+ capture = captureRuntimeProfileIntoEssence({
2272
+ essenceManager, essenceId: id, runtimeProfileDir, logger: ctx.logger,
2273
+ })
2274
+ } catch (error) {
2275
+ capture = { ok: false, captured: false, error: 'capture-threw', detail: String(error?.message ?? error) }
2276
+ }
2277
+ return { ok: true, essenceId: id, forkId, stopped: out?.ok !== false, capture }
2249
2278
  },
2250
2279
  essenceRuntimeStatus: (essenceId) => {
2251
2280
  const id = String(essenceId ?? '').trim()