@twinsearth/dsh-fang 3.2.1 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client.js +40 -18
- package/docs/DSH-ARCHITECTURE-MAP.md +73 -0
- package/docs/MAIN-CITY-GATE.md +57 -0
- package/package.json +1 -1
- package/src/kernel/types.mjs +1 -1
- package/src/lib/decision-policy.mjs +22 -4
- package/src/lib/main-gate.mjs +526 -0
- package/src/lib/restart-contract.mjs +103 -1
- package/src/plugins/decision-center.mjs +72 -12
- package/src/plugins/forker.mjs +16 -0
- package/src/plugins/healer.mjs +38 -0
- package/src/plugins/restart-guard.mjs +75 -1
- package/src/plugins/scorer.mjs +37 -0
- package/tools/fangctl.mjs +21 -2
- package/tools/gate/main-city.mjs +204 -0
|
@@ -0,0 +1,526 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
|
|
3
|
+
//
|
|
4
|
+
// v3.3.0 主城门禁(main-city gate)
|
|
5
|
+
// ------------------------------------------------------------
|
|
6
|
+
// 目标:任何「进主城」的动作(打包、发布、安装、部署、新建 profile)都必须先过
|
|
7
|
+
// 同一套可复核的检查;拿不到证据时 fail-closed,而不是静默放行。
|
|
8
|
+
//
|
|
9
|
+
// 设计约束:
|
|
10
|
+
// * 纯本地、只读优先:默认不写 profile、不联网、不改产物。
|
|
11
|
+
// * 产物校验以 sha256/manifest 为准;profile 校验以「不越界 + 可解析 + 不覆盖」为准。
|
|
12
|
+
// * 崩溃循环 / 安全模式 / 审计链断裂 = blocker:系统级故障不能靠重试绕过。
|
|
13
|
+
// * 需要写盘的两个例外都显式开关:--repair 建 profile 备份;--create 新建 profile。
|
|
14
|
+
import fs from 'node:fs'
|
|
15
|
+
import path from 'node:path'
|
|
16
|
+
import crypto from 'node:crypto'
|
|
17
|
+
|
|
18
|
+
import { parseYamlSubset } from './rule-registry.mjs'
|
|
19
|
+
import { appendChained, verifyChain } from '../kernel/ledger.mjs'
|
|
20
|
+
import { scoreGateFindings } from '../plugins/scorer.mjs'
|
|
21
|
+
import { gateRepairPlan } from '../plugins/healer.mjs'
|
|
22
|
+
import { CRASH_LOOP_DEFAULTS, detectCrashLoop } from './restart-contract.mjs'
|
|
23
|
+
|
|
24
|
+
export const GATE_TARGETS = Object.freeze(['source', 'package', 'publish', 'install', 'deploy', 'profile'])
|
|
25
|
+
export const GATE_SEVERITIES = Object.freeze(['blocker', 'warning', 'info'])
|
|
26
|
+
export const DEFAULT_MIN_FREE_BYTES = 512 * 1024 * 1024
|
|
27
|
+
export const RESERVED_PROFILE_NAMES = Object.freeze(['desktop', 'plugin'])
|
|
28
|
+
export const PROFILE_NAME_RE = /^[a-z0-9][a-z0-9-]{0,62}$/
|
|
29
|
+
|
|
30
|
+
const REQUIRED_SOURCE_FILES = Object.freeze([
|
|
31
|
+
'package.json',
|
|
32
|
+
'client.js',
|
|
33
|
+
'cordis.patch.yml',
|
|
34
|
+
'src/index.mjs',
|
|
35
|
+
'src/lib/boot-guard.mjs',
|
|
36
|
+
'src/lib/fork-supervisor.mjs',
|
|
37
|
+
'src/lib/restart-contract.mjs',
|
|
38
|
+
'src/lib/main-gate.mjs',
|
|
39
|
+
'src/plugins/restart-guard.mjs',
|
|
40
|
+
'src/plugins/scorer.mjs',
|
|
41
|
+
'src/plugins/approver.mjs',
|
|
42
|
+
'src/plugins/auditor.mjs',
|
|
43
|
+
'src/plugins/healer.mjs',
|
|
44
|
+
'tools/gate/main-city.mjs',
|
|
45
|
+
'tools/release/build.mjs',
|
|
46
|
+
'tools/release/preflight.mjs',
|
|
47
|
+
'docs/CRASH-SAFETY.md',
|
|
48
|
+
'docs/MAIN-CITY-GATE.md',
|
|
49
|
+
'docs/DSH-ARCHITECTURE-MAP.md',
|
|
50
|
+
])
|
|
51
|
+
|
|
52
|
+
const REQUIRED_ARTIFACT_FILES = Object.freeze([
|
|
53
|
+
'package.json',
|
|
54
|
+
'client.js',
|
|
55
|
+
'cordis.patch.yml',
|
|
56
|
+
'src/index.mjs',
|
|
57
|
+
'src/lib/boot-guard.mjs',
|
|
58
|
+
'src/lib/main-gate.mjs',
|
|
59
|
+
'src/plugins/restart-guard.mjs',
|
|
60
|
+
'tools/gate/main-city.mjs',
|
|
61
|
+
])
|
|
62
|
+
|
|
63
|
+
const SECRET_PATTERNS = Object.freeze([
|
|
64
|
+
{ id: 'aws-access-key', re: /AKIA[0-9A-Z]{16}/ },
|
|
65
|
+
{ id: 'github-token', re: /gh[pousr]_[A-Za-z0-9]{20,}/ },
|
|
66
|
+
{ id: 'openai-key', re: /sk-[A-Za-z0-9]{20,}/ },
|
|
67
|
+
{ id: 'pem-private-key', re: /-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----/ },
|
|
68
|
+
])
|
|
69
|
+
|
|
70
|
+
const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex')
|
|
71
|
+
export const sha256File = (file) => sha256(fs.readFileSync(file))
|
|
72
|
+
|
|
73
|
+
function readJsonSafe(file) {
|
|
74
|
+
try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function isInside(parent, child) {
|
|
78
|
+
const p = path.resolve(String(parent ?? ''))
|
|
79
|
+
const c = path.resolve(String(child ?? ''))
|
|
80
|
+
const rel = path.relative(p, c)
|
|
81
|
+
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function readTextSafe(file, fallback = '') {
|
|
85
|
+
try { return fs.readFileSync(file, 'utf8') } catch { return fallback }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function pidAlive(pid) {
|
|
89
|
+
if (!Number.isInteger(pid) || pid <= 0) return false
|
|
90
|
+
try { process.kill(pid, 0); return true } catch (error) { return error?.code === 'EPERM' }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function diskFree(dir) {
|
|
94
|
+
try {
|
|
95
|
+
const stat = fs.statfsSync(dir)
|
|
96
|
+
return Number(stat.bavail) * Number(stat.bsize)
|
|
97
|
+
} catch { return null }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function addCheck(checks, id, ok, severity, detail, repair = '') {
|
|
101
|
+
const level = ok ? 'info' : severity
|
|
102
|
+
checks.push({ id, ok: !!ok, severity: level, detail: String(detail ?? ''), ...(repair ? { repair } : {}) })
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function fail(checks, id, detail, repair = '') {
|
|
106
|
+
addCheck(checks, id, false, 'blocker', detail, repair)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function warn(checks, id, detail, repair = '') {
|
|
110
|
+
addCheck(checks, id, false, 'warning', detail, repair)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function pass(checks, id, detail = '') {
|
|
114
|
+
addCheck(checks, id, true, 'info', detail)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function walkFiles(dir, rel = '', out = [], limit = 5000) {
|
|
118
|
+
if (out.length >= limit) return out
|
|
119
|
+
let entries = []
|
|
120
|
+
try { entries = fs.readdirSync(path.join(dir, rel), { withFileTypes: true }) } catch { return out }
|
|
121
|
+
for (const entry of entries) {
|
|
122
|
+
if (out.length >= limit) break
|
|
123
|
+
const child = rel ? path.join(rel, entry.name) : entry.name
|
|
124
|
+
if (entry.isDirectory()) walkFiles(dir, child, out, limit)
|
|
125
|
+
else if (entry.isFile()) out.push(child)
|
|
126
|
+
}
|
|
127
|
+
return out
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** 源码树:版本、文档、vendored 契约、关键防线文件、危险默认值。 */
|
|
131
|
+
export function checkSourceTree({ root = process.cwd(), version = '' } = {}) {
|
|
132
|
+
const checks = []
|
|
133
|
+
const base = path.resolve(root)
|
|
134
|
+
const pkg = readJsonSafe(path.join(base, 'package.json'))
|
|
135
|
+
const declared = String(pkg?.version ?? version ?? '').trim()
|
|
136
|
+
if (!/^\d+\.\d+\.\d+$/.test(declared)) fail(checks, 'source: semver', declared || '(missing)')
|
|
137
|
+
else pass(checks, 'source: semver', declared)
|
|
138
|
+
if (version && declared !== version) fail(checks, 'source: version matches requested', `${declared} != ${version}`)
|
|
139
|
+
else pass(checks, 'source: version matches requested', declared)
|
|
140
|
+
|
|
141
|
+
const kernel = readTextSafe(path.join(base, 'src/kernel/types.mjs'))
|
|
142
|
+
addCheck(checks, 'source: kernel FANG_VERSION', kernel.includes(`FANG_VERSION = '${declared}'`), 'blocker', declared)
|
|
143
|
+
addCheck(checks, 'source: CHANGELOG section', readTextSafe(path.join(base, 'docs/CHANGELOG.md')).includes(`## v${declared}`), 'blocker', `## v${declared}`)
|
|
144
|
+
addCheck(checks, 'source: AUDIT file', fs.existsSync(path.join(base, `docs/AUDIT-v${declared}.md`)), 'blocker', `docs/AUDIT-v${declared}.md`)
|
|
145
|
+
|
|
146
|
+
const missing = REQUIRED_SOURCE_FILES.filter((rel) => !fs.existsSync(path.join(base, rel)))
|
|
147
|
+
addCheck(checks, 'source: required guard files', missing.length === 0, 'blocker', missing.length ? `missing=${missing.join(',')}` : `${REQUIRED_SOURCE_FILES.length} files`, missing.length ? 'restore the missing guard files before packaging' : '')
|
|
148
|
+
|
|
149
|
+
const patch = parseYamlSubset(readTextSafe(path.join(base, 'cordis.patch.yml')))
|
|
150
|
+
addCheck(checks, 'source: bundle patch parses', patch.errors.length === 0, 'blocker', patch.errors[0] ?? 'ok')
|
|
151
|
+
|
|
152
|
+
const restart = readTextSafe(path.join(base, 'src/plugins/restart-guard.mjs'))
|
|
153
|
+
addCheck(checks, 'source: restart default observe', restart.includes("mode: 'observe'"), 'blocker', 'mode default must stay observe')
|
|
154
|
+
addCheck(checks, 'source: process restart disarmed by default', restart.includes('allowProcessRestart: false'), 'blocker', 'allowProcessRestart default must stay false')
|
|
155
|
+
addCheck(checks, 'source: crash-loop breaker present', restart.includes('crash-loop') && restart.includes('clearSafeMode'), 'blocker', 'restart-guard crash-loop breaker')
|
|
156
|
+
addCheck(checks, 'source: gate wired into build', readTextSafe(path.join(base, 'tools/release/build.mjs')).includes('main-city.mjs'), 'blocker', 'build must call the gate')
|
|
157
|
+
addCheck(checks, 'source: gate wired into publish', readTextSafe(path.join(base, 'tools/release/publish-npm.mjs')).includes('main-city.mjs'), 'blocker', 'publish must call the gate')
|
|
158
|
+
|
|
159
|
+
const vendor = readJsonSafe(path.join(base, 'src/contract/VENDOR.json'))
|
|
160
|
+
if (!vendor) fail(checks, 'source: vendored contract manifest', 'src/contract/VENDOR.json missing', 're-sync contract from npm')
|
|
161
|
+
else {
|
|
162
|
+
const drifted = []
|
|
163
|
+
for (const [name, expected] of Object.entries(vendor.sha256 ?? {})) {
|
|
164
|
+
const file = path.join(base, 'src/contract', name)
|
|
165
|
+
try { if (sha256File(file) !== expected) drifted.push(name) } catch { drifted.push(name + ':missing') }
|
|
166
|
+
}
|
|
167
|
+
addCheck(checks, 'source: vendored contract bytes', drifted.length === 0, 'blocker', drifted.length ? `drift=${drifted.join(',')}` : `${Object.keys(vendor.sha256 ?? {}).length} files @ ${vendor.version}`)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const secretHits = []
|
|
171
|
+
for (const rel of walkFiles(base, 'src').slice(0, 2000)) {
|
|
172
|
+
const text = readTextSafe(path.join(base, rel))
|
|
173
|
+
for (const pattern of SECRET_PATTERNS) if (pattern.re.test(text)) secretHits.push(`${rel}:${pattern.id}`)
|
|
174
|
+
}
|
|
175
|
+
addCheck(checks, 'source: no hardcoded secrets', secretHits.length === 0, 'blocker', secretHits.length ? secretHits.slice(0, 5).join(',') : 'clean')
|
|
176
|
+
|
|
177
|
+
return { target: 'source', checks, version: declared }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function checkStagedPackage({ packageDir, version }) {
|
|
181
|
+
const checks = []
|
|
182
|
+
const dir = path.resolve(String(packageDir ?? ''))
|
|
183
|
+
const pkg = readJsonSafe(path.join(dir, 'package.json'))
|
|
184
|
+
if (!pkg) { fail(checks, 'package: staged package.json', dir); return { checks, pkg: null } }
|
|
185
|
+
pass(checks, 'package: staged package.json', `${pkg.name ?? '?'}@${pkg.version ?? '?'}`)
|
|
186
|
+
addCheck(checks, 'package: name', pkg.name === '@twinsearth/dsh-fang', 'blocker', String(pkg.name))
|
|
187
|
+
addCheck(checks, 'package: version', !version || pkg.version === version, 'blocker', `${pkg.version}${version ? ' vs ' + version : ''}`)
|
|
188
|
+
addCheck(checks, 'package: not private', pkg.private !== true, 'blocker', String(pkg.private))
|
|
189
|
+
addCheck(checks, 'package: client half', pkg.dsh?.client?.platform === 'web', 'blocker', JSON.stringify(pkg.dsh?.client ?? null))
|
|
190
|
+
const bundlePatch = String(pkg.dsh?.bundle?.patch ?? '').trim()
|
|
191
|
+
addCheck(checks, 'package: bundle manifest', bundlePatch.length > 0, 'blocker', bundlePatch || 'missing dsh.bundle.patch')
|
|
192
|
+
if (bundlePatch) addCheck(checks, 'package: bundle file', fs.existsSync(path.join(dir, bundlePatch)), 'blocker', bundlePatch)
|
|
193
|
+
const missing = REQUIRED_ARTIFACT_FILES.filter((rel) => !fs.existsSync(path.join(dir, rel)))
|
|
194
|
+
addCheck(checks, 'package: required artifact files', missing.length === 0, 'blocker', missing.length ? `missing=${missing.join(',')}` : `${REQUIRED_ARTIFACT_FILES.length} files`)
|
|
195
|
+
return { checks, pkg }
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function checkTarball({ distDir, version, tarball, manifest }) {
|
|
199
|
+
const checks = []
|
|
200
|
+
const dist = path.resolve(String(distDir ?? 'dist'))
|
|
201
|
+
let doc = manifest ?? readJsonSafe(path.join(dist, 'manifest.json'))
|
|
202
|
+
if (!doc) { fail(checks, 'artifact: manifest', 'dist/manifest.json missing', 'run build first'); return { checks, manifest: null, tarballPath: null } }
|
|
203
|
+
pass(checks, 'artifact: manifest', `${doc.name}@${doc.version}`)
|
|
204
|
+
addCheck(checks, 'artifact: manifest name', doc.name === '@twinsearth/dsh-fang', 'blocker', String(doc.name))
|
|
205
|
+
addCheck(checks, 'artifact: manifest version', !version || doc.version === version, 'blocker', `${doc.version}${version ? ' vs ' + version : ''}`)
|
|
206
|
+
const tgz = tarball ? path.resolve(tarball) : path.join(dist, path.basename(String(doc.tarball ?? '')))
|
|
207
|
+
if (!fs.existsSync(tgz)) { fail(checks, 'artifact: tarball exists', tgz, 'rebuild the artifact'); return { checks, manifest: doc, tarballPath: tgz } }
|
|
208
|
+
const actual = sha256File(tgz)
|
|
209
|
+
addCheck(checks, 'artifact: tarball sha256', actual === doc.sha256, 'blocker', actual.slice(0, 16))
|
|
210
|
+
const sidecar = `${tgz}.sha256`
|
|
211
|
+
if (!fs.existsSync(sidecar)) warn(checks, 'artifact: sha256 sidecar', 'missing sidecar', 'rebuild writes the sidecar')
|
|
212
|
+
else {
|
|
213
|
+
const expected = readTextSafe(sidecar).trim().split(/\s+/)[0]
|
|
214
|
+
addCheck(checks, 'artifact: sha256 sidecar', expected === actual, 'blocker', expected ? expected.slice(0, 16) : 'empty')
|
|
215
|
+
}
|
|
216
|
+
const files = Array.isArray(doc.files) ? doc.files : []
|
|
217
|
+
addCheck(checks, 'artifact: file list present', files.length > 0, 'blocker', `${files.length} entries`)
|
|
218
|
+
const bad = files.filter((rel) => /^package\/(dist|node_modules|\.git|\.env)/.test(rel) || /\.pem$|npm-token|gh-master-token/i.test(rel))
|
|
219
|
+
addCheck(checks, 'artifact: no forbidden entries', bad.length === 0, 'blocker', bad.length ? bad.slice(0, 5).join(',') : 'clean')
|
|
220
|
+
const missing = REQUIRED_ARTIFACT_FILES.map((rel) => `package/${rel}`).filter((rel) => !files.includes(rel))
|
|
221
|
+
addCheck(checks, 'artifact: required files inside tarball', missing.length === 0, 'blocker', missing.length ? `missing=${missing.join(',')}` : `${REQUIRED_ARTIFACT_FILES.length} files`)
|
|
222
|
+
return { checks, manifest: doc, tarballPath: tgz }
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function checkProfile({ homeDir, profile, profileDir }) {
|
|
226
|
+
const checks = []
|
|
227
|
+
const home = path.resolve(String(homeDir ?? ''))
|
|
228
|
+
const name = String(profile ?? path.basename(path.resolve(String(profileDir ?? '')))).trim()
|
|
229
|
+
const dir = path.resolve(String(profileDir ?? path.join(home, 'profiles', name)))
|
|
230
|
+
if (!home) fail(checks, 'profile: home required', home, 'pass --home')
|
|
231
|
+
addCheck(checks, 'profile: name format', PROFILE_NAME_RE.test(name), 'blocker', name)
|
|
232
|
+
addCheck(checks, 'profile: reserved name', !RESERVED_PROFILE_NAMES.includes(name), 'blocker', name)
|
|
233
|
+
addCheck(checks, 'profile: inside home/profiles', isInside(path.join(home, 'profiles'), dir), 'blocker', dir, 'refuse paths outside $DSH_HOME/profiles')
|
|
234
|
+
if (!fs.existsSync(dir)) {
|
|
235
|
+
warn(checks, 'profile: profile directory', `not created yet: ${dir}`, 'create it through the gate (--create)')
|
|
236
|
+
return { checks, dir, name, exists: false, pkg: null }
|
|
237
|
+
}
|
|
238
|
+
const pkg = readJsonSafe(path.join(dir, 'package.json'))
|
|
239
|
+
if (!pkg) fail(checks, 'profile: package.json', dir)
|
|
240
|
+
else {
|
|
241
|
+
pass(checks, 'profile: package.json', pkg.name ?? name)
|
|
242
|
+
const bundles = Array.isArray(pkg?.dsh?.profile?.bundles) ? pkg.dsh.profile.bundles.map(String) : null
|
|
243
|
+
if (!bundles) fail(checks, 'profile: bundles array', JSON.stringify(pkg?.dsh?.profile ?? null))
|
|
244
|
+
else {
|
|
245
|
+
const dup = bundles.filter((id, index) => bundles.indexOf(id) !== index)
|
|
246
|
+
addCheck(checks, 'profile: no duplicate bundles', dup.length === 0, 'blocker', dup.length ? dup.join(',') : `${bundles.length} bundles`)
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
const patchFile = path.join(dir, 'cordis.patch.yml')
|
|
250
|
+
if (!fs.existsSync(patchFile)) warn(checks, 'profile: patch file', 'cordis.patch.yml missing', 'profile may still boot; create an empty [] patch')
|
|
251
|
+
else {
|
|
252
|
+
const text = readTextSafe(patchFile)
|
|
253
|
+
// 空 patch 的合法形式:空文件、`[]`(DSH 模板常见)。
|
|
254
|
+
const empty = text.trim() === '' || text.trim() === '[]' || text.trim() === '{}'
|
|
255
|
+
if (empty) pass(checks, 'profile: patch parses', 'empty patch')
|
|
256
|
+
else {
|
|
257
|
+
const parsed = parseYamlSubset(text)
|
|
258
|
+
addCheck(checks, 'profile: patch parses', parsed.errors.length === 0, 'blocker', parsed.errors[0] ?? 'ok')
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
const backup = fs.existsSync(dir) && fs.readdirSync(dir).some((file) => /^package\.json\.bak-|^cordis\.patch\.yml\.bak-|^\.gate-backups$/.test(file))
|
|
262
|
+
addCheck(checks, 'profile: backup available', backup, 'warning', backup ? 'present' : 'none', 'run gate --repair to create a backup before changing this profile')
|
|
263
|
+
return { checks, dir, name, exists: true, pkg, backup }
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function checkRuntimeGuards({ homeDir, profile }) {
|
|
267
|
+
const checks = []
|
|
268
|
+
const home = path.resolve(String(homeDir ?? ''))
|
|
269
|
+
const dataDir = path.join(home, 'fang', String(profile ?? ''))
|
|
270
|
+
const pidFile = path.join(dataDir, 'fang.pid')
|
|
271
|
+
const pidDoc = readJsonSafe(pidFile)
|
|
272
|
+
const live = pidDoc && pidAlive(Number(pidDoc.pid))
|
|
273
|
+
addCheck(checks, 'runtime: no live host on this profile', !live, 'blocker', live ? `pid=${pidDoc.pid} is alive` : 'no live fang.pid', 'fully exit the DSH client before install/deploy')
|
|
274
|
+
const safeFile = path.join(dataDir, 'restart/safe-mode.json')
|
|
275
|
+
const safe = readJsonSafe(safeFile)
|
|
276
|
+
addCheck(checks, 'runtime: restart safe-mode clear', !(safe && safe.active === true), 'blocker', safe?.active === true ? `${safe.reason ?? 'active'} at ${safe.at ?? '?'}` : 'clear', 'clear it only after investigating crashes: fangctl restart-safe clear --by <you>')
|
|
277
|
+
const crashFile = path.join(dataDir, 'restart/runtime-crash.jsonl')
|
|
278
|
+
const crash = fs.existsSync(crashFile) ? detectCrashLoop(readTextSafe(crashFile), { windowMs: CRASH_LOOP_DEFAULTS.windowMs, threshold: CRASH_LOOP_DEFAULTS.threshold }) : { active: false, count: 0 }
|
|
279
|
+
addCheck(checks, 'runtime: no active crash loop', crash.active !== true, 'blocker', crash.active ? `${crash.count} crashes in ${crash.windowMs}ms` : `count=${crash.count}`, 'inspect runtime-crash.jsonl and restart-guard safe mode; do not redeploy blindly')
|
|
280
|
+
const auditFile = path.join(dataDir, 'audit.jsonl')
|
|
281
|
+
if (fs.existsSync(auditFile)) {
|
|
282
|
+
const chain = verifyChain(auditFile)
|
|
283
|
+
addCheck(checks, 'audit: hash chain verifies', chain.ok === true, 'blocker', chain.ok ? `records=${chain.count}` : `${chain.reason}@${chain.badIndex}`, 'do not append/deploy on a broken audit chain; restore the ledger from backup and investigate')
|
|
284
|
+
} else {
|
|
285
|
+
pass(checks, 'audit: hash chain verifies', 'no ledger yet (first install)')
|
|
286
|
+
}
|
|
287
|
+
const ledger = path.join(home, 'audit.jsonl')
|
|
288
|
+
if (fs.existsSync(ledger) && ledger !== auditFile) {
|
|
289
|
+
const chain = verifyChain(ledger)
|
|
290
|
+
addCheck(checks, 'audit: home ledger verifies', chain.ok === true, 'blocker', chain.ok ? `records=${chain.count}` : `${chain.reason}@${chain.badIndex}`)
|
|
291
|
+
}
|
|
292
|
+
return { checks, dataDir }
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function checkDiskSpace({ homeDir, minFreeBytes = DEFAULT_MIN_FREE_BYTES }) {
|
|
296
|
+
const checks = []
|
|
297
|
+
const target = path.resolve(String(homeDir ?? ''))
|
|
298
|
+
let dir = target
|
|
299
|
+
while (dir && !fs.existsSync(dir)) dir = path.dirname(dir)
|
|
300
|
+
const free = diskFree(dir)
|
|
301
|
+
if (free === null) warn(checks, 'disk: free space available', 'statfs unavailable', 'verify free space manually')
|
|
302
|
+
else addCheck(checks, 'disk: free space available', free >= minFreeBytes, 'blocker', `${(free / 1024 / 1024).toFixed(0)} MiB free (need ${(minFreeBytes / 1024 / 1024).toFixed(0)} MiB)`, 'free disk space before creating profiles / installing artifacts')
|
|
303
|
+
return { checks, free }
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function checkPublishMetadata({ version, tag, npmLatest, allowExisting }) {
|
|
307
|
+
const checks = []
|
|
308
|
+
addCheck(checks, 'publish: version present', /^\d+\.\d+\.\d+$/.test(String(version ?? '')), 'blocker', String(version ?? ''))
|
|
309
|
+
if (tag !== undefined && String(tag).trim() !== '') {
|
|
310
|
+
addCheck(checks, 'publish: tag matches version', String(tag).trim() === `v${version}`, 'blocker', `${tag} vs v${version}`, 'create the annotated tag from the same version')
|
|
311
|
+
} else {
|
|
312
|
+
warn(checks, 'publish: tag provided', 'no tag supplied; CI tag/version check is skipped', 'pass --tag v<version> in release workflows')
|
|
313
|
+
}
|
|
314
|
+
if (npmLatest !== undefined && npmLatest !== null && String(npmLatest).trim() !== '') {
|
|
315
|
+
const existing = String(npmLatest).trim()
|
|
316
|
+
const equal = existing === String(version)
|
|
317
|
+
addCheck(checks, 'publish: registry version not already used', allowExisting === true || !equal, 'blocker', equal ? `npm latest already ${existing}` : `npm latest ${existing}`, 'bump the version; never overwrite an already published version')
|
|
318
|
+
} else {
|
|
319
|
+
pass(checks, 'publish: registry version not already used', 'not checked (no --npm-latest)')
|
|
320
|
+
}
|
|
321
|
+
return { checks }
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function aggregate(target, checks, extra = {}) {
|
|
325
|
+
const blockers = checks.filter((item) => item.severity === 'blocker' && item.ok === false)
|
|
326
|
+
const warnings = checks.filter((item) => item.severity === 'warning' && item.ok === false)
|
|
327
|
+
const infos = checks.filter((item) => item.severity === 'info' && item.ok === true)
|
|
328
|
+
const score = scoreGateFindings(checks.map((item) => ({ severity: item.ok ? 'info' : item.severity })))
|
|
329
|
+
// 修复建议由 healer 统一给出(未知 blocker 也回落到 fail-closed 提示)。
|
|
330
|
+
const healerHints = new Map(gateRepairPlan(checks.map((item) => ({ ...item }))).map((item) => [item.id, item.hint]))
|
|
331
|
+
const repair = checks
|
|
332
|
+
.filter((item) => item.ok === false)
|
|
333
|
+
.map((item) => ({ id: item.id, hint: item.repair || healerHints.get(item.id) || 'inspect the gate report; do not bypass' }))
|
|
334
|
+
return {
|
|
335
|
+
ok: blockers.length === 0,
|
|
336
|
+
target,
|
|
337
|
+
at: new Date().toISOString(),
|
|
338
|
+
summary: { blockers: blockers.length, warnings: warnings.length, infos: infos.length, checks: checks.length },
|
|
339
|
+
score,
|
|
340
|
+
blockers: blockers.map((item) => ({ id: item.id, detail: item.detail })),
|
|
341
|
+
warnings: warnings.map((item) => ({ id: item.id, detail: item.detail })),
|
|
342
|
+
repair,
|
|
343
|
+
checks,
|
|
344
|
+
...extra,
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** 主入口:按 target 聚合检查。缺参数时 fail-closed,不猜。 */
|
|
349
|
+
export function runMainGate(options = {}) {
|
|
350
|
+
const target = String(options.target ?? 'package').trim()
|
|
351
|
+
if (!GATE_TARGETS.includes(target)) {
|
|
352
|
+
return aggregate(target, [{ id: 'gate: target', ok: false, severity: 'blocker', detail: `unknown target ${target}` }])
|
|
353
|
+
}
|
|
354
|
+
const checks = []
|
|
355
|
+
let version = String(options.version ?? '').trim()
|
|
356
|
+
if (!version) version = String(readJsonSafe(path.join(path.resolve(String(options.root ?? process.cwd())), 'package.json'))?.version ?? '')
|
|
357
|
+
let dataDir = String(options.dataDir ?? '').trim()
|
|
358
|
+
if (!dataDir && options.homeDir && options.profile) dataDir = path.join(path.resolve(String(options.homeDir)), 'fang', String(options.profile))
|
|
359
|
+
|
|
360
|
+
if (target === 'source') {
|
|
361
|
+
const out = checkSourceTree({ root: options.root ?? process.cwd(), version })
|
|
362
|
+
checks.push(...out.checks)
|
|
363
|
+
version = out.version
|
|
364
|
+
}
|
|
365
|
+
if (target === 'package' || target === 'publish' || target === 'install' || target === 'deploy') {
|
|
366
|
+
if (options.packageDir) {
|
|
367
|
+
const out = checkStagedPackage({ packageDir: options.packageDir, version })
|
|
368
|
+
checks.push(...out.checks)
|
|
369
|
+
} else if (target === 'package' || target === 'publish') {
|
|
370
|
+
fail(checks, 'package: staged package directory', 'missing --package-dir', 'run build and pass dist/npm/package')
|
|
371
|
+
}
|
|
372
|
+
if (target === 'package' || target === 'publish') {
|
|
373
|
+
const out = checkTarball({ distDir: options.distDir ?? 'dist', version, tarball: options.tarball, manifest: options.manifest })
|
|
374
|
+
checks.push(...out.checks)
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
if (target === 'publish') {
|
|
378
|
+
const out = checkPublishMetadata({ version, tag: options.tag, npmLatest: options.npmLatest, allowExisting: options.allowExisting === true })
|
|
379
|
+
checks.push(...out.checks)
|
|
380
|
+
}
|
|
381
|
+
if (target === 'install' || target === 'deploy' || target === 'profile') {
|
|
382
|
+
if (!options.homeDir) fail(checks, 'profile: home required', 'missing --home', 'pass the DSH_HOME that owns the profile')
|
|
383
|
+
if (!options.profile) fail(checks, 'profile: name required', 'missing --profile', 'pass the profile name')
|
|
384
|
+
if (options.homeDir && options.profile) {
|
|
385
|
+
const out = checkProfile({ homeDir: options.homeDir, profile: options.profile, profileDir: options.profileDir })
|
|
386
|
+
checks.push(...out.checks)
|
|
387
|
+
if (out.exists && !out.backup && options.repair === true) {
|
|
388
|
+
const backup = createProfileBackup(out.dir)
|
|
389
|
+
addCheck(checks, 'profile: backup created by repair', backup.ok === true, 'blocker', backup.ok ? backup.dir : backup.error, 'repair could not create a backup')
|
|
390
|
+
}
|
|
391
|
+
if (out.exists && !out.backup && options.requireBackup === true && options.repair !== true) {
|
|
392
|
+
fail(checks, 'profile: backup required before deploy', out.dir, 'run gate --repair (or make a .bak copy) before deploy')
|
|
393
|
+
}
|
|
394
|
+
const guards = checkRuntimeGuards({ homeDir: options.homeDir, profile: options.profile })
|
|
395
|
+
checks.push(...guards.checks)
|
|
396
|
+
const disk = checkDiskSpace({ homeDir: options.homeDir, minFreeBytes: options.minFreeBytes })
|
|
397
|
+
checks.push(...disk.checks)
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
if (target === 'deploy') {
|
|
401
|
+
if (options.supervisorPresent !== true) {
|
|
402
|
+
warn(checks, 'deploy: external supervisor', 'no live supervisor marker supplied', 'start restart-watchdog --execute if unattended restart is required')
|
|
403
|
+
} else pass(checks, 'deploy: external supervisor', 'present')
|
|
404
|
+
}
|
|
405
|
+
if (target === 'profile' && options.create === true) {
|
|
406
|
+
const home = path.resolve(String(options.homeDir ?? ''))
|
|
407
|
+
const name = String(options.profile ?? '')
|
|
408
|
+
const dir = path.join(home, 'profiles', name)
|
|
409
|
+
if (!PROFILE_NAME_RE.test(name)) fail(checks, 'profile-create: name', name, 'use lowercase letters/digits/hyphens, 1-63 chars')
|
|
410
|
+
if (RESERVED_PROFILE_NAMES.includes(name)) fail(checks, 'profile-create: reserved', name, 'desktop/plugin are reserved')
|
|
411
|
+
if (!isInside(path.join(home, 'profiles'), dir)) fail(checks, 'profile-create: inside home/profiles', dir)
|
|
412
|
+
if (fs.existsSync(dir) && options.force !== true) fail(checks, 'profile-create: does not exist', dir, 'use --force only after a verified backup')
|
|
413
|
+
if (fs.existsSync(dir) && options.force === true) warn(checks, 'profile-create: overwrite requested', dir, 'existing profile will be replaced; backup is mandatory')
|
|
414
|
+
const disk = checkDiskSpace({ homeDir: home, minFreeBytes: options.minFreeBytes })
|
|
415
|
+
checks.push(...disk.checks)
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
const report = aggregate(target, checks, { version, dataDir: dataDir || null })
|
|
419
|
+
if (dataDir && (target === 'install' || target === 'deploy' || target === 'publish')) {
|
|
420
|
+
const audit = recordGateDecision({ dataDir, target, report, actor: options.actor })
|
|
421
|
+
report.audit = audit
|
|
422
|
+
if (audit.ok === false && audit.reason === 'chain-broken') {
|
|
423
|
+
report.ok = false
|
|
424
|
+
report.blockers.push({ id: 'audit: append gate record', detail: 'hash chain broken; refusing to append a gate record' })
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
return report
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** 在 profile 目录写 .gate-backups/<stamp>/(只复制配置,不动 node_modules/会话)。 */
|
|
431
|
+
export function createProfileBackup(profileDir) {
|
|
432
|
+
const dir = path.resolve(String(profileDir ?? ''))
|
|
433
|
+
if (!fs.existsSync(dir)) return { ok: false, error: 'profile-missing', dir }
|
|
434
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
|
|
435
|
+
const target = path.join(dir, '.gate-backups', stamp)
|
|
436
|
+
try {
|
|
437
|
+
fs.mkdirSync(target, { recursive: true })
|
|
438
|
+
const copied = []
|
|
439
|
+
for (const name of ['package.json', 'cordis.patch.yml', 'cordis.yml']) {
|
|
440
|
+
const from = path.join(dir, name)
|
|
441
|
+
if (!fs.existsSync(from)) continue
|
|
442
|
+
fs.copyFileSync(from, path.join(target, name))
|
|
443
|
+
copied.push(name)
|
|
444
|
+
}
|
|
445
|
+
fs.writeFileSync(path.join(target, 'MANIFEST.json'), JSON.stringify({ at: new Date().toISOString(), profileDir: dir, copied }, null, 2), 'utf8')
|
|
446
|
+
return { ok: true, dir: target, copied }
|
|
447
|
+
} catch (error) {
|
|
448
|
+
return { ok: false, error: String(error?.message ?? error), dir: target }
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** 把门禁结论写进链式审计;没有 dataDir 时跳过。链坏了拒绝追加,避免洗白。 */
|
|
453
|
+
export function recordGateDecision({ dataDir, target, report, actor = '' } = {}) {
|
|
454
|
+
if (!dataDir) return { ok: false, skipped: true, reason: 'no-data-dir' }
|
|
455
|
+
const ledger = path.join(String(dataDir), 'audit.jsonl')
|
|
456
|
+
try {
|
|
457
|
+
fs.mkdirSync(String(dataDir), { recursive: true })
|
|
458
|
+
if (fs.existsSync(ledger)) {
|
|
459
|
+
const chain = verifyChain(ledger)
|
|
460
|
+
if (!chain.ok) return { ok: false, skipped: true, reason: 'chain-broken', chain }
|
|
461
|
+
}
|
|
462
|
+
const record = appendChained(ledger, {
|
|
463
|
+
kind: 'main-city-gate',
|
|
464
|
+
target,
|
|
465
|
+
ok: report?.ok === true,
|
|
466
|
+
version: report?.version ?? null,
|
|
467
|
+
blockers: report?.blockers?.map((item) => item.id).slice(0, 20) ?? [],
|
|
468
|
+
warnings: report?.warnings?.map((item) => item.id).slice(0, 20) ?? [],
|
|
469
|
+
grade: report?.score?.grade ?? null,
|
|
470
|
+
actor: String(actor ?? '').slice(0, 200) || null,
|
|
471
|
+
at: new Date().toISOString(),
|
|
472
|
+
})
|
|
473
|
+
return { ok: true, ledger, record }
|
|
474
|
+
} catch (error) {
|
|
475
|
+
return { ok: false, skipped: true, reason: 'append-failed', error: String(error?.message ?? error) }
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/** 把 blocker 汇总成可直接打在 CI/终端上的一行(不隐藏原因)。 */
|
|
480
|
+
export function formatGateFailure(report) {
|
|
481
|
+
const blockers = report?.blockers ?? []
|
|
482
|
+
if (!blockers.length) return 'gate GREEN'
|
|
483
|
+
return blockers.map((item) => `${item.id}: ${item.detail}`).join(' | ')
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
export const DEFAULT_PROFILE_BUNDLES = Object.freeze([
|
|
487
|
+
'@deepseek-ai/dsh-base',
|
|
488
|
+
'@deepseek-ai/dsh-web-app',
|
|
489
|
+
'@twinsearth/dsh-fang',
|
|
490
|
+
])
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* 通过门禁后真正创建一个新 profile(唯一允许的写路径)。
|
|
494
|
+
* 再次校验名称/路径/存在性,避免调用方跳过 gate 直接调用。
|
|
495
|
+
*/
|
|
496
|
+
export function createGatedProfile({ homeDir, profile, bundles = DEFAULT_PROFILE_BUNDLES, force = false, minFreeBytes = DEFAULT_MIN_FREE_BYTES } = {}) {
|
|
497
|
+
const home = path.resolve(String(homeDir ?? ''))
|
|
498
|
+
const name = String(profile ?? '').trim()
|
|
499
|
+
if (!home) return { ok: false, error: 'home-required' }
|
|
500
|
+
if (!PROFILE_NAME_RE.test(name)) return { ok: false, error: 'profile-name-invalid', detail: name }
|
|
501
|
+
if (RESERVED_PROFILE_NAMES.includes(name)) return { ok: false, error: 'profile-name-reserved', detail: name }
|
|
502
|
+
const dir = path.join(home, 'profiles', name)
|
|
503
|
+
if (!isInside(path.join(home, 'profiles'), dir)) return { ok: false, error: 'profile-path-escape', detail: dir }
|
|
504
|
+
if (fs.existsSync(dir) && force !== true) return { ok: false, error: 'profile-exists', detail: dir }
|
|
505
|
+
const free = diskFree(home)
|
|
506
|
+
if (free !== null && free < minFreeBytes) return { ok: false, error: 'disk-low', detail: `${free} < ${minFreeBytes}` }
|
|
507
|
+
const list = (Array.isArray(bundles) ? bundles : DEFAULT_PROFILE_BUNDLES).map(String).filter(Boolean)
|
|
508
|
+
if (!list.length || new Set(list).size !== list.length) return { ok: false, error: 'bundles-invalid' }
|
|
509
|
+
try {
|
|
510
|
+
fs.mkdirSync(path.join(home, 'profiles'), { recursive: true })
|
|
511
|
+
if (fs.existsSync(dir) && force === true) {
|
|
512
|
+
const backup = createProfileBackup(dir)
|
|
513
|
+
if (!backup.ok) return { ok: false, error: 'backup-failed', detail: backup.error }
|
|
514
|
+
}
|
|
515
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
516
|
+
const pkg = { name: `dsh-profile-${name}`, private: true, dsh: { profile: { bundles: list } } }
|
|
517
|
+
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(pkg, null, 2) + '\n', 'utf8')
|
|
518
|
+
const patch = path.join(dir, 'cordis.patch.yml')
|
|
519
|
+
if (!fs.existsSync(patch)) fs.writeFileSync(patch, '[]\n', 'utf8')
|
|
520
|
+
return { ok: true, dir, profile: name, bundles: list }
|
|
521
|
+
} catch (error) {
|
|
522
|
+
return { ok: false, error: 'create-failed', detail: String(error?.message ?? error), dir }
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
export const _internals = { checkSourceTree, checkStagedPackage, checkTarball, checkProfile, checkRuntimeGuards, checkPublishMetadata, isInside, pidAlive, diskFree }
|
|
@@ -29,7 +29,7 @@ import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'
|
|
|
29
29
|
|
|
30
30
|
import { EXIT, RISK_RANK } from '../kernel/core.mjs'
|
|
31
31
|
import { sha256 } from '../kernel/fsx.mjs'
|
|
32
|
-
import { canonical } from '../kernel/ledger.mjs'
|
|
32
|
+
import { appendChained, canonical, verifyChain } from '../kernel/ledger.mjs'
|
|
33
33
|
|
|
34
34
|
export const CONTRACT_VERSION = 1
|
|
35
35
|
export const APPROVAL_KIND = 'fang-restart-approval'
|
|
@@ -648,3 +648,105 @@ export function summarizeApproval(inspected) {
|
|
|
648
648
|
reason: inspected?.manifestVerification?.reason ?? inspected?.reason ?? null,
|
|
649
649
|
}
|
|
650
650
|
}
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
// ── v3.3.0 崩溃循环制动(纯函数,供 restart-guard / main-city gate / watchdog 共用)──
|
|
654
|
+
export const CRASH_LOOP_DEFAULTS = Object.freeze({
|
|
655
|
+
windowMs: 15 * 60_000,
|
|
656
|
+
threshold: 3,
|
|
657
|
+
})
|
|
658
|
+
|
|
659
|
+
/** 容错解析 crash ledger(JSONL);坏行跳过,供「只读判死」使用。 */
|
|
660
|
+
export function parseCrashLedgerText(text) {
|
|
661
|
+
const out = []
|
|
662
|
+
for (const line of String(text ?? '').split(/\r?\n/)) {
|
|
663
|
+
if (!line.trim()) continue
|
|
664
|
+
try {
|
|
665
|
+
const rec = JSON.parse(line)
|
|
666
|
+
if (rec && typeof rec === 'object') out.push(rec)
|
|
667
|
+
} catch { /* 坏行不是证据 */ }
|
|
668
|
+
}
|
|
669
|
+
return out
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/**
|
|
673
|
+
* 崩溃循环判定:windowMs 内 >= threshold 次崩溃 = active。
|
|
674
|
+
* 只看数字 at;没有 at 的记录不参与,避免用无时间证据误杀。
|
|
675
|
+
*/
|
|
676
|
+
export function detectCrashLoop(input, options = {}) {
|
|
677
|
+
const opts = {
|
|
678
|
+
now: Number.isFinite(Number(options.now)) ? Number(options.now) : Date.now(),
|
|
679
|
+
windowMs: Number(options.windowMs) > 0 ? Number(options.windowMs) : CRASH_LOOP_DEFAULTS.windowMs,
|
|
680
|
+
threshold: Number(options.threshold) > 0 ? Math.floor(Number(options.threshold)) : CRASH_LOOP_DEFAULTS.threshold,
|
|
681
|
+
}
|
|
682
|
+
const records = Array.isArray(input) ? input : parseCrashLedgerText(input)
|
|
683
|
+
const recent = records
|
|
684
|
+
.map((rec) => Number(rec?.at))
|
|
685
|
+
.filter((at) => Number.isFinite(at) && at > 0 && opts.now - at <= opts.windowMs)
|
|
686
|
+
.sort((a, b) => a - b)
|
|
687
|
+
const active = recent.length >= opts.threshold
|
|
688
|
+
return {
|
|
689
|
+
active,
|
|
690
|
+
count: recent.length,
|
|
691
|
+
threshold: opts.threshold,
|
|
692
|
+
windowMs: opts.windowMs,
|
|
693
|
+
firstAt: recent[0] ?? null,
|
|
694
|
+
lastAt: recent[recent.length - 1] ?? null,
|
|
695
|
+
reason: active ? 'crash-loop' : 'below-threshold',
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
/** 读取 crash ledger 文件并判定;文件不存在/不可读 = 空证据(inactive)。 */
|
|
700
|
+
export function readCrashLoop(file, options = {}) {
|
|
701
|
+
try {
|
|
702
|
+
const raw = fs.readFileSync(String(file ?? ''), 'utf8')
|
|
703
|
+
return detectCrashLoop(raw, options)
|
|
704
|
+
} catch {
|
|
705
|
+
return detectCrashLoop([], options)
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
/**
|
|
710
|
+
* v3.3.0:离线人工解除 restart 崩溃循环安全模式。
|
|
711
|
+
* 只做三件事:归档 runtime-crash.jsonl、把 safe-mode.json 标成人工清除、写一条链式审计(若账本可读)。
|
|
712
|
+
* 不做重启、不改 profile、不删除崩溃证据。
|
|
713
|
+
*/
|
|
714
|
+
export function clearCrashLoopSafeMode(dataDir, options = {}) {
|
|
715
|
+
const by = options && options.by !== undefined ? options.by : ''
|
|
716
|
+
const note = options && options.note !== undefined ? options.note : ''
|
|
717
|
+
const now = Number(options && options.now) > 0 ? Number(options.now) : Date.now()
|
|
718
|
+
const base = String(dataDir ?? '').trim()
|
|
719
|
+
if (!base) return { ok: false, reason: 'data-dir-required' }
|
|
720
|
+
const stateDir = base + '/restart'
|
|
721
|
+
const safeFile = stateDir + '/safe-mode.json'
|
|
722
|
+
const crashFile = stateDir + '/runtime-crash.jsonl'
|
|
723
|
+
let current = null
|
|
724
|
+
try { current = JSON.parse(fs.readFileSync(safeFile, "utf8")) } catch { current = null }
|
|
725
|
+
if (!current || current.active !== true) return { ok: true, cleared: false, reason: 'not-active', file: safeFile }
|
|
726
|
+
const stamp = new Date(now).toISOString().replace(/[:.]/g, '-')
|
|
727
|
+
let archived = null
|
|
728
|
+
try {
|
|
729
|
+
if (fs.existsSync(crashFile)) {
|
|
730
|
+
archived = crashFile + '.cleared-' + stamp
|
|
731
|
+
fs.renameSync(crashFile, archived)
|
|
732
|
+
}
|
|
733
|
+
fs.mkdirSync(stateDir, { recursive: true })
|
|
734
|
+
fs.writeFileSync(safeFile, JSON.stringify({
|
|
735
|
+
version: 1, active: false, reason: 'cleared', at: now, clearedAt: now,
|
|
736
|
+
clearedBy: String(by ?? '').slice(0, 200) || null,
|
|
737
|
+
note: String(note ?? '').slice(0, 500) || null,
|
|
738
|
+
archived,
|
|
739
|
+
}, null, 2) + '\n', 'utf8')
|
|
740
|
+
} catch (error) {
|
|
741
|
+
return { ok: false, cleared: false, reason: 'clear-failed', error: String(error?.message ?? error) }
|
|
742
|
+
}
|
|
743
|
+
let audit = null
|
|
744
|
+
try {
|
|
745
|
+
const ledger = base + '/audit.jsonl'
|
|
746
|
+
const chain = verifyChain(ledger)
|
|
747
|
+
if (chain.ok) {
|
|
748
|
+
audit = appendChained(ledger, { kind: 'restart-safe-mode-cleared', by: String(by ?? '') || null, note: String(note ?? '') || null, archived, at: new Date(now).toISOString() })
|
|
749
|
+
}
|
|
750
|
+
} catch { /* 审计失败不阻断人工恢复 */ }
|
|
751
|
+
return { ok: true, cleared: true, file: safeFile, archived, audit }
|
|
752
|
+
}
|