@twinsearth/dsh-fang 3.3.1 → 3.7.6
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/README.md +3 -3
- package/client.js +709 -61
- package/cordis.patch.yml +26 -20
- package/docs/APPROVAL-DRILL.md +42 -0
- package/docs/AUTO-WATCHDOG.md +46 -0
- package/docs/DECISION-LOSSLESS.md +36 -0
- package/docs/ESSENCE-AUTO-SYNC.md +32 -0
- package/docs/INBOX-SCROLL.md +33 -0
- package/docs/OVERLAY-MASTER-SWITCH.md +35 -0
- package/docs/PACKAGE-RENAME-v3.3.3.md +40 -0
- package/docs/RESTART-CONFIRMATION.md +29 -0
- package/docs/TEST-STABILITY-v3.4.0.md +30 -0
- package/package.json +9 -5
- package/src/compose.mjs +4 -1
- package/src/contract/VENDOR.json +6 -5
- package/src/contract/constants.js +16 -1
- package/src/contract/relay.js +12 -6
- package/src/kernel/types.mjs +3 -1
- package/src/lib/accelerated-fork.mjs +813 -0
- package/src/lib/accelerated-install.mjs +295 -0
- package/src/lib/accelerated-web.mjs +103 -0
- package/src/lib/approval-drill.mjs +111 -0
- package/src/lib/boot-guard.mjs +6 -2
- package/src/lib/chat-import-delegation.mjs +47 -0
- package/src/lib/compat.mjs +5 -1
- package/src/lib/contract-delegation.mjs +161 -0
- package/src/lib/default-essence.mjs +7 -4
- package/src/lib/essence.mjs +113 -7
- package/src/lib/fork-config-lock.mjs +2 -2
- package/src/lib/fork-core-settings.mjs +95 -0
- package/src/lib/fork-export.mjs +85 -0
- package/src/lib/global-redline.mjs +164 -0
- package/src/lib/http-auth.mjs +36 -0
- package/src/lib/install-snapshot.mjs +77 -0
- package/src/lib/lsp-delegation.mjs +70 -0
- package/src/lib/lsp-provider.mjs +250 -0
- package/src/lib/main-gate.mjs +34 -28
- package/src/lib/mirror.mjs +115 -4
- package/src/lib/node-compat.mjs +24 -0
- package/src/lib/pro-delegation.mjs +185 -0
- package/src/lib/runtime-capture.mjs +11 -3
- package/src/lib/watch-guard.mjs +51 -0
- package/src/plugins/approver.mjs +5 -2
- package/src/plugins/auditor.mjs +125 -18
- package/src/plugins/decision-center.mjs +77 -34
- package/src/plugins/forker.mjs +258 -33
- package/src/plugins/orchestrator.mjs +1508 -65
- package/src/plugins/restart-guard.mjs +79 -2
- package/src/plugins/session-catalog.mjs +127 -40
- package/tools/approval-drill.mjs +21 -0
- package/tools/fangctl.mjs +21 -4
- package/tools/gate/main-city.mjs +1 -1
- package/tools/restart-supervisor.mjs +425 -0
- package/tools/restart-watchdog.mjs +568 -0
- package/vault/client.js +49 -0
- package/vault/cordis.patch.yml +3 -0
- package/vault/lib/vault.mjs +219 -0
- package/vault/package.json +29 -0
package/src/lib/main-gate.mjs
CHANGED
|
@@ -1,16 +1,10 @@
|
|
|
1
|
-
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
-
// Copyright (c) 2026 dsh-Fang contributors
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (c) 2026 dsh-Fang contributors 鈥?see LICENSE-CORE.
|
|
3
3
|
//
|
|
4
|
-
// v3.3.0
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
// 设计约束:
|
|
10
|
-
// * 纯本地、只读优先:默认不写 profile、不联网、不改产物。
|
|
11
|
-
// * 产物校验以 sha256/manifest 为准;profile 校验以「不越界 + 可解析 + 不覆盖」为准。
|
|
12
|
-
// * 崩溃循环 / 安全模式 / 审计链断裂 = blocker:系统级故障不能靠重试绕过。
|
|
13
|
-
// * 需要写盘的两个例外都显式开关:--repair 建 profile 备份;--create 新建 profile。
|
|
4
|
+
// v3.3.0 涓诲煄闂ㄧ锛坢ain-city gate锛?// ------------------------------------------------------------
|
|
5
|
+
// 鐩爣锛氫换浣曘€岃繘涓诲煄銆嶇殑鍔ㄤ綔锛堟墦鍖呫€佸彂甯冦€佸畨瑁呫€侀儴缃层€佹柊寤?profile锛夐兘蹇呴』鍏堣繃
|
|
6
|
+
// 鍚屼竴濂楀彲澶嶆牳鐨勬鏌ワ紱鎷夸笉鍒拌瘉鎹椂 fail-closed锛岃€屼笉鏄潤榛樻斁琛屻€?//
|
|
7
|
+
// 璁捐绾︽潫锛?// * 绾湰鍦般€佸彧璇讳紭鍏堬細榛樿涓嶅啓 profile銆佷笉鑱旂綉銆佷笉鏀逛骇鐗┿€?// * 浜х墿鏍¢獙浠?sha256/manifest 涓哄噯锛沺rofile 鏍¢獙浠ャ€屼笉瓒婄晫 + 鍙В鏋?+ 涓嶈鐩栥€嶄负鍑嗐€?// * 宕╂簝寰幆 / 瀹夊叏妯″紡 / 瀹¤閾炬柇瑁?= blocker锛氱郴缁熺骇鏁呴殰涓嶈兘闈犻噸璇曠粫杩囥€?// * 闇€瑕佸啓鐩樼殑涓や釜渚嬪閮芥樉寮忓紑鍏筹細--repair 寤?profile 澶囦唤锛?-create 鏂板缓 profile銆?
|
|
14
8
|
import fs from 'node:fs'
|
|
15
9
|
import path from 'node:path'
|
|
16
10
|
import crypto from 'node:crypto'
|
|
@@ -36,17 +30,30 @@ const REQUIRED_SOURCE_FILES = Object.freeze([
|
|
|
36
30
|
'src/lib/fork-supervisor.mjs',
|
|
37
31
|
'src/lib/restart-contract.mjs',
|
|
38
32
|
'src/lib/main-gate.mjs',
|
|
33
|
+
'src/lib/approval-drill.mjs',
|
|
34
|
+
'tools/approval-drill.mjs',
|
|
39
35
|
'src/plugins/restart-guard.mjs',
|
|
40
36
|
'src/plugins/scorer.mjs',
|
|
41
37
|
'src/plugins/approver.mjs',
|
|
42
38
|
'src/plugins/auditor.mjs',
|
|
43
39
|
'src/plugins/healer.mjs',
|
|
44
40
|
'tools/gate/main-city.mjs',
|
|
41
|
+
'tools/restart-watchdog.mjs',
|
|
42
|
+
'tools/restart-supervisor.mjs',
|
|
45
43
|
'tools/release/build.mjs',
|
|
46
44
|
'tools/release/preflight.mjs',
|
|
47
45
|
'docs/CRASH-SAFETY.md',
|
|
48
46
|
'docs/MAIN-CITY-GATE.md',
|
|
49
47
|
'docs/DSH-ARCHITECTURE-MAP.md',
|
|
48
|
+
'docs/OVERLAY-MASTER-SWITCH.md',
|
|
49
|
+
'docs/PACKAGE-RENAME-v3.3.3.md',
|
|
50
|
+
'docs/APPROVAL-DRILL.md',
|
|
51
|
+
'docs/RESTART-CONFIRMATION.md',
|
|
52
|
+
'docs/AUTO-WATCHDOG.md',
|
|
53
|
+
'docs/ESSENCE-AUTO-SYNC.md',
|
|
54
|
+
'docs/DECISION-LOSSLESS.md',
|
|
55
|
+
'docs/INBOX-SCROLL.md',
|
|
56
|
+
'docs/TEST-STABILITY-v3.4.0.md',
|
|
50
57
|
])
|
|
51
58
|
|
|
52
59
|
const REQUIRED_ARTIFACT_FILES = Object.freeze([
|
|
@@ -58,6 +65,8 @@ const REQUIRED_ARTIFACT_FILES = Object.freeze([
|
|
|
58
65
|
'src/lib/main-gate.mjs',
|
|
59
66
|
'src/plugins/restart-guard.mjs',
|
|
60
67
|
'tools/gate/main-city.mjs',
|
|
68
|
+
'tools/restart-watchdog.mjs',
|
|
69
|
+
'tools/restart-supervisor.mjs',
|
|
61
70
|
])
|
|
62
71
|
|
|
63
72
|
const SECRET_PATTERNS = Object.freeze([
|
|
@@ -127,7 +136,7 @@ function walkFiles(dir, rel = '', out = [], limit = 5000) {
|
|
|
127
136
|
return out
|
|
128
137
|
}
|
|
129
138
|
|
|
130
|
-
/**
|
|
139
|
+
/** 婧愮爜鏍戯細鐗堟湰銆佹枃妗c€乿endored 濂戠害銆佸叧閿槻绾挎枃浠躲€佸嵄闄╅粯璁ゅ€笺€?*/
|
|
131
140
|
export function checkSourceTree({ root = process.cwd(), version = '' } = {}) {
|
|
132
141
|
const checks = []
|
|
133
142
|
const base = path.resolve(root)
|
|
@@ -180,9 +189,7 @@ export function checkSourceTree({ root = process.cwd(), version = '' } = {}) {
|
|
|
180
189
|
}
|
|
181
190
|
|
|
182
191
|
/**
|
|
183
|
-
* v3.3.1
|
|
184
|
-
* 工作流是「谁能发布、能写什么」的执行入口;它被改坏时,源码门禁可能完全绕过。
|
|
185
|
-
*/
|
|
192
|
+
* v3.3.1锛氱涓冪被鐩爣 workflows 鈥斺€?CI/鍙戝竷宸ヤ綔娴佹湰韬殑瀹¤銆? * 宸ヤ綔娴佹槸銆岃皝鑳藉彂甯冦€佽兘鍐欎粈涔堛€嶇殑鎵ц鍏ュ彛锛涘畠琚敼鍧忔椂锛屾簮鐮侀棬绂佸彲鑳藉畬鍏ㄧ粫杩囥€? */
|
|
186
193
|
export function checkWorkflows({ root = process.cwd() } = {}) {
|
|
187
194
|
const checks = []
|
|
188
195
|
const base = path.resolve(String(root))
|
|
@@ -229,10 +236,11 @@ function checkStagedPackage({ packageDir, version }) {
|
|
|
229
236
|
const pkg = readJsonSafe(path.join(dir, 'package.json'))
|
|
230
237
|
if (!pkg) { fail(checks, 'package: staged package.json', dir); return { checks, pkg: null } }
|
|
231
238
|
pass(checks, 'package: staged package.json', `${pkg.name ?? '?'}@${pkg.version ?? '?'}`)
|
|
232
|
-
addCheck(checks, 'package: name', pkg.name === '@twinsearth/dsh-
|
|
239
|
+
addCheck(checks, 'package: name', pkg.name === '@twinsearth/fang-dsh-plugin', 'blocker', String(pkg.name))
|
|
233
240
|
addCheck(checks, 'package: version', !version || pkg.version === version, 'blocker', `${pkg.version}${version ? ' vs ' + version : ''}`)
|
|
234
241
|
addCheck(checks, 'package: not private', pkg.private !== true, 'blocker', String(pkg.private))
|
|
235
242
|
addCheck(checks, 'package: client half', pkg.dsh?.client?.platform === 'web', 'blocker', JSON.stringify(pkg.dsh?.client ?? null))
|
|
243
|
+
addCheck(checks, 'package: publish access public', pkg.publishConfig?.access === 'public' || pkg.access === 'public', 'blocker', String(pkg.publishConfig?.access ?? pkg.access ?? 'missing'), "add publishConfig.access=public so scoped npm publish does not 402")
|
|
236
244
|
const bundlePatch = String(pkg.dsh?.bundle?.patch ?? '').trim()
|
|
237
245
|
addCheck(checks, 'package: bundle manifest', bundlePatch.length > 0, 'blocker', bundlePatch || 'missing dsh.bundle.patch')
|
|
238
246
|
if (bundlePatch) addCheck(checks, 'package: bundle file', fs.existsSync(path.join(dir, bundlePatch)), 'blocker', bundlePatch)
|
|
@@ -247,7 +255,7 @@ function checkTarball({ distDir, version, tarball, manifest }) {
|
|
|
247
255
|
let doc = manifest ?? readJsonSafe(path.join(dist, 'manifest.json'))
|
|
248
256
|
if (!doc) { fail(checks, 'artifact: manifest', 'dist/manifest.json missing', 'run build first'); return { checks, manifest: null, tarballPath: null } }
|
|
249
257
|
pass(checks, 'artifact: manifest', `${doc.name}@${doc.version}`)
|
|
250
|
-
addCheck(checks, 'artifact: manifest name', doc.name === '@twinsearth/dsh-
|
|
258
|
+
addCheck(checks, 'artifact: manifest name', doc.name === '@twinsearth/fang-dsh-plugin', 'blocker', String(doc.name))
|
|
251
259
|
addCheck(checks, 'artifact: manifest version', !version || doc.version === version, 'blocker', `${doc.version}${version ? ' vs ' + version : ''}`)
|
|
252
260
|
const tgz = tarball ? path.resolve(tarball) : path.join(dist, path.basename(String(doc.tarball ?? '')))
|
|
253
261
|
if (!fs.existsSync(tgz)) { fail(checks, 'artifact: tarball exists', tgz, 'rebuild the artifact'); return { checks, manifest: doc, tarballPath: tgz } }
|
|
@@ -296,7 +304,7 @@ function checkProfile({ homeDir, profile, profileDir }) {
|
|
|
296
304
|
if (!fs.existsSync(patchFile)) warn(checks, 'profile: patch file', 'cordis.patch.yml missing', 'profile may still boot; create an empty [] patch')
|
|
297
305
|
else {
|
|
298
306
|
const text = readTextSafe(patchFile)
|
|
299
|
-
//
|
|
307
|
+
// 绌?patch 鐨勫悎娉曞舰寮忥細绌烘枃浠躲€乣[]`锛圖SH 妯℃澘甯歌锛夈€?
|
|
300
308
|
const empty = text.trim() === '' || text.trim() === '[]' || text.trim() === '{}'
|
|
301
309
|
if (empty) pass(checks, 'profile: patch parses', 'empty patch')
|
|
302
310
|
else {
|
|
@@ -372,7 +380,7 @@ function aggregate(target, checks, extra = {}) {
|
|
|
372
380
|
const warnings = checks.filter((item) => item.severity === 'warning' && item.ok === false)
|
|
373
381
|
const infos = checks.filter((item) => item.severity === 'info' && item.ok === true)
|
|
374
382
|
const score = scoreGateFindings(checks.map((item) => ({ severity: item.ok ? 'info' : item.severity })))
|
|
375
|
-
//
|
|
383
|
+
// 淇寤鸿鐢?healer 缁熶竴缁欏嚭锛堟湭鐭?blocker 涔熷洖钀藉埌 fail-closed 鎻愮ず锛夈€?
|
|
376
384
|
const healerHints = new Map(gateRepairPlan(checks.map((item) => ({ ...item }))).map((item) => [item.id, item.hint]))
|
|
377
385
|
const repair = checks
|
|
378
386
|
.filter((item) => item.ok === false)
|
|
@@ -391,7 +399,7 @@ function aggregate(target, checks, extra = {}) {
|
|
|
391
399
|
}
|
|
392
400
|
}
|
|
393
401
|
|
|
394
|
-
/**
|
|
402
|
+
/** 涓诲叆鍙o細鎸?target 鑱氬悎妫€鏌ャ€傜己鍙傛暟鏃?fail-closed锛屼笉鐚溿€?*/
|
|
395
403
|
export function runMainGate(options = {}) {
|
|
396
404
|
const target = String(options.target ?? 'package').trim()
|
|
397
405
|
if (!GATE_TARGETS.includes(target)) {
|
|
@@ -477,7 +485,7 @@ export function runMainGate(options = {}) {
|
|
|
477
485
|
return report
|
|
478
486
|
}
|
|
479
487
|
|
|
480
|
-
/**
|
|
488
|
+
/** 鍦?profile 鐩綍鍐?.gate-backups/<stamp>/锛堝彧澶嶅埗閰嶇疆锛屼笉鍔?node_modules/浼氳瘽锛夈€?*/
|
|
481
489
|
export function createProfileBackup(profileDir) {
|
|
482
490
|
const dir = path.resolve(String(profileDir ?? ''))
|
|
483
491
|
if (!fs.existsSync(dir)) return { ok: false, error: 'profile-missing', dir }
|
|
@@ -499,7 +507,7 @@ export function createProfileBackup(profileDir) {
|
|
|
499
507
|
}
|
|
500
508
|
}
|
|
501
509
|
|
|
502
|
-
/**
|
|
510
|
+
/** 鎶婇棬绂佺粨璁哄啓杩涢摼寮忓璁★紱娌℃湁 dataDir 鏃惰烦杩囥€傞摼鍧忎簡鎷掔粷杩藉姞锛岄伩鍏嶆礂鐧姐€?*/
|
|
503
511
|
export function recordGateDecision({ dataDir, target, report, actor = '' } = {}) {
|
|
504
512
|
if (!dataDir) return { ok: false, skipped: true, reason: 'no-data-dir' }
|
|
505
513
|
const ledger = path.join(String(dataDir), 'audit.jsonl')
|
|
@@ -526,7 +534,7 @@ export function recordGateDecision({ dataDir, target, report, actor = '' } = {})
|
|
|
526
534
|
}
|
|
527
535
|
}
|
|
528
536
|
|
|
529
|
-
/**
|
|
537
|
+
/** 鎶?blocker 姹囨€绘垚鍙洿鎺ユ墦鍦?CI/缁堢涓婄殑涓€琛岋紙涓嶉殣钘忓師鍥狅級銆?*/
|
|
530
538
|
export function formatGateFailure(report) {
|
|
531
539
|
const blockers = report?.blockers ?? []
|
|
532
540
|
if (!blockers.length) return 'gate GREEN'
|
|
@@ -536,13 +544,11 @@ export function formatGateFailure(report) {
|
|
|
536
544
|
export const DEFAULT_PROFILE_BUNDLES = Object.freeze([
|
|
537
545
|
'@deepseek-ai/dsh-base',
|
|
538
546
|
'@deepseek-ai/dsh-web-app',
|
|
539
|
-
'@twinsearth/dsh-
|
|
547
|
+
'@twinsearth/fang-dsh-plugin',
|
|
540
548
|
])
|
|
541
549
|
|
|
542
550
|
/**
|
|
543
|
-
*
|
|
544
|
-
* 再次校验名称/路径/存在性,避免调用方跳过 gate 直接调用。
|
|
545
|
-
*/
|
|
551
|
+
* 閫氳繃闂ㄧ鍚庣湡姝e垱寤轰竴涓柊 profile锛堝敮涓€鍏佽鐨勫啓璺緞锛夈€? * 鍐嶆鏍¢獙鍚嶇О/璺緞/瀛樺湪鎬э紝閬垮厤璋冪敤鏂硅烦杩?gate 鐩存帴璋冪敤銆? */
|
|
546
552
|
export function createGatedProfile({ homeDir, profile, bundles = DEFAULT_PROFILE_BUNDLES, force = false, minFreeBytes = DEFAULT_MIN_FREE_BYTES } = {}) {
|
|
547
553
|
const home = path.resolve(String(homeDir ?? ''))
|
|
548
554
|
const name = String(profile ?? '').trim()
|
package/src/lib/mirror.mjs
CHANGED
|
@@ -41,9 +41,27 @@ export const UPGRADE_STAGE = Object.freeze({
|
|
|
41
41
|
SWAPPING: 'swapping', FINALIZING: 'finalizing', DONE: 'done', FAILED: 'failed',
|
|
42
42
|
})
|
|
43
43
|
|
|
44
|
+
/** 官方最新版缓存默认有效期:60 秒内复用上次结果,不重复请求官方源(R13)。 */
|
|
45
|
+
export const OFFICIAL_LATEST_MAX_AGE_MS = 60_000
|
|
46
|
+
|
|
44
47
|
const HOUR_MS = 3_600_000
|
|
45
48
|
const BACKUP_ID_RE = /^\d{10,16}-[a-z0-9]{4,12}$/
|
|
46
49
|
|
|
50
|
+
/** 错误对象 → 可读文本(绝不把 Promise/对象 String 成 "[object Promise]")。 */
|
|
51
|
+
function formatError(error) {
|
|
52
|
+
if (error instanceof Error && typeof error.message === 'string' && error.message.length > 0) return error.message
|
|
53
|
+
if (typeof error === 'string' && error.length > 0) return error
|
|
54
|
+
return 'unknown error'
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 描述官方源非法返回值的类型(诊断用,不泄漏 "[object Promise]")。 */
|
|
58
|
+
function describeVersionValue(value) {
|
|
59
|
+
if (value === null) return 'null'
|
|
60
|
+
if (Array.isArray(value)) return 'array'
|
|
61
|
+
if (typeof value === 'object') return 'object'
|
|
62
|
+
return typeof value
|
|
63
|
+
}
|
|
64
|
+
|
|
47
65
|
/** @param {unknown} value */
|
|
48
66
|
function normalizeIntervalHours(value) {
|
|
49
67
|
const hours = Number(value)
|
|
@@ -92,6 +110,12 @@ export class MirrorManager {
|
|
|
92
110
|
this.logger = options.logger ?? {}
|
|
93
111
|
this.now = typeof options.now === 'function' ? options.now : () => Date.now()
|
|
94
112
|
this.usageProvider = typeof options.usageProvider === 'function' ? options.usageProvider : null
|
|
113
|
+
// R13:官方最新版缓存。getStatus() 只同步读它,刷新走 refreshOfficialLatest()。
|
|
114
|
+
// version —— 最近一次成功取到的版本(失败时保留上次成功值,绝不存 Promise);
|
|
115
|
+
// checkedAt —— 最近一次尝试刷新的时间(用于 maxAge 去重,未尝试过为 null);
|
|
116
|
+
// error —— 最近一次失败原因(成功为 null)。
|
|
117
|
+
this.officialLatest = { version: null, checkedAt: null, error: null }
|
|
118
|
+
this.officialLatestInFlight = null
|
|
95
119
|
// v3.0.9:升级成功后的副作用钩子(由协调器注入;异步触发,不阻塞 upgrade 返回)
|
|
96
120
|
this.postUpgradeHook = typeof options.postUpgradeHook === 'function' ? options.postUpgradeHook : null
|
|
97
121
|
// v3.0.3:客户端升级后的兼容性门禁;失败时保持子插件关闭(默认策略)
|
|
@@ -169,22 +193,31 @@ export class MirrorManager {
|
|
|
169
193
|
|
|
170
194
|
/**
|
|
171
195
|
* 完整状态(供 UI / 路由)。
|
|
196
|
+
*
|
|
197
|
+
* R13:本方法保持同步、只读内存缓存,**绝不**直接调用异步的
|
|
198
|
+
* officialSource.getLatestVersion()。旧实现直接 `String(getLatestVersion())`,async 源会被
|
|
199
|
+
* 字符串化成 "[object Promise]"、updateAvailable 恒为 true,且未被 }catch 的 rejection
|
|
200
|
+
* 会变成未处理拒绝(可导致进程崩溃)。官方最新版由 refreshOfficialLatest() 异步刷新,
|
|
201
|
+
* 路由在返回状态前 await 它即可。
|
|
172
202
|
* @returns {Record<string, unknown>}
|
|
173
203
|
*/
|
|
174
204
|
getStatus() {
|
|
175
205
|
this.ensureLayoutWithoutRecursion()
|
|
176
206
|
const meta = this.readMeta()
|
|
177
|
-
|
|
178
|
-
if (this.officialSource !== null && typeof this.officialSource.getLatestVersion === 'function') {
|
|
179
|
-
try { latest = String(this.officialSource.getLatestVersion() ?? null) } catch { latest = null }
|
|
180
|
-
}
|
|
207
|
+
const latest = this.officialLatest.version
|
|
181
208
|
const usage = this.usageProvider === null ? {} : (this.usageProvider() ?? {})
|
|
182
209
|
return {
|
|
183
210
|
ok: true,
|
|
184
211
|
meta,
|
|
185
212
|
currentVersion: meta.version,
|
|
213
|
+
// 兼容字段:缓存中的官方最新版(无缓存即 null),永远是字符串或 null。
|
|
186
214
|
officialLatest: latest,
|
|
187
215
|
updateAvailable: latest !== null && latest !== meta.version,
|
|
216
|
+
officialSource: {
|
|
217
|
+
latest,
|
|
218
|
+
checkedAt: this.officialLatest.checkedAt,
|
|
219
|
+
error: this.officialLatest.error,
|
|
220
|
+
},
|
|
188
221
|
backups: this.listBackups(),
|
|
189
222
|
activeEssenceCount: Number(usage.activeEssenceCount ?? 0) || 0,
|
|
190
223
|
activeSessionCount: Number(usage.activeSessionCount ?? 0) || 0,
|
|
@@ -192,6 +225,84 @@ export class MirrorManager {
|
|
|
192
225
|
}
|
|
193
226
|
}
|
|
194
227
|
|
|
228
|
+
/**
|
|
229
|
+
* 官方最新版缓存快照(同步、不发起请求)。
|
|
230
|
+
* @param {boolean} [refreshed] 本次调用是否真的请求了官方源
|
|
231
|
+
* @returns {{latest: string|null, checkedAt: number|null, error: string|null, refreshed: boolean}}
|
|
232
|
+
*/
|
|
233
|
+
officialSourceStatus(refreshed = false) {
|
|
234
|
+
return {
|
|
235
|
+
latest: this.officialLatest.version,
|
|
236
|
+
checkedAt: this.officialLatest.checkedAt,
|
|
237
|
+
error: this.officialLatest.error,
|
|
238
|
+
refreshed: refreshed === true,
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* 刷新官方最新版缓存:await 官方源、校验 string、catch 一切异常,**绝不抛出**。
|
|
244
|
+
* - maxAgeMs(默认 60s)内的缓存直接复用,不重复请求;
|
|
245
|
+
* - 并发调用共享同一个 in-flight 请求;
|
|
246
|
+
* - 失败只写 error(并保留上次成功版本),不会产生未处理的 Promise rejection。
|
|
247
|
+
* @param {{maxAgeMs?: number}} [options] maxAgeMs=0 表示强制刷新
|
|
248
|
+
* @returns {Promise<{latest: string|null, checkedAt: number|null, error: string|null, refreshed: boolean}>}
|
|
249
|
+
*/
|
|
250
|
+
async refreshOfficialLatest(options = {}) {
|
|
251
|
+
const requestedMaxAge = Number(options?.maxAgeMs)
|
|
252
|
+
const maxAgeMs = Number.isFinite(requestedMaxAge) && requestedMaxAge >= 0
|
|
253
|
+
? requestedMaxAge
|
|
254
|
+
: OFFICIAL_LATEST_MAX_AGE_MS
|
|
255
|
+
if (this.officialLatest.checkedAt !== null && this.now() - this.officialLatest.checkedAt < maxAgeMs) {
|
|
256
|
+
return this.officialSourceStatus(false)
|
|
257
|
+
}
|
|
258
|
+
if (this.officialLatestInFlight !== null) {
|
|
259
|
+
try { return await this.officialLatestInFlight } catch { return this.officialSourceStatus(false) }
|
|
260
|
+
}
|
|
261
|
+
const pending = this.fetchOfficialLatest()
|
|
262
|
+
this.officialLatestInFlight = pending
|
|
263
|
+
try {
|
|
264
|
+
return await pending
|
|
265
|
+
} finally {
|
|
266
|
+
if (this.officialLatestInFlight === pending) this.officialLatestInFlight = null
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* 真正请求官方源并写入缓存;仅供 refreshOfficialLatest 在去重后调用,自身也不抛。
|
|
272
|
+
* @returns {Promise<{latest: string|null, checkedAt: number|null, error: string|null, refreshed: boolean}>}
|
|
273
|
+
*/
|
|
274
|
+
async fetchOfficialLatest() {
|
|
275
|
+
const previous = this.officialLatest
|
|
276
|
+
let version = null
|
|
277
|
+
let error = null
|
|
278
|
+
try {
|
|
279
|
+
const source = this.officialSource
|
|
280
|
+
if (source === null || typeof source.getLatestVersion !== 'function') {
|
|
281
|
+
error = 'official-source-unavailable'
|
|
282
|
+
} else {
|
|
283
|
+
// 同步返回与 async 返回统一 await;getLatestVersion() 自身抛错也被这里 catch。
|
|
284
|
+
const raw = await Promise.resolve(source.getLatestVersion())
|
|
285
|
+
if (typeof raw === 'string' && raw.trim().length > 0) {
|
|
286
|
+
version = raw.trim()
|
|
287
|
+
} else {
|
|
288
|
+
error = `official-source-invalid-version: expected non-empty string, received ${describeVersionValue(raw)}`
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
} catch (cause) {
|
|
292
|
+
error = `official-source-failed: ${formatError(cause)}`
|
|
293
|
+
}
|
|
294
|
+
this.officialLatest = {
|
|
295
|
+
// 失败时保留上次成功版本:已知的最新版仍然有效,UI 可同时展示 error。
|
|
296
|
+
version: version !== null ? version : previous.version,
|
|
297
|
+
checkedAt: this.now(),
|
|
298
|
+
error,
|
|
299
|
+
}
|
|
300
|
+
if (error !== null) {
|
|
301
|
+
try { this.logger?.warn?.(`[mirror] official latest unavailable: ${error}`) } catch { /* 日志失败不影响状态 */ }
|
|
302
|
+
}
|
|
303
|
+
return this.officialSourceStatus(true)
|
|
304
|
+
}
|
|
305
|
+
|
|
195
306
|
/** getStatus 内部调用;只补齐目录,避免递归。 */
|
|
196
307
|
ensureLayoutWithoutRecursion() {
|
|
197
308
|
ensureDir(this.backupDir())
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// src/lib/node-compat.mjs — Node/Electron 宿主兼容垫片。
|
|
3
|
+
//
|
|
4
|
+
// 2026-11-22:DSH experimental-inspector 在 Node 26 上报
|
|
5
|
+
// "inspector: globalThis.fetch is an accessor and cannot be observed safely"
|
|
6
|
+
// Node 的 fetch 是 accessor;inspector 用属性观察方式包裹它时拒绝。把 fetch 归一成
|
|
7
|
+
// 数据属性(value=原 getter 绑定),不改变行为,只让观察者可以安全包装。
|
|
8
|
+
export function normalizeFetchDescriptor(target = globalThis) {
|
|
9
|
+
try {
|
|
10
|
+
const descriptor = Object.getOwnPropertyDescriptor(target, 'fetch')
|
|
11
|
+
if (!descriptor || typeof descriptor.get !== 'function') return { ok: true, changed: false }
|
|
12
|
+
if (descriptor.configurable !== true) return { ok: false, changed: false, error: 'fetch-not-configurable' }
|
|
13
|
+
const value = descriptor.get.call(target)
|
|
14
|
+
Object.defineProperty(target, 'fetch', {
|
|
15
|
+
value,
|
|
16
|
+
writable: true,
|
|
17
|
+
configurable: true,
|
|
18
|
+
enumerable: descriptor.enumerable === true,
|
|
19
|
+
})
|
|
20
|
+
return { ok: true, changed: true }
|
|
21
|
+
} catch (error) {
|
|
22
|
+
return { ok: false, changed: false, error: String(error?.message ?? error) }
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
|
|
3
|
+
//
|
|
4
|
+
// B-8 专业版(Pro)能力激活链:① 专业版开关(默认 false)→ ② 该项显式 allow →
|
|
5
|
+
// ③ 每次调用审批票(一次性/TTL/绑定能力与参数摘要)→ ④ 全程审计 + 资源限额。
|
|
6
|
+
// 缺任一环即拒绝,拒绝路径显式可读(错误码 + stage + reason),不静默降级。
|
|
7
|
+
import crypto from 'node:crypto'
|
|
8
|
+
|
|
9
|
+
import { DELEGATE_ERROR } from './contract-delegation.mjs'
|
|
10
|
+
|
|
11
|
+
export const PRO_CAPABILITY = 'fang.code.run'
|
|
12
|
+
export const PRO_CAPABILITIES = Object.freeze([PRO_CAPABILITY])
|
|
13
|
+
|
|
14
|
+
export const PRO_STAGE = Object.freeze({
|
|
15
|
+
DISABLED: 'pro-disabled',
|
|
16
|
+
NOT_ALLOWED: 'pro-not-allowed',
|
|
17
|
+
APPROVAL_REQUIRED: 'approval-required',
|
|
18
|
+
APPROVAL_INVALID: 'approval-invalid',
|
|
19
|
+
RATE_LIMITED: 'pro-rate-limited',
|
|
20
|
+
LIMIT_EXCEEDED: 'pro-limit-exceeded',
|
|
21
|
+
PROVIDER_MISSING: 'provider-missing',
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
export const PRO_DEFAULTS = Object.freeze({
|
|
25
|
+
enabled: false,
|
|
26
|
+
allow: Object.freeze([]),
|
|
27
|
+
approvalTtlMs: 120000,
|
|
28
|
+
maxConcurrent: 1,
|
|
29
|
+
timeoutMs: 30000,
|
|
30
|
+
maxOutputBytes: 64 * 1024,
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
/** Normalize the `contract.delegate.pro` config block (default off, per-item allow). */
|
|
34
|
+
export function normalizeProConfig(input = {}) {
|
|
35
|
+
const raw = input && typeof input === 'object' ? input : {}
|
|
36
|
+
const allow = Array.isArray(raw.allow) ? [...new Set(raw.allow.map((item) => String(item ?? '').trim()).filter((item) => PRO_CAPABILITIES.includes(item)))] : [...PRO_DEFAULTS.allow]
|
|
37
|
+
return {
|
|
38
|
+
enabled: raw.enabled === true,
|
|
39
|
+
allow,
|
|
40
|
+
approvalTtlMs: Number.isFinite(Number(raw.approvalTtlMs)) && Number(raw.approvalTtlMs) >= 1000
|
|
41
|
+
? Math.min(3600000, Math.round(Number(raw.approvalTtlMs))) : PRO_DEFAULTS.approvalTtlMs,
|
|
42
|
+
maxConcurrent: Number.isFinite(Number(raw.maxConcurrent)) && Number(raw.maxConcurrent) >= 1
|
|
43
|
+
? Math.min(8, Math.round(Number(raw.maxConcurrent))) : PRO_DEFAULTS.maxConcurrent,
|
|
44
|
+
timeoutMs: Number.isFinite(Number(raw.timeoutMs)) && Number(raw.timeoutMs) >= 100
|
|
45
|
+
? Math.min(600000, Math.round(Number(raw.timeoutMs))) : PRO_DEFAULTS.timeoutMs,
|
|
46
|
+
maxOutputBytes: Number.isFinite(Number(raw.maxOutputBytes)) && Number(raw.maxOutputBytes) >= 1024
|
|
47
|
+
? Math.min(1024 * 1024, Math.round(Number(raw.maxOutputBytes))) : PRO_DEFAULTS.maxOutputBytes,
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Stable digest of delegated params for approval binding (never logs the raw params). */
|
|
52
|
+
export function paramsDigest(params) {
|
|
53
|
+
let text = ''
|
|
54
|
+
try { text = JSON.stringify(params ?? null) } catch { text = 'unserializable' }
|
|
55
|
+
return crypto.createHash('sha256').update(text).digest('hex').slice(0, 16)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Approval-bound params digest. The one-time ticket id is itself part of the call params
|
|
60
|
+
* (`approvalTicket`), so it must be excluded — otherwise nothing could ever match the
|
|
61
|
+
* digest computed at issue time. Returns the digest of the remaining payload.
|
|
62
|
+
*/
|
|
63
|
+
export function proParamsDigest(params) {
|
|
64
|
+
if (!params || typeof params !== 'object' || Array.isArray(params)) return paramsDigest(params ?? null)
|
|
65
|
+
const { approvalTicket: _ticket, ...rest } = params
|
|
66
|
+
return paramsDigest(rest)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const digestTicket = (ticketId) => crypto.createHash('sha256').update(String(ticketId ?? '')).digest('hex').slice(0, 12)
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* One-time approval tickets for pro capabilities: issue (operator action), consume (per call).
|
|
73
|
+
* TTL + capability + params digest binding; consumed tickets cannot be replayed.
|
|
74
|
+
*/
|
|
75
|
+
export function createProApprovalStore({ now = () => Date.now(), idFactory } = {}) {
|
|
76
|
+
const tickets = new Map()
|
|
77
|
+
const makeId = idFactory ?? (() => `pro_${crypto.randomBytes(12).toString('hex')}`)
|
|
78
|
+
const prune = () => {
|
|
79
|
+
const at = now()
|
|
80
|
+
for (const [id, ticket] of tickets) if (ticket.expiresAt <= at) tickets.delete(id)
|
|
81
|
+
}
|
|
82
|
+
return {
|
|
83
|
+
issue({ capability, source = '', digest = '', ttlMs } = {}) {
|
|
84
|
+
if (!PRO_CAPABILITIES.includes(String(capability))) return { ok: false, reason: 'unsupported-capability' }
|
|
85
|
+
prune()
|
|
86
|
+
const id = makeId()
|
|
87
|
+
const ttl = Number.isFinite(Number(ttlMs)) ? Math.max(1000, Math.round(Number(ttlMs))) : PRO_DEFAULTS.approvalTtlMs
|
|
88
|
+
const ticket = { id, capability: String(capability), source: String(source ?? '').slice(0, 120), digest: String(digest ?? ''), issuedAt: now(), expiresAt: now() + ttl, consumedAt: null }
|
|
89
|
+
tickets.set(id, ticket)
|
|
90
|
+
return { ok: true, ticket: { ...ticket } }
|
|
91
|
+
},
|
|
92
|
+
consume({ id, capability, source = '', digest = '' } = {}) {
|
|
93
|
+
const ticket = tickets.get(String(id ?? ''))
|
|
94
|
+
if (!ticket) return { ok: false, reason: 'unknown-ticket', stage: PRO_STAGE.APPROVAL_INVALID }
|
|
95
|
+
if (ticket.consumedAt !== null) return { ok: false, reason: 'ticket-consumed', stage: PRO_STAGE.APPROVAL_INVALID }
|
|
96
|
+
if (ticket.expiresAt <= now()) { tickets.delete(ticket.id); return { ok: false, reason: 'ticket-expired', stage: PRO_STAGE.APPROVAL_INVALID } }
|
|
97
|
+
if (ticket.capability !== String(capability ?? '')) return { ok: false, reason: 'capability-mismatch', stage: PRO_STAGE.APPROVAL_INVALID }
|
|
98
|
+
// v3.5.5(安全):参数摘要必须绑定且在消费时强制校验;旧的无摘要票一律失效(fail-closed)。
|
|
99
|
+
if (!ticket.digest) return { ok: false, reason: 'params-unbound', stage: PRO_STAGE.APPROVAL_INVALID }
|
|
100
|
+
if (ticket.digest !== String(digest ?? '')) return { ok: false, reason: 'params-mismatch', stage: PRO_STAGE.APPROVAL_INVALID }
|
|
101
|
+
if (ticket.source && ticket.source !== String(source ?? '')) return { ok: false, reason: 'source-mismatch', stage: PRO_STAGE.APPROVAL_INVALID }
|
|
102
|
+
ticket.consumedAt = now()
|
|
103
|
+
return { ok: true, ticket: { ...ticket } }
|
|
104
|
+
},
|
|
105
|
+
pendingCount() { prune(); return tickets.size },
|
|
106
|
+
snapshot() { prune(); return [...tickets.values()].map((ticket) => ({ ...ticket })) },
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The activation chain gate: returns an explicit rejection (code + stage + readable message)
|
|
112
|
+
* until every stage passes; never silently downgrades.
|
|
113
|
+
*/
|
|
114
|
+
export function checkProGate({ method, config, ticketId, source, params } = {}) {
|
|
115
|
+
const pro = normalizeProConfig(config)
|
|
116
|
+
if (!PRO_CAPABILITIES.includes(String(method ?? ''))) {
|
|
117
|
+
return { ok: false, code: DELEGATE_ERROR.UNSUPPORTED, stage: 'not-pro', message: `not a pro capability: ${method}` }
|
|
118
|
+
}
|
|
119
|
+
if (!pro.enabled) {
|
|
120
|
+
return { ok: false, code: DELEGATE_ERROR.UNSUPPORTED, stage: PRO_STAGE.DISABLED, message: 'pro capability disabled (default off): enable contract.delegate.pro.enabled first' }
|
|
121
|
+
}
|
|
122
|
+
if (!pro.allow.includes(method)) {
|
|
123
|
+
return { ok: false, code: DELEGATE_ERROR.UNSUPPORTED, stage: PRO_STAGE.NOT_ALLOWED, message: `pro capability not activated: add '${method}' to contract.delegate.pro.allow` }
|
|
124
|
+
}
|
|
125
|
+
if (!ticketId) {
|
|
126
|
+
return { ok: false, code: DELEGATE_ERROR.APPROVAL_REQUIRED, stage: PRO_STAGE.APPROVAL_REQUIRED, message: 'per-call approval ticket required: issue one via POST /fang/api/contract/pro/approval and pass params.approvalTicket', digest: paramsDigest(params) }
|
|
127
|
+
}
|
|
128
|
+
return { ok: true, pro, stage: 'approval-verified', digest: proParamsDigest(params), ticketDigest: digestTicket(ticketId) }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Audit record for every pro attempt (stage/outcome/limits; ticket id is hashed, not logged). */
|
|
132
|
+
export function proAuditRecord({ method, source = '', outcome, stage, ticketId, error = null, latencyMs = 0, limits = {} } = {}) {
|
|
133
|
+
return {
|
|
134
|
+
capability: String(method ?? ''),
|
|
135
|
+
source: String(source ?? '').slice(0, 120),
|
|
136
|
+
outcome: String(outcome ?? 'unknown'),
|
|
137
|
+
stage: String(stage ?? ''),
|
|
138
|
+
error: error ?? null,
|
|
139
|
+
approval: ticketId ? digestTicket(ticketId) : null,
|
|
140
|
+
latencyMs: Math.max(0, Math.round(Number(latencyMs) || 0)),
|
|
141
|
+
limits: {
|
|
142
|
+
timeoutMs: Number(limits.timeoutMs) || null,
|
|
143
|
+
maxConcurrent: Number(limits.maxConcurrent) || null,
|
|
144
|
+
maxOutputBytes: Number(limits.maxOutputBytes) || null,
|
|
145
|
+
},
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Run a pro capability behind the resource limits: concurrency gate, timeout, output cap.
|
|
151
|
+
* Providers are injected; the current build has no code-runtime provider and returns
|
|
152
|
+
* provider-missing explicitly instead of pretending success.
|
|
153
|
+
*/
|
|
154
|
+
export async function runProCapability({ execute, timeoutMs, maxOutputBytes, gate } = {}) {
|
|
155
|
+
const slot = gate?.tryAcquire ? gate.tryAcquire() : { ok: true }
|
|
156
|
+
if (slot.ok !== true) return { ok: false, stage: PRO_STAGE.RATE_LIMITED, code: DELEGATE_ERROR.RATE_LIMITED, message: 'pro capability concurrency limit reached' }
|
|
157
|
+
const started = Date.now()
|
|
158
|
+
try {
|
|
159
|
+
const result = await Promise.race([
|
|
160
|
+
Promise.resolve().then(() => execute()),
|
|
161
|
+
new Promise((resolve) => setTimeout(() => resolve({ ok: false, stage: PRO_STAGE.LIMIT_EXCEEDED, code: DELEGATE_ERROR.TIMEOUT, message: `pro capability timed out after ${timeoutMs}ms` }), Math.max(1, Number(timeoutMs) || PRO_DEFAULTS.timeoutMs))),
|
|
162
|
+
])
|
|
163
|
+
if (!result || typeof result !== 'object') return { ok: false, stage: PRO_STAGE.LIMIT_EXCEEDED, code: DELEGATE_ERROR.UNAVAILABLE, message: 'pro capability returned no result' }
|
|
164
|
+
if (result.ok === true) {
|
|
165
|
+
let bytes = 0
|
|
166
|
+
try { bytes = Buffer.byteLength(JSON.stringify(result.value ?? null), 'utf8') } catch { bytes = Number.MAX_SAFE_INTEGER }
|
|
167
|
+
if (bytes > (Number(maxOutputBytes) || PRO_DEFAULTS.maxOutputBytes)) {
|
|
168
|
+
return { ok: false, stage: PRO_STAGE.LIMIT_EXCEEDED, code: DELEGATE_ERROR.INVALID, message: `pro capability output exceeds maxOutputBytes (${bytes} > ${maxOutputBytes})` }
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return { ...result, latencyMs: Date.now() - started }
|
|
172
|
+
} finally {
|
|
173
|
+
try { gate?.release?.() } catch { /* ignore */ }
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Default pro executor: no code-runtime provider is installed on this build (explicit, no side effect). */
|
|
178
|
+
export function providerMissingResult(method) {
|
|
179
|
+
return {
|
|
180
|
+
ok: false,
|
|
181
|
+
stage: PRO_STAGE.PROVIDER_MISSING,
|
|
182
|
+
code: DELEGATE_ERROR.UNAVAILABLE,
|
|
183
|
+
message: `activation chain verified, but no provider installed for '${method}' (code-runtime absent); execution refused without side effects`,
|
|
184
|
+
}
|
|
185
|
+
}
|
|
@@ -211,7 +211,9 @@ export function runtimeCaptureSignature(runtimeProfileDir) {
|
|
|
211
211
|
const patchText = readText(path.join(String(runtimeProfileDir ?? ''), 'cordis.patch.yml'))
|
|
212
212
|
let modulesMtime = 0
|
|
213
213
|
try { modulesMtime = fs.statSync(path.join(String(runtimeProfileDir ?? ''), 'node_modules', '.modules.yaml')).mtimeMs } catch { modulesMtime = 0 }
|
|
214
|
-
|
|
214
|
+
let settingsMtime = 0
|
|
215
|
+
try { settingsMtime = fs.statSync(path.join(String(runtimeProfileDir ?? ''), 'settings')).mtimeMs } catch { settingsMtime = 0 }
|
|
216
|
+
return `${packageText.length}:${patchText.length}:${modulesMtime}:${settingsMtime}`
|
|
215
217
|
}
|
|
216
218
|
|
|
217
219
|
function readCaptureMarker(runtimeProfileDir) {
|
|
@@ -249,23 +251,29 @@ export function captureRuntimeProfileIntoEssence({ essenceManager, essenceId, ru
|
|
|
249
251
|
const mergedPatchText = readText(path.join(mergedProfile, 'cordis.patch.yml'))
|
|
250
252
|
const runtimeEntries = parsePatchEntries(runtimePatchText).entries
|
|
251
253
|
const mergedEntries = parsePatchEntries(mergedPatchText).entries
|
|
254
|
+
const readSettings = (dir) => (typeof essenceManager.readProfileSettings === 'function'
|
|
255
|
+
? essenceManager.readProfileSettings(dir) : {})
|
|
256
|
+
const runtimeSettings = readSettings(profileDir)
|
|
257
|
+
const mergedSettings = readSettings(mergedProfile)
|
|
258
|
+
const settingsChanged = stableStringify(runtimeSettings) !== stableStringify(mergedSettings)
|
|
252
259
|
const packageChanged = stableStringify(pickProfilePackage(runtimePkg)) !== stableStringify(pickProfilePackage(mergedPkg))
|
|
253
260
|
const { changed, removedIds } = diffPatchEntries(mergedEntries, runtimeEntries)
|
|
254
261
|
const runtimeModules = path.join(profileDir, 'node_modules')
|
|
255
262
|
const essenceModules = path.join(mergedProfile, 'node_modules')
|
|
256
263
|
const modulePlan = planRuntimeModuleChanges(runtimeModules, essenceModules)
|
|
257
264
|
const moduleChanges = modulePlan.copy.length + modulePlan.remove.length
|
|
258
|
-
if (!packageChanged && changed.length === 0 && removedIds.length === 0 && moduleChanges === 0) {
|
|
265
|
+
if (!packageChanged && changed.length === 0 && removedIds.length === 0 && moduleChanges === 0 && !settingsChanged) {
|
|
259
266
|
writeCaptureMarker(profileDir, { at: Date.now(), signature, captured: false })
|
|
260
267
|
return { ok: true, captured: false, skipped: 'no-plugin-changes' }
|
|
261
268
|
}
|
|
262
269
|
|
|
263
|
-
// 1) overlay: package.json (deps + bundles + profile metadata)
|
|
270
|
+
// 1) overlay: package.json (deps + bundles + profile metadata), changed patch entries, settings
|
|
264
271
|
const overlay = essenceManager.loadOverlay(root)
|
|
265
272
|
if (packageChanged) overlay.packageJson = { ...overlay.packageJson, ...pickProfilePackage(runtimePkg) }
|
|
266
273
|
if (changed.length > 0 || removedIds.length > 0) {
|
|
267
274
|
overlay.patchEntries = mergeOverlayPatchEntries(overlay.patchEntries ?? [], { changed, removedIds }, mergedEntries)
|
|
268
275
|
}
|
|
276
|
+
if (settingsChanged) overlay.settings = { ...runtimeSettings }
|
|
269
277
|
essenceManager.saveOverlay(root, overlay)
|
|
270
278
|
// 2) pnpm dependency graph files ride with the overlay so every rematerialization keeps them
|
|
271
279
|
const overlayRoot = path.join(root, 'overlay')
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// src/lib/watch-guard.mjs — 2026-11-22 宿主 EPERM watch 崩溃的止损层。
|
|
3
|
+
//
|
|
4
|
+
// DSH Desktop host 的 fs.watch 在 profile 目录被替换/权限变化时会发出
|
|
5
|
+
// `error {code:'EPERM'}`;如果没有 error 监听,Node 会抛 uncaughtException 并让 host
|
|
6
|
+
// 以 exit 1 退出(真机事故)。这里在瓮城插件加载时包装 fs.watch / fs.watchFile,
|
|
7
|
+
// 为每个 watcher 挂 error 监听并降级为日志,绝不让单个 watcher 错误杀死宿主。
|
|
8
|
+
//
|
|
9
|
+
// 注意:这是止损,不是替代 DSH 上游修复;上游仍应把 watcher error 记录为 warning 并重建 watcher。
|
|
10
|
+
import fs from 'node:fs'
|
|
11
|
+
|
|
12
|
+
const GUARDED = Symbol.for('fang.watchGuard.installed')
|
|
13
|
+
const ORIGINAL_WATCH = fs.watch
|
|
14
|
+
const ORIGINAL_WATCH_FILE = fs.watchFile
|
|
15
|
+
|
|
16
|
+
export function installWatchGuard({ logger = null } = {}) {
|
|
17
|
+
if (fs.watch[GUARDED] === true) return { ok: true, already: true, repaired: 0 }
|
|
18
|
+
let repaired = 0
|
|
19
|
+
const onError = (scope) => (error) => {
|
|
20
|
+
repaired += 1
|
|
21
|
+
const code = String(error?.code ?? 'unknown')
|
|
22
|
+
try { logger?.warn?.(`[fang] ${scope} watcher error downgraded: ${code}`) } catch { /* logger must never throw */ }
|
|
23
|
+
}
|
|
24
|
+
const watched = function fangGuardedWatch(...args) {
|
|
25
|
+
const watcher = ORIGINAL_WATCH.apply(this, args)
|
|
26
|
+
try { watcher.on('error', onError('fs.watch')) } catch { /* non-EventEmitter watcher */ }
|
|
27
|
+
return watcher
|
|
28
|
+
}
|
|
29
|
+
watched[GUARDED] = true
|
|
30
|
+
watched.__fangOriginal = ORIGINAL_WATCH
|
|
31
|
+
const watchedFile = function fangGuardedWatchFile(...args) {
|
|
32
|
+
const out = ORIGINAL_WATCH_FILE.apply(this, args)
|
|
33
|
+
return out
|
|
34
|
+
}
|
|
35
|
+
watchedFile[GUARDED] = true
|
|
36
|
+
watchedFile.__fangOriginal = ORIGINAL_WATCH_FILE
|
|
37
|
+
try { fs.watch = watched } catch { return { ok: false, error: 'fs-watch-readonly' } }
|
|
38
|
+
try { fs.watchFile = watchedFile } catch { /* optional */ }
|
|
39
|
+
return { ok: true, already: false, repaired }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function watchGuardInstalled() {
|
|
43
|
+
return fs.watch[GUARDED] === true
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function uninstallWatchGuard() {
|
|
47
|
+
if (fs.watch[GUARDED] !== true) return { ok: true, removed: false }
|
|
48
|
+
try { fs.watch = fs.watch.__fangOriginal ?? ORIGINAL_WATCH } catch { /* ignore */ }
|
|
49
|
+
try { fs.watchFile = fs.watchFile.__fangOriginal ?? ORIGINAL_WATCH_FILE } catch { /* ignore */ }
|
|
50
|
+
return { ok: true, removed: true }
|
|
51
|
+
}
|