@furongjun1999/dsh-memory 0.4.8 → 0.4.10
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/README.md +54 -26
- package/codebuddy/CODEBUDDY.md +196 -195
- package/codebuddy/README.md +13 -1
- package/codebuddy/mcp.json +9 -0
- package/docs/GBrain/345/217/257/345/200/237/351/211/264/347/202/271_/347/201/265/346/236/242/350/220/275/347/202/271/344/272/244/346/216/245_20260919.md +169 -0
- package/docs/README.md +1 -1
- package/docs/discipline/harnesses.yaml +18 -7
- package/docs/discipline/templates/full.md.tmpl +4 -3
- package/docs/experiments/linkref_backfill/candidates_20260917.json +726 -0
- package/docs/experiments/linkref_backfill/candidates_internal_20260917.json +602 -0
- package/docs/experiments/linkref_backfill/candidates_internal_v2.json +603 -0
- package/docs/experiments/linkref_backfill/candidates_secret_20260917.json +884 -0
- package/docs/experiments/linkref_backfill/candidates_secret_v2.json +789 -0
- package/docs/hive//345/244/232/347/253/257harness/351/200/232/344/277/241/345/245/221/347/272/246_v0.1.md +42 -0
- package/docs/hive//346/243/200/347/264/242/346/224/266/346/225/233/345/256/236/346/265/213/344/270/216S1b/350/256/276/350/256/241_v0.1.md +43 -0
- package/docs/hive//346/243/200/347/264/242/350/267/257/345/276/204/344/270/216/350/256/244/347/237/245/347/273/223/346/236/204/345/245/221/347/272/246_v0.1.md +102 -0
- package/docs/hive//347/234/237/345/256/236/345/272/223/347/253/257/345/210/260/347/253/257/345/256/236/346/265/213_S1b/344/270/216/345/217/254/345/233/236/346/235/203/350/241/241_v0.1.md +57 -0
- package/docs/hive//347/234/237/345/256/236/345/272/223/347/253/257/345/210/260/347/253/257/345/256/236/346/265/213_S7/345/200/222/346/216/222/345/200/231/351/200/211/345/261/202_v0.1.md +126 -0
- package/docs/hive//350/234/202/345/267/242/345/217/214/345/256/236/344/276/213/344/272/222/351/252/214_/350/256/276/350/256/241/345/256/232/347/250/277.md +503 -0
- package/docs/mdcg/D_meta_/345/267/245/347/250/213/345/214/226/346/226/271/346/241/210_v0.2.md +216 -0
- package/docs/mdcg/README/350/257/246/347/273/206/347/211/210_v0.4.5.md +631 -625
- package/docs/mdcg//344/273/243/347/240/201/350/257/204/345/256/241/344/270/216/346/235/241/344/273/266/345/214/226/346/263/250/351/207/212_/345/245/221/347/272/246_v0.1.md +82 -0
- package/docs/mdcg//345/205/250/345/272/223/344/273/243/347/240/201/350/257/204/345/256/241/344/270/216/346/235/241/344/273/266/345/214/226/346/263/250/351/207/212_/350/256/241/345/210/222_v0.1.md +600 -0
- package/docs/mdcg//345/212/237/350/203/275/350/260/203/347/224/250/346/230/240/345/260/204/350/241/250_v0.1.md +47 -45
- package/docs/mdcg//345/255/220/344/273/243/347/220/206/351/205/215/347/275/256/346/240/207/345/207/{206_v0.4.md → 206_v0.5.md} +92 -4
- package/docs/mdcg//347/201/265/346/236/242/350/256/260/345/277/206/345/212/250/350/257/215/345/215/217/350/256/256_v1.0-draft.md +172 -0
- package/docs/mdcg//347/216/257/344/272/214_/347/231/275/347/256/261/345/241/253/345/205/205/346/265/201/346/260/264/347/272/277_v0.1.md +31 -0
- package/docs/mdcg//350/267/250/347/253/257/351/252/214/350/257/201/344/270/216/345/220/214/346/255/245/345/215/217/350/256/256_v0.1.md +93 -0
- package/docs/theory//345/271/266/345/217/221/345/277/205/347/204/266/346/200/247/347/220/206/350/256/272_v0.2.md +2 -2
- package/docs/theory//347/220/206/350/256/272_/346/234/272/345/210/266_/344/273/243/347/240/201_/345/256/236/351/252/214_/347/274/272/345/217/243/347/237/251/351/230/265_v0.1.md +3 -3
- package/docs/theory//350/256/244/347/237/245/344/273/243/347/220/206/344/270/216/346/224/266/346/225/233/347/273/223/346/236/204_/346/235/241/344/273/266/350/256/272/351/207/215/346/236/204_v0.1.md +2 -2
- package/docs//345/267/245/344/275/234/347/272/252/345/276/213_/350/256/244/347/237/245/345/233/276/346/235/241/347/233/256_v1.1.json +434 -433
- package/docs//347/201/265/346/236/242/350/207/252/346/210/221/346/224/271/350/277/233/345/267/245/344/275/234/350/256/241/345/210/222_/345/244/226/351/203/250/347/240/224/347/251/266/347/263/273/345/210/227/345/220/270/346/224/266_v1_20260919.md +286 -0
- package/dsh/README.md +33 -0
- package/dsh/cordis.yml.example +13 -7
- package/dsh/hive-mcp-probe.mjs +94 -0
- package/dsh/hive-mcp.example.yml +62 -0
- package/dsh/update-lingshu.bat +11 -0
- package/dsh/update-lingshu.ps1 +337 -0
- package/lib/hooks.d.ts +3 -0
- package/lib/hooks.js +17 -23
- package/lib/index.d.ts +4 -2
- package/lib/index.js +29 -6
- package/lib/lib/datapath.d.ts +76 -1
- package/lib/lib/datapath.js +199 -13
- package/lib/lib/mdcg_client.d.ts +40 -3
- package/lib/lib/mdcg_client.js +46 -22
- package/lib/lib/mutual.js +4 -4
- package/lib/lib/token_store.js +4 -5
- package/md_cg/audit.py +17 -2
- package/md_cg/autonomy.py +86 -15
- package/md_cg/backfill.py +36 -1
- package/md_cg/backfill_bigdomain.py +34 -0
- package/md_cg/bench6_arms.py +28 -1
- package/md_cg/bench6_common.py +10 -1
- package/md_cg/bench6_competitors.py +6 -1
- package/md_cg/bench_axis_domain.py +9 -1
- package/md_cg/bench_blind_comp.py +7 -1
- package/md_cg/bench_en_atoms_public.py +9 -0
- package/md_cg/bench_governance.py +348 -0
- package/md_cg/bench_lme_zh.py +16 -1
- package/md_cg/bench_locomo.py +2 -1
- package/md_cg/bench_locomo_zh.py +16 -1
- package/md_cg/bench_locomo_zh_public.py +4 -1
- package/md_cg/bench_longmem.py +2 -1
- package/md_cg/bench_membench.py +27 -1
- package/md_cg/bench_p0.py +4 -1
- package/md_cg/bench_progressive.py +13 -1
- package/md_cg/bench_role_views.py +238 -0
- package/md_cg/bench_task_ab.py +8 -1
- package/md_cg/bench_task_ab_llm.py +13 -1
- package/md_cg/bench_unified_en.py +6 -1
- package/md_cg/bench_zh_mad.py +20 -1
- package/md_cg/blindspot_tickets.py +123 -0
- package/md_cg/branches.py +12 -1
- package/md_cg/build_postings.py +73 -0
- package/md_cg/ccgc.py +67 -2
- package/md_cg/census.py +5 -1
- package/md_cg/chain.py +24 -3
- package/md_cg/codeindex.py +134 -17
- package/md_cg/coldverify.py +265 -0
- package/md_cg/comment_gate.py +338 -0
- package/md_cg/cond_compose.py +190 -0
- package/md_cg/cond_facts.py +155 -0
- package/md_cg/cond_template.json +107 -0
- package/md_cg/condition_anchor.py +143 -0
- package/md_cg/conformance.py +69 -4
- package/md_cg/consistency.py +24 -1
- package/md_cg/consolidate.py +53 -2
- package/md_cg/corpus.py +4 -0
- package/md_cg/crosscheck.py +42 -2
- package/md_cg/crypto.py +35 -1
- package/md_cg/d_meta.py +310 -0
- package/md_cg/datapath.py +201 -26
- package/md_cg/docindex.py +122 -1
- package/md_cg/eval_common.py +29 -1
- package/md_cg/evidence.py +27 -1
- package/md_cg/evolution.py +21 -1
- package/md_cg/export.py +11 -1
- package/md_cg/forgetting.py +23 -1
- package/md_cg/fsutil.py +18 -1
- package/md_cg/hotcache.py +214 -0
- package/md_cg/hyperedge.py +251 -0
- package/md_cg/identity.py +18 -1
- package/md_cg/insight.py +17 -1
- package/md_cg/lexicon/build_cedict_en_zh.py +9 -0
- package/md_cg/lexicon/build_standard_en.py +171 -168
- package/md_cg/lexicon/expand_en_zh.py +6 -0
- package/md_cg/lifecycle.py +12 -1
- package/md_cg/linkref.py +281 -0
- package/md_cg/links.py +29 -1
- package/md_cg/mcp_server.py +362 -43
- package/md_cg/md_whitebox.py +53 -1
- package/md_cg/mdcg.py +1003 -27
- package/md_cg/mdcos.py +558 -36
- package/md_cg/metacognition.py +37 -2
- package/md_cg/migrate.py +4 -0
- package/md_cg/migrate_aeis.py +221 -213
- package/md_cg/migrate_roleplay.py +8 -0
- package/md_cg/migrate_wisdom_graph.py +14 -1
- package/md_cg/mreview/__main__.py +3 -0
- package/md_cg/mreview/bundle.py +8 -0
- package/md_cg/mreview/candidates.py +9 -0
- package/md_cg/mreview/govern.py +21 -1
- package/md_cg/mreview/locate.py +34 -0
- package/md_cg/mreview/pipeline.py +29 -1
- package/md_cg/mreview/ruleset.py +16 -1
- package/md_cg/nodefile.py +233 -3
- package/md_cg/pooling.py +23 -1
- package/md_cg/postings.py +298 -0
- package/md_cg/predict.py +89 -9
- package/md_cg/progressive.py +3 -0
- package/md_cg/protect.py +14 -1
- package/md_cg/protocol.py +372 -0
- package/md_cg/provenance.py +262 -0
- package/md_cg/reach.py +453 -0
- package/md_cg/refindex.py +47 -2
- package/md_cg/refine.py +20 -1
- package/md_cg/roleviews.py +89 -0
- package/md_cg/routing.py +76 -0
- package/md_cg/scrub.py +63 -2
- package/md_cg/security.py +26 -1
- package/md_cg/self_state.py +64 -1
- package/md_cg/selfreport.py +151 -0
- package/md_cg/semantic/canonical.py +5 -0
- package/md_cg/semantic/en_normalizer.py +364 -355
- package/md_cg/semantic/zh_en_atoms.py +139 -136
- package/md_cg/signer.py +41 -1
- package/md_cg/sources.py +583 -547
- package/md_cg/statushdr.py +179 -0
- package/md_cg/stg.py +59 -18
- package/md_cg/subgraph.py +23 -0
- package/md_cg/sustain.py +56 -1
- package/md_cg/tasks.py +26 -2
- package/md_cg/test_autonomy.py +26 -0
- package/md_cg/test_bench_governance.py +102 -0
- package/md_cg/test_blindspot_tickets.py +166 -0
- package/md_cg/test_ccgc.py +10 -0
- package/md_cg/test_codeindex.py +338 -0
- package/md_cg/test_comment_gate.py +187 -0
- package/md_cg/test_cond_compose_anchors.py +76 -0
- package/md_cg/test_condition_anchor.py +82 -0
- package/md_cg/test_d_meta.py +412 -0
- package/md_cg/test_datapath_root.py +188 -0
- package/md_cg/test_gain_gate.py +47 -1
- package/md_cg/test_hot_cold.py +187 -0
- package/md_cg/test_hyperedge.py +245 -0
- package/md_cg/test_linkref.py +306 -0
- package/md_cg/test_md_access_parity.py +15 -3
- package/md_cg/test_mr_m1.py +108 -18
- package/md_cg/test_mr_m3.py +8 -1
- package/md_cg/test_p26_refindex.py +49 -20
- package/md_cg/test_p27_docindex.py +236 -2
- package/md_cg/test_p2_mcp.py +1 -1
- package/md_cg/test_p31_insight.py +24 -0
- package/md_cg/test_p44_md_whitebox.py +14 -1
- package/md_cg/test_protocol.py +243 -0
- package/md_cg/test_reach.py +378 -0
- package/md_cg/test_reach_keys.py +201 -0
- package/md_cg/test_reach_meta_exits.py +145 -0
- package/md_cg/test_read_clip.py +8 -4
- package/md_cg/test_retr_s1.py +340 -0
- package/md_cg/test_retr_s1b.py +209 -0
- package/md_cg/test_retr_s3.py +194 -0
- package/md_cg/test_retr_s4.py +163 -0
- package/md_cg/test_retr_s5.py +200 -0
- package/md_cg/test_retr_s6.py +157 -0
- package/md_cg/test_retr_s7.py +385 -0
- package/md_cg/test_retr_s8_time.py +316 -0
- package/md_cg/test_retr_s9_edges.py +286 -0
- package/md_cg/test_retr_s9_entity_ctx.py +175 -0
- package/md_cg/test_review_conformance.py +59 -2
- package/md_cg/test_role_views.py +354 -0
- package/md_cg/test_subproc_encoding.py +188 -0
- package/md_cg/test_trust.py +361 -0
- package/md_cg/test_units_poll.py +71 -0
- package/md_cg/test_v14_fixes.py +397 -0
- package/md_cg/test_validity_filter.py +280 -0
- package/md_cg/test_wisdom_md_store.py +7 -3
- package/md_cg/test_writepipe.py +5 -1
- package/md_cg/theory.py +16 -1
- package/md_cg/tokens.py +40 -8
- package/md_cg/tool_face.py +13 -2
- package/md_cg/trust.py +943 -0
- package/md_cg/twophase.py +12 -1
- package/md_cg/units.py +132 -10
- package/md_cg/vision_evidence.py +24 -1
- package/md_cg/weights.py +24 -1
- package/md_cg/whitebox.py +32 -1
- package/md_cg/whitebox_kb/data/verify_cache.json +21210 -365
- package/md_cg/whitebox_kb/data/verify_savings.jsonl +5078 -0
- package/md_cg/whitebox_kb/wisdom/audit_log/chain_heat.json +10 -10
- package/md_cg/whitebox_kb/wisdom/code_compose.py +113 -6
- package/md_cg/whitebox_kb/wisdom/code_solidified.json +1 -1
- package/md_cg/whitebox_kb/wisdom/verifier.py +340 -55
- package/md_cg/whitebox_kb/wisdom/wisdom-book-cloud.db +0 -0
- package/md_cg/writelimit.py +18 -4
- package/md_cg/writepipe.py +178 -7
- package/package.json +2 -2
- package/skills/skills/designer-perspective/scripts/__pycache__/designer.cpython-310.pyc +0 -0
- package/skills/skills/designer-perspective/scripts/designer.py +17 -1
- package/skills/skills/designer-perspective/tests/selftest.py +3 -1
- package/src/hooks.ts +17 -21
- package/src/index.ts +33 -6
- package/src/lib/datapath.ts +211 -13
- package/src/lib/mdcg_client.ts +64 -25
- package/src/lib/mutual.ts +411 -411
- package/src/lib/token_store.ts +4 -5
- package/zcode/AGENTS.md +196 -195
- package/zcode/README.md +4 -0
- package/md_cg/whitebox_kb/wisdom/wisdom-book-cloud.db-shm +0 -0
- package/md_cg/whitebox_kb/wisdom/wisdom-book-cloud.db-wal +0 -0
package/src/lib/mutual.ts
CHANGED
|
@@ -1,411 +1,411 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* dsh-memory · 互维维护(Mutual Sustain Loop v1.1)——沙箱 B 侧
|
|
3
|
-
*
|
|
4
|
-
* 职责(与 A 侧 guardian.py 对称):
|
|
5
|
-
* 1. 心跳写戳:10min 写 ~/.lingxu_net/heartbeat.web.stamp({ts,pid,task_running})
|
|
6
|
-
* 2. 守护 A:检测 harness 进程(wmic 特征)→ 不存在则 detached 拉起
|
|
7
|
-
* (python -m harness.guardian;幂等:拉起前确认不存在 + 60s 冷却)
|
|
8
|
-
* 3. 任务验证:轮询 ~/.lingxu_net/tasks/task-*.json → 双通道验证
|
|
9
|
-
* (白箱 base_verify + DeepSeek 复核)→ 写回 result-<id>.json
|
|
10
|
-
*
|
|
11
|
-
* 协议:CommonTrustProtocol/docs/mutual-sustain-loop.md v1.1
|
|
12
|
-
* 失联分级:25min 告警 / 35min 重启 / task_running 豁免 ×2=70min
|
|
13
|
-
*/
|
|
14
|
-
import { exec, spawn } from 'node:child_process'
|
|
15
|
-
import * as fs from 'node:fs'
|
|
16
|
-
import * as path from 'node:path'
|
|
17
|
-
import * as os from 'node:os'
|
|
18
|
-
import { pythonPathValue,
|
|
19
|
-
|
|
20
|
-
export interface MutualOptions {
|
|
21
|
-
/** 心跳间隔(毫秒),默认 10min */
|
|
22
|
-
heartbeatMs: number
|
|
23
|
-
/** 失联告警阈值(毫秒),默认 25min */
|
|
24
|
-
warnMs: number
|
|
25
|
-
/** 失联重启阈值(毫秒),默认 35min */
|
|
26
|
-
deadMs: number
|
|
27
|
-
/** 任务中豁免倍数,默认 ×2 */
|
|
28
|
-
workingFactor: number
|
|
29
|
-
/** 拉起冷却(毫秒),默认 60s */
|
|
30
|
-
restartCooldownMs: number
|
|
31
|
-
/** 互维网络目录,默认 ~/.lingxu_net */
|
|
32
|
-
netDir: string
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
const DEFAULTS: MutualOptions = {
|
|
36
|
-
heartbeatMs: 10 * 60 * 1000,
|
|
37
|
-
warnMs: 25 * 60 * 1000,
|
|
38
|
-
deadMs: 35 * 60 * 1000,
|
|
39
|
-
workingFactor: 2,
|
|
40
|
-
restartCooldownMs: 60 * 1000,
|
|
41
|
-
netDir: path.join(os.homedir(), '.lingxu_net'),
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
/** 互维网络目录定位 */
|
|
45
|
-
export function netDir(opts: MutualOptions = DEFAULTS): string {
|
|
46
|
-
return opts.netDir
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
// ---------------------------------------------------------------------------
|
|
50
|
-
// 心跳(B 侧写戳)
|
|
51
|
-
// ---------------------------------------------------------------------------
|
|
52
|
-
|
|
53
|
-
export function writeHeartbeat(opts: MutualOptions = DEFAULTS, taskRunning = false): void {
|
|
54
|
-
const dir = netDir(opts)
|
|
55
|
-
fs.mkdirSync(dir, { recursive: true })
|
|
56
|
-
const stamp = {
|
|
57
|
-
ts: Date.now() / 1000,
|
|
58
|
-
pid: process.pid,
|
|
59
|
-
task_running: taskRunning,
|
|
60
|
-
}
|
|
61
|
-
fs.writeFileSync(path.join(dir, 'heartbeat.web.stamp'),
|
|
62
|
-
JSON.stringify(stamp), 'utf-8')
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
export function readHeartbeat(which: 'a' | 'web', opts: MutualOptions = DEFAULTS): {
|
|
66
|
-
ts: number; pid: number; task_running: boolean; ageMs: number
|
|
67
|
-
} | null {
|
|
68
|
-
try {
|
|
69
|
-
const raw = fs.readFileSync(path.join(netDir(opts), `heartbeat.${which}.stamp`), 'utf-8')
|
|
70
|
-
const s = JSON.parse(raw)
|
|
71
|
-
const ageMs = Date.now() - (s.ts as number) * 1000
|
|
72
|
-
return { ts: s.ts, pid: s.pid, task_running: !!s.task_running, ageMs }
|
|
73
|
-
} catch {
|
|
74
|
-
return null
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/** 失联分级判定(纯函数,A 侧 judge_stamp 的 B 侧镜像) */
|
|
79
|
-
export function judgeStamp(stamp: { ageMs: number; task_running: boolean } | null,
|
|
80
|
-
opts: MutualOptions = DEFAULTS): 'alive' | 'alive_working' | 'warning' | 'dead' | 'no_stamp' {
|
|
81
|
-
if (!stamp) return 'no_stamp'
|
|
82
|
-
const threshold = stamp.task_running ? opts.deadMs * opts.workingFactor : opts.deadMs
|
|
83
|
-
if (stamp.ageMs < opts.warnMs) return 'alive'
|
|
84
|
-
if (stamp.task_running && stamp.ageMs < threshold) return 'alive_working'
|
|
85
|
-
if (stamp.ageMs < threshold) return 'warning'
|
|
86
|
-
return 'dead'
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
// ---------------------------------------------------------------------------
|
|
90
|
-
// 守护 A(检测 harness 进程 + 拉起)
|
|
91
|
-
// ---------------------------------------------------------------------------
|
|
92
|
-
|
|
93
|
-
const HARNESS_PROC = ['python', 'harness.guardian'] // wmic 特征
|
|
94
|
-
|
|
95
|
-
function execP(cmd: string): Promise<string> {
|
|
96
|
-
return new Promise((resolve) => {
|
|
97
|
-
exec(cmd, { windowsHide: true, timeout: 15_000 }, (err, stdout) => {
|
|
98
|
-
resolve(err ? '' : String(stdout))
|
|
99
|
-
})
|
|
100
|
-
})
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/** 检测 harness 进程是否存在
|
|
104
|
-
* P1 完善(GPT 审查·wmic 兼容):wmic 在 Win11+ 已被移除——失败时
|
|
105
|
-
* fallback PowerShell Get-CimInstance(Win);非 Windows 用 ps 查询。 */
|
|
106
|
-
export async function harnessRunning(): Promise<boolean> {
|
|
107
|
-
if (process.platform === 'win32') {
|
|
108
|
-
// ① wmic(旧 Win10 可用)
|
|
109
|
-
const out = await execP(
|
|
110
|
-
`wmic process where "name='python.exe'" get commandline 2>nul`)
|
|
111
|
-
if (out.includes('harness.guardian') || out.includes('harness.main')) return true
|
|
112
|
-
// ② wmic 不可用(Win11 移除)→ PowerShell
|
|
113
|
-
const psOut = await execP(
|
|
114
|
-
`powershell -NoProfile -Command "Get-CimInstance Win32_Process -Filter \\"name='python.exe'\\" | Select-Object -ExpandProperty CommandLine"`)
|
|
115
|
-
return psOut.includes('harness.guardian') || psOut.includes('harness.main')
|
|
116
|
-
}
|
|
117
|
-
// 非 Windows(Linux/macOS):ps 查询
|
|
118
|
-
const psOut = await execP(`ps -eo command | grep -E 'harness\\.(guardian|main)' | grep -v grep`)
|
|
119
|
-
return !!psOut
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/** detached 拉起 A 侧 harness.guardian(幂等:先确认不存在) */
|
|
123
|
-
export async function ensureHarness(python = 'python',
|
|
124
|
-
opts: MutualOptions = DEFAULTS): Promise<'started' | 'already' | 'failed'> {
|
|
125
|
-
const running = await harnessRunning()
|
|
126
|
-
if (running) return 'already'
|
|
127
|
-
// P1 修复(GPT 审查):spawn 找不到可执行文件是异步 error 事件,无监听
|
|
128
|
-
// 会直接崩 Node(Unhandled 'error' event)。加监听 + 超时判定拉起失败。
|
|
129
|
-
return new Promise((resolve) => {
|
|
130
|
-
let child: ReturnType<typeof spawn> | null = null
|
|
131
|
-
let failTimer: NodeJS.Timeout | null = null
|
|
132
|
-
let okTimer: NodeJS.Timeout | null = null
|
|
133
|
-
let settled = false
|
|
134
|
-
const finish = (r: 'started' | 'failed'): void => {
|
|
135
|
-
if (settled) return
|
|
136
|
-
settled = true
|
|
137
|
-
if (failTimer) clearTimeout(failTimer)
|
|
138
|
-
if (okTimer) clearTimeout(okTimer)
|
|
139
|
-
resolve(r)
|
|
140
|
-
}
|
|
141
|
-
try {
|
|
142
|
-
child = spawn(python, ['-m', 'harness.guardian'], {
|
|
143
|
-
windowsHide: true,
|
|
144
|
-
detached: true,
|
|
145
|
-
stdio: 'ignore',
|
|
146
|
-
//
|
|
147
|
-
//
|
|
148
|
-
cwd:
|
|
149
|
-
env: { ...process.env, PYTHONPATH: pythonPathValue() },
|
|
150
|
-
})
|
|
151
|
-
} catch (e) {
|
|
152
|
-
log(opts, `守护失败:${String(e)}`)
|
|
153
|
-
finish('failed')
|
|
154
|
-
return
|
|
155
|
-
}
|
|
156
|
-
// 拉起失败(python 不存在等)→ 记录 + failed,不崩 Node。
|
|
157
|
-
// spawn 的 error 事件是异步的:不能立即判 started——等 50ms error 窗口,
|
|
158
|
-
// 无 error 才算拉起成功(GPT 审查:此前立即返回 started,错误路径也报成功)。
|
|
159
|
-
child.on('error', (err) => {
|
|
160
|
-
log(opts, `守护拉起错误:${err.message}`)
|
|
161
|
-
finish('failed')
|
|
162
|
-
})
|
|
163
|
-
// 拉起成功但立即退出(harness.guardian 不存在)→ failed
|
|
164
|
-
child.on('exit', (code) => {
|
|
165
|
-
if (code !== null && code !== 0) {
|
|
166
|
-
log(opts, `守护进程退出 code=${code}(guardian 可能不可用)`)
|
|
167
|
-
finish('failed')
|
|
168
|
-
}
|
|
169
|
-
})
|
|
170
|
-
okTimer = setTimeout(() => finish('started'), 50)
|
|
171
|
-
failTimer = setTimeout(() => {
|
|
172
|
-
log(opts, `守护拉起超时(10s 无健康确认)`)
|
|
173
|
-
finish('failed')
|
|
174
|
-
}, 10_000)
|
|
175
|
-
child.unref()
|
|
176
|
-
log(opts, `守护动作:拉起 harness.guardian(pid=${child.pid ?? '?'})`)
|
|
177
|
-
})
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
// ---------------------------------------------------------------------------
|
|
181
|
-
// 任务验证邮箱(双通道:白箱 base_verify + DeepSeek 复核)
|
|
182
|
-
// ---------------------------------------------------------------------------
|
|
183
|
-
|
|
184
|
-
export interface VerifyTask {
|
|
185
|
-
id: string
|
|
186
|
-
type: 'verify' | 'knowledge_sync'
|
|
187
|
-
from: 'A' | 'B'
|
|
188
|
-
to: 'B' | 'A'
|
|
189
|
-
payload: { claim: string; evidence?: string; expected?: string; source_ref?: string }
|
|
190
|
-
status: 'pending' | 'processing' | 'done'
|
|
191
|
-
created_at: number
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
export interface VerifyResult {
|
|
195
|
-
task_id: string
|
|
196
|
-
verdict: 'pass' | 'fail' | 'needs_revision'
|
|
197
|
-
whitebox: { judgment: string; best: string; d_norm: number; record_id: string }
|
|
198
|
-
llm_review: { conclusion: string; reason: string }
|
|
199
|
-
reasons: string[]
|
|
200
|
-
evidence: string[]
|
|
201
|
-
verifier: 'B'
|
|
202
|
-
at: number
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
/** 扫描互维目录里 A→B 的 pending 任务 */
|
|
206
|
-
export function scanTasks(opts: MutualOptions = DEFAULTS): VerifyTask[] {
|
|
207
|
-
const dir = path.join(netDir(opts), 'tasks')
|
|
208
|
-
if (!fs.existsSync(dir)) return []
|
|
209
|
-
const out: VerifyTask[] = []
|
|
210
|
-
for (const f of fs.readdirSync(dir)) {
|
|
211
|
-
if (!f.startsWith('task-') || !f.endsWith('.json')) continue
|
|
212
|
-
try {
|
|
213
|
-
const t = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf-8'))
|
|
214
|
-
if (t.to === 'B' && t.status === 'pending') out.push(t)
|
|
215
|
-
} catch { /* 跳过坏文件 */ }
|
|
216
|
-
}
|
|
217
|
-
return out
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
/** 白箱通道:智慧之书 base_verify(通过 bridge 调用,或本地注入) */
|
|
221
|
-
export async function whiteboxVerify(claim: string,
|
|
222
|
-
verifyFn: (c: string) => Promise<{ judgment: string; best: string; d_norm: number; record_id: string }>): Promise<VerifyResult['whitebox']> {
|
|
223
|
-
try {
|
|
224
|
-
return await verifyFn(claim)
|
|
225
|
-
} catch (e) {
|
|
226
|
-
return { judgment: `whitebox_error: ${String(e)}`, best: '', d_norm: -1, record_id: '' }
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
/** 复核通道:DeepSeek 独立复核(在白箱判定之上) */
|
|
231
|
-
export async function llmReview(claim: string, whitebox: VerifyResult['whitebox'],
|
|
232
|
-
reviewFn: (c: string, w: VerifyResult['whitebox']) => Promise<{ conclusion: string; reason: string }>): Promise<VerifyResult['llm_review']> {
|
|
233
|
-
try {
|
|
234
|
-
return await reviewFn(claim, whitebox)
|
|
235
|
-
} catch (e) {
|
|
236
|
-
return { conclusion: `llm_error: ${String(e)}`, reason: '' }
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
/** 综合 verdict(白箱优先) */
|
|
241
|
-
export function combineVerdict(w: VerifyResult['whitebox'],
|
|
242
|
-
l: VerifyResult['llm_review']): VerifyResult['verdict'] {
|
|
243
|
-
const c = l.conclusion || ''
|
|
244
|
-
// P1 修复(GPT 审查):白箱通道异常 → fail-closed(不因复核「同意」而 pass)
|
|
245
|
-
if (w.judgment.startsWith('whitebox_error') || w.judgment.startsWith('llm_error')
|
|
246
|
-
|| w.d_norm < 0) {
|
|
247
|
-
return 'needs_revision'
|
|
248
|
-
}
|
|
249
|
-
if (w.judgment.startsWith('采纳')) {
|
|
250
|
-
// 白箱采纳:复核质疑/不同意→needs_revision(白箱优先,记录分歧);否则 pass
|
|
251
|
-
return c.includes('质疑') || c.includes('不同意') || c.includes('不通过')
|
|
252
|
-
? 'needs_revision' : 'pass'
|
|
253
|
-
}
|
|
254
|
-
if (w.judgment.includes('fail') || w.judgment.includes('不成立')) return 'fail'
|
|
255
|
-
// 证据不足/无法判断 → 白箱不确定,交给复核决定(「不同意」须排除「同意」子串)
|
|
256
|
-
if (c.includes('不同意') || c.includes('不通过')) return 'needs_revision'
|
|
257
|
-
if (c.includes('通过') || c.includes('同意')) return 'pass'
|
|
258
|
-
// P1 修复(GPT 审查):「质疑」是分歧信号——白箱不确定 + 复核质疑 → 需要修订,
|
|
259
|
-
// 此前把「质疑」当 pass 与白箱采纳分支语义矛盾。
|
|
260
|
-
if (c.includes('质疑')) return 'needs_revision'
|
|
261
|
-
return 'needs_revision'
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
/** 任务 ID 安全校验(P1 修复:防路径穿越——task.id 可含 ../../ 写目录外) */
|
|
265
|
-
const TASK_ID_RE = /^[A-Za-z0-9._-]{1,64}$/
|
|
266
|
-
|
|
267
|
-
export function safeTaskId(id: string): boolean {
|
|
268
|
-
return TASK_ID_RE.test(id) && !id.includes('..')
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
/** 处理单个任务:双通道验证 → 写回 result */
|
|
272
|
-
export async function processTask(task: VerifyTask,
|
|
273
|
-
verifyFn: (c: string) => Promise<{ judgment: string; best: string; d_norm: number; record_id: string }>,
|
|
274
|
-
reviewFn: (c: string, w: VerifyResult['whitebox']) => Promise<{ conclusion: string; reason: string }>,
|
|
275
|
-
opts: MutualOptions = DEFAULTS): Promise<VerifyResult | null> {
|
|
276
|
-
const dir = path.join(netDir(opts), 'tasks')
|
|
277
|
-
// P1 修复(GPT 审查):task.id 路径穿越——非法 id 拒绝处理,不写任何文件
|
|
278
|
-
if (!safeTaskId(task.id)) {
|
|
279
|
-
log(opts, `任务 ${JSON.stringify(task.id)} 非法(路径穿越风险),拒绝处理`)
|
|
280
|
-
throw new Error(`非法任务 id: ${task.id}`)
|
|
281
|
-
}
|
|
282
|
-
const taskPath = path.join(dir, `task-${task.id}.json`)
|
|
283
|
-
// P1 完善(GPT 审查·任务竞态):原子 claim——rename task→processing。
|
|
284
|
-
// 多实例同时 scanTasks 读到同一 pending 时,rename 只有一方成功;
|
|
285
|
-
// 失败(文件已被 rename/不存在)= 其他实例正在处理 → 跳过(返回 null)。
|
|
286
|
-
// 此前无锁:多实例都写 processing/result/done,结果互相覆盖。
|
|
287
|
-
const claimPath = path.join(dir, `processing-${task.id}.json`)
|
|
288
|
-
try {
|
|
289
|
-
fs.renameSync(taskPath, claimPath)
|
|
290
|
-
}
|
|
291
|
-
catch {
|
|
292
|
-
return null // 已被其他实例 claim,或文件不存在
|
|
293
|
-
}
|
|
294
|
-
try {
|
|
295
|
-
const w = await whiteboxVerify(task.payload.claim, verifyFn)
|
|
296
|
-
const l = await llmReview(task.payload.claim, w, reviewFn)
|
|
297
|
-
const verdict = combineVerdict(w, l)
|
|
298
|
-
const result: VerifyResult = {
|
|
299
|
-
task_id: task.id,
|
|
300
|
-
verdict,
|
|
301
|
-
whitebox: w,
|
|
302
|
-
llm_review: l,
|
|
303
|
-
reasons: [
|
|
304
|
-
`白箱判定:${w.judgment}(best=${w.best},d_norm=${w.d_norm})`,
|
|
305
|
-
`复核结论:${l.conclusion}`,
|
|
306
|
-
],
|
|
307
|
-
evidence: [task.payload.source_ref || ''].filter(Boolean),
|
|
308
|
-
verifier: 'B',
|
|
309
|
-
at: Date.now() / 1000,
|
|
310
|
-
}
|
|
311
|
-
// 结果先写 tmp 再 rename(原子,防半写文件)
|
|
312
|
-
const resultTmp = path.join(dir, `result-${task.id}.json.tmp`)
|
|
313
|
-
fs.writeFileSync(resultTmp, JSON.stringify(result, null, 2), 'utf-8')
|
|
314
|
-
fs.renameSync(resultTmp, path.join(dir, `result-${task.id}.json`))
|
|
315
|
-
// 完成:清理 claim 文件(rename 回 done 标记供审计)
|
|
316
|
-
fs.renameSync(claimPath, path.join(dir, `done-${task.id}.json`))
|
|
317
|
-
log(opts, `任务 ${task.id} 验证完成:${verdict}`)
|
|
318
|
-
return result
|
|
319
|
-
}
|
|
320
|
-
catch (e) {
|
|
321
|
-
// 处理失败:释放 claim(rename 回 task 供重试)
|
|
322
|
-
try {
|
|
323
|
-
fs.renameSync(claimPath, taskPath)
|
|
324
|
-
}
|
|
325
|
-
catch { /* 文件可能已不在 */ }
|
|
326
|
-
throw e
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
// ---------------------------------------------------------------------------
|
|
331
|
-
// 日志 / last_contact
|
|
332
|
-
// ---------------------------------------------------------------------------
|
|
333
|
-
|
|
334
|
-
export function log(opts: MutualOptions, msg: string): void {
|
|
335
|
-
try {
|
|
336
|
-
const p = path.join(netDir(opts), 'mutual.log')
|
|
337
|
-
fs.appendFileSync(p, `[B ${new Date().toISOString()}] ${msg}\n`, 'utf-8')
|
|
338
|
-
} catch { /* 日志失败不阻塞 */ }
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
export function writeLastContact(opts: MutualOptions = DEFAULTS): void {
|
|
342
|
-
try {
|
|
343
|
-
fs.writeFileSync(path.join(netDir(opts), 'last_contact.json'),
|
|
344
|
-
JSON.stringify({ last_contact_b: Date.now() / 1000 }), 'utf-8')
|
|
345
|
-
} catch { /* 非阻塞 */ }
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
// ---------------------------------------------------------------------------
|
|
349
|
-
// 安装(ctx.effect 作用域内,卸载时清理)
|
|
350
|
-
// ---------------------------------------------------------------------------
|
|
351
|
-
|
|
352
|
-
export function installMutualMaintenance(
|
|
353
|
-
ctx: { logger: { info(m: string): void }; effect(fn: () => () => void, name?: string): void },
|
|
354
|
-
config: Partial<MutualOptions> = {},
|
|
355
|
-
hooks: {
|
|
356
|
-
verify?: (c: string) => Promise<{ judgment: string; best: string; d_norm: number; record_id: string }>
|
|
357
|
-
review?: (c: string, w: VerifyResult['whitebox']) => Promise<{ conclusion: string; reason: string }>
|
|
358
|
-
} = {},
|
|
359
|
-
): void {
|
|
360
|
-
const opts: MutualOptions = { ...DEFAULTS, ...config }
|
|
361
|
-
|
|
362
|
-
// 1. 心跳写戳 + 守护 A(10min 周期)
|
|
363
|
-
// P1 修复(GPT 审查):cordis-plugin-timer 签名是 interval(callback, delay)
|
|
364
|
-
// ——此前 (ms, fn) 写反:数字被当 callback、函数被当 delay,回调永不执行,
|
|
365
|
-
// 互维心跳/任务扫描实际不工作。
|
|
366
|
-
// P2 修复:不能用 ctx.interval——那是 cordis-plugin-timer 注入的快捷属性,
|
|
367
|
-
// 未声明 `timer` inject 时访问抛 "cannot get property without inject"。
|
|
368
|
-
// 改用 Node 原生 setInterval(互维不需要 Cordis effect 生命周期管理)。
|
|
369
|
-
const heartbeatTimer = setInterval(() => {
|
|
370
|
-
try {
|
|
371
|
-
writeHeartbeat(opts)
|
|
372
|
-
// 守护 A:harness 不在 → 拉起
|
|
373
|
-
ensureHarness('python', opts).then((r) => {
|
|
374
|
-
if (r === 'started') ctx.logger.info(`mutual: 已拉起 A 侧 harness(${r})`)
|
|
375
|
-
})
|
|
376
|
-
// 读 A 戳分级判定
|
|
377
|
-
const a = readHeartbeat('a', opts)
|
|
378
|
-
const verdict = judgeStamp(a, opts)
|
|
379
|
-
if (verdict === 'warning') ctx.logger.info('mutual: A 侧心跳告警(>25min 未更新)')
|
|
380
|
-
if (verdict === 'dead') ctx.logger.info('mutual: A 侧失联(>35min),等待 guardian 自愈或告警')
|
|
381
|
-
writeLastContact(opts)
|
|
382
|
-
} catch (e) { /* 单次失败不中断 */ }
|
|
383
|
-
}, opts.heartbeatMs)
|
|
384
|
-
heartbeatTimer.unref?.()
|
|
385
|
-
|
|
386
|
-
// 2. 任务轮询(30s 周期,检查 A→B 任务)
|
|
387
|
-
const taskTimer = setInterval(() => {
|
|
388
|
-
try {
|
|
389
|
-
const tasks = scanTasks(opts)
|
|
390
|
-
for (const t of tasks) {
|
|
391
|
-
if (!hooks.verify || !hooks.review) continue
|
|
392
|
-
processTask(t, hooks.verify, hooks.review, opts).catch((e) => {
|
|
393
|
-
log(opts, `任务 ${t.id} 处理异常:${String(e)}`)
|
|
394
|
-
})
|
|
395
|
-
}
|
|
396
|
-
} catch (e) { /* 单次失败不中断 */ }
|
|
397
|
-
}, 30_000)
|
|
398
|
-
taskTimer.unref?.()
|
|
399
|
-
|
|
400
|
-
// 3. effect 作用域清理
|
|
401
|
-
ctx.effect(() => {
|
|
402
|
-
return () => {
|
|
403
|
-
try {
|
|
404
|
-
clearInterval(heartbeatTimer)
|
|
405
|
-
clearInterval(taskTimer)
|
|
406
|
-
} catch { /* 清理失败不阻塞 */ }
|
|
407
|
-
}
|
|
408
|
-
}, 'dsh-memory-mutual')
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
export default { installMutualMaintenance, writeHeartbeat, readHeartbeat, judgeStamp, scanTasks, processTask }
|
|
1
|
+
/**
|
|
2
|
+
* dsh-memory · 互维维护(Mutual Sustain Loop v1.1)——沙箱 B 侧
|
|
3
|
+
*
|
|
4
|
+
* 职责(与 A 侧 guardian.py 对称):
|
|
5
|
+
* 1. 心跳写戳:10min 写 ~/.lingxu_net/heartbeat.web.stamp({ts,pid,task_running})
|
|
6
|
+
* 2. 守护 A:检测 harness 进程(wmic 特征)→ 不存在则 detached 拉起
|
|
7
|
+
* (python -m harness.guardian;幂等:拉起前确认不存在 + 60s 冷却)
|
|
8
|
+
* 3. 任务验证:轮询 ~/.lingxu_net/tasks/task-*.json → 双通道验证
|
|
9
|
+
* (白箱 base_verify + DeepSeek 复核)→ 写回 result-<id>.json
|
|
10
|
+
*
|
|
11
|
+
* 协议:CommonTrustProtocol/docs/mutual-sustain-loop.md v1.1
|
|
12
|
+
* 失联分级:25min 告警 / 35min 重启 / task_running 豁免 ×2=70min
|
|
13
|
+
*/
|
|
14
|
+
import { exec, spawn } from 'node:child_process'
|
|
15
|
+
import * as fs from 'node:fs'
|
|
16
|
+
import * as path from 'node:path'
|
|
17
|
+
import * as os from 'node:os'
|
|
18
|
+
import { pythonPathValue, runRoot } from './datapath.js'
|
|
19
|
+
|
|
20
|
+
export interface MutualOptions {
|
|
21
|
+
/** 心跳间隔(毫秒),默认 10min */
|
|
22
|
+
heartbeatMs: number
|
|
23
|
+
/** 失联告警阈值(毫秒),默认 25min */
|
|
24
|
+
warnMs: number
|
|
25
|
+
/** 失联重启阈值(毫秒),默认 35min */
|
|
26
|
+
deadMs: number
|
|
27
|
+
/** 任务中豁免倍数,默认 ×2 */
|
|
28
|
+
workingFactor: number
|
|
29
|
+
/** 拉起冷却(毫秒),默认 60s */
|
|
30
|
+
restartCooldownMs: number
|
|
31
|
+
/** 互维网络目录,默认 ~/.lingxu_net */
|
|
32
|
+
netDir: string
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const DEFAULTS: MutualOptions = {
|
|
36
|
+
heartbeatMs: 10 * 60 * 1000,
|
|
37
|
+
warnMs: 25 * 60 * 1000,
|
|
38
|
+
deadMs: 35 * 60 * 1000,
|
|
39
|
+
workingFactor: 2,
|
|
40
|
+
restartCooldownMs: 60 * 1000,
|
|
41
|
+
netDir: path.join(os.homedir(), '.lingxu_net'),
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 互维网络目录定位 */
|
|
45
|
+
export function netDir(opts: MutualOptions = DEFAULTS): string {
|
|
46
|
+
return opts.netDir
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// ---------------------------------------------------------------------------
|
|
50
|
+
// 心跳(B 侧写戳)
|
|
51
|
+
// ---------------------------------------------------------------------------
|
|
52
|
+
|
|
53
|
+
export function writeHeartbeat(opts: MutualOptions = DEFAULTS, taskRunning = false): void {
|
|
54
|
+
const dir = netDir(opts)
|
|
55
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
56
|
+
const stamp = {
|
|
57
|
+
ts: Date.now() / 1000,
|
|
58
|
+
pid: process.pid,
|
|
59
|
+
task_running: taskRunning,
|
|
60
|
+
}
|
|
61
|
+
fs.writeFileSync(path.join(dir, 'heartbeat.web.stamp'),
|
|
62
|
+
JSON.stringify(stamp), 'utf-8')
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function readHeartbeat(which: 'a' | 'web', opts: MutualOptions = DEFAULTS): {
|
|
66
|
+
ts: number; pid: number; task_running: boolean; ageMs: number
|
|
67
|
+
} | null {
|
|
68
|
+
try {
|
|
69
|
+
const raw = fs.readFileSync(path.join(netDir(opts), `heartbeat.${which}.stamp`), 'utf-8')
|
|
70
|
+
const s = JSON.parse(raw)
|
|
71
|
+
const ageMs = Date.now() - (s.ts as number) * 1000
|
|
72
|
+
return { ts: s.ts, pid: s.pid, task_running: !!s.task_running, ageMs }
|
|
73
|
+
} catch {
|
|
74
|
+
return null
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** 失联分级判定(纯函数,A 侧 judge_stamp 的 B 侧镜像) */
|
|
79
|
+
export function judgeStamp(stamp: { ageMs: number; task_running: boolean } | null,
|
|
80
|
+
opts: MutualOptions = DEFAULTS): 'alive' | 'alive_working' | 'warning' | 'dead' | 'no_stamp' {
|
|
81
|
+
if (!stamp) return 'no_stamp'
|
|
82
|
+
const threshold = stamp.task_running ? opts.deadMs * opts.workingFactor : opts.deadMs
|
|
83
|
+
if (stamp.ageMs < opts.warnMs) return 'alive'
|
|
84
|
+
if (stamp.task_running && stamp.ageMs < threshold) return 'alive_working'
|
|
85
|
+
if (stamp.ageMs < threshold) return 'warning'
|
|
86
|
+
return 'dead'
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ---------------------------------------------------------------------------
|
|
90
|
+
// 守护 A(检测 harness 进程 + 拉起)
|
|
91
|
+
// ---------------------------------------------------------------------------
|
|
92
|
+
|
|
93
|
+
const HARNESS_PROC = ['python', 'harness.guardian'] // wmic 特征
|
|
94
|
+
|
|
95
|
+
function execP(cmd: string): Promise<string> {
|
|
96
|
+
return new Promise((resolve) => {
|
|
97
|
+
exec(cmd, { windowsHide: true, timeout: 15_000 }, (err, stdout) => {
|
|
98
|
+
resolve(err ? '' : String(stdout))
|
|
99
|
+
})
|
|
100
|
+
})
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** 检测 harness 进程是否存在
|
|
104
|
+
* P1 完善(GPT 审查·wmic 兼容):wmic 在 Win11+ 已被移除——失败时
|
|
105
|
+
* fallback PowerShell Get-CimInstance(Win);非 Windows 用 ps 查询。 */
|
|
106
|
+
export async function harnessRunning(): Promise<boolean> {
|
|
107
|
+
if (process.platform === 'win32') {
|
|
108
|
+
// ① wmic(旧 Win10 可用)
|
|
109
|
+
const out = await execP(
|
|
110
|
+
`wmic process where "name='python.exe'" get commandline 2>nul`)
|
|
111
|
+
if (out.includes('harness.guardian') || out.includes('harness.main')) return true
|
|
112
|
+
// ② wmic 不可用(Win11 移除)→ PowerShell
|
|
113
|
+
const psOut = await execP(
|
|
114
|
+
`powershell -NoProfile -Command "Get-CimInstance Win32_Process -Filter \\"name='python.exe'\\" | Select-Object -ExpandProperty CommandLine"`)
|
|
115
|
+
return psOut.includes('harness.guardian') || psOut.includes('harness.main')
|
|
116
|
+
}
|
|
117
|
+
// 非 Windows(Linux/macOS):ps 查询
|
|
118
|
+
const psOut = await execP(`ps -eo command | grep -E 'harness\\.(guardian|main)' | grep -v grep`)
|
|
119
|
+
return !!psOut
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** detached 拉起 A 侧 harness.guardian(幂等:先确认不存在) */
|
|
123
|
+
export async function ensureHarness(python = 'python',
|
|
124
|
+
opts: MutualOptions = DEFAULTS): Promise<'started' | 'already' | 'failed'> {
|
|
125
|
+
const running = await harnessRunning()
|
|
126
|
+
if (running) return 'already'
|
|
127
|
+
// P1 修复(GPT 审查):spawn 找不到可执行文件是异步 error 事件,无监听
|
|
128
|
+
// 会直接崩 Node(Unhandled 'error' event)。加监听 + 超时判定拉起失败。
|
|
129
|
+
return new Promise((resolve) => {
|
|
130
|
+
let child: ReturnType<typeof spawn> | null = null
|
|
131
|
+
let failTimer: NodeJS.Timeout | null = null
|
|
132
|
+
let okTimer: NodeJS.Timeout | null = null
|
|
133
|
+
let settled = false
|
|
134
|
+
const finish = (r: 'started' | 'failed'): void => {
|
|
135
|
+
if (settled) return
|
|
136
|
+
settled = true
|
|
137
|
+
if (failTimer) clearTimeout(failTimer)
|
|
138
|
+
if (okTimer) clearTimeout(okTimer)
|
|
139
|
+
resolve(r)
|
|
140
|
+
}
|
|
141
|
+
try {
|
|
142
|
+
child = spawn(python, ['-m', 'harness.guardian'], {
|
|
143
|
+
windowsHide: true,
|
|
144
|
+
detached: true,
|
|
145
|
+
stdio: 'ignore',
|
|
146
|
+
// 同 mdcg_client:cwd 必须在包外(否则 pnpm 更新时 rmdir 包目录被 Windows
|
|
147
|
+
// 拒绝 → ERR_PNPM_EBUSY);模块解析由 PYTHONPATH 保证,见 datapath.runRoot()。
|
|
148
|
+
cwd: runRoot(),
|
|
149
|
+
env: { ...process.env, PYTHONPATH: pythonPathValue() },
|
|
150
|
+
})
|
|
151
|
+
} catch (e) {
|
|
152
|
+
log(opts, `守护失败:${String(e)}`)
|
|
153
|
+
finish('failed')
|
|
154
|
+
return
|
|
155
|
+
}
|
|
156
|
+
// 拉起失败(python 不存在等)→ 记录 + failed,不崩 Node。
|
|
157
|
+
// spawn 的 error 事件是异步的:不能立即判 started——等 50ms error 窗口,
|
|
158
|
+
// 无 error 才算拉起成功(GPT 审查:此前立即返回 started,错误路径也报成功)。
|
|
159
|
+
child.on('error', (err) => {
|
|
160
|
+
log(opts, `守护拉起错误:${err.message}`)
|
|
161
|
+
finish('failed')
|
|
162
|
+
})
|
|
163
|
+
// 拉起成功但立即退出(harness.guardian 不存在)→ failed
|
|
164
|
+
child.on('exit', (code) => {
|
|
165
|
+
if (code !== null && code !== 0) {
|
|
166
|
+
log(opts, `守护进程退出 code=${code}(guardian 可能不可用)`)
|
|
167
|
+
finish('failed')
|
|
168
|
+
}
|
|
169
|
+
})
|
|
170
|
+
okTimer = setTimeout(() => finish('started'), 50)
|
|
171
|
+
failTimer = setTimeout(() => {
|
|
172
|
+
log(opts, `守护拉起超时(10s 无健康确认)`)
|
|
173
|
+
finish('failed')
|
|
174
|
+
}, 10_000)
|
|
175
|
+
child.unref()
|
|
176
|
+
log(opts, `守护动作:拉起 harness.guardian(pid=${child.pid ?? '?'})`)
|
|
177
|
+
})
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// ---------------------------------------------------------------------------
|
|
181
|
+
// 任务验证邮箱(双通道:白箱 base_verify + DeepSeek 复核)
|
|
182
|
+
// ---------------------------------------------------------------------------
|
|
183
|
+
|
|
184
|
+
export interface VerifyTask {
|
|
185
|
+
id: string
|
|
186
|
+
type: 'verify' | 'knowledge_sync'
|
|
187
|
+
from: 'A' | 'B'
|
|
188
|
+
to: 'B' | 'A'
|
|
189
|
+
payload: { claim: string; evidence?: string; expected?: string; source_ref?: string }
|
|
190
|
+
status: 'pending' | 'processing' | 'done'
|
|
191
|
+
created_at: number
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export interface VerifyResult {
|
|
195
|
+
task_id: string
|
|
196
|
+
verdict: 'pass' | 'fail' | 'needs_revision'
|
|
197
|
+
whitebox: { judgment: string; best: string; d_norm: number; record_id: string }
|
|
198
|
+
llm_review: { conclusion: string; reason: string }
|
|
199
|
+
reasons: string[]
|
|
200
|
+
evidence: string[]
|
|
201
|
+
verifier: 'B'
|
|
202
|
+
at: number
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** 扫描互维目录里 A→B 的 pending 任务 */
|
|
206
|
+
export function scanTasks(opts: MutualOptions = DEFAULTS): VerifyTask[] {
|
|
207
|
+
const dir = path.join(netDir(opts), 'tasks')
|
|
208
|
+
if (!fs.existsSync(dir)) return []
|
|
209
|
+
const out: VerifyTask[] = []
|
|
210
|
+
for (const f of fs.readdirSync(dir)) {
|
|
211
|
+
if (!f.startsWith('task-') || !f.endsWith('.json')) continue
|
|
212
|
+
try {
|
|
213
|
+
const t = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf-8'))
|
|
214
|
+
if (t.to === 'B' && t.status === 'pending') out.push(t)
|
|
215
|
+
} catch { /* 跳过坏文件 */ }
|
|
216
|
+
}
|
|
217
|
+
return out
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** 白箱通道:智慧之书 base_verify(通过 bridge 调用,或本地注入) */
|
|
221
|
+
export async function whiteboxVerify(claim: string,
|
|
222
|
+
verifyFn: (c: string) => Promise<{ judgment: string; best: string; d_norm: number; record_id: string }>): Promise<VerifyResult['whitebox']> {
|
|
223
|
+
try {
|
|
224
|
+
return await verifyFn(claim)
|
|
225
|
+
} catch (e) {
|
|
226
|
+
return { judgment: `whitebox_error: ${String(e)}`, best: '', d_norm: -1, record_id: '' }
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** 复核通道:DeepSeek 独立复核(在白箱判定之上) */
|
|
231
|
+
export async function llmReview(claim: string, whitebox: VerifyResult['whitebox'],
|
|
232
|
+
reviewFn: (c: string, w: VerifyResult['whitebox']) => Promise<{ conclusion: string; reason: string }>): Promise<VerifyResult['llm_review']> {
|
|
233
|
+
try {
|
|
234
|
+
return await reviewFn(claim, whitebox)
|
|
235
|
+
} catch (e) {
|
|
236
|
+
return { conclusion: `llm_error: ${String(e)}`, reason: '' }
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** 综合 verdict(白箱优先) */
|
|
241
|
+
export function combineVerdict(w: VerifyResult['whitebox'],
|
|
242
|
+
l: VerifyResult['llm_review']): VerifyResult['verdict'] {
|
|
243
|
+
const c = l.conclusion || ''
|
|
244
|
+
// P1 修复(GPT 审查):白箱通道异常 → fail-closed(不因复核「同意」而 pass)
|
|
245
|
+
if (w.judgment.startsWith('whitebox_error') || w.judgment.startsWith('llm_error')
|
|
246
|
+
|| w.d_norm < 0) {
|
|
247
|
+
return 'needs_revision'
|
|
248
|
+
}
|
|
249
|
+
if (w.judgment.startsWith('采纳')) {
|
|
250
|
+
// 白箱采纳:复核质疑/不同意→needs_revision(白箱优先,记录分歧);否则 pass
|
|
251
|
+
return c.includes('质疑') || c.includes('不同意') || c.includes('不通过')
|
|
252
|
+
? 'needs_revision' : 'pass'
|
|
253
|
+
}
|
|
254
|
+
if (w.judgment.includes('fail') || w.judgment.includes('不成立')) return 'fail'
|
|
255
|
+
// 证据不足/无法判断 → 白箱不确定,交给复核决定(「不同意」须排除「同意」子串)
|
|
256
|
+
if (c.includes('不同意') || c.includes('不通过')) return 'needs_revision'
|
|
257
|
+
if (c.includes('通过') || c.includes('同意')) return 'pass'
|
|
258
|
+
// P1 修复(GPT 审查):「质疑」是分歧信号——白箱不确定 + 复核质疑 → 需要修订,
|
|
259
|
+
// 此前把「质疑」当 pass 与白箱采纳分支语义矛盾。
|
|
260
|
+
if (c.includes('质疑')) return 'needs_revision'
|
|
261
|
+
return 'needs_revision'
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** 任务 ID 安全校验(P1 修复:防路径穿越——task.id 可含 ../../ 写目录外) */
|
|
265
|
+
const TASK_ID_RE = /^[A-Za-z0-9._-]{1,64}$/
|
|
266
|
+
|
|
267
|
+
export function safeTaskId(id: string): boolean {
|
|
268
|
+
return TASK_ID_RE.test(id) && !id.includes('..')
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** 处理单个任务:双通道验证 → 写回 result */
|
|
272
|
+
export async function processTask(task: VerifyTask,
|
|
273
|
+
verifyFn: (c: string) => Promise<{ judgment: string; best: string; d_norm: number; record_id: string }>,
|
|
274
|
+
reviewFn: (c: string, w: VerifyResult['whitebox']) => Promise<{ conclusion: string; reason: string }>,
|
|
275
|
+
opts: MutualOptions = DEFAULTS): Promise<VerifyResult | null> {
|
|
276
|
+
const dir = path.join(netDir(opts), 'tasks')
|
|
277
|
+
// P1 修复(GPT 审查):task.id 路径穿越——非法 id 拒绝处理,不写任何文件
|
|
278
|
+
if (!safeTaskId(task.id)) {
|
|
279
|
+
log(opts, `任务 ${JSON.stringify(task.id)} 非法(路径穿越风险),拒绝处理`)
|
|
280
|
+
throw new Error(`非法任务 id: ${task.id}`)
|
|
281
|
+
}
|
|
282
|
+
const taskPath = path.join(dir, `task-${task.id}.json`)
|
|
283
|
+
// P1 完善(GPT 审查·任务竞态):原子 claim——rename task→processing。
|
|
284
|
+
// 多实例同时 scanTasks 读到同一 pending 时,rename 只有一方成功;
|
|
285
|
+
// 失败(文件已被 rename/不存在)= 其他实例正在处理 → 跳过(返回 null)。
|
|
286
|
+
// 此前无锁:多实例都写 processing/result/done,结果互相覆盖。
|
|
287
|
+
const claimPath = path.join(dir, `processing-${task.id}.json`)
|
|
288
|
+
try {
|
|
289
|
+
fs.renameSync(taskPath, claimPath)
|
|
290
|
+
}
|
|
291
|
+
catch {
|
|
292
|
+
return null // 已被其他实例 claim,或文件不存在
|
|
293
|
+
}
|
|
294
|
+
try {
|
|
295
|
+
const w = await whiteboxVerify(task.payload.claim, verifyFn)
|
|
296
|
+
const l = await llmReview(task.payload.claim, w, reviewFn)
|
|
297
|
+
const verdict = combineVerdict(w, l)
|
|
298
|
+
const result: VerifyResult = {
|
|
299
|
+
task_id: task.id,
|
|
300
|
+
verdict,
|
|
301
|
+
whitebox: w,
|
|
302
|
+
llm_review: l,
|
|
303
|
+
reasons: [
|
|
304
|
+
`白箱判定:${w.judgment}(best=${w.best},d_norm=${w.d_norm})`,
|
|
305
|
+
`复核结论:${l.conclusion}`,
|
|
306
|
+
],
|
|
307
|
+
evidence: [task.payload.source_ref || ''].filter(Boolean),
|
|
308
|
+
verifier: 'B',
|
|
309
|
+
at: Date.now() / 1000,
|
|
310
|
+
}
|
|
311
|
+
// 结果先写 tmp 再 rename(原子,防半写文件)
|
|
312
|
+
const resultTmp = path.join(dir, `result-${task.id}.json.tmp`)
|
|
313
|
+
fs.writeFileSync(resultTmp, JSON.stringify(result, null, 2), 'utf-8')
|
|
314
|
+
fs.renameSync(resultTmp, path.join(dir, `result-${task.id}.json`))
|
|
315
|
+
// 完成:清理 claim 文件(rename 回 done 标记供审计)
|
|
316
|
+
fs.renameSync(claimPath, path.join(dir, `done-${task.id}.json`))
|
|
317
|
+
log(opts, `任务 ${task.id} 验证完成:${verdict}`)
|
|
318
|
+
return result
|
|
319
|
+
}
|
|
320
|
+
catch (e) {
|
|
321
|
+
// 处理失败:释放 claim(rename 回 task 供重试)
|
|
322
|
+
try {
|
|
323
|
+
fs.renameSync(claimPath, taskPath)
|
|
324
|
+
}
|
|
325
|
+
catch { /* 文件可能已不在 */ }
|
|
326
|
+
throw e
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// ---------------------------------------------------------------------------
|
|
331
|
+
// 日志 / last_contact
|
|
332
|
+
// ---------------------------------------------------------------------------
|
|
333
|
+
|
|
334
|
+
export function log(opts: MutualOptions, msg: string): void {
|
|
335
|
+
try {
|
|
336
|
+
const p = path.join(netDir(opts), 'mutual.log')
|
|
337
|
+
fs.appendFileSync(p, `[B ${new Date().toISOString()}] ${msg}\n`, 'utf-8')
|
|
338
|
+
} catch { /* 日志失败不阻塞 */ }
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
export function writeLastContact(opts: MutualOptions = DEFAULTS): void {
|
|
342
|
+
try {
|
|
343
|
+
fs.writeFileSync(path.join(netDir(opts), 'last_contact.json'),
|
|
344
|
+
JSON.stringify({ last_contact_b: Date.now() / 1000 }), 'utf-8')
|
|
345
|
+
} catch { /* 非阻塞 */ }
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// ---------------------------------------------------------------------------
|
|
349
|
+
// 安装(ctx.effect 作用域内,卸载时清理)
|
|
350
|
+
// ---------------------------------------------------------------------------
|
|
351
|
+
|
|
352
|
+
export function installMutualMaintenance(
|
|
353
|
+
ctx: { logger: { info(m: string): void }; effect(fn: () => () => void, name?: string): void },
|
|
354
|
+
config: Partial<MutualOptions> = {},
|
|
355
|
+
hooks: {
|
|
356
|
+
verify?: (c: string) => Promise<{ judgment: string; best: string; d_norm: number; record_id: string }>
|
|
357
|
+
review?: (c: string, w: VerifyResult['whitebox']) => Promise<{ conclusion: string; reason: string }>
|
|
358
|
+
} = {},
|
|
359
|
+
): void {
|
|
360
|
+
const opts: MutualOptions = { ...DEFAULTS, ...config }
|
|
361
|
+
|
|
362
|
+
// 1. 心跳写戳 + 守护 A(10min 周期)
|
|
363
|
+
// P1 修复(GPT 审查):cordis-plugin-timer 签名是 interval(callback, delay)
|
|
364
|
+
// ——此前 (ms, fn) 写反:数字被当 callback、函数被当 delay,回调永不执行,
|
|
365
|
+
// 互维心跳/任务扫描实际不工作。
|
|
366
|
+
// P2 修复:不能用 ctx.interval——那是 cordis-plugin-timer 注入的快捷属性,
|
|
367
|
+
// 未声明 `timer` inject 时访问抛 "cannot get property without inject"。
|
|
368
|
+
// 改用 Node 原生 setInterval(互维不需要 Cordis effect 生命周期管理)。
|
|
369
|
+
const heartbeatTimer = setInterval(() => {
|
|
370
|
+
try {
|
|
371
|
+
writeHeartbeat(opts)
|
|
372
|
+
// 守护 A:harness 不在 → 拉起
|
|
373
|
+
ensureHarness('python', opts).then((r) => {
|
|
374
|
+
if (r === 'started') ctx.logger.info(`mutual: 已拉起 A 侧 harness(${r})`)
|
|
375
|
+
})
|
|
376
|
+
// 读 A 戳分级判定
|
|
377
|
+
const a = readHeartbeat('a', opts)
|
|
378
|
+
const verdict = judgeStamp(a, opts)
|
|
379
|
+
if (verdict === 'warning') ctx.logger.info('mutual: A 侧心跳告警(>25min 未更新)')
|
|
380
|
+
if (verdict === 'dead') ctx.logger.info('mutual: A 侧失联(>35min),等待 guardian 自愈或告警')
|
|
381
|
+
writeLastContact(opts)
|
|
382
|
+
} catch (e) { /* 单次失败不中断 */ }
|
|
383
|
+
}, opts.heartbeatMs)
|
|
384
|
+
heartbeatTimer.unref?.()
|
|
385
|
+
|
|
386
|
+
// 2. 任务轮询(30s 周期,检查 A→B 任务)
|
|
387
|
+
const taskTimer = setInterval(() => {
|
|
388
|
+
try {
|
|
389
|
+
const tasks = scanTasks(opts)
|
|
390
|
+
for (const t of tasks) {
|
|
391
|
+
if (!hooks.verify || !hooks.review) continue
|
|
392
|
+
processTask(t, hooks.verify, hooks.review, opts).catch((e) => {
|
|
393
|
+
log(opts, `任务 ${t.id} 处理异常:${String(e)}`)
|
|
394
|
+
})
|
|
395
|
+
}
|
|
396
|
+
} catch (e) { /* 单次失败不中断 */ }
|
|
397
|
+
}, 30_000)
|
|
398
|
+
taskTimer.unref?.()
|
|
399
|
+
|
|
400
|
+
// 3. effect 作用域清理
|
|
401
|
+
ctx.effect(() => {
|
|
402
|
+
return () => {
|
|
403
|
+
try {
|
|
404
|
+
clearInterval(heartbeatTimer)
|
|
405
|
+
clearInterval(taskTimer)
|
|
406
|
+
} catch { /* 清理失败不阻塞 */ }
|
|
407
|
+
}
|
|
408
|
+
}, 'dsh-memory-mutual')
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
export default { installMutualMaintenance, writeHeartbeat, readHeartbeat, judgeStamp, scanTasks, processTask }
|