@twinsearth/dsh-fang 3.2.2 → 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/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/main-gate.mjs +526 -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
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# DSH 系统架构 × 瓮城安全边界(v3.3.0)
|
|
2
|
+
|
|
3
|
+
> 依据:DeepSeek Harness 0.2.2 架构文档与仓库内实际代码(`dsh --profile <name> --dump-config` 是最终事实)。
|
|
4
|
+
> 本文只记录「哪些层会影响主城安全、瓮城在哪一层设闸」。逐文件行号会随 DSH 版本变化,结论以能力边界为准。
|
|
5
|
+
|
|
6
|
+
## 1. 分层总图
|
|
7
|
+
|
|
8
|
+
```text
|
|
9
|
+
入口:dsh CLI / Web / Electron / SDK / ACP
|
|
10
|
+
└─ Profile($DSH_HOME/profiles/<name>)
|
|
11
|
+
├─ 有序 bundles(dsh-base / dsh-web-app / 树外插件)
|
|
12
|
+
├─ profile cordis.patch.yml
|
|
13
|
+
└─ home 级 cordis.patch.yml + CLI --patch
|
|
14
|
+
└─ Cordis 插件树(一切皆是插件)
|
|
15
|
+
├─ Host Plane:llm / sessions / tools / sandbox / approval / subagents / presets
|
|
16
|
+
├─ Agent Plane:每个 Agent 的 tools / prompt sections / delegation
|
|
17
|
+
└─ Session:append-only SessionEvent 日志(模型可见 ⟺ 已记录)
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## 2. 与主城安全直接相关的十层
|
|
21
|
+
|
|
22
|
+
| 层 | DSH 机制 | 失败后果 | 瓮城闸门 |
|
|
23
|
+
|---|---|---|---|
|
|
24
|
+
| Profile 组合 | bundles 有序 + patch 逐层覆盖 | 缺 bundle/重复/坏 patch → 起不来或半残 | `profile` gate:路径、名称、bundles 去重、patch 解析、磁盘 |
|
|
25
|
+
| 插件生命周期 | Cordis Fiber;PENDING/LOADING/ACTIVE/FAILED;effect 可回收 | 注册泄漏/依赖缺失 → 静默无能力 | boot-guard + 关键防线文件 + 插件冒烟 |
|
|
26
|
+
| Host/Agent 平面 | 注册表与工具作用域隔离 | 把 host 注册表塞进 isolate → 名称解析失败 | 不在门禁里改 profile 层,只做只读校验 |
|
|
27
|
+
| Agent Loop | turn/step/工具批次;错误恢复 append-only | 半途崩溃留下不一致历史 | restart safe-mode + 审计链 |
|
|
28
|
+
| Session 日志 | 追加式、版本化、可重建 | 篡改/删行会让重放失真 | `audit` 链 + Session 版本校验(DSH 自身) |
|
|
29
|
+
| 工具执行 | tools/pre-execute → guard → execute → post-execute | 权限绕过/危险命令 | DSH guard/approval/sandbox 原生;瓮城不削弱默认值 |
|
|
30
|
+
| Guard/Approval/Sandbox | 三层安全,fail-closed | 静默放行不可回滚动作 | restart 默认 observe;自动重启默认 false;崩溃循环直接 disarm |
|
|
31
|
+
| Preset/HMR | 修订保留;活 Agent 组合稳定 | 热替换失败拖垮进程 | 门禁不热改 profile;变更必须 restart 路径 |
|
|
32
|
+
| KV Cache | 前缀稳定是硬约束 | 无关安全,但错误重试造成成本/时序异常 | 门禁报告只读,不改请求前缀 |
|
|
33
|
+
| 打包/发布 | bundle 分发即代码执行 | 坏产物/错标签/重复发布污染 registry | `package` / `publish` gate;sha256/manifest/tag 校验 |
|
|
34
|
+
|
|
35
|
+
## 3. 瓮城 18 个子插件的职责与主城关系
|
|
36
|
+
|
|
37
|
+
| 子插件 | 关键风险 | 现有保护 | v3.3.0 增量 |
|
|
38
|
+
|---|---|---|---|
|
|
39
|
+
| orchestrator | 路由/派生/状态机 | 鉴权、fail-closed、配额 | 新 profile 建前过 gate |
|
|
40
|
+
| forker | 子进程/端口/配置锁 | 端口池、退避、孤儿回收、只读修复 | `provision` 新建 profile 过 gate |
|
|
41
|
+
| restart-guard | 交接执行权 = 进程退出/重启 | 三重门禁 + 审批 + supervisor 契约 | **崩溃循环 15m≥3 → safe-mode,人工清除前永不 handoff** |
|
|
42
|
+
| restart-supervisor/watchdog | 外部拉起 | 授权清单 + 回执 + boot-guard | 增加 deploy gate(含备份/审计链/崩溃循环) |
|
|
43
|
+
| approver | 快照/回滚会覆盖目录 | digest 校验、代际、TTL | 门禁写 profile 前自动 `.gate-backups` |
|
|
44
|
+
| auditor | 审计链是最后证据 | 全链重算 + 篡改检测 | 部署/安装/发布前验链;门禁结论入链 |
|
|
45
|
+
| scorer | 静态评分 | A–E 分档、C3 宽限、veto | **scoreGateFindings:0 warning=A,1–2=B,3+=C,blocker=E** |
|
|
46
|
+
| healer | 修复建议不得放行 | 只读、UNKNOWN fail-closed | **gateRepairPlan:blocker→可执行修复建议** |
|
|
47
|
+
| decision-center | 通知/审批/阻塞 | 红阻塞、黄蓝绿状态机 | 不作为主城放行依据;不绕过 restart/approval |
|
|
48
|
+
| session-* / imports | 会话复制/恢复 | 有界读取、摘要大小限制 | profile gate 校验路径与磁盘 |
|
|
49
|
+
| essence/mirror/compat | 元主/镜像升级 | 指纹、备份、兼容矩阵 | install/deploy gate 校验 profile |
|
|
50
|
+
| hot-reloader | 热替换 | 只做可回收注册 | 主城变更不允许热替换 profile |
|
|
51
|
+
| buffer/queue-journal | 持久化队列 | journal/outbox | 门禁不删除运行数据 |
|
|
52
|
+
| adapter/approver 客户端 | 跨进程通信 | Bearer/HMAC | 门禁不联网 |
|
|
53
|
+
|
|
54
|
+
## 4. 为什么必须 fail-closed
|
|
55
|
+
|
|
56
|
+
1. **Cordis 的注册是副作用**:一个坏插件可以在 ACTIVE 后注册工具/服务,进程看似正常但能力错误。
|
|
57
|
+
2. **Profile 是分层覆盖**:任何时候都可能出现「上一层覆盖导致另一层失效」,只看源码无法证明最终组合。
|
|
58
|
+
3. **Session 是唯一真相源**:日志损坏后,resume/fork/transcript 全部失真,重装后仍可能复现。
|
|
59
|
+
4. **重启是唯一把代码变成新事实的动作**:在崩溃循环/审计链断裂时重启,很可能只是把故障带入下一次启动。
|
|
60
|
+
5. **DSH 明确是 Developer Preview**:沙箱/审批降低风险但不保证隔离;对不可信输入应使用一次性环境。
|
|
61
|
+
|
|
62
|
+
## 5. 门禁的最小信任链
|
|
63
|
+
|
|
64
|
+
```text
|
|
65
|
+
源码(版本/文档/契约/防线)
|
|
66
|
+
→ 产物(sha256/sidecar/manifest/必需文件)
|
|
67
|
+
→ 发布(tag/版本/registry 幂等)
|
|
68
|
+
→ 安装(profile 路径/无活宿主/磁盘)
|
|
69
|
+
→ 部署(备份/审计链/崩溃循环/supervisor)
|
|
70
|
+
→ 运行(restart-guard 三重门禁 + safe-mode)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
任何一环缺少证据 = blocker;不允许「先跑起来再说」。
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# 主城门禁(main-city gate)
|
|
2
|
+
|
|
3
|
+
> 目标:任何会影响 DSH 端安全的动作——打包、发布、安装、部署、新建 profile——都必须先通过同一套可复核检查。门禁拿不到证据时 **fail-closed**,不允许「先上再补」。
|
|
4
|
+
|
|
5
|
+
## 1. 六个入口
|
|
6
|
+
|
|
7
|
+
| target | 何时 | 关键检查 |
|
|
8
|
+
|---|---|---|
|
|
9
|
+
| `source` | 提交/CI/发布前 | 版本、CHANGELOG/AUDIT、vendored contract 逐字节、关键防线文件、restart 默认 observe/不自动重启、build/publish 已接线 |
|
|
10
|
+
| `package` | 打包完成后 | staged package 名称/版本/private/client/bundle;tarball sha256、sidecar、manifest、禁用产物条目、必需文件 |
|
|
11
|
+
| `publish` | npm 发布前 | package 检查 + tag 与版本一致 + registry 同版本重复发布阻断(可显式 `--allow-existing`) |
|
|
12
|
+
| `install` | 干净 profile 安装 | package + profile 路径/捆绑去重/patch 可解析 + 无活跃宿主 + 崩溃循环/safe-mode + 审计链 + 磁盘 |
|
|
13
|
+
| `deploy` | 重启/部署前 | install 检查 + 备份(可 `--repair` 自动建)+ supervisor 证据 |
|
|
14
|
+
| `profile` | 新建/覆盖 profile | 名称白名单、禁止 `desktop`/`plugin`、路径必须在 `$DSH_HOME/profiles`、磁盘、已存在须 `--force` + 自动备份 |
|
|
15
|
+
|
|
16
|
+
## 2. 输出与退出码
|
|
17
|
+
|
|
18
|
+
- JSON 报告写入 `dist/main-city-gate.json`;
|
|
19
|
+
- `ok=false` 当且仅当存在 `blocker`;`warning` 不阻断但会进入评分;
|
|
20
|
+
- 评分由 `scorer.scoreGateFindings` 折算 A–E:0 warning=A,1–2=B,3+=C,任何 blocker=E;
|
|
21
|
+
- 退出码 0=GREEN,1=RED,2=用法错误。
|
|
22
|
+
|
|
23
|
+
## 3. 与五个子插件的关系
|
|
24
|
+
|
|
25
|
+
| 子插件 | 在主城门的职责 |
|
|
26
|
+
|---|---|
|
|
27
|
+
| restart-guard | 崩溃循环(15 分钟内 ≥3 次)自动进入安全模式并**永久放弃交接执行权**,直到人工 `clearSafeMode`;门禁把 safe-mode/崩溃循环当 blocker |
|
|
28
|
+
| scorer | `scoreGateFindings` 把 findings 折成准入分;A/B 才放行 |
|
|
29
|
+
| approver | 需要写 profile 时由门禁生成 `.gate-backups/<stamp>/`(审批式快照,不覆盖) |
|
|
30
|
+
| auditor | 部署/安装/发布时校验 `audit.jsonl` 链;门禁结论写链(`main-city-gate`),链坏拒绝追加 |
|
|
31
|
+
| healer | 输出修复建议;修复不确定时保持 fail-closed(`blockingOnUnknown`) |
|
|
32
|
+
| 门禁/CI | build/publish/install/deploy 全部调用同一 CLI;CI hygiene/release guard 先跑 source gate |
|
|
33
|
+
|
|
34
|
+
## 4. 常用命令
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
node tools/gate/main-city.mjs --target source
|
|
38
|
+
node tools/gate/main-city.mjs --target package --package-dir dist/npm/package --tarball dist/dsh-fang-X.tgz
|
|
39
|
+
node tools/gate/main-city.mjs --target publish --tag vX --check-registry
|
|
40
|
+
node tools/gate/main-city.mjs --target install --home <DSH_HOME> --profile fang-x
|
|
41
|
+
node tools/gate/main-city.mjs --target deploy --home <DSH_HOME> --profile fang-x --repair
|
|
42
|
+
node tools/gate/main-city.mjs --target profile --home <DSH_HOME> --profile demo --create
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## 5. 人工解除崩溃循环安全模式
|
|
46
|
+
|
|
47
|
+
1. 先读 `<dataDir>/restart/safe-mode.json` 与 `runtime-crash.jsonl`,确认崩溃原因;
|
|
48
|
+
2. 在运行中的宿主里调用 `ctx.get('fangRestart').clearSafeMode({ by, note })`(或对应面板);
|
|
49
|
+
3. `clearSafeMode` 会把 crash ledger 改名为 `.cleared-<stamp>`,并写链式审计,下一次启动不会按旧证据重新触发;
|
|
50
|
+
4. 重新跑 deploy gate;`runtime: no active crash loop` 与 `runtime: restart safe-mode clear` 必须为 PASS。
|
|
51
|
+
|
|
52
|
+
## 6. 明确不做
|
|
53
|
+
|
|
54
|
+
- 不自动「修复」产物 hash/sidecar(会掩盖损坏),只报修复建议;
|
|
55
|
+
- 不自动清审计链或崩溃记录;
|
|
56
|
+
- 不在门禁里调用网络(`--check-registry` 例外,且只读 registry 的 latest);
|
|
57
|
+
- 不改 DSH 核心文件;写 profile 仅限 `--repair` 备份和 `profile --create`。
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@twinsearth/dsh-fang",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.3.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "dsh-Fang (瓮城) — mother/fork plugin development environment for DeepSeek Harness: one readonly mother, a disposable child dsh-Web per task.",
|
package/src/kernel/types.mjs
CHANGED
|
@@ -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
|
+
}
|
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
|
+
}
|