@twinsearth/dsh-fang 3.2.2 → 3.3.1
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/docs/DSH-ARCHITECTURE-MAP.md +73 -0
- package/docs/MAIN-CITY-GATE.md +58 -0
- package/package.json +1 -1
- package/src/kernel/types.mjs +1 -1
- package/src/lib/main-gate.mjs +576 -0
- package/src/lib/restart-contract.mjs +103 -1
- 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
|
@@ -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
|
+
}
|
package/src/plugins/forker.mjs
CHANGED
|
@@ -61,6 +61,7 @@ import {
|
|
|
61
61
|
} from '../kernel/index.mjs'
|
|
62
62
|
import { computeBackoff, planRestart, reconcileOrphans, writeForkMeta, probeHttpAlive, SUPERVISION_DEFAULTS } from '../lib/fork-supervisor.mjs'
|
|
63
63
|
import { applyForkConfigLock, setProfileConfigReadonly } from '../lib/fork-config-lock.mjs'
|
|
64
|
+
import { runMainGate, formatGateFailure } from '../lib/main-gate.mjs'
|
|
64
65
|
import { DEFAULT_FORK_SEED, applyForkSeedToProfile } from '../lib/fork-seed.mjs'
|
|
65
66
|
|
|
66
67
|
export const name = 'fang-forker'
|
|
@@ -867,6 +868,21 @@ export function apply(ctx, config) {
|
|
|
867
868
|
const homeDir = path.resolve(homeRaw)
|
|
868
869
|
const profile = safeProfile(opts.profile ?? (cleanTemplate ? forkProfileTag : path.basename(sourceTemplateDir)))
|
|
869
870
|
const profileDir = path.join(homeDir, 'profiles', profile)
|
|
871
|
+
// v3.3.0 主城门禁(新建 profile):分身/元主运行态首次落盘前必须过路径/磁盘/门禁。
|
|
872
|
+
// 已存在的 profile 走 restart 路径,不重复新建检查。
|
|
873
|
+
if (!exists(profileDir)) {
|
|
874
|
+
const gate = runMainGate({
|
|
875
|
+
target: 'profile',
|
|
876
|
+
homeDir,
|
|
877
|
+
profile,
|
|
878
|
+
profileDir,
|
|
879
|
+
create: true,
|
|
880
|
+
force: false,
|
|
881
|
+
})
|
|
882
|
+
if (!gate.ok) {
|
|
883
|
+
return { ok: false, error: 'main-city-gate-blocked', detail: formatGateFailure(gate), gate }
|
|
884
|
+
}
|
|
885
|
+
}
|
|
870
886
|
ensureDir(homeDir)
|
|
871
887
|
ensureDir(profileDir)
|
|
872
888
|
|
package/src/plugins/healer.mjs
CHANGED
|
@@ -66,6 +66,44 @@ const EFFECT_RE = /ctx\.effect\s*\(/
|
|
|
66
66
|
const PROVIDE_RE = /ctx\.provide\s*\(/
|
|
67
67
|
const INJECT_RE = /export\s+const\s+inject\s*=\s*(\[[^\]]*\])/
|
|
68
68
|
|
|
69
|
+
/** v3.3.0:主城门禁 blocker → 可执行的修复动作(只给建议,不写盘)。 */
|
|
70
|
+
export const GATE_REPAIR_HINTS = Object.freeze({
|
|
71
|
+
'source: semver': 'fix package.json version to a semver x.y.z',
|
|
72
|
+
'source: kernel FANG_VERSION': 'update src/kernel/types.mjs FANG_VERSION to the package version',
|
|
73
|
+
'source: CHANGELOG section': 'add a "## v<version>" section to docs/CHANGELOG.md',
|
|
74
|
+
'source: AUDIT file': 'add docs/AUDIT-v<version>.md with the release evidence',
|
|
75
|
+
'source: required guard files': 'restore the missing crash-safety files before building',
|
|
76
|
+
'source: vendored contract bytes': 're-sync src/contract from the pinned @twinsearth/dsh-fang-contract version',
|
|
77
|
+
'source: gate wired into build': 'call tools/gate/main-city.mjs from tools/release/build.mjs',
|
|
78
|
+
'source: gate wired into publish': 'call tools/gate/main-city.mjs from tools/release/publish-npm.mjs',
|
|
79
|
+
'package: client half': 'restore dsh.client.platform=web in package.json',
|
|
80
|
+
'package: bundle manifest': 'restore dsh.bundle.patch and the referenced patch file',
|
|
81
|
+
'artifact: tarball sha256': 'rebuild the artifact; never publish a tarball whose sha256 differs from manifest',
|
|
82
|
+
'artifact: sha256 sidecar': 'rebuild so the .sha256 sidecar is regenerated with the tarball',
|
|
83
|
+
'artifact: required files inside tarball': 'add the missing guard/gate files to package.json files and rebuild',
|
|
84
|
+
'publish: tag matches version': 'recreate the annotated tag as v<package version>',
|
|
85
|
+
'publish: registry version not already used': 'bump the version; published versions are immutable',
|
|
86
|
+
'profile: inside home/profiles': 'point --home/--profile at $DSH_HOME/profiles; never write outside it',
|
|
87
|
+
'profile: no duplicate bundles': 'remove duplicate entries from dsh.profile.bundles',
|
|
88
|
+
'profile: patch parses': 'repair cordis.patch.yml indentation or restore the previous patch from .gate-backups',
|
|
89
|
+
'profile: backup available': 'run gate --repair (creates .gate-backups/<stamp>/) before changing the profile',
|
|
90
|
+
'runtime: no live host on this profile': 'fully exit the DSH client before install/deploy',
|
|
91
|
+
'runtime: restart safe-mode clear': 'investigate restart safe-mode; clear only via fangRestart.clearSafeMode({by,note})',
|
|
92
|
+
'runtime: no active crash loop': 'inspect runtime-crash.jsonl and the restart guard; do not redeploy until the loop is understood',
|
|
93
|
+
'audit: hash chain verifies': 'restore audit.jsonl from backup and investigate tampering; never append to a broken chain',
|
|
94
|
+
'disk: free space available': 'free disk space before creating profiles or installing packages',
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
export function gateRepairPlan(findings) {
|
|
98
|
+
return (Array.isArray(findings) ? findings : [])
|
|
99
|
+
.filter((item) => item && item.ok !== true)
|
|
100
|
+
.map((item) => ({
|
|
101
|
+
id: item.id,
|
|
102
|
+
severity: item.severity ?? 'blocker',
|
|
103
|
+
hint: GATE_REPAIR_HINTS[item.id] ?? item.repair ?? 'inspect the gate report and fix the underlying cause; do not bypass',
|
|
104
|
+
}))
|
|
105
|
+
}
|
|
106
|
+
|
|
69
107
|
export const GATE_IDS = ['G1', 'G2', 'G3', 'G4', 'G5', 'G6', 'G7', 'G8', 'G9', 'G10', 'G11', 'G12']
|
|
70
108
|
|
|
71
109
|
function safeGet(ctx, key) {
|
|
@@ -41,6 +41,8 @@ import {
|
|
|
41
41
|
pruneRestartState,
|
|
42
42
|
receiptFile,
|
|
43
43
|
reconcileRestartState,
|
|
44
|
+
readCrashLoop,
|
|
45
|
+
detectCrashLoop,
|
|
44
46
|
resolveHmacSecret,
|
|
45
47
|
summarizeApproval,
|
|
46
48
|
summarizeApprovalCounts,
|
|
@@ -160,6 +162,31 @@ export function apply(ctx, config) {
|
|
|
160
162
|
const supervisorMarkerFile = path.join(stateDir, 'supervisor.present')
|
|
161
163
|
const bootStateFile = path.join(stateDir, 'boot-state.json')
|
|
162
164
|
const crashLedgerFile = path.join(stateDir, 'runtime-crash.jsonl')
|
|
165
|
+
const safeModeFile = path.join(stateDir, 'safe-mode.json')
|
|
166
|
+
const readSafeMode = () => {
|
|
167
|
+
const doc = readJson(safeModeFile, null)
|
|
168
|
+
return doc && doc.active === true
|
|
169
|
+
? { active: true, reason: String(doc.reason ?? 'unknown'), at: Number(doc.at) || 0, crashCount: Number(doc.crashCount) || 0, file: safeModeFile }
|
|
170
|
+
: { active: false, reason: null, at: 0, crashCount: 0, file: safeModeFile }
|
|
171
|
+
}
|
|
172
|
+
let safeMode = readSafeMode()
|
|
173
|
+
const crashLoopAtBoot = readCrashLoop(crashLedgerFile)
|
|
174
|
+
if (crashLoopAtBoot.active && !safeMode.active) {
|
|
175
|
+
safeMode = {
|
|
176
|
+
active: true,
|
|
177
|
+
reason: 'crash-loop',
|
|
178
|
+
at: Date.now(),
|
|
179
|
+
crashCount: crashLoopAtBoot.count,
|
|
180
|
+
file: safeModeFile,
|
|
181
|
+
windowMs: crashLoopAtBoot.windowMs,
|
|
182
|
+
threshold: crashLoopAtBoot.threshold,
|
|
183
|
+
}
|
|
184
|
+
try {
|
|
185
|
+
ensureDir(stateDir)
|
|
186
|
+
writeJsonAtomic(safeModeFile, { version: 1, active: true, reason: 'crash-loop', at: safeMode.at, crashCount: safeMode.crashCount, windowMs: crashLoopAtBoot.windowMs, threshold: crashLoopAtBoot.threshold })
|
|
187
|
+
} catch { /* 安全模式落盘失败也不能阻断启动;内存 active 仍生效 */ }
|
|
188
|
+
log('warn', 'crash loop detected (' + crashLoopAtBoot.count + '/' + crashLoopAtBoot.threshold + ' in ' + crashLoopAtBoot.windowMs + 'ms): restart handoff disabled until manual clear')
|
|
189
|
+
}
|
|
163
190
|
const SUPERVISOR_MARKER_TTL_MS = 60000
|
|
164
191
|
const pidAlive = (pid) => {
|
|
165
192
|
if (!Number.isInteger(pid) || pid <= 0) return false
|
|
@@ -234,11 +261,17 @@ export function apply(ctx, config) {
|
|
|
234
261
|
/** 三重门禁:enforce ∧ allowProcessRestart ∧ supervisor 在位,才允许把执行权交出去。 */
|
|
235
262
|
const executionArmed = () => {
|
|
236
263
|
const supervisor = detectSupervisor()
|
|
264
|
+
const crashLoop = readCrashLoop(crashLedgerFile)
|
|
265
|
+
const sm = readSafeMode()
|
|
266
|
+
if (sm.active) safeMode = sm
|
|
237
267
|
return {
|
|
238
|
-
|
|
268
|
+
// v3.3.0:崩溃循环/安全模式下即使三重门禁全绿,也绝不交接执行权。
|
|
269
|
+
armed: cfg.mode === 'enforce' && cfg.allowProcessRestart === true && supervisor.present === true && safeMode.active !== true,
|
|
239
270
|
supervisor,
|
|
240
271
|
mode: cfg.mode,
|
|
241
272
|
allowProcessRestart: cfg.allowProcessRestart === true,
|
|
273
|
+
safeMode: { ...safeMode },
|
|
274
|
+
crashLoop,
|
|
242
275
|
}
|
|
243
276
|
}
|
|
244
277
|
writeHostPid()
|
|
@@ -734,6 +767,8 @@ export function apply(ctx, config) {
|
|
|
734
767
|
supervisorPresent: supervisor.present === true,
|
|
735
768
|
supervisor,
|
|
736
769
|
executionArmed: gateState.armed === true,
|
|
770
|
+
safeMode: { ...gateState.safeMode },
|
|
771
|
+
crashLoop: gateState.crashLoop,
|
|
737
772
|
execution: { executed: false, decisionOnly: true },
|
|
738
773
|
}
|
|
739
774
|
}
|
|
@@ -756,6 +791,8 @@ export function apply(ctx, config) {
|
|
|
756
791
|
supervisorPresent: supervisor.present === true,
|
|
757
792
|
supervisor,
|
|
758
793
|
executionArmed: gateState.armed === true,
|
|
794
|
+
safeMode: { ...gateState.safeMode },
|
|
795
|
+
crashLoop: gateState.crashLoop,
|
|
759
796
|
}
|
|
760
797
|
}
|
|
761
798
|
|
|
@@ -774,6 +811,8 @@ export function apply(ctx, config) {
|
|
|
774
811
|
manifestTtlMs: cfg.manifestTtlMs,
|
|
775
812
|
supervisorPresent: gateState.supervisor.present === true,
|
|
776
813
|
executionArmed: gateState.armed === true,
|
|
814
|
+
safeMode: { ...gateState.safeMode },
|
|
815
|
+
crashLoop: gateState.crashLoop,
|
|
777
816
|
approval: {
|
|
778
817
|
kind: APPROVAL_KIND,
|
|
779
818
|
dir: approvedDir,
|
|
@@ -905,6 +944,8 @@ export function apply(ctx, config) {
|
|
|
905
944
|
add('pid-file-foreign-live', 'warn', `pid=${pidDoc.pid}`)
|
|
906
945
|
}
|
|
907
946
|
if (lastUncleanBoot) add('unclean-boot', 'warn', `${lastUncleanBoot.state} pid=${lastUncleanBoot.pid ?? 'n/a'}`)
|
|
947
|
+
if (safeMode.active) add('safe-mode-active', 'block', `${safeMode.reason} at=${safeMode.at || 'n/a'} crashCount=${safeMode.crashCount || 0}`)
|
|
948
|
+
if (crashLoopAtBoot.active) add('crash-loop', 'warn', `${crashLoopAtBoot.count}/${crashLoopAtBoot.threshold} in ${crashLoopAtBoot.windowMs}ms`)
|
|
908
949
|
let crashCount = 0
|
|
909
950
|
try {
|
|
910
951
|
const raw = readTextSafe(crashLedgerFile, '')
|
|
@@ -921,8 +962,41 @@ export function apply(ctx, config) {
|
|
|
921
962
|
}
|
|
922
963
|
}
|
|
923
964
|
|
|
965
|
+
/** 人工解除安全模式:归档 crash ledger,避免下一次启动按旧证据再次触发。 */
|
|
966
|
+
const clearSafeMode = (options = {}) => {
|
|
967
|
+
if (!safeMode.active) return { ok: true, cleared: false, reason: 'not-active' }
|
|
968
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
|
|
969
|
+
let archived = null
|
|
970
|
+
try {
|
|
971
|
+
if (fs.existsSync(crashLedgerFile)) {
|
|
972
|
+
archived = `${crashLedgerFile}.cleared-${stamp}`
|
|
973
|
+
fs.renameSync(crashLedgerFile, archived)
|
|
974
|
+
}
|
|
975
|
+
} catch (error) {
|
|
976
|
+
return { ok: false, cleared: false, reason: 'archive-failed', error: errText(error) }
|
|
977
|
+
}
|
|
978
|
+
try {
|
|
979
|
+
ensureDir(stateDir)
|
|
980
|
+
writeJsonAtomic(safeModeFile, {
|
|
981
|
+
version: 1, active: false, reason: 'cleared',
|
|
982
|
+
at: Date.now(), clearedAt: Date.now(),
|
|
983
|
+
clearedBy: options.by ? String(options.by).slice(0, 200) : null,
|
|
984
|
+
note: options.note ? String(options.note).slice(0, 500) : null,
|
|
985
|
+
archived,
|
|
986
|
+
})
|
|
987
|
+
} catch (error) {
|
|
988
|
+
return { ok: false, cleared: false, reason: 'persist-failed', error: errText(error) }
|
|
989
|
+
}
|
|
990
|
+
safeMode = { active: false, reason: null, at: 0, crashCount: 0, file: safeModeFile }
|
|
991
|
+
audit('restart-safe-mode-cleared', { by: options.by ?? null, note: options.note ?? null, archived })
|
|
992
|
+
log('warn', `safe mode cleared manually (by=${String(options.by ?? 'unknown').slice(0, 80)})`)
|
|
993
|
+
return { ok: true, cleared: true, archived, file: safeModeFile }
|
|
994
|
+
}
|
|
995
|
+
|
|
924
996
|
const service = {
|
|
925
997
|
request, decideOnly, state, impact, policy, executionContract, approvals, executionStatus, verifyApproval, selfCheck,
|
|
998
|
+
safeMode: () => ({ ...safeMode, crashLoop: readCrashLoop(crashLedgerFile) }),
|
|
999
|
+
clearSafeMode,
|
|
926
1000
|
runtimeGuard: () => ({
|
|
927
1001
|
lastUncleanBoot,
|
|
928
1002
|
bootStateFile,
|
package/src/plugins/scorer.mjs
CHANGED
|
@@ -452,6 +452,43 @@ function safeGet(ctx, key) {
|
|
|
452
452
|
try { return ctx?.get?.(key) } catch { return undefined }
|
|
453
453
|
}
|
|
454
454
|
|
|
455
|
+
export const ADMISSION_DEFAULT_MAX_GRADE = 'B'
|
|
456
|
+
const GRADE_RANK = Object.freeze({ A: 1, B: 2, C: 3, D: 4, E: 5 })
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* v3.3.0:把「主城门禁」的结构化 findings 折算成 A–E 准入分。
|
|
460
|
+
* 约定:blocker 直接 E;warning 每项 10 分;info 不扣分。
|
|
461
|
+
* 默认只放行 A/B(maxGrade='B'),C 及以上阻断——与 healer 静态门禁同一套分档。
|
|
462
|
+
*/
|
|
463
|
+
export function scoreGateFindings(findings, options = {}) {
|
|
464
|
+
const list = Array.isArray(findings) ? findings : []
|
|
465
|
+
const maxGrade = String(options.maxGrade ?? ADMISSION_DEFAULT_MAX_GRADE).toUpperCase()
|
|
466
|
+
if (!GRADE_RANK[maxGrade]) throw new Error('invalid maxGrade: ' + maxGrade)
|
|
467
|
+
const blockers = list.filter((item) => item && item.severity === 'blocker')
|
|
468
|
+
const warnings = list.filter((item) => item && item.severity === 'warning')
|
|
469
|
+
const infos = list.filter((item) => item && item.severity === 'info')
|
|
470
|
+
// 0 warning = A;1–2 个 = B;3 个起 = C(需修复后重跑)。
|
|
471
|
+
const S = blockers.length > 0
|
|
472
|
+
? 100
|
|
473
|
+
: warnings.length === 0 ? 0 : Math.min(100, 20 + warnings.length * 10)
|
|
474
|
+
const grade = gradeOf(S, BAND_DEFAULTS.mother)
|
|
475
|
+
const reasons = []
|
|
476
|
+
if (blockers.length > 0) reasons.push('blockers=' + blockers.length)
|
|
477
|
+
if (warnings.length > 0) reasons.push('warnings=' + warnings.length)
|
|
478
|
+
if (GRADE_RANK[grade] > GRADE_RANK[maxGrade]) reasons.push('grade=' + grade + '>' + maxGrade)
|
|
479
|
+
return {
|
|
480
|
+
ok: blockers.length === 0 && GRADE_RANK[grade] <= GRADE_RANK[maxGrade],
|
|
481
|
+
grade,
|
|
482
|
+
S,
|
|
483
|
+
maxGrade,
|
|
484
|
+
blockers: blockers.length,
|
|
485
|
+
warnings: warnings.length,
|
|
486
|
+
infos: infos.length,
|
|
487
|
+
reasons,
|
|
488
|
+
basis: basisOf(ROLE.MOTHER, BAND_DEFAULTS.mother),
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
455
492
|
export function apply(ctx, config) {
|
|
456
493
|
const gate = roleGate('scorer', { cfgRole: config?.role, logger: ctx.logger })
|
|
457
494
|
// v2 部署矩阵:scorer 在 mother 与 fork 都激活;这里只守住“未部署角色不得注册服务”。
|
package/tools/fangctl.mjs
CHANGED
|
@@ -21,7 +21,7 @@ import {
|
|
|
21
21
|
resolveFangLayout, resolveProfileDir, resolveDshHome, parseWebUrl,
|
|
22
22
|
exists, readJson, readJsonl, isLink, verifyChain, FANG_VERSION,
|
|
23
23
|
} from '../src/kernel/index.mjs'
|
|
24
|
-
import { readRestartStatus } from '../src/lib/restart-contract.mjs'
|
|
24
|
+
import { readRestartStatus, clearCrashLoopSafeMode } from '../src/lib/restart-contract.mjs'
|
|
25
25
|
|
|
26
26
|
function parseArgs(argv) {
|
|
27
27
|
const args = { _: [] }
|
|
@@ -364,6 +364,25 @@ switch (cmd) {
|
|
|
364
364
|
try { code = await cmdRestartStatus(layout, args) } catch (error) { console.error(String(error?.message ?? error)); code = 1 }
|
|
365
365
|
break
|
|
366
366
|
}
|
|
367
|
+
case 'restart-safe': {
|
|
368
|
+
const action = args._[1] ?? 'status'
|
|
369
|
+
const safeFile = path.join(layout.dataDir, 'restart', 'safe-mode.json')
|
|
370
|
+
if (action === 'clear') {
|
|
371
|
+
const result = clearCrashLoopSafeMode(layout.dataDir, { by: args.by ?? 'fangctl', note: args.note ?? '' })
|
|
372
|
+
if (args.json) console.log(JSON.stringify(result, null, 2))
|
|
373
|
+
else if (result.ok) console.log(result.cleared ? `safe-mode cleared; crash ledger archived: ${result.archived ?? '(none)'}` : 'safe-mode is not active')
|
|
374
|
+
else console.error(`FAIL ${result.reason}: ${result.error ?? ''}`)
|
|
375
|
+
code = result.ok ? 0 : 1
|
|
376
|
+
break
|
|
377
|
+
}
|
|
378
|
+
let doc = null
|
|
379
|
+
try { doc = JSON.parse(fs.readFileSync(safeFile, 'utf8')) } catch { doc = null }
|
|
380
|
+
if (args.json) console.log(JSON.stringify({ file: safeFile, safeMode: doc }, null, 2))
|
|
381
|
+
else if (!doc || doc.active !== true) console.log(`safe-mode: clear (${safeFile})`)
|
|
382
|
+
else console.log(`safe-mode: ACTIVE reason=${doc.reason ?? '?'} at=${fmtTime(doc.at)} crashCount=${doc.crashCount ?? '?'} file=${safeFile}`)
|
|
383
|
+
code = 0
|
|
384
|
+
break
|
|
385
|
+
}
|
|
367
386
|
case 'verify': code = cmdVerify(layout); break
|
|
368
387
|
case 'tail': code = cmdTail(layout, Number(args._[1] ?? 20)); break
|
|
369
388
|
case 'doctor': code = cmdDoctor(layout); break
|
|
@@ -383,7 +402,7 @@ switch (cmd) {
|
|
|
383
402
|
break
|
|
384
403
|
}
|
|
385
404
|
default:
|
|
386
|
-
console.log('usage: fangctl.mjs <status|forks|verify|tail [n]|doctor|restart-status [limit]|parse-url <line>|approvals|approve <source:id>|deny <source:id>> [--profile name] [--data-root dir] [--url url] [--token token] [--note text] [--by who] [--json]')
|
|
405
|
+
console.log('usage: fangctl.mjs <status|forks|verify|tail [n]|doctor|restart-status [limit]|restart-safe [status|clear]|parse-url <line>|approvals|approve <source:id>|deny <source:id>> [--profile name] [--data-root dir] [--url url] [--token token] [--note text] [--by who] [--json]')
|
|
387
406
|
code = 64
|
|
388
407
|
}
|
|
389
408
|
process.exitCode = code
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
|
|
4
|
+
//
|
|
5
|
+
// 主城门禁 CLI:任何进主城的动作(打包/发布/安装/部署/新建 profile)先过这里。
|
|
6
|
+
// node tools/gate/main-city.mjs --target source
|
|
7
|
+
// node tools/gate/main-city.mjs --target package --package-dir dist/npm/package --tarball dist/dsh-fang-X.tgz
|
|
8
|
+
// node tools/gate/main-city.mjs --target publish --package-dir ... --tarball ... --tag vX --check-registry
|
|
9
|
+
// node tools/gate/main-city.mjs --target install --home <DSH_HOME> --profile fang-x --package-dir <dir>
|
|
10
|
+
// node tools/gate/main-city.mjs --target deploy --home <DSH_HOME> --profile fang-x --repair
|
|
11
|
+
// node tools/gate/main-city.mjs --target profile --home <DSH_HOME> --profile demo --create
|
|
12
|
+
import fs from 'node:fs'
|
|
13
|
+
import path from 'node:path'
|
|
14
|
+
import { fileURLToPath } from 'node:url'
|
|
15
|
+
|
|
16
|
+
import {
|
|
17
|
+
DEFAULT_MIN_FREE_BYTES,
|
|
18
|
+
DEFAULT_PROFILE_BUNDLES,
|
|
19
|
+
GATE_TARGETS,
|
|
20
|
+
createGatedProfile,
|
|
21
|
+
formatGateFailure,
|
|
22
|
+
runMainGate,
|
|
23
|
+
} from '../../src/lib/main-gate.mjs'
|
|
24
|
+
|
|
25
|
+
function parseArgs(argv = []) {
|
|
26
|
+
const out = { target: 'package', json: false, repair: false, create: false, force: false, allowExisting: false, checkRegistry: false }
|
|
27
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
28
|
+
const arg = String(argv[index])
|
|
29
|
+
const next = () => {
|
|
30
|
+
if (index + 1 >= argv.length) throw new Error(`missing value for ${arg}`)
|
|
31
|
+
return String(argv[++index])
|
|
32
|
+
}
|
|
33
|
+
if (arg === '--json') { out.json = true; continue }
|
|
34
|
+
if (arg === '--repair') { out.repair = true; continue }
|
|
35
|
+
if (arg === '--create') { out.create = true; continue }
|
|
36
|
+
if (arg === '--force') { out.force = true; continue }
|
|
37
|
+
if (arg === '--allow-existing') { out.allowExisting = true; continue }
|
|
38
|
+
if (arg === '--require-backup') { out.requireBackup = true; continue }
|
|
39
|
+
if (arg === '--check-registry') { out.checkRegistry = true; continue }
|
|
40
|
+
if (arg === '--supervisor-present') { out.supervisorPresent = true; continue }
|
|
41
|
+
if (arg === '--help' || arg === '-h') { out.help = true; continue }
|
|
42
|
+
if (arg === '--target') { out.target = next(); continue }
|
|
43
|
+
if (arg.startsWith('--target=')) { out.target = arg.slice(9); continue }
|
|
44
|
+
if (arg === '--root') { out.root = next(); continue }
|
|
45
|
+
if (arg.startsWith('--root=')) { out.root = arg.slice(7); continue }
|
|
46
|
+
if (arg === '--version') { out.version = next(); continue }
|
|
47
|
+
if (arg.startsWith('--version=')) { out.version = arg.slice(10); continue }
|
|
48
|
+
if (arg === '--dist') { out.distDir = next(); continue }
|
|
49
|
+
if (arg.startsWith('--dist=')) { out.distDir = arg.slice(7); continue }
|
|
50
|
+
if (arg === '--package-dir') { out.packageDir = next(); continue }
|
|
51
|
+
if (arg.startsWith('--package-dir=')) { out.packageDir = arg.slice(14); continue }
|
|
52
|
+
if (arg === '--tarball') { out.tarball = next(); continue }
|
|
53
|
+
if (arg.startsWith('--tarball=')) { out.tarball = arg.slice(10); continue }
|
|
54
|
+
if (arg === '--tag') { out.tag = next(); continue }
|
|
55
|
+
if (arg.startsWith('--tag=')) { out.tag = arg.slice(6); continue }
|
|
56
|
+
if (arg === '--npm-latest') { out.npmLatest = next(); continue }
|
|
57
|
+
if (arg.startsWith('--npm-latest=')) { out.npmLatest = arg.slice(13); continue }
|
|
58
|
+
if (arg === '--home') { out.homeDir = next(); continue }
|
|
59
|
+
if (arg.startsWith('--home=')) { out.homeDir = arg.slice(7); continue }
|
|
60
|
+
if (arg === '--profile') { out.profile = next(); continue }
|
|
61
|
+
if (arg.startsWith('--profile=')) { out.profile = arg.slice(10); continue }
|
|
62
|
+
if (arg === '--profile-dir') { out.profileDir = next(); continue }
|
|
63
|
+
if (arg.startsWith('--profile-dir=')) { out.profileDir = arg.slice(14); continue }
|
|
64
|
+
if (arg === '--data-dir') { out.dataDir = next(); continue }
|
|
65
|
+
if (arg.startsWith('--data-dir=')) { out.dataDir = arg.slice(11); continue }
|
|
66
|
+
if (arg === '--actor') { out.actor = next(); continue }
|
|
67
|
+
if (arg.startsWith('--actor=')) { out.actor = arg.slice(8); continue }
|
|
68
|
+
if (arg === '--bundles') { out.bundles = next().split(',').map((item) => item.trim()).filter(Boolean); continue }
|
|
69
|
+
if (arg.startsWith('--bundles=')) { out.bundles = arg.slice(10).split(',').map((item) => item.trim()).filter(Boolean); continue }
|
|
70
|
+
if (arg === '--min-free-mb') { out.minFreeBytes = Math.max(0, Number(next()) || 0) * 1024 * 1024; continue }
|
|
71
|
+
if (arg.startsWith('--min-free-mb=')) { out.minFreeBytes = Math.max(0, Number(arg.slice(14)) || 0) * 1024 * 1024; continue }
|
|
72
|
+
throw new Error(`unknown argument: ${arg}`)
|
|
73
|
+
}
|
|
74
|
+
if (!out.minFreeBytes) out.minFreeBytes = DEFAULT_MIN_FREE_BYTES
|
|
75
|
+
return out
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const USAGE = `usage: node tools/gate/main-city.mjs --target <${GATE_TARGETS.join('|')}> [options]
|
|
79
|
+
|
|
80
|
+
options:
|
|
81
|
+
--root <dir> source root (default: process.cwd())
|
|
82
|
+
--version <semver> expected version (default: package.json)
|
|
83
|
+
--dist <dir> dist directory containing manifest.json/tarball (default: dist)
|
|
84
|
+
--package-dir <dir> staged package directory (dist/npm/package)
|
|
85
|
+
--tarball <file> explicit tarball path
|
|
86
|
+
--tag <vX.Y.Z> release tag to match against version
|
|
87
|
+
--npm-latest <version> current registry latest (offline check)
|
|
88
|
+
--check-registry fetch npm latest before publish check
|
|
89
|
+
--allow-existing allow an already-published version (idempotent republish)
|
|
90
|
+
--home <dir> DSH_HOME that owns the profile
|
|
91
|
+
--profile <name> profile name
|
|
92
|
+
--profile-dir <dir> explicit profile directory
|
|
93
|
+
--data-dir <dir> explicit fang data dir (default <home>/fang/<profile>)
|
|
94
|
+
--create create the profile after a green gate
|
|
95
|
+
--force allow replacing an existing profile (backup taken)
|
|
96
|
+
--repair create a .gate-backups snapshot when a profile has none
|
|
97
|
+
--require-backup block deploy when no profile backup exists
|
|
98
|
+
--bundles a,b,c bundles for a newly created profile
|
|
99
|
+
--min-free-mb <n> minimum free disk space (default ${Math.round(DEFAULT_MIN_FREE_BYTES / 1024 / 1024)})
|
|
100
|
+
--actor <id> recorded in the chained audit record
|
|
101
|
+
--json machine-readable report
|
|
102
|
+
-h, --help
|
|
103
|
+
`
|
|
104
|
+
|
|
105
|
+
async function npmLatest(version) {
|
|
106
|
+
try {
|
|
107
|
+
const res = await fetch('https://registry.npmjs.org/@twinsearth%2Fdsh-fang', { signal: AbortSignal.timeout(15000) })
|
|
108
|
+
if (!res.ok) return { ok: false, detail: `registry HTTP ${res.status}` }
|
|
109
|
+
const body = await res.json()
|
|
110
|
+
return { ok: true, latest: String(body?.['dist-tags']?.latest ?? '') }
|
|
111
|
+
} catch (error) {
|
|
112
|
+
return { ok: false, detail: String(error?.message ?? error) }
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function main() {
|
|
117
|
+
let args
|
|
118
|
+
try { args = parseArgs(process.argv.slice(2)) } catch (error) {
|
|
119
|
+
console.error(`[main-city] ${error?.message ?? error}`)
|
|
120
|
+
console.error(USAGE)
|
|
121
|
+
return 2
|
|
122
|
+
}
|
|
123
|
+
if (args.help) { console.log(USAGE); return 0 }
|
|
124
|
+
if (!GATE_TARGETS.includes(args.target)) {
|
|
125
|
+
console.error(`[main-city] unknown target: ${args.target}`)
|
|
126
|
+
console.error(USAGE)
|
|
127
|
+
return 2
|
|
128
|
+
}
|
|
129
|
+
if (args.checkRegistry && args.target === 'publish') {
|
|
130
|
+
const latest = await npmLatest()
|
|
131
|
+
if (latest.ok) args.npmLatest = latest.latest
|
|
132
|
+
else if (!args.json) console.warn(`[main-city] registry check skipped: ${latest.detail}`)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
let report = runMainGate({
|
|
136
|
+
target: args.target,
|
|
137
|
+
root: args.root,
|
|
138
|
+
version: args.version,
|
|
139
|
+
distDir: args.distDir,
|
|
140
|
+
packageDir: args.packageDir,
|
|
141
|
+
tarball: args.tarball,
|
|
142
|
+
tag: args.tag,
|
|
143
|
+
npmLatest: args.npmLatest,
|
|
144
|
+
allowExisting: args.allowExisting,
|
|
145
|
+
homeDir: args.homeDir,
|
|
146
|
+
profile: args.profile,
|
|
147
|
+
profileDir: args.profileDir,
|
|
148
|
+
dataDir: args.dataDir,
|
|
149
|
+
repair: args.repair,
|
|
150
|
+
requireBackup: args.requireBackup,
|
|
151
|
+
supervisorPresent: args.supervisorPresent,
|
|
152
|
+
create: args.create,
|
|
153
|
+
force: args.force,
|
|
154
|
+
minFreeBytes: args.minFreeBytes,
|
|
155
|
+
actor: args.actor,
|
|
156
|
+
})
|
|
157
|
+
|
|
158
|
+
if (args.target === 'profile' && args.create === true && report.ok) {
|
|
159
|
+
const created = createGatedProfile({
|
|
160
|
+
homeDir: args.homeDir,
|
|
161
|
+
profile: args.profile,
|
|
162
|
+
bundles: args.bundles ?? DEFAULT_PROFILE_BUNDLES,
|
|
163
|
+
force: args.force,
|
|
164
|
+
minFreeBytes: args.minFreeBytes,
|
|
165
|
+
})
|
|
166
|
+
report = { ...report, create: created }
|
|
167
|
+
if (!created.ok) {
|
|
168
|
+
report.ok = false
|
|
169
|
+
report.blockers = [...(report.blockers ?? []), { id: 'profile-create: failed', detail: `${created.error}${created.detail ? ': ' + created.detail : ''}` }]
|
|
170
|
+
report.summary = { ...report.summary, blockers: report.summary.blockers + 1 }
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const reportFile = path.join(process.cwd(), 'dist', 'main-city-gate.json')
|
|
175
|
+
try {
|
|
176
|
+
fs.mkdirSync(path.dirname(reportFile), { recursive: true })
|
|
177
|
+
fs.writeFileSync(reportFile, JSON.stringify(report, null, 2) + '\n', 'utf8')
|
|
178
|
+
} catch { /* report is best-effort */ }
|
|
179
|
+
|
|
180
|
+
if (args.json) console.log(JSON.stringify(report, null, 2))
|
|
181
|
+
else {
|
|
182
|
+
for (const item of report.checks ?? []) {
|
|
183
|
+
if (item.ok && item.severity === 'info') continue
|
|
184
|
+
console.log(`${item.ok ? 'PASS' : 'FAIL'} ${item.id.padEnd(48)} ${item.detail}`)
|
|
185
|
+
if (item.repair) console.log(` repair: ${item.repair}`)
|
|
186
|
+
}
|
|
187
|
+
console.log(`\n${report.ok ? 'GREEN' : 'RED'} main-city gate ${report.target} ` +
|
|
188
|
+
`blockers=${report.summary?.blockers ?? 0} warnings=${report.summary?.warnings ?? 0} grade=${report.score?.grade ?? '?'}`)
|
|
189
|
+
if (!report.ok) console.log(formatGateFailure(report))
|
|
190
|
+
console.log(`report: ${reportFile}`)
|
|
191
|
+
}
|
|
192
|
+
return report.ok ? 0 : 1
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const isMain = (() => {
|
|
196
|
+
try { return Boolean(process.argv[1]) && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url)) } catch { return false }
|
|
197
|
+
})()
|
|
198
|
+
|
|
199
|
+
if (isMain) {
|
|
200
|
+
main().then((code) => { process.exitCode = code }).catch((error) => {
|
|
201
|
+
console.error(`[main-city] ${error?.stack ?? error}`)
|
|
202
|
+
process.exitCode = 1
|
|
203
|
+
})
|
|
204
|
+
}
|