@twinsearth/dsh-fang 3.1.7 → 3.1.9
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/client.js +18 -13
- package/package.json +1 -1
- package/src/kernel/fsx.mjs +41 -0
- package/src/kernel/types.mjs +1 -1
- package/src/lib/essence.mjs +23 -0
- package/src/lib/pnpm-store.mjs +184 -0
- package/src/lib/runtime-capture.mjs +307 -0
- package/src/plugins/buffer-keeper.mjs +6 -4
- package/src/plugins/orchestrator.mjs +48 -17
package/client.js
CHANGED
|
@@ -599,7 +599,7 @@ window.__ModuleLoader__.load({
|
|
|
599
599
|
--f-focus:${TOKENS.focus}; --f-radius-panel:${TOKENS.radiusPanel}; --f-radius-card:${TOKENS.radiusCard}; --f-radius-ctl:${TOKENS.radiusCtl};
|
|
600
600
|
--f-shadow-card:${TOKENS.shadowCard}; --f-shadow-panel:${TOKENS.shadowPanel}; --f-shadow-float:${TOKENS.shadowFloat};
|
|
601
601
|
--f-font:${TOKENS.font}; --f-mono:${TOKENS.mono};
|
|
602
|
-
position:relative;color-scheme:light;min-height:
|
|
602
|
+
position:relative;color-scheme:light;height:100%;min-height:0;box-sizing:border-box;overflow:hidden;
|
|
603
603
|
display:flex;flex-direction:column;gap:16px;padding:18px 20px 22px;
|
|
604
604
|
background:var(--f-bg);color:var(--f-text);font-family:var(--f-font);font-size:13px;line-height:1.5;
|
|
605
605
|
-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility;
|
|
@@ -673,18 +673,18 @@ window.__ModuleLoader__.load({
|
|
|
673
673
|
.chip--neutral{color:var(--f-text-3);background:var(--f-surface-2);border-color:var(--f-border)}
|
|
674
674
|
|
|
675
675
|
/* layout */
|
|
676
|
-
.fang-body{position:relative;display:grid;grid-template-columns:minmax(320px,50fr) minmax(0,50fr);gap:16px;align-items:
|
|
676
|
+
.fang-body{position:relative;display:grid;grid-template-columns:minmax(320px,50fr) minmax(0,50fr);gap:16px;align-items:stretch;height:100%;min-height:0;flex:1 1 auto;overflow:hidden}
|
|
677
677
|
.fang-body.is-resizing{cursor:col-resize;user-select:none}
|
|
678
678
|
.fang-body.is-resizing *{user-select:none}
|
|
679
679
|
.fang-split-handle{position:absolute;top:0;bottom:0;left:50%;width:10px;transform:translateX(-50%);cursor:col-resize;z-index:6;border-radius:6px;background:transparent;touch-action:none}
|
|
680
680
|
.fang-split-handle::after{content:"";position:absolute;top:50%;left:50%;width:3px;height:46px;transform:translate(-50%,-50%);border-radius:3px;background:var(--f-border-strong,var(--f-border));opacity:.55;transition:opacity .15s,background .15s}
|
|
681
681
|
.fang-split-handle:hover::after,.fang-split-handle:focus-visible::after,.fang-body.is-resizing .fang-split-handle::after{opacity:1;background:var(--f-blue,#3b82f6)}
|
|
682
682
|
.fang-split-handle:focus-visible{outline:2px solid var(--f-blue,#3b82f6);outline-offset:2px}
|
|
683
|
-
@media (max-width:1100px){.fang-body{grid-template-columns:1fr}.fang-split-handle{display:none}}
|
|
683
|
+
@media (max-width:1100px){.fang-console{overflow:auto}.fang-body{grid-template-columns:1fr;align-items:start;height:auto;flex:1 0 auto;overflow:visible}.fang-split-handle{display:none}}
|
|
684
684
|
.panel{background:var(--f-surface);border:1px solid var(--f-border);border-radius:var(--f-radius-panel);
|
|
685
685
|
box-shadow:var(--f-shadow-card);display:flex;flex-direction:column;min-height:0;overflow:hidden;
|
|
686
|
-
max-height:
|
|
687
|
-
@media (max-width:1100px){.panel{max-height:
|
|
686
|
+
height:100%;max-height:100%}
|
|
687
|
+
@media (max-width:1100px){.panel{height:auto;max-height:62vh}}
|
|
688
688
|
.panel-head{flex:0 0 auto;padding:16px 16px 10px;display:flex;flex-direction:column;gap:10px}
|
|
689
689
|
.panel-title-row{display:flex;align-items:center;gap:10px;min-height:28px}
|
|
690
690
|
.panel-title{font-size:20px;font-weight:600;letter-spacing:-.014em;line-height:26px;margin:0}
|
|
@@ -692,11 +692,13 @@ window.__ModuleLoader__.load({
|
|
|
692
692
|
.panel-count{margin-left:auto;display:inline-flex;align-items:center;gap:6px;height:26px;padding:0 10px;
|
|
693
693
|
border:1px solid var(--f-border);border-radius:999px;background:var(--f-surface-2);
|
|
694
694
|
font-size:11px;color:var(--f-text-3);font-variant-numeric:tabular-nums;white-space:nowrap}
|
|
695
|
-
.panel-scroll{flex:1 1 auto;min-height:0;overflow:auto;overscroll-behavior:contain;
|
|
696
|
-
scrollbar-
|
|
697
|
-
|
|
698
|
-
.panel-scroll::-webkit-scrollbar
|
|
699
|
-
.panel-scroll::-webkit-scrollbar-
|
|
695
|
+
.panel-scroll{flex:1 1 auto;min-height:0;overflow-y:auto;overflow-x:hidden;overscroll-behavior:contain;
|
|
696
|
+
scrollbar-gutter:stable;padding:0 10px 14px;
|
|
697
|
+
scrollbar-width:thin;scrollbar-color:rgba(16,17,20,.32) rgba(16,17,20,.06)}
|
|
698
|
+
.panel-scroll::-webkit-scrollbar{width:12px;height:12px}
|
|
699
|
+
.panel-scroll::-webkit-scrollbar-track{background:rgba(16,17,20,.05);border-radius:999px}
|
|
700
|
+
.panel-scroll::-webkit-scrollbar-thumb{background:rgba(16,17,20,.30);border:3px solid #fff;border-radius:999px;background-clip:padding-box}
|
|
701
|
+
.panel-scroll::-webkit-scrollbar-thumb:hover{background:rgba(16,17,20,.46);border:2px solid #fff;background-clip:padding-box}
|
|
700
702
|
|
|
701
703
|
/* search */
|
|
702
704
|
.search{position:relative;display:flex;align-items:center}
|
|
@@ -3215,11 +3217,14 @@ window.__ModuleLoader__.load({
|
|
|
3215
3217
|
: null,
|
|
3216
3218
|
...essences.map((essence) => renderEssenceCard(S, app, essence, defaultEssenceId)))
|
|
3217
3219
|
|
|
3220
|
+
// v3.1.9:元主工作区只有一个滚动容器 —— 元主卡片(可能很多)与母体会话列表一起
|
|
3221
|
+
// 滚动,鼠标滚轮/拖动滚动条都作用在同一列;否则卡片区会把会话滚动区挤到 0 高。
|
|
3222
|
+
scroll.prepend(essenceList)
|
|
3223
|
+
scroll.prepend(essenceHead)
|
|
3224
|
+
|
|
3218
3225
|
return h('section', { class: 'panel', 'data-zone': 'mother', 'data-freshness': freshness, 'aria-labelledby': 'fang-mother-title' },
|
|
3219
3226
|
head,
|
|
3220
3227
|
h('div', { class: 'mother-slots' }, renderSlotStrip(projectCapacity(S.status.data, S.tasks.items))),
|
|
3221
|
-
essenceHead,
|
|
3222
|
-
essenceList,
|
|
3223
3228
|
scroll)
|
|
3224
3229
|
}
|
|
3225
3230
|
|
|
@@ -6045,7 +6050,7 @@ window.__ModuleLoader__.load({
|
|
|
6045
6050
|
key: 'fang',
|
|
6046
6051
|
}, () => React.createElement(DomMount, {
|
|
6047
6052
|
mount: mountPanel,
|
|
6048
|
-
style: { display: '
|
|
6053
|
+
style: { display: 'flex', flexDirection: 'column', flex: '1 1 auto', minWidth: 0, minHeight: 0, height: '100%', overflow: 'hidden' },
|
|
6049
6054
|
}))))
|
|
6050
6055
|
// 输入框下方徽标
|
|
6051
6056
|
disposers.push(ctx.slots.inject('conversation.composer.dock', () => ctx.slots.register({
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@twinsearth/dsh-fang",
|
|
3
|
-
"version": "3.1.
|
|
3
|
+
"version": "3.1.9",
|
|
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.",
|
package/src/kernel/fsx.mjs
CHANGED
|
@@ -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))
|
package/src/kernel/types.mjs
CHANGED
package/src/lib/essence.mjs
CHANGED
|
@@ -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
|
-
|
|
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
|
|
@@ -19,6 +19,8 @@ import {
|
|
|
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
|
-
|
|
2165
|
-
|
|
2166
|
-
|
|
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 =
|
|
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 才能发现并清掉。
|
|
@@ -2218,7 +2225,19 @@ export function apply(ctx, config) {
|
|
|
2218
2225
|
} catch (error) {
|
|
2219
2226
|
throw new Error(`runtime-node-modules-mirror-failed: ${String(error?.message ?? error)}`)
|
|
2220
2227
|
}
|
|
2221
|
-
|
|
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) }
|
|
2240
|
+
}
|
|
2222
2241
|
// 先导入选中的进行中会话,再拉起实例(实例启动时就能看到它们)。
|
|
2223
2242
|
const importedSessions = importSessionsInto(homeDir, input?.sessionIds)
|
|
2224
2243
|
// 注意:forker.spawn 需要显式 homeDir/profile(它不从 provision 记录里猜)。
|
|
@@ -2235,15 +2254,27 @@ export function apply(ctx, config) {
|
|
|
2235
2254
|
url: started.url, port: started.port, pid: started.pid,
|
|
2236
2255
|
sandboxHome: homeDir,
|
|
2237
2256
|
importedSessions,
|
|
2257
|
+
pnpmConfig,
|
|
2258
|
+
capture,
|
|
2238
2259
|
}
|
|
2239
2260
|
},
|
|
2240
|
-
stopEssenceRuntime: (essenceId) => {
|
|
2261
|
+
stopEssenceRuntime: async (essenceId) => {
|
|
2241
2262
|
const id = String(essenceId ?? '').trim()
|
|
2242
2263
|
const f = forker()
|
|
2243
2264
|
if (!f || typeof f.stop !== 'function') return { ok: false, error: 'forker-unavailable' }
|
|
2244
2265
|
const forkId = runtimeForkId(id)
|
|
2245
2266
|
const out = f.stop(forkId)
|
|
2246
|
-
|
|
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 }
|
|
2247
2278
|
},
|
|
2248
2279
|
essenceRuntimeStatus: (essenceId) => {
|
|
2249
2280
|
const id = String(essenceId ?? '').trim()
|