@twinsearth/dsh-fang 3.1.0 → 3.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client.js +1511 -1
- package/cordis.patch.yml +9 -0
- package/package.json +6 -2
- package/src/compose.mjs +4 -1
- package/src/kernel/paths.mjs +9 -1
- package/src/kernel/role.mjs +1 -0
- package/src/kernel/types.mjs +5 -1
- package/src/lib/ai-secret-store.mjs +202 -0
- package/src/lib/boot-guard.mjs +182 -0
- package/src/lib/business-producers.mjs +109 -0
- package/src/lib/compat.mjs +1 -1
- package/src/lib/composer-journal.mjs +8 -0
- package/src/lib/decision-events.mjs +129 -0
- package/src/lib/decision-ingest-client.mjs +41 -0
- package/src/lib/decision-outbox.mjs +129 -0
- package/src/lib/desktop-launch.mjs +138 -0
- package/src/lib/fork-supervision-settings.mjs +58 -0
- package/src/lib/mirror-official-source.mjs +93 -0
- package/src/lib/mirror.mjs +10 -3
- package/src/lib/producer-contract.mjs +162 -0
- package/src/lib/restart-contract.mjs +650 -0
- package/src/lib/rule-registry.mjs +69 -0
- package/src/lib/ssrf-guard.mjs +170 -0
- package/src/lib/umbrella.mjs +143 -18
- package/src/plugins/adapter.mjs +31 -2
- package/src/plugins/approver.mjs +423 -40
- package/src/plugins/decision-center.mjs +2255 -0
- package/src/plugins/forker.mjs +20 -1
- package/src/plugins/healer.mjs +53 -20
- package/src/plugins/imports.mjs +48 -0
- package/src/plugins/orchestrator.mjs +814 -42
- package/src/plugins/restart-guard.mjs +645 -52
- package/src/plugins/scorer.mjs +227 -15
- package/src/plugins/umbrella.mjs +18 -14
- package/tools/boot-guard.mjs +95 -0
- package/tools/decision-ingest.mjs +53 -0
- package/tools/desktop-launch.mjs +71 -0
- package/tools/fangctl.mjs +229 -1
|
@@ -4,14 +4,47 @@
|
|
|
4
4
|
//
|
|
5
5
|
// 硬边界(CONTRACTS §1.2 / §1.3):
|
|
6
6
|
// * 只服务母体重启;分身重启 = forker.reap() + 重新 fork(),不经过本插件。
|
|
7
|
-
// *
|
|
8
|
-
//
|
|
7
|
+
// * v3.1.x 默认「决策 + 审计 + 审批 + 授权清单」,**不退出**进程。
|
|
8
|
+
// 只有三重门禁同时满足时才把执行权交出去:mode==='enforce' ∧ allowProcessRestart===true
|
|
9
|
+
// ∧ 外部 supervisor 在位(FANG_RESTART_SUPERVISOR 环境变量,或 watchdog 写的
|
|
10
|
+
// <stateDir>/supervisor.present 且 execute===true、未过期、写入进程存活)。
|
|
11
|
+
// 三者缺一:只写清单、execution.executed 恒 false,进程继续运行。
|
|
12
|
+
// 契约见 src/lib/restart-contract.mjs 与 docs/RESTART-SUPERVISOR-CONTRACT.md。
|
|
9
13
|
// * 单飞状态机 idle → collecting → awaiting → executing → idle;并发请求的第二个直接 busy 拒绝。
|
|
10
14
|
// * 决策矩阵移植自 dsh-hot-update/packages/restart-guard/index.js 的 classifyRisk/findGrant/decide
|
|
11
15
|
// (policy.mode = 授权模式 manual|temp|auto,与 policy() 里的守卫层 mode=observe|enforce 不是同一个字段)。
|
|
12
16
|
// * needs-approval 时通过 ctx.get(SERVICE.approver)?.request(...) 走审批;审批服务缺失或抛错 => fail-closed。
|
|
13
|
-
import
|
|
17
|
+
import path from 'node:path'
|
|
18
|
+
import fs from 'node:fs'
|
|
19
|
+
import { AUDIT, EXIT, GUARD_STATE, RISK, SERVICE, bus, newId, newUuid, riskAtLeast, z } from '../kernel/index.mjs'
|
|
20
|
+
import {
|
|
21
|
+
appendJsonl,
|
|
22
|
+
ensureDir,
|
|
23
|
+
readJson,
|
|
24
|
+
readTextSafe,
|
|
25
|
+
resolveFangLayout,
|
|
26
|
+
writeJsonAtomic,
|
|
27
|
+
} from '../kernel/index.mjs'
|
|
14
28
|
import { roleGate } from '../kernel/index.mjs'
|
|
29
|
+
import {
|
|
30
|
+
APPROVAL_KIND,
|
|
31
|
+
CONTRACT_VERSION,
|
|
32
|
+
EXECUTION_KIND,
|
|
33
|
+
LATEST_KIND,
|
|
34
|
+
approvalDir,
|
|
35
|
+
approvalFile,
|
|
36
|
+
buildApprovalManifest,
|
|
37
|
+
executionDir,
|
|
38
|
+
inspectApproval,
|
|
39
|
+
latestApprovalFile,
|
|
40
|
+
listApprovalIds,
|
|
41
|
+
pruneRestartState,
|
|
42
|
+
receiptFile,
|
|
43
|
+
reconcileRestartState,
|
|
44
|
+
resolveHmacSecret,
|
|
45
|
+
summarizeApproval,
|
|
46
|
+
summarizeApprovalCounts,
|
|
47
|
+
} from '../lib/restart-contract.mjs'
|
|
15
48
|
|
|
16
49
|
export const name = 'fang-restart-guard'
|
|
17
50
|
export const inject = []
|
|
@@ -23,11 +56,13 @@ const DEFAULTS = Object.freeze({
|
|
|
23
56
|
approvalTimeoutMs: 300000,
|
|
24
57
|
allowProcessRestart: false,
|
|
25
58
|
autoPromoteAfterHours: 24,
|
|
59
|
+
dataRoot: '',
|
|
60
|
+
manifestTtlMs: 60000,
|
|
26
61
|
})
|
|
27
62
|
|
|
28
63
|
export const Config = z.object({
|
|
29
64
|
mode: z.union(['observe', 'enforce']).default('observe')
|
|
30
|
-
.description('守卫执行层:observe
|
|
65
|
+
.description('守卫执行层:observe 只决策不退出;enforce 是与 allowProcessRestart + supervisor 在位 共同组成的三重门禁'),
|
|
31
66
|
authMode: z.union(['manual', 'temp', 'auto']).default('manual')
|
|
32
67
|
.description('授权模式:manual 逐次询问 / temp 临时授权 / auto 非红自动放行(决策矩阵的 policy.mode)'),
|
|
33
68
|
strictRedLine: z.boolean().default(true)
|
|
@@ -35,15 +70,20 @@ export const Config = z.object({
|
|
|
35
70
|
approvalTimeoutMs: z.number().min(1000).max(86400000).default(300000)
|
|
36
71
|
.description('审批等待上限(毫秒);审批服务本身也会收到 ttlMs'),
|
|
37
72
|
allowProcessRestart: z.boolean().default(false)
|
|
38
|
-
.description('
|
|
73
|
+
.description('第二把钥匙:默认 false。只有 enforce + true + supervisor 在位时才在批准后 exit(75) 交接执行权'),
|
|
39
74
|
autoPromoteAfterHours: z.union([6, 12, 24]).default(24)
|
|
40
75
|
.description('保留字段(bundle 配置兼容):自动晋升归属编排器/晋升流程,本插件不消费'),
|
|
76
|
+
dataRoot: z.string().default('')
|
|
77
|
+
.description('Fang 数据根目录;留空 = resolveFangLayout() 默认。状态存 <dataDir>/restart/state.json'),
|
|
78
|
+
manifestTtlMs: z.number().min(1000).max(900000).default(60000)
|
|
79
|
+
.description('授权清单(supervisor 契约)的有效期(毫秒);过期清单不能再被执行'),
|
|
41
80
|
})
|
|
42
81
|
|
|
43
82
|
export const RISK_VALUES = [RISK.BLUE, RISK.YELLOW, RISK.RED]
|
|
44
83
|
const RANK = { blue: 1, yellow: 2, red: 3 }
|
|
45
84
|
const REQUESTED_TOPIC = 'fang/restart-requested'
|
|
46
85
|
const RESOLVED_TOPIC = 'fang/restart-resolved'
|
|
86
|
+
const APPROVED_TOPIC = 'fang/restart-approved'
|
|
47
87
|
|
|
48
88
|
const errText = (e) => String(e?.message ?? e)
|
|
49
89
|
const safeGet = (ctx, key) => { try { return ctx.get(key) } catch { return undefined } }
|
|
@@ -98,11 +138,133 @@ export function apply(ctx, config) {
|
|
|
98
138
|
const cfg = { ...DEFAULTS, ...validated }
|
|
99
139
|
/** 决策矩阵用授权策略;注意它的 mode 是 manual|temp|auto(不是守卫层 observe|enforce)。 */
|
|
100
140
|
const authPolicy = { mode: cfg.authMode, grants: [], strictRedLine: cfg.strictRedLine, approvalTimeoutMs: cfg.approvalTimeoutMs }
|
|
141
|
+
const tempEffectiveManual = cfg.authMode === 'temp' && authPolicy.grants.length === 0
|
|
101
142
|
const log = (level, msg) => { try { ctx.logger?.[level]?.(`[fang-restart-guard] ${msg}`) } catch { /* 日志不许破状态机 */ } }
|
|
143
|
+
if (tempEffectiveManual) log('warn', 'authMode=temp has no grants; effective mode is manual (temp-effective-manual)')
|
|
144
|
+
if (cfg.strictRedLine === false) log('warn', 'strictRedLine=false: red requests may be auto-allowed in auto mode')
|
|
102
145
|
|
|
103
146
|
/** 单飞状态机:pending 只描述「正在处理的唯一请求」。 */
|
|
104
147
|
const machine = { state: GUARD_STATE.IDLE, pending: null }
|
|
105
148
|
const timers = new Set()
|
|
149
|
+
/** Set while awaiting an approval; dispose() calls it so the outer request settles. */
|
|
150
|
+
let abortActiveApproval = null
|
|
151
|
+
|
|
152
|
+
const layout = resolveFangLayout({ dataRoot: cfg.dataRoot })
|
|
153
|
+
const stateDir = path.join(layout.dataDir, 'restart')
|
|
154
|
+
const stateFile = path.join(stateDir, 'state.json')
|
|
155
|
+
// supervisor 契约落盘目录(详见 src/lib/restart-contract.mjs 与 docs/RESTART-SUPERVISOR-CONTRACT.md)
|
|
156
|
+
const approvedDir = approvalDir(stateDir)
|
|
157
|
+
const executedDir = executionDir(stateDir)
|
|
158
|
+
const instanceId = newUuid()
|
|
159
|
+
const pidFile = layout.pidFile
|
|
160
|
+
const supervisorMarkerFile = path.join(stateDir, 'supervisor.present')
|
|
161
|
+
const bootStateFile = path.join(stateDir, 'boot-state.json')
|
|
162
|
+
const crashLedgerFile = path.join(stateDir, 'runtime-crash.jsonl')
|
|
163
|
+
const SUPERVISOR_MARKER_TTL_MS = 60000
|
|
164
|
+
const pidAlive = (pid) => {
|
|
165
|
+
if (!Number.isInteger(pid) || pid <= 0) return false
|
|
166
|
+
try { process.kill(pid, 0); return true } catch (error) { return error?.code === 'EPERM' }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// 运行时崩溃账本:只监听 uncaughtExceptionMonitor(不改变宿主退出行为),记录后供下次启动/
|
|
170
|
+
// launcher 判断“上次是不是启动期崩溃”。真正的 apply/import 硬失败仍由宿主决定是否退出。
|
|
171
|
+
const previousBoot = readJson(bootStateFile, null)
|
|
172
|
+
const lastUncleanBoot = previousBoot
|
|
173
|
+
&& (previousBoot.state === 'booting' || previousBoot.state === 'crashed')
|
|
174
|
+
&& Number(previousBoot.pid) !== process.pid
|
|
175
|
+
&& !pidAlive(Number(previousBoot.pid))
|
|
176
|
+
? { state: String(previousBoot.state), pid: Number(previousBoot.pid) || null, at: Number(previousBoot.at) || 0, error: previousBoot.error ?? null }
|
|
177
|
+
: null
|
|
178
|
+
const writeBootState = (state, extra = {}) => {
|
|
179
|
+
try {
|
|
180
|
+
ensureDir(stateDir)
|
|
181
|
+
writeJsonAtomic(bootStateFile, { state, pid: process.pid, at: Date.now(), ...extra })
|
|
182
|
+
} catch { /* boot state must never break boot */ }
|
|
183
|
+
}
|
|
184
|
+
writeBootState('booting', lastUncleanBoot ? { previous: lastUncleanBoot } : {})
|
|
185
|
+
const bootTimer = setTimeout(() => writeBootState('running'), 10000)
|
|
186
|
+
bootTimer.unref?.()
|
|
187
|
+
const onUncaughtException = (error, origin) => {
|
|
188
|
+
try {
|
|
189
|
+
appendJsonl(crashLedgerFile, {
|
|
190
|
+
at: Date.now(), pid: process.pid, origin: String(origin ?? 'uncaughtException'),
|
|
191
|
+
message: String(error?.message ?? error).slice(0, 500),
|
|
192
|
+
stack: String(error?.stack ?? '').slice(0, 4000),
|
|
193
|
+
})
|
|
194
|
+
} catch { /* crash ledger must never throw */ }
|
|
195
|
+
writeBootState('crashed', { error: String(error?.message ?? error).slice(0, 500), origin: String(origin ?? '') })
|
|
196
|
+
}
|
|
197
|
+
process.on('uncaughtExceptionMonitor', onUncaughtException)
|
|
198
|
+
ctx.effect(() => () => {
|
|
199
|
+
try { clearTimeout(bootTimer) } catch { /* ignore */ }
|
|
200
|
+
try { process.off('uncaughtExceptionMonitor', onUncaughtException) } catch { /* ignore */ }
|
|
201
|
+
writeBootState('clean')
|
|
202
|
+
})
|
|
203
|
+
/** 母体 pid 文件:外部看护(watchdog)用它判断「哪个宿主死了」。 */
|
|
204
|
+
const writeHostPid = () => {
|
|
205
|
+
try {
|
|
206
|
+
ensureDir(path.dirname(pidFile))
|
|
207
|
+
writeJsonAtomic(pidFile, { version: 1, pid: process.pid, role: gate.role, at: Date.now() })
|
|
208
|
+
} catch (error) {
|
|
209
|
+
log('warn', `pid file write failed: ${errText(error)}`)
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
const clearHostPid = () => {
|
|
213
|
+
try {
|
|
214
|
+
const raw = readJson(pidFile, null)
|
|
215
|
+
if (raw && Number(raw.pid) === process.pid) fs.unlinkSync(pidFile)
|
|
216
|
+
} catch { /* pid 文件清理失败不影响退出 */ }
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* 外部看护是否在位。只认两种可信来源:
|
|
220
|
+
* 1) 环境变量 FANG_RESTART_SUPERVISOR(由用户/启动脚本显式设置);
|
|
221
|
+
* 2) <stateDir>/supervisor.present,且 execute===true、未过 TTL、写入进程仍存活。
|
|
222
|
+
* 幽灵 marker(watchdog 崩溃)不会被当成 supervisor。
|
|
223
|
+
*/
|
|
224
|
+
const detectSupervisor = () => {
|
|
225
|
+
const envValue = String(process.env.FANG_RESTART_SUPERVISOR ?? '').trim()
|
|
226
|
+
if (envValue) return { present: true, via: 'env', id: envValue }
|
|
227
|
+
const marker = readJson(supervisorMarkerFile, null)
|
|
228
|
+
if (!marker || marker.execute !== true) return { present: false, via: null, id: null }
|
|
229
|
+
const at = Number(marker.at)
|
|
230
|
+
if (!Number.isFinite(at) || Date.now() - at > SUPERVISOR_MARKER_TTL_MS) return { present: false, via: null, id: null }
|
|
231
|
+
if (!pidAlive(Number(marker.pid))) return { present: false, via: null, id: null }
|
|
232
|
+
return { present: true, via: 'file', id: String(marker.supervisor ?? 'watchdog') }
|
|
233
|
+
}
|
|
234
|
+
/** 三重门禁:enforce ∧ allowProcessRestart ∧ supervisor 在位,才允许把执行权交出去。 */
|
|
235
|
+
const executionArmed = () => {
|
|
236
|
+
const supervisor = detectSupervisor()
|
|
237
|
+
return {
|
|
238
|
+
armed: cfg.mode === 'enforce' && cfg.allowProcessRestart === true && supervisor.present === true,
|
|
239
|
+
supervisor,
|
|
240
|
+
mode: cfg.mode,
|
|
241
|
+
allowProcessRestart: cfg.allowProcessRestart === true,
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
writeHostPid()
|
|
245
|
+
/** 本进程最近一次成功写出的授权清单(仅供 state() 展示,不是执行依据)。 */
|
|
246
|
+
let lastManifest = null
|
|
247
|
+
let lastInterrupted = null
|
|
248
|
+
const persistState = (extra = {}) => {
|
|
249
|
+
try {
|
|
250
|
+
ensureDir(stateDir)
|
|
251
|
+
writeJsonAtomic(stateFile, {
|
|
252
|
+
version: 1,
|
|
253
|
+
state: machine.state,
|
|
254
|
+
pending: machine.pending ? { ...machine.pending } : null,
|
|
255
|
+
at: Date.now(),
|
|
256
|
+
...(lastInterrupted ? { lastInterrupted } : {}),
|
|
257
|
+
...extra,
|
|
258
|
+
})
|
|
259
|
+
} catch (error) {
|
|
260
|
+
log('warn', `state persist failed: ${errText(error)}`)
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
const readState = () => {
|
|
264
|
+
const raw = readTextSafe(stateFile, '')
|
|
265
|
+
if (!raw) return null
|
|
266
|
+
try { return JSON.parse(raw) } catch { return null }
|
|
267
|
+
}
|
|
106
268
|
|
|
107
269
|
const audit = (kind, data) => {
|
|
108
270
|
try {
|
|
@@ -117,6 +279,66 @@ export function apply(ctx, config) {
|
|
|
117
279
|
try { return bus.emit(topic, payload) } catch (e) { log('warn', `emit ${topic} failed: ${errText(e)}`); return 0 }
|
|
118
280
|
}
|
|
119
281
|
|
|
282
|
+
// 清单签名 key(env 优先;否则 stateDir/restart-hmac.key,0600,首次生成)。
|
|
283
|
+
const hmac = resolveHmacSecret(stateDir)
|
|
284
|
+
if (!hmac.ok) log('warn', `manifest HMAC unavailable (${hmac.reason}); manifests remain digest-only`)
|
|
285
|
+
const hmacSecret = hmac.ok ? hmac.secret : null
|
|
286
|
+
const inspectOptions = (now = Date.now()) => ({ now, hmacSecret, requireSignature: hmacSecret !== null })
|
|
287
|
+
|
|
288
|
+
// 启动对账 + 旧清单 prune:不信任「上次进程还活着」的残留状态。
|
|
289
|
+
try {
|
|
290
|
+
const reconciled = reconcileRestartState(stateDir, { hmacSecret })
|
|
291
|
+
if (reconciled.checked > 0) {
|
|
292
|
+
log('info', `startup reconcile: checked=${reconciled.checked} armed=${reconciled.counts.armed} executed=${reconciled.counts.executed} stale=${reconciled.counts.stale} invalid=${reconciled.counts.invalid}`)
|
|
293
|
+
audit('restart-reconcile', { checked: reconciled.checked, counts: reconciled.counts, hmac: hmac.ok ? hmac.source : 'unavailable' })
|
|
294
|
+
}
|
|
295
|
+
const pruned = pruneRestartState(stateDir, { hmacSecret })
|
|
296
|
+
if (pruned.removed.length > 0) {
|
|
297
|
+
log('info', `startup prune: removed ${pruned.removed.length} old manifest(s)`)
|
|
298
|
+
audit('restart-manifest-pruned', { removed: pruned.removed, kept: pruned.kept })
|
|
299
|
+
}
|
|
300
|
+
} catch (error) {
|
|
301
|
+
log('warn', `startup reconcile/prune failed: ${errText(error)}`)
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// Crash/interrupted recovery: the old Promise no longer exists. Mark it interrupted,
|
|
305
|
+
// pair the audit trail, and never pretend the request is still pending.
|
|
306
|
+
const previousState = readState()
|
|
307
|
+
if (previousState && previousState.state && previousState.state !== GUARD_STATE.IDLE) {
|
|
308
|
+
const old = previousState.pending ?? {}
|
|
309
|
+
const interruptedId = String(old.id ?? newId('rst'))
|
|
310
|
+
const interruptedRisk = isRisk(old.risk) ? old.risk : RISK.RED
|
|
311
|
+
lastInterrupted = {
|
|
312
|
+
id: interruptedId,
|
|
313
|
+
risk: interruptedRisk,
|
|
314
|
+
previousState: previousState.state,
|
|
315
|
+
previousPhase: old.phase ?? null,
|
|
316
|
+
approvalId: old.approvalId ?? null,
|
|
317
|
+
at: Date.now(),
|
|
318
|
+
}
|
|
319
|
+
audit(AUDIT.RESTART_RESOLVED, {
|
|
320
|
+
id: interruptedId,
|
|
321
|
+
outcome: 'interrupted',
|
|
322
|
+
decision: 'needs-approval',
|
|
323
|
+
risk: interruptedRisk,
|
|
324
|
+
reason: String(old.reason ?? 'process-restarted'),
|
|
325
|
+
deniedReason: 'process-restarted',
|
|
326
|
+
by: 'restart',
|
|
327
|
+
approvalId: old.approvalId ?? null,
|
|
328
|
+
previousState: previousState.state,
|
|
329
|
+
previousPhase: old.phase ?? null,
|
|
330
|
+
})
|
|
331
|
+
emit(RESOLVED_TOPIC, {
|
|
332
|
+
id: interruptedId,
|
|
333
|
+
outcome: 'interrupted',
|
|
334
|
+
reason: String(old.reason ?? 'process-restarted'),
|
|
335
|
+
risk: interruptedRisk,
|
|
336
|
+
deniedReason: 'process-restarted',
|
|
337
|
+
approvalId: old.approvalId ?? null,
|
|
338
|
+
})
|
|
339
|
+
persistState()
|
|
340
|
+
}
|
|
341
|
+
|
|
120
342
|
/**
|
|
121
343
|
* 影响面:从 forker.list() 与 buffer.state() 收集;服务缺失/抛错一律降级为空(绝不因收集失败拒绝请求)。
|
|
122
344
|
* pendingPromotes 来自 approver.pending() 里的 promote 工单;activeSessions 在 v1.0.0 没有可读会话服务 → 0。
|
|
@@ -155,8 +377,12 @@ export function apply(ctx, config) {
|
|
|
155
377
|
return report
|
|
156
378
|
}
|
|
157
379
|
|
|
158
|
-
/** 显式 risk
|
|
159
|
-
const normalizeRisk = (input = {}) =>
|
|
380
|
+
/** 显式 risk 只能提高风险,不能压过 classifyRisk;低报不再能绕过升级。 */
|
|
381
|
+
const normalizeRisk = (input = {}) => {
|
|
382
|
+
const classified = classifyRisk(input)
|
|
383
|
+
if (!isRisk(input.risk)) return classified
|
|
384
|
+
return RANK[input.risk] > RANK[classified] ? input.risk : classified
|
|
385
|
+
}
|
|
160
386
|
|
|
161
387
|
/** 审批等待的兜底计时器:审批服务永不 resolve 时也要回到 idle,不许把状态机卡死。 */
|
|
162
388
|
const withDeadline = (promise, ms) => new Promise((resolve, reject) => {
|
|
@@ -177,30 +403,145 @@ export function apply(ctx, config) {
|
|
|
177
403
|
machine.state = GUARD_STATE.IDLE
|
|
178
404
|
const wasPending = machine.pending
|
|
179
405
|
machine.pending = null
|
|
406
|
+
persistState()
|
|
180
407
|
return wasPending
|
|
181
408
|
}
|
|
182
409
|
|
|
183
|
-
/**
|
|
410
|
+
/**
|
|
411
|
+
* 组装并原子落盘授权清单(supervisor 契约的阶段 1)。
|
|
412
|
+
* 这是「批准」唯一的外化凭据:没有清单 = supervisor 不得执行。
|
|
413
|
+
*/
|
|
414
|
+
const writeApprovalManifest = (req, { by, outcome, approvalId, approvedAt }) => {
|
|
415
|
+
const manifest = buildApprovalManifest({
|
|
416
|
+
id: req.id,
|
|
417
|
+
risk: req.risk,
|
|
418
|
+
outcome,
|
|
419
|
+
approvalId,
|
|
420
|
+
approvedBy: by,
|
|
421
|
+
reason: req.reason,
|
|
422
|
+
scope: req.scope,
|
|
423
|
+
origin: req.origin,
|
|
424
|
+
digests: req.digests,
|
|
425
|
+
impactSource: req.impactSource ?? null,
|
|
426
|
+
requestedAt: req.requestedAt,
|
|
427
|
+
approvedAt,
|
|
428
|
+
ttlMs: cfg.manifestTtlMs,
|
|
429
|
+
hmacSecret,
|
|
430
|
+
guard: {
|
|
431
|
+
mode: cfg.mode,
|
|
432
|
+
authMode: cfg.authMode,
|
|
433
|
+
strictRedLine: cfg.strictRedLine,
|
|
434
|
+
allowProcessRestart: cfg.allowProcessRestart,
|
|
435
|
+
pid: process.pid,
|
|
436
|
+
instanceId,
|
|
437
|
+
},
|
|
438
|
+
})
|
|
439
|
+
const file = approvalFile(stateDir, manifest.id)
|
|
440
|
+
writeJsonAtomic(file, manifest)
|
|
441
|
+
// latest.json 只是给外部入口的便利指针,不是执行依据;清单本身才是。
|
|
442
|
+
try {
|
|
443
|
+
writeJsonAtomic(latestApprovalFile(stateDir), {
|
|
444
|
+
version: CONTRACT_VERSION,
|
|
445
|
+
kind: LATEST_KIND,
|
|
446
|
+
id: manifest.id,
|
|
447
|
+
file: path.basename(file),
|
|
448
|
+
digest: manifest.digest,
|
|
449
|
+
approvedAt: manifest.approvedAt,
|
|
450
|
+
expiresAt: manifest.expiresAt,
|
|
451
|
+
at: Date.now(),
|
|
452
|
+
})
|
|
453
|
+
} catch (error) {
|
|
454
|
+
log('warn', `latest approval pointer write failed: ${errText(error)}`)
|
|
455
|
+
}
|
|
456
|
+
return manifest
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* executing 阶段:默认只记录状态(不退出/不重启)。
|
|
461
|
+
* 批准必须落盘授权清单;写不进去 => fail-closed,按拒绝处理。
|
|
462
|
+
* 三重门禁(enforce + allowProcessRestart + supervisor 在位)齐了才把执行权交出去:
|
|
463
|
+
* 清单/审计/事件落盘后 exit(75),由 watchdog 拉起新宿主并写回执。
|
|
464
|
+
*/
|
|
184
465
|
const finishApproved = (req, { decision, by = null, outcome, approvalId = null, t0 }) => {
|
|
466
|
+
const approvedAt = Date.now()
|
|
467
|
+
let manifest
|
|
468
|
+
try {
|
|
469
|
+
manifest = writeApprovalManifest(req, { by, outcome, approvalId, approvedAt })
|
|
470
|
+
} catch (error) {
|
|
471
|
+
// 契约层失败:不能对外声称存在一份可执行的批准。
|
|
472
|
+
return finishDenied(req, 'manifest-write-failed', 'denied', {
|
|
473
|
+
by, approvalId, error: errText(error), ms: Date.now() - t0,
|
|
474
|
+
})
|
|
475
|
+
}
|
|
185
476
|
machine.state = GUARD_STATE.EXECUTING
|
|
186
477
|
if (machine.pending) machine.pending.phase = GUARD_STATE.EXECUTING
|
|
478
|
+
const gateState = executionArmed()
|
|
479
|
+
const handoff = gateState.armed === true
|
|
480
|
+
persistState(handoff ? {
|
|
481
|
+
handoff: { to: 'supervisor', via: gateState.supervisor.via, at: Date.now(), exitCode: EXIT.RESTART },
|
|
482
|
+
} : {})
|
|
187
483
|
const execution = {
|
|
188
484
|
executed: false,
|
|
189
|
-
reason: '
|
|
485
|
+
reason: handoff ? 'supervisor-handoff' : 'v3.1.x-decision-only',
|
|
190
486
|
guardMode: cfg.mode,
|
|
191
487
|
allowProcessRestart: cfg.allowProcessRestart === true,
|
|
192
|
-
plannedExitCode: EXIT.RESTART, // 与 forker.classifyExit 的 restart-request
|
|
488
|
+
plannedExitCode: EXIT.RESTART, // 与 forker.classifyExit 的 restart-request 契约对齐
|
|
489
|
+
manifestDigest: manifest.digest,
|
|
490
|
+
manifestExpiresAt: manifest.expiresAt,
|
|
491
|
+
handoff: handoff ? {
|
|
492
|
+
requested: true, to: 'supervisor', via: gateState.supervisor.via,
|
|
493
|
+
id: gateState.supervisor.id, exitCode: EXIT.RESTART,
|
|
494
|
+
} : null,
|
|
495
|
+
}
|
|
496
|
+
const authorization = {
|
|
497
|
+
contractVersion: CONTRACT_VERSION,
|
|
498
|
+
manifestId: manifest.id,
|
|
499
|
+
nonce: manifest.nonce,
|
|
500
|
+
digest: manifest.digest,
|
|
501
|
+
expiresAt: manifest.expiresAt,
|
|
502
|
+
manifestPath: approvalFile(stateDir, manifest.id),
|
|
503
|
+
receiptPath: receiptFile(stateDir, manifest.id),
|
|
504
|
+
}
|
|
505
|
+
lastManifest = {
|
|
506
|
+
id: manifest.id, digest: manifest.digest, expiresAt: manifest.expiresAt, path: authorization.manifestPath,
|
|
193
507
|
}
|
|
194
508
|
const result = {
|
|
195
509
|
id: req.id, outcome, decision, risk: req.risk, by, approvalId,
|
|
196
|
-
|
|
510
|
+
impactSource: req.impactSource ?? null,
|
|
511
|
+
requestedAt: req.requestedAt, execution, authorization, ms: Date.now() - t0,
|
|
197
512
|
}
|
|
198
513
|
audit(AUDIT.RESTART_RESOLVED, {
|
|
199
514
|
id: req.id, outcome, decision, risk: req.risk, reason: req.reason, scope: req.scope,
|
|
200
|
-
origin: req.origin, by, approvalId, execution, guardMode: cfg.mode,
|
|
515
|
+
origin: req.origin, by, approvalId, execution, guardMode: cfg.mode,
|
|
516
|
+
impactSource: req.impactSource ?? null, ms: result.ms,
|
|
517
|
+
manifestDigest: manifest.digest, manifestExpiresAt: manifest.expiresAt,
|
|
518
|
+
manifestPath: authorization.manifestPath,
|
|
519
|
+
handoff: handoff ? { to: 'supervisor', via: gateState.supervisor.via, exitCode: EXIT.RESTART } : null,
|
|
201
520
|
})
|
|
202
|
-
emit(RESOLVED_TOPIC, { id: req.id, outcome })
|
|
203
|
-
|
|
521
|
+
emit(RESOLVED_TOPIC, { id: req.id, outcome, reason: req.reason, risk: req.risk, approvalId })
|
|
522
|
+
// Supervisor contract: this event is advisory only. Durability lives in the manifest;
|
|
523
|
+
// a supervisor must verify the manifest and write an execution receipt with
|
|
524
|
+
// execution.executed === true before a restart counts as executed.
|
|
525
|
+
if (outcome === 'approved' || outcome === 'auto-allow') {
|
|
526
|
+
emit(APPROVED_TOPIC, {
|
|
527
|
+
id: req.id, outcome, decision, risk: req.risk, reason: req.reason,
|
|
528
|
+
scope: req.scope, origin: req.origin, approvalId,
|
|
529
|
+
impactSource: req.impactSource ?? null, execution, authorization,
|
|
530
|
+
handoff: execution.handoff,
|
|
531
|
+
})
|
|
532
|
+
}
|
|
533
|
+
if (handoff) {
|
|
534
|
+
// 三重门禁齐了才走到这里:清单/审计/事件已经落盘,交执行权给外部 supervisor。
|
|
535
|
+
// 25ms 让调用方 Promise 结算、审计行 flush;之后宿主退出码 75,由 watchdog 拉起。
|
|
536
|
+
log('warn', `restart ${req.id} approved and armed; handing off to supervisor (${gateState.supervisor.via}); exit(${EXIT.RESTART})`)
|
|
537
|
+
const exitTimer = setTimeout(() => {
|
|
538
|
+
process.exitCode = EXIT.RESTART
|
|
539
|
+
process.exit(EXIT.RESTART)
|
|
540
|
+
}, 25)
|
|
541
|
+
timers.add(exitTimer)
|
|
542
|
+
} else {
|
|
543
|
+
release()
|
|
544
|
+
}
|
|
204
545
|
return result
|
|
205
546
|
}
|
|
206
547
|
|
|
@@ -208,15 +549,20 @@ export function apply(ctx, config) {
|
|
|
208
549
|
const result = {
|
|
209
550
|
id: req.id, outcome, decision: 'needs-approval', risk: req.risk,
|
|
210
551
|
reason, by: extra.by ?? null, approvalId: extra.approvalId ?? null, ms: extra.ms ?? 0,
|
|
552
|
+
impactSource: req.impactSource ?? null,
|
|
211
553
|
...(extra.error ? { error: extra.error } : {}),
|
|
212
554
|
}
|
|
213
555
|
audit(AUDIT.RESTART_RESOLVED, {
|
|
214
556
|
id: req.id, outcome, decision: 'needs-approval', risk: req.risk, reason: req.reason,
|
|
215
557
|
scope: req.scope, origin: req.origin, deniedReason: reason,
|
|
216
558
|
by: result.by, approvalId: result.approvalId, guardMode: cfg.mode,
|
|
559
|
+
impactSource: req.impactSource ?? null,
|
|
217
560
|
...(extra.error ? { error: extra.error } : {}),
|
|
218
561
|
})
|
|
219
|
-
emit(RESOLVED_TOPIC, {
|
|
562
|
+
emit(RESOLVED_TOPIC, {
|
|
563
|
+
id: req.id, outcome, reason: req.reason, risk: req.risk,
|
|
564
|
+
deniedReason: reason, approvalId: extra.approvalId ?? null,
|
|
565
|
+
})
|
|
220
566
|
release()
|
|
221
567
|
return result
|
|
222
568
|
}
|
|
@@ -226,41 +572,68 @@ export function apply(ctx, config) {
|
|
|
226
572
|
* -> Promise<{id, outcome:'approved'|'denied'|'timeout'|'auto-allow', decision, risk, ...}>
|
|
227
573
|
* 单飞:非 idle 时第二个请求直接 {outcome:'denied', reason:'busy'}(不排队)。
|
|
228
574
|
*/
|
|
229
|
-
const request = async (
|
|
575
|
+
const request = async (rawInput = {}) => {
|
|
576
|
+
const input = rawInput && typeof rawInput === 'object' ? rawInput : {}
|
|
230
577
|
const t0 = Date.now()
|
|
231
578
|
const risk = normalizeRisk(input)
|
|
232
579
|
const reason = String(input.reason ?? 'unspecified')
|
|
233
580
|
const scope = String(input.scope ?? 'mother')
|
|
234
581
|
const origin = String(input.origin ?? 'unknown')
|
|
235
|
-
|
|
236
582
|
if (machine.state !== GUARD_STATE.IDLE) {
|
|
237
|
-
// 准入层拒绝:不占用状态机,但仍留一对审计以证明发生过竞争。
|
|
238
583
|
const busyId = newId('rst')
|
|
584
|
+
const activeId = machine.pending?.id ?? null
|
|
585
|
+
const activeSince = machine.pending?.since ?? null
|
|
586
|
+
const retryAfterMs = Number.isFinite(machine.pending?.deadlineAt)
|
|
587
|
+
? Math.max(0, machine.pending.deadlineAt - Date.now())
|
|
588
|
+
: null
|
|
239
589
|
audit(AUDIT.RESTART_REQUESTED, {
|
|
240
590
|
id: busyId, risk, reason, scope, origin, phase: 'rejected-busy',
|
|
241
|
-
activeState: machine.state, activeId
|
|
591
|
+
activeState: machine.state, activeId, activeSince, retryAfterMs,
|
|
592
|
+
})
|
|
593
|
+
audit(AUDIT.RESTART_RESOLVED, {
|
|
594
|
+
id: busyId, outcome: 'denied', deniedReason: 'busy', risk,
|
|
595
|
+
activeId, activeState: machine.state, retryAfterMs,
|
|
242
596
|
})
|
|
243
|
-
|
|
244
|
-
|
|
597
|
+
return {
|
|
598
|
+
id: busyId, outcome: 'denied', reason: 'busy', decision: 'needs-approval', risk,
|
|
599
|
+
activeId, activeState: machine.state, retryAfterMs, retryable: true,
|
|
600
|
+
}
|
|
245
601
|
}
|
|
246
|
-
|
|
247
602
|
// 单飞认领:在这行之后任何并发 request 都会看到非 idle(async 体在首个 await 前同步执行)。
|
|
248
603
|
machine.state = GUARD_STATE.COLLECTING
|
|
604
|
+
let impactFromCaller = false
|
|
605
|
+
let impactSource = 'service'
|
|
249
606
|
const req = {
|
|
250
607
|
id: newId('rst'),
|
|
251
608
|
risk, reason, scope, origin,
|
|
252
609
|
digests: Array.isArray(input.digests) ? input.digests.map(String) : [],
|
|
253
610
|
forcedApproval: input.forcedApproval === true,
|
|
611
|
+
impactSource,
|
|
254
612
|
requestedAt: t0,
|
|
255
613
|
deadlineAt: t0 + cfg.approvalTimeoutMs,
|
|
256
614
|
}
|
|
257
|
-
|
|
258
|
-
|
|
615
|
+
let impactReport
|
|
616
|
+
try {
|
|
617
|
+
impactFromCaller = input.impact !== undefined && input.impact !== null
|
|
618
|
+
impactSource = impactFromCaller ? 'caller' : 'service'
|
|
619
|
+
req.impactSource = impactSource
|
|
620
|
+
impactReport = impactFromCaller ? input.impact : impact()
|
|
621
|
+
} catch (e) {
|
|
622
|
+
// A throwing caller-supplied impact getter must not leave the guard stuck in COLLECTING.
|
|
623
|
+
return finishDenied(req, 'impact-failed', 'denied', { error: errText(e), ms: Date.now() - t0 })
|
|
624
|
+
}
|
|
625
|
+
machine.pending = {
|
|
626
|
+
id: req.id, risk: req.risk, reason, scope, origin,
|
|
627
|
+
phase: GUARD_STATE.COLLECTING, since: t0,
|
|
628
|
+
deadlineAt: req.deadlineAt, approvalId: null,
|
|
629
|
+
}
|
|
630
|
+
persistState()
|
|
259
631
|
|
|
260
632
|
audit(AUDIT.RESTART_REQUESTED, {
|
|
261
633
|
id: req.id, risk: req.risk, reason, scope, origin, digests: req.digests,
|
|
262
634
|
forcedApproval: req.forcedApproval, guardMode: cfg.mode, authMode: cfg.authMode,
|
|
263
|
-
strictRedLine: cfg.strictRedLine,
|
|
635
|
+
strictRedLine: cfg.strictRedLine, tempEffectiveManual,
|
|
636
|
+
impactSource, impact: impactReport,
|
|
264
637
|
})
|
|
265
638
|
emit(REQUESTED_TOPIC, { id: req.id, risk: req.risk })
|
|
266
639
|
|
|
@@ -278,23 +651,37 @@ export function apply(ctx, config) {
|
|
|
278
651
|
// needs-approval:进入 awaiting,走审批服务;服务缺失/抛错 => fail-closed。
|
|
279
652
|
machine.state = GUARD_STATE.AWAITING
|
|
280
653
|
if (machine.pending) machine.pending.phase = GUARD_STATE.AWAITING
|
|
654
|
+
persistState()
|
|
281
655
|
const approver = safeGet(ctx, SERVICE.approver)
|
|
282
656
|
if (!approver || typeof approver.request !== 'function') {
|
|
283
657
|
return finishDenied(req, 'approver-unavailable', 'denied', { ms: Date.now() - t0 })
|
|
284
658
|
}
|
|
285
659
|
|
|
286
660
|
let answer
|
|
661
|
+
let aborted = false
|
|
662
|
+
const abortPromise = new Promise((resolve) => {
|
|
663
|
+
abortActiveApproval = () => { aborted = true; resolve({ outcome: 'guard-disposed' }) }
|
|
664
|
+
})
|
|
287
665
|
try {
|
|
288
|
-
answer = await
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
666
|
+
answer = await Promise.race([
|
|
667
|
+
withDeadline(approver.request({
|
|
668
|
+
kind: 'restart',
|
|
669
|
+
risk: req.risk,
|
|
670
|
+
title: `母体重启:${reason}`,
|
|
671
|
+
detail: `origin=${origin} scope=${scope} risk=${req.risk} guardMode=${cfg.mode}`,
|
|
672
|
+
impact: impactReport,
|
|
673
|
+
impactSource,
|
|
674
|
+
ttlMs: cfg.approvalTimeoutMs,
|
|
675
|
+
}), cfg.approvalTimeoutMs),
|
|
676
|
+
abortPromise,
|
|
677
|
+
])
|
|
296
678
|
} catch (e) {
|
|
297
679
|
return finishDenied(req, 'approver-error', 'denied', { error: errText(e), ms: Date.now() - t0 })
|
|
680
|
+
} finally {
|
|
681
|
+
abortActiveApproval = null
|
|
682
|
+
}
|
|
683
|
+
if (aborted) {
|
|
684
|
+
return finishDenied(req, 'guard-disposed', 'denied', { ms: Date.now() - t0 })
|
|
298
685
|
}
|
|
299
686
|
|
|
300
687
|
const outcome = answer?.outcome ?? 'timeout'
|
|
@@ -321,34 +708,240 @@ export function apply(ctx, config) {
|
|
|
321
708
|
return { decision: decide(req, authPolicy, Date.now()), risk }
|
|
322
709
|
}
|
|
323
710
|
|
|
324
|
-
const state = () =>
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
711
|
+
const state = () => {
|
|
712
|
+
const supervisor = detectSupervisor()
|
|
713
|
+
const gateState = executionArmed()
|
|
714
|
+
return {
|
|
715
|
+
state: machine.state,
|
|
716
|
+
pending: machine.pending ? { ...machine.pending } : null,
|
|
717
|
+
mode: cfg.mode, // 守卫执行层 observe|enforce
|
|
718
|
+
authMode: cfg.authMode, // 决策矩阵授权模式 manual|temp|auto
|
|
719
|
+
strictRedLine: cfg.strictRedLine,
|
|
720
|
+
redLineAutoAllowed: cfg.strictRedLine === false,
|
|
721
|
+
tempEffectiveManual,
|
|
722
|
+
grants: authPolicy.grants.length,
|
|
723
|
+
allowProcessRestart: cfg.allowProcessRestart === true,
|
|
724
|
+
restartExitCode: EXIT.RESTART,
|
|
725
|
+
stateFile,
|
|
726
|
+
pidFile,
|
|
727
|
+
lastInterrupted,
|
|
728
|
+
// supervisor 契约(只读展示):清单目录、回执目录、最近一次授权
|
|
729
|
+
contractVersion: CONTRACT_VERSION,
|
|
730
|
+
manifestTtlMs: cfg.manifestTtlMs,
|
|
731
|
+
approvalDir: approvedDir,
|
|
732
|
+
executionDir: executedDir,
|
|
733
|
+
lastManifest,
|
|
734
|
+
supervisorPresent: supervisor.present === true,
|
|
735
|
+
supervisor,
|
|
736
|
+
executionArmed: gateState.armed === true,
|
|
737
|
+
execution: { executed: false, decisionOnly: true },
|
|
738
|
+
}
|
|
739
|
+
}
|
|
333
740
|
|
|
334
|
-
const policy = () =>
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
741
|
+
const policy = () => {
|
|
742
|
+
const supervisor = detectSupervisor()
|
|
743
|
+
const gateState = executionArmed()
|
|
744
|
+
return {
|
|
745
|
+
mode: cfg.mode, // observe|enforce(守卫执行层,不是决策矩阵的授权模式)
|
|
746
|
+
authMode: cfg.authMode, // manual|temp|auto
|
|
747
|
+
strictRedLine: cfg.strictRedLine,
|
|
748
|
+
redLineAutoAllowed: cfg.strictRedLine === false,
|
|
749
|
+
tempEffectiveManual,
|
|
750
|
+
grants: authPolicy.grants.length,
|
|
751
|
+
approvalTimeoutMs: cfg.approvalTimeoutMs,
|
|
752
|
+
allowProcessRestart: cfg.allowProcessRestart === true,
|
|
753
|
+
restartExitCode: EXIT.RESTART,
|
|
754
|
+
decisionOnly: true,
|
|
755
|
+
manifestTtlMs: cfg.manifestTtlMs,
|
|
756
|
+
supervisorPresent: supervisor.present === true,
|
|
757
|
+
supervisor,
|
|
758
|
+
executionArmed: gateState.armed === true,
|
|
759
|
+
}
|
|
760
|
+
}
|
|
342
761
|
|
|
343
|
-
|
|
762
|
+
/**
|
|
763
|
+
* supervisor 契约(阶段 1 授权清单 / 阶段 2 执行回执)。
|
|
764
|
+
* 默认决策层不退出;三重门禁齐了才 exit(75) 交接给外部 watchdog。
|
|
765
|
+
* 任何「已执行」结论只认回执 execution.executed === true。
|
|
766
|
+
*/
|
|
767
|
+
const executionContract = () => {
|
|
768
|
+
const gateState = executionArmed()
|
|
769
|
+
return {
|
|
770
|
+
version: CONTRACT_VERSION,
|
|
771
|
+
decisionOnly: true,
|
|
772
|
+
guardExecuted: false,
|
|
773
|
+
plannedExitCode: EXIT.RESTART,
|
|
774
|
+
manifestTtlMs: cfg.manifestTtlMs,
|
|
775
|
+
supervisorPresent: gateState.supervisor.present === true,
|
|
776
|
+
executionArmed: gateState.armed === true,
|
|
777
|
+
approval: {
|
|
778
|
+
kind: APPROVAL_KIND,
|
|
779
|
+
dir: approvedDir,
|
|
780
|
+
pattern: '<requestId>.json',
|
|
781
|
+
latest: latestApprovalFile(stateDir),
|
|
782
|
+
},
|
|
783
|
+
receipt: {
|
|
784
|
+
kind: EXECUTION_KIND,
|
|
785
|
+
dir: executedDir,
|
|
786
|
+
pattern: '<requestId>.json',
|
|
787
|
+
},
|
|
788
|
+
supervisor: {
|
|
789
|
+
armedWhen: [
|
|
790
|
+
'manifest.guard.mode === "enforce"',
|
|
791
|
+
'manifest.guard.allowProcessRestart === true',
|
|
792
|
+
],
|
|
793
|
+
handoffWhen: [
|
|
794
|
+
'config.mode === "enforce"',
|
|
795
|
+
'config.allowProcessRestart === true',
|
|
796
|
+
'supervisor present (FANG_RESTART_SUPERVISOR env or live <stateDir>/supervisor.present with execute === true)',
|
|
797
|
+
],
|
|
798
|
+
handoff: 'guard writes the manifest + audit, then exits 75; watchdog relaunches and writes the receipt',
|
|
799
|
+
mayExecuteWhen: [
|
|
800
|
+
'manifest digest valid (sha256 over canonical body)',
|
|
801
|
+
'manifest not expired (expiresAt > now)',
|
|
802
|
+
'manifest.execution.executed === false (the guard never restarts by itself)',
|
|
803
|
+
'manifest.execution.decisionOnly === true',
|
|
804
|
+
'manifest is armed (guard.mode=enforce and allowProcessRestart=true)',
|
|
805
|
+
'no execution receipt exists for this request id',
|
|
806
|
+
],
|
|
807
|
+
mustWriteReceipt: true,
|
|
808
|
+
receiptRequirements: [
|
|
809
|
+
'receipt.execution.executed === true',
|
|
810
|
+
'receipt.nonce equals manifest.nonce',
|
|
811
|
+
'receipt.manifestDigest equals manifest.digest',
|
|
812
|
+
],
|
|
813
|
+
},
|
|
814
|
+
rule: '「已执行」只认回执里的 execution.executed === true;授权清单里恒为 false。',
|
|
815
|
+
note: gateState.armed
|
|
816
|
+
? 'armed: the next approved restart writes the manifest and exits 75 for the supervisor to relaunch.'
|
|
817
|
+
: 'disarmed: decision-only. No supervisor handoff happens until enforce + allowProcessRestart + supervisorPresent are all true.',
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/** 只读:列出最近的授权清单摘要(含状态:authorized/executed/stale/invalid)。 */
|
|
822
|
+
const approvals = ({ limit = 50, now = Date.now() } = {}) => {
|
|
823
|
+
const max = Math.min(200, Math.max(1, Number.isFinite(limit) ? Math.floor(limit) : 50))
|
|
824
|
+
const rows = listApprovalIds(stateDir)
|
|
825
|
+
.map(id => summarizeApproval(inspectApproval(stateDir, id, inspectOptions(now))))
|
|
826
|
+
.sort((a, b) => (b.approvedAt ?? 0) - (a.approvedAt ?? 0))
|
|
827
|
+
return {
|
|
828
|
+
contractVersion: CONTRACT_VERSION,
|
|
829
|
+
items: rows.slice(0, max),
|
|
830
|
+
counts: summarizeApprovalCounts(rows),
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/** 只读:单份授权的完整检查(清单 + 回执 + 校验结果),不写盘、不审计。 */
|
|
835
|
+
const executionStatus = (id, { now = Date.now() } = {}) => inspectApproval(stateDir, id, inspectOptions(now))
|
|
836
|
+
|
|
837
|
+
/** 只读:当前这份授权是否可以交给 supervisor 执行(唯一放行语义)。 */
|
|
838
|
+
const verifyApproval = (id, { now = Date.now() } = {}) => {
|
|
839
|
+
const inspected = inspectApproval(stateDir, id, inspectOptions(now))
|
|
840
|
+
return {
|
|
841
|
+
id,
|
|
842
|
+
found: inspected.found,
|
|
843
|
+
ok: inspected.authorized === true,
|
|
844
|
+
reason: inspected.blockedReason ?? null,
|
|
845
|
+
expired: inspected.expired,
|
|
846
|
+
digestValid: inspected.manifestVerification?.digestValid === true,
|
|
847
|
+
armed: inspected.armed === true,
|
|
848
|
+
authorized: inspected.authorized === true,
|
|
849
|
+
executed: inspected.executed === true,
|
|
850
|
+
stale: inspected.stale === true,
|
|
851
|
+
receiptState: inspected.receiptState,
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
/**
|
|
856
|
+
* 启动自检(只读):让 UI/CLI 在重启前看到“重启契约是否健康”。
|
|
857
|
+
* block 级问题意味着“现在不可能安全重启”;warn 表示可重启但会降级(如无 HMAC)。
|
|
858
|
+
*/
|
|
859
|
+
const selfCheck = () => {
|
|
860
|
+
const findings = []
|
|
861
|
+
const add = (code, level, detail = '') => findings.push({ code, level, detail })
|
|
862
|
+
try {
|
|
863
|
+
fs.accessSync(stateDir, fs.constants.R_OK | fs.constants.W_OK)
|
|
864
|
+
add('state-dir-writable', 'ok', stateDir)
|
|
865
|
+
} catch (error) {
|
|
866
|
+
add('state-dir-not-writable', 'block', String(error?.message ?? error))
|
|
867
|
+
}
|
|
868
|
+
const stateFile = path.join(stateDir, 'state.json')
|
|
869
|
+
const rawState = readJson(stateFile, null)
|
|
870
|
+
if (rawState !== null && (typeof rawState !== 'object' || Array.isArray(rawState))) {
|
|
871
|
+
add('state-json-invalid', 'warn', stateFile)
|
|
872
|
+
}
|
|
873
|
+
if (!hmac.ok) add('hmac-unavailable', 'warn', String(hmac.reason ?? 'unavailable'))
|
|
874
|
+
else add('hmac-available', 'ok', String(hmac.source ?? 'available'))
|
|
875
|
+
|
|
876
|
+
const approvalIds = (() => { try { return listApprovalIds(stateDir) } catch (error) { add('approvals-unreadable', 'warn', String(error?.message ?? error)); return [] } })()
|
|
877
|
+
let armed = 0
|
|
878
|
+
let executed = 0
|
|
879
|
+
let invalid = 0
|
|
880
|
+
for (const id of approvalIds) {
|
|
881
|
+
try {
|
|
882
|
+
const inspected = inspectApproval(stateDir, id, inspectOptions())
|
|
883
|
+
if (!inspected?.ok) invalid += 1
|
|
884
|
+
else if (inspected.state === 'executed') executed += 1
|
|
885
|
+
else if (inspected.state === 'armed') armed += 1
|
|
886
|
+
} catch (error) {
|
|
887
|
+
invalid += 1
|
|
888
|
+
add('approval-inspect-failed', 'warn', `${id}: ${String(error?.message ?? error).slice(0, 160)}`)
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
if (invalid > 0) add('approval-manifests-invalid', 'warn', `${invalid}/${approvalIds.length}`)
|
|
892
|
+
add('approvals-summary', 'ok', `total=${approvalIds.length} armed=${armed} executed=${executed} invalid=${invalid}`)
|
|
893
|
+
|
|
894
|
+
const marker = (() => { try { return readJson(supervisorMarkerFile, null) } catch { return null } })()
|
|
895
|
+
if (marker && marker.execute === true) {
|
|
896
|
+
const at = Number(marker.at)
|
|
897
|
+
const fresh = Number.isFinite(at) && Date.now() - at <= SUPERVISOR_MARKER_TTL_MS
|
|
898
|
+
const alive = pidAlive(Number(marker.pid))
|
|
899
|
+
add('supervisor-marker', fresh && alive ? 'ok' : 'warn', `pid=${marker.pid ?? 'n/a'} fresh=${fresh} alive=${alive}`)
|
|
900
|
+
} else {
|
|
901
|
+
add('supervisor-marker', 'warn', 'absent')
|
|
902
|
+
}
|
|
903
|
+
const pidDoc = (() => { try { return readJson(pidFile, null) } catch { return null } })()
|
|
904
|
+
if (pidDoc && Number(pidDoc.pid) !== process.pid && pidAlive(Number(pidDoc.pid))) {
|
|
905
|
+
add('pid-file-foreign-live', 'warn', `pid=${pidDoc.pid}`)
|
|
906
|
+
}
|
|
907
|
+
if (lastUncleanBoot) add('unclean-boot', 'warn', `${lastUncleanBoot.state} pid=${lastUncleanBoot.pid ?? 'n/a'}`)
|
|
908
|
+
let crashCount = 0
|
|
909
|
+
try {
|
|
910
|
+
const raw = readTextSafe(crashLedgerFile, '')
|
|
911
|
+
crashCount = raw.split(/\r?\n/).filter((line) => line.trim()).length
|
|
912
|
+
} catch { /* ignore */ }
|
|
913
|
+
if (crashCount > 0) add('runtime-crash-ledger', 'warn', `${crashCount} record(s)`)
|
|
914
|
+
const block = findings.filter((finding) => finding.level === 'block').length
|
|
915
|
+
const warn = findings.filter((finding) => finding.level === 'warn').length
|
|
916
|
+
return {
|
|
917
|
+
ok: block === 0, block, warn, at: Date.now(),
|
|
918
|
+
stateDir, hmac: hmac.ok ? { source: hmac.source } : { unavailable: hmac.reason ?? 'unavailable' },
|
|
919
|
+
approvals: { total: approvalIds.length, armed, executed, invalid },
|
|
920
|
+
findings,
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
const service = {
|
|
925
|
+
request, decideOnly, state, impact, policy, executionContract, approvals, executionStatus, verifyApproval, selfCheck,
|
|
926
|
+
runtimeGuard: () => ({
|
|
927
|
+
lastUncleanBoot,
|
|
928
|
+
bootStateFile,
|
|
929
|
+
crashLedgerFile,
|
|
930
|
+
bootState: readJson(bootStateFile, null),
|
|
931
|
+
}),
|
|
932
|
+
}
|
|
344
933
|
ctx.effect(() => ctx.provide(SERVICE.restart, service))
|
|
345
934
|
|
|
346
|
-
//
|
|
935
|
+
// 定时器清理:审批兜底计时器必须随插件卸载一起清掉;退出交接触发器一并取消(fail-safe:不退出)。
|
|
347
936
|
ctx.effect(() => () => {
|
|
937
|
+
try { abortActiveApproval?.() } catch { /* dispose must not throw */ }
|
|
938
|
+
abortActiveApproval = null
|
|
348
939
|
for (const t of timers) clearTimeout(t)
|
|
349
940
|
timers.clear()
|
|
350
941
|
machine.state = GUARD_STATE.IDLE
|
|
351
942
|
machine.pending = null
|
|
943
|
+
persistState({ disposed: true })
|
|
944
|
+
clearHostPid()
|
|
352
945
|
})
|
|
353
946
|
|
|
354
947
|
return service
|