@twinsearth/dsh-fang 3.2.1 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client.js +40 -18
- package/docs/DSH-ARCHITECTURE-MAP.md +73 -0
- package/docs/MAIN-CITY-GATE.md +57 -0
- package/package.json +1 -1
- package/src/kernel/types.mjs +1 -1
- package/src/lib/decision-policy.mjs +22 -4
- package/src/lib/main-gate.mjs +526 -0
- package/src/lib/restart-contract.mjs +103 -1
- package/src/plugins/decision-center.mjs +72 -12
- package/src/plugins/forker.mjs +16 -0
- package/src/plugins/healer.mjs +38 -0
- package/src/plugins/restart-guard.mjs +75 -1
- package/src/plugins/scorer.mjs +37 -0
- package/tools/fangctl.mjs +21 -2
- package/tools/gate/main-city.mjs +204 -0
|
@@ -34,7 +34,16 @@ import { createAiSecretStore } from '../lib/ai-secret-store.mjs'
|
|
|
34
34
|
import { createDecisionOutbox, resolveMotherTarget } from '../lib/decision-outbox.mjs'
|
|
35
35
|
import { producerCatalog } from '../lib/producer-contract.mjs'
|
|
36
36
|
import { assertEndpointSafe, classifyEndpointHost } from '../lib/ssrf-guard.mjs'
|
|
37
|
-
import {
|
|
37
|
+
import {
|
|
38
|
+
DECISION_LEVEL_POLICY,
|
|
39
|
+
DECISION_PRIORITIES,
|
|
40
|
+
DECISION_RISKS,
|
|
41
|
+
decisionPolicy,
|
|
42
|
+
decisionWaitMs,
|
|
43
|
+
normalizeDecisionPriority,
|
|
44
|
+
normalizeDecisionRisk,
|
|
45
|
+
recommendedDecisionOption,
|
|
46
|
+
} from '../lib/decision-policy.mjs'
|
|
38
47
|
|
|
39
48
|
export const name = 'fang-decision-center'
|
|
40
49
|
export const inject = []
|
|
@@ -76,7 +85,8 @@ export const PM_DECISION_POLICY = Object.freeze({
|
|
|
76
85
|
'一次只问一个决定点,问题要具体到「选哪个」或「能不能做」',
|
|
77
86
|
'必须给出 2-4 个可执行选项,推荐项放第一个并把标签后缀 "(推荐)"',
|
|
78
87
|
'context 里写清:为什么需要人决定、每个选项的代价与风险、不决定的后果',
|
|
79
|
-
'red
|
|
88
|
+
'red 只用于真正阻塞(人不在就没法继续);yellow 用于影响方向/进度的建议(3 分钟后继续但可补选);blue 用于低风险日常建议(1 分钟后按推荐执行);green 用于阶段完成/自动执行留底(不提醒)',
|
|
89
|
+
'优先级与风险默认随等级:red=P0/high,yellow=P1/medium,blue=P2/low,green=P3/info;确实不符时显式传 priority/risk 覆盖',
|
|
80
90
|
'绝对不要因为「不确定」而把问题原样抛回给开发者——先把能自己查的查清',
|
|
81
91
|
],
|
|
82
92
|
})
|
|
@@ -306,6 +316,9 @@ function publicTicket(ticket) {
|
|
|
306
316
|
autoReason: ticket.autoReason ?? null,
|
|
307
317
|
lateResponse: ticket.lateResponse === true,
|
|
308
318
|
policyTimeoutMs: ticket.policyTimeoutMs ?? null,
|
|
319
|
+
// v3.2.2:优先级与风险程度是正式字段,默认由等级推导,调用方可覆盖。
|
|
320
|
+
priority: ticket.priority ?? decisionPolicy(ticket.level).priority,
|
|
321
|
+
risk: ticket.risk ?? decisionPolicy(ticket.level).risk,
|
|
309
322
|
}
|
|
310
323
|
}
|
|
311
324
|
|
|
@@ -393,7 +406,9 @@ function applyForkDecisionCenter(ctx, config, gate) {
|
|
|
393
406
|
type: 'object',
|
|
394
407
|
additionalProperties: false,
|
|
395
408
|
properties: {
|
|
396
|
-
level: { type: 'string', enum: ['red', 'yellow', 'blue', 'green'], description: '
|
|
409
|
+
level: { type: 'string', enum: ['red', 'yellow', 'blue', 'green'], description: '注意力等级;默认优先级/风险:红=P0/high,黄=P1/medium,蓝=P2/low,绿=P3/info' },
|
|
410
|
+
priority: { type: 'string', enum: ['P0', 'P1', 'P2', 'P3'], description: '可选:覆盖默认优先级' },
|
|
411
|
+
risk: { type: 'string', enum: ['high', 'medium', 'low', 'info'], description: '可选:覆盖默认风险' },
|
|
397
412
|
title: { type: 'string' },
|
|
398
413
|
context: { type: 'string' },
|
|
399
414
|
options: {
|
|
@@ -445,6 +460,7 @@ function applyForkDecisionCenter(ctx, config, gate) {
|
|
|
445
460
|
ticketId: ticket.id, level: ticket.level, blocking: false,
|
|
446
461
|
status: 'pending', outcome: 'deferred', deferred: true,
|
|
447
462
|
continueWithoutDecision: true, canAnswerLater: true, queued: false,
|
|
463
|
+
priority: ticket.priority, risk: ticket.risk,
|
|
448
464
|
}
|
|
449
465
|
}
|
|
450
466
|
throw new Error(`fork 决策未在时限内完成(${settled.reason})`)
|
|
@@ -456,6 +472,7 @@ function applyForkDecisionCenter(ctx, config, gate) {
|
|
|
456
472
|
status: 'pending', outcome: 'deferred', deferred: true,
|
|
457
473
|
continueWithoutDecision: true, canAnswerLater: true,
|
|
458
474
|
deferredAt: resolved.deferredAt ?? undefined, queued: false,
|
|
475
|
+
priority: resolved.priority, risk: resolved.risk,
|
|
459
476
|
}
|
|
460
477
|
}
|
|
461
478
|
if (resolved.status !== 'resolved' && resolved.status !== 'abandoned' && resolved.status !== 'expired' && resolved.status !== 'acked') {
|
|
@@ -468,6 +485,7 @@ function applyForkDecisionCenter(ctx, config, gate) {
|
|
|
468
485
|
selectedActionId: resolved.selectedActionId ?? undefined,
|
|
469
486
|
autoResolved: resolved.autoResolved === true,
|
|
470
487
|
autoReason: resolved.autoReason ?? undefined,
|
|
488
|
+
priority: resolved.priority, risk: resolved.risk,
|
|
471
489
|
queued: false,
|
|
472
490
|
}
|
|
473
491
|
}
|
|
@@ -1154,6 +1172,8 @@ export function apply(ctx, config) {
|
|
|
1154
1172
|
autoReason: null,
|
|
1155
1173
|
lateResponse: false,
|
|
1156
1174
|
policyTimeoutMs,
|
|
1175
|
+
priority: normalizeDecisionPriority(raw.priority, level),
|
|
1176
|
+
risk: normalizeDecisionRisk(raw.risk, level),
|
|
1157
1177
|
}
|
|
1158
1178
|
ticket.rev = nextRevision()
|
|
1159
1179
|
tickets.set(ticket.id, ticket)
|
|
@@ -1297,6 +1317,8 @@ export function apply(ctx, config) {
|
|
|
1297
1317
|
autoReason: item.autoReason ?? null,
|
|
1298
1318
|
lateResponse: item.lateResponse === true,
|
|
1299
1319
|
policyTimeoutMs: Number(item.policyTimeoutMs) || null,
|
|
1320
|
+
priority: normalizeDecisionPriority(item.priority, normalizeLevel(item.level, 'gray')),
|
|
1321
|
+
risk: normalizeDecisionRisk(item.risk, normalizeLevel(item.level, 'gray')),
|
|
1300
1322
|
}
|
|
1301
1323
|
if (ticket.status === 'pending') {
|
|
1302
1324
|
// v3.1.24:进程重启后 pending 仍保留给人回答(浮窗/收件箱可见),
|
|
@@ -2232,6 +2254,8 @@ export function apply(ctx, config) {
|
|
|
2232
2254
|
statuses: [...STATUSES],
|
|
2233
2255
|
blockingLevels: [...BLOCKING_LEVELS],
|
|
2234
2256
|
levelPolicies: DECISION_LEVEL_POLICY,
|
|
2257
|
+
priorities: [...DECISION_PRIORITIES],
|
|
2258
|
+
risks: [...DECISION_RISKS],
|
|
2235
2259
|
maxTickets: cfg.maxTickets,
|
|
2236
2260
|
maxPendingRed: cfg.maxPendingRed,
|
|
2237
2261
|
defaultTimeoutMinutes: cfg.defaultTimeoutMinutes,
|
|
@@ -2286,12 +2310,14 @@ export function apply(ctx, config) {
|
|
|
2286
2310
|
if (!tools || typeof tools.register !== 'function') return
|
|
2287
2311
|
const unregister = tools.register({
|
|
2288
2312
|
name: 'request_human_decision',
|
|
2289
|
-
description: '当需要人类授权、选择方案、或汇报重要结果时,创建一张决策中心 ticket
|
|
2313
|
+
description: '当需要人类授权、选择方案、或汇报重要结果时,创建一张决策中心 ticket。红色强制等待人工(P0/高);黄色最多等 3 分钟后继续且可补选(P1/中);蓝色最多等 1 分钟后按推荐自动执行(P2/低);绿色自动执行并留底(P3/信息)。必须按风险选等级,不要全部用红色。\n' + PM_PROACTIVE_HINT,
|
|
2290
2314
|
parameters: {
|
|
2291
2315
|
type: 'object',
|
|
2292
2316
|
additionalProperties: false,
|
|
2293
2317
|
properties: {
|
|
2294
|
-
level: { type: 'string', enum: ['red', 'yellow', 'blue', 'green'], description: '
|
|
2318
|
+
level: { type: 'string', enum: ['red', 'yellow', 'blue', 'green'], description: '注意力等级(默认优先级/风险:红=P0/high,黄=P1/medium,蓝=P2/low,绿=P3/info);red 会阻塞 Agent' },
|
|
2319
|
+
priority: { type: 'string', enum: ['P0', 'P1', 'P2', 'P3'], description: '可选:覆盖等级默认优先级' },
|
|
2320
|
+
risk: { type: 'string', enum: ['high', 'medium', 'low', 'info'], description: '可选:覆盖等级默认风险程度' },
|
|
2295
2321
|
title: { type: 'string', description: '一句话标题' },
|
|
2296
2322
|
context: { type: 'string', description: '为什么需要人类介入' },
|
|
2297
2323
|
options: {
|
|
@@ -2329,6 +2355,11 @@ export function apply(ctx, config) {
|
|
|
2329
2355
|
outcome: { type: 'string' },
|
|
2330
2356
|
selectedValue: { type: 'string' },
|
|
2331
2357
|
selectedActionId: { type: 'string' },
|
|
2358
|
+
priority: { type: 'string' },
|
|
2359
|
+
risk: { type: 'string' },
|
|
2360
|
+
autoResolved: { type: 'boolean' },
|
|
2361
|
+
lateResponse: { type: 'boolean' },
|
|
2362
|
+
continueWithoutDecision: { type: 'boolean' },
|
|
2332
2363
|
},
|
|
2333
2364
|
},
|
|
2334
2365
|
render(_args, value) {
|
|
@@ -2370,6 +2401,7 @@ export function apply(ctx, config) {
|
|
|
2370
2401
|
status: 'pending', outcome: 'deferred', deferred: true,
|
|
2371
2402
|
continueWithoutDecision: true, canAnswerLater: true,
|
|
2372
2403
|
deferredAt: result.deferredAt ?? undefined,
|
|
2404
|
+
priority: result.priority, risk: result.risk,
|
|
2373
2405
|
}
|
|
2374
2406
|
}
|
|
2375
2407
|
if (outcome !== 'resolved' && outcome !== 'acked') {
|
|
@@ -2384,6 +2416,7 @@ export function apply(ctx, config) {
|
|
|
2384
2416
|
autoResolved: result.autoResolved === true,
|
|
2385
2417
|
autoReason: result.autoReason ?? undefined,
|
|
2386
2418
|
lateResponse: result.lateResponse === true,
|
|
2419
|
+
priority: result.priority, risk: result.risk,
|
|
2387
2420
|
}
|
|
2388
2421
|
}
|
|
2389
2422
|
return {
|
|
@@ -2392,13 +2425,14 @@ export function apply(ctx, config) {
|
|
|
2392
2425
|
autoResolved: ticket.autoResolved === true,
|
|
2393
2426
|
selectedValue: ticket.resolvedOption ?? undefined,
|
|
2394
2427
|
selectedActionId: ticket.selectedActionId ?? undefined,
|
|
2428
|
+
priority: ticket.priority, risk: ticket.risk,
|
|
2395
2429
|
}
|
|
2396
2430
|
},
|
|
2397
2431
|
})
|
|
2398
2432
|
// PM 交互式选择:独立工具名,语义 = 红色决策 ticket(默认红、阻塞等待选择)。
|
|
2399
2433
|
const unregisterChoice = tools.register({
|
|
2400
2434
|
name: 'ask_user_choice',
|
|
2401
|
-
description: 'PM
|
|
2435
|
+
description: 'PM 交互式选择:向人类提出一个带选项的问题。默认红色阻塞;但**必须按风险选等级**:只有人不在就没法继续时才用 red,方向/进度建议用 yellow,低风险日常建议用 blue,阶段完成汇报用 green。不要所有问题都用红色。'
|
|
2402
2436
|
+ '\n凡属下列情形,PM 必须用本工具开票而不是自行决定或把问题丢回给开发者:'
|
|
2403
2437
|
+ PM_DECISION_POLICY.mustAsk.join(';')
|
|
2404
2438
|
+ '。每次只问一个决定点,给 2-4 个选项并标出推荐项。',
|
|
@@ -2418,7 +2452,9 @@ export function apply(ctx, config) {
|
|
|
2418
2452
|
},
|
|
2419
2453
|
description: '可选项(至少一个)',
|
|
2420
2454
|
},
|
|
2421
|
-
level: { type: 'string', enum: ['red', 'yellow', 'blue'], description: '
|
|
2455
|
+
level: { type: 'string', enum: ['red', 'yellow', 'blue', 'green'], description: '可选;默认 red(真正阻塞才用红)。yellow=3 分钟可补选,blue=1 分钟按推荐执行,green=自动留底' },
|
|
2456
|
+
priority: { type: 'string', enum: ['P0', 'P1', 'P2', 'P3'], description: '可选:覆盖等级默认优先级' },
|
|
2457
|
+
risk: { type: 'string', enum: ['high', 'medium', 'low', 'info'], description: '可选:覆盖等级默认风险' },
|
|
2422
2458
|
timeoutMinutes: { type: 'number' },
|
|
2423
2459
|
},
|
|
2424
2460
|
required: ['question', 'choices'],
|
|
@@ -2439,9 +2475,14 @@ export function apply(ctx, config) {
|
|
|
2439
2475
|
}))
|
|
2440
2476
|
.filter((option) => option.value.length > 0)
|
|
2441
2477
|
if (!options.length) throw new Error('ask_user_choice requires at least one choice')
|
|
2478
|
+
const level = ['red', 'yellow', 'blue', 'green'].includes(String(input.level))
|
|
2479
|
+
? String(input.level)
|
|
2480
|
+
: 'red'
|
|
2442
2481
|
const created = create({
|
|
2443
|
-
//
|
|
2444
|
-
level
|
|
2482
|
+
// 默认红;只有真正阻塞才用红,常规建议应显式传 yellow/blue,完成汇报传 green。
|
|
2483
|
+
level,
|
|
2484
|
+
priority: input.priority,
|
|
2485
|
+
risk: input.risk,
|
|
2445
2486
|
title: input.question ?? input.title,
|
|
2446
2487
|
context: input.context ?? input.question,
|
|
2447
2488
|
options,
|
|
@@ -2457,15 +2498,34 @@ export function apply(ctx, config) {
|
|
|
2457
2498
|
})
|
|
2458
2499
|
if (!created.ok) throw new Error(`decision center rejected choice: ${created.reason}`)
|
|
2459
2500
|
const ticket = created.ticket
|
|
2460
|
-
if (
|
|
2501
|
+
if (ticket.status !== 'pending') {
|
|
2502
|
+
return {
|
|
2503
|
+
ticketId: ticket.id, level: ticket.level, blocking: false,
|
|
2504
|
+
status: ticket.status, outcome: ticket.outcome,
|
|
2505
|
+
autoResolved: ticket.autoResolved === true,
|
|
2506
|
+
selectedValue: ticket.resolvedOption ?? undefined,
|
|
2507
|
+
priority: ticket.priority, risk: ticket.risk,
|
|
2508
|
+
}
|
|
2509
|
+
}
|
|
2461
2510
|
const result = await wait(ticket.id, exec?.signal)
|
|
2462
|
-
const outcome = String(result?.outcome ?? 'expired')
|
|
2511
|
+
const outcome = String(result?.outcome ?? (result.status === 'pending' ? 'deferred' : 'expired'))
|
|
2512
|
+
if (result.status === 'pending' && result.level === 'yellow') {
|
|
2513
|
+
return {
|
|
2514
|
+
ticketId: result.id, level: result.level, blocking: false,
|
|
2515
|
+
status: 'pending', outcome: 'deferred', deferred: true,
|
|
2516
|
+
continueWithoutDecision: true, canAnswerLater: true,
|
|
2517
|
+
priority: result.priority, risk: result.risk,
|
|
2518
|
+
}
|
|
2519
|
+
}
|
|
2463
2520
|
if (outcome !== 'resolved' && outcome !== 'acked') {
|
|
2464
2521
|
throw new Error(`用户未处理该选择(outcome=${outcome})`)
|
|
2465
2522
|
}
|
|
2466
2523
|
return {
|
|
2467
|
-
ticketId:
|
|
2524
|
+
ticketId: result.id, level: result.level, blocking: result.level === 'red',
|
|
2468
2525
|
outcome, selectedValue: result.resolvedOption ?? undefined,
|
|
2526
|
+
autoResolved: result.autoResolved === true,
|
|
2527
|
+
lateResponse: result.lateResponse === true,
|
|
2528
|
+
priority: result.priority, risk: result.risk,
|
|
2469
2529
|
}
|
|
2470
2530
|
},
|
|
2471
2531
|
})
|
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
|