@furongjun1999/dsh-memory 0.2.8 → 0.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/src/index.ts ADDED
@@ -0,0 +1,237 @@
1
+ /**
2
+ * @furongjun1999/dsh-memory —— 灵枢(AEIS)DeepSeek Harness 插件
3
+ *
4
+ * 把灵枢的时空记忆/知识飞轮/自我认知接入 DSH:
5
+ * - 工具桥接:Agent 可调用 lingshu_remember / recall / search / think 等
6
+ * - 自动记忆:DSH 对话自动沉淀进灵枢记忆库(去重+重要性)
7
+ *
8
+ * 用法(cordis.yml):
9
+ * ```yaml
10
+ * - id: lingshu-memory
11
+ * name: '@furongjun1999/dsh-memory'
12
+ * config:
13
+ * dbPath: 'D:/path/to/lingshu.db'
14
+ * identity: '灵枢'
15
+ * memory:
16
+ * userMessage: true
17
+ * ```
18
+ */
19
+
20
+ import type { Context } from '@deepseek-ai/cordis'
21
+ import z from '@deepseek-ai/schemastery'
22
+ import { LingshuBridge, type McpCallResult } from './bridge.js'
23
+ import { registerLingshuTools, type ToolSelection } from './tools.js'
24
+ import { installMemoryHooks, type MemoryHooksOptions } from './hooks.js'
25
+ import { installRoleplayWeb } from './roleplay_web.js'
26
+
27
+ export const name = 'dsh-memory'
28
+
29
+ /** P1 修复(GPT 审查):MCP 调用的标准结果在 content[].text,
30
+ * 代码此前误读不存在的 .result 字段导致互维拿不到 judgment/best/复核文本 */
31
+ function mcpText(r: McpCallResult): string {
32
+ return (r.content ?? []).map((c) => c.text ?? '').join('\n')
33
+ }
34
+
35
+ /** 本插件依赖的工具注册服务。
36
+ * P1 修复(GPT 审查):timer/webServer 是可选增强(互维/角色网页),此前强声明
37
+ * 导致最小 host(只有 tools)插件永远 PENDING 不激活。只强依赖 tools;
38
+ * timer/webServer 在 apply 内动态检测(存在则启用,缺失则告警跳过)。 */
39
+ export const inject = ['tools']
40
+
41
+ /** 插件配置。 */
42
+ export interface Config {
43
+ /** 工具命名空间前缀(默认 lingshu → lingshu_remember)。 */
44
+ serverName: string
45
+ /** Python 可执行文件(或 aeis-mcp console script)。 */
46
+ python: string
47
+ /** 传给 python 的参数(默认启动灵枢 MCP server)。 */
48
+ moduleArgs: string[]
49
+ /** 灵枢记忆库 SQLite 路径(目录自动创建)。 */
50
+ dbPath: string
51
+ /** 灵枢身份标识(写入记忆的自我模型)。 */
52
+ identity: string
53
+ /** 额外环境变量(BOCHA_API_KEY / AEIS_DESIGNER_KEY 等,可 !!js 注入)。 */
54
+ env: Record<string, string>
55
+ /** 暴露的工具集合:'core' | 'brain' | 'all' | 工具名数组。 */
56
+ tools: ToolSelection
57
+ /** 护栏宪章版本声明(接入即接受宪章约束,docs/guardrail-charter.md)。 */
58
+ charter: string
59
+ /** 自动记忆开关。 */
60
+ memory: MemoryHooksOptions
61
+ /** 单次工具调用超时(毫秒)。 */
62
+ toolCallTimeoutMs: number
63
+ /** 断线重连最大间隔(毫秒)。 */
64
+ maxRetryDelayMs: number
65
+ /** 启动失败是否让插件激活失败(否则告警后继续重试)。 */
66
+ failOnStartupError: boolean
67
+ /** 互维维护(Mutual Sustain Loop v1.1):心跳写戳 + 守护 A + 任务验证。 */
68
+ mutual: {
69
+ enabled: boolean
70
+ heartbeatMs: number
71
+ }
72
+ }
73
+
74
+ export const Config: z<Config> = z.object({
75
+ serverName: z.string().default('lingshu'),
76
+ python: z.string().default('python'),
77
+ moduleArgs: z.array(String).default(['-m', 'aeis.mcp.server']),
78
+ dbPath: z.string().default('data/lingshu.db'),
79
+ identity: z.string().default('灵枢'),
80
+ env: z.dict(String).default({}),
81
+ tools: z.union([z.const('core'), z.const('brain'), z.const('all'), z.array(String)]).default('brain'),
82
+ /** 护栏宪章版本声明(接入即接受宪章约束,docs/guardrail-charter.md)。 */
83
+ charter: z.string().default('v2.0-published'),
84
+ memory: z
85
+ .object({
86
+ userMessage: z.boolean().default(true),
87
+ assistantMessage: z.boolean().default(false),
88
+ toolResult: z.boolean().default(false),
89
+ importance: z.number().default(0.6),
90
+ autoRecall: z.boolean().default(true),
91
+ autoRecallLimit: z.number().default(4),
92
+ desensitize: z.boolean().default(true),
93
+ })
94
+ .default({ userMessage: true, assistantMessage: false, toolResult: false, importance: 0.6, autoRecall: true, autoRecallLimit: 4, desensitize: true }),
95
+ toolCallTimeoutMs: z.number().default(60_000),
96
+ maxRetryDelayMs: z.number().default(30_000),
97
+ failOnStartupError: z.boolean().default(false),
98
+ /** 互维维护(v1.1):心跳 10min / 任务验证双通道。 */
99
+ mutual: z
100
+ .object({
101
+ enabled: z.boolean().default(false),
102
+ heartbeatMs: z.number().default(10 * 60 * 1000),
103
+ })
104
+ .default({ enabled: false, heartbeatMs: 10 * 60 * 1000 }),
105
+ })
106
+
107
+ /**
108
+ * 插件激活:启动灵枢子进程 → 注册工具 → 安装自动记忆钩子。
109
+ * 卸载时清理全部资源(effect 作用域内自动回收)。
110
+ */
111
+ export async function apply(ctx: Context, config: Config): Promise<void> {
112
+ // 宪章宣告(接入即接受宪章约束——docs/guardrail-charter.md v2.0-published)
113
+ ctx.logger.info(
114
+ `dsh-memory: 灵枢插件激活(大脑模式)· 接受护栏宪章 ${config.charter} —— ` +
115
+ '接入即接受宪章约束(公开/可执行/可审计/设计者终裁)',
116
+ )
117
+ const bridge = new LingshuBridge({
118
+ python: config.python,
119
+ args: config.moduleArgs,
120
+ env: {
121
+ AEIS_DB: config.dbPath,
122
+ AEIS_IDENTITY: config.identity,
123
+ ...config.env,
124
+ },
125
+ timeoutMs: config.toolCallTimeoutMs,
126
+ maxRetryDelayMs: config.maxRetryDelayMs,
127
+ })
128
+ bridge.start()
129
+ const ready = await bridge.waitReady()
130
+ if (!ready) {
131
+ const message = '灵枢进程无法启动(检查 python 是否可用、aeis 是否安装:pip install aeis)'
132
+ if (config.failOnStartupError) {
133
+ // P1 修复(GPT 审查):启动失败抛错前必须 dispose——此前 throw 在 try 之前,
134
+ // 桥接对象泄漏 + 后台重试计时器继续跑
135
+ bridge.dispose()
136
+ throw new Error(message)
137
+ }
138
+ ctx.logger.warn(`dsh-memory: ${message},继续后台重试`)
139
+ }
140
+
141
+ const disposers: Array<() => void> = []
142
+ let toolsPoll: NodeJS.Timeout | null = null
143
+ try {
144
+ // 工具注册:初始就绪立即注册;若启动时未就绪(python 暂不可用/aeis 未装等
145
+ // 竞态),桥重连成功后自动补注册——修复"工具永久缺失"问题。
146
+ let toolsRegistered = false
147
+ const tryRegister = async () => {
148
+ if (toolsRegistered || !bridge.isReady()) return
149
+ try {
150
+ const dispose = await registerLingshuTools(ctx, bridge, {
151
+ selection: config.tools,
152
+ toolPrefix: `${config.serverName}_`,
153
+ })
154
+ disposers.push(dispose)
155
+ toolsRegistered = true
156
+ // P1 修复(GPT 审查):注册成功后清除轮询——此前 setInterval 永久保留
157
+ if (toolsPoll) {
158
+ clearInterval(toolsPoll)
159
+ toolsPoll = null
160
+ }
161
+ ctx.logger.info('dsh-memory: 灵枢工具已注册(就绪后补注册)')
162
+ }
163
+ catch (err) {
164
+ ctx.logger.warn(`dsh-memory: 工具注册失败,稍后重试: ${String(err)}`)
165
+ }
166
+ }
167
+ if (ready) await tryRegister()
168
+ if (!toolsRegistered) {
169
+ toolsPoll = setInterval(() => { void tryRegister() }, 2000)
170
+ disposers.push(() => { if (toolsPoll) clearInterval(toolsPoll) })
171
+ }
172
+ installMemoryHooks(ctx, bridge, config.memory)
173
+ // 角色扮演网页(同源挂载 /roleplay,复用本插件 bridge)
174
+ await installRoleplayWeb(ctx, bridge, config, disposers)
175
+
176
+ // 互维维护(v1.1):心跳写戳 + 守护 A + 任务验证双通道
177
+ if (config.mutual.enabled) {
178
+ // P1 修复(GPT 审查):timer 是可选服务——缺失时告警跳过互维,
179
+ // 不让插件因互维而阻塞(inject 已不再强声明 timer)
180
+ const hasTimer = (ctx as { timer?: unknown }).timer !== undefined
181
+ if (!hasTimer) {
182
+ ctx.logger.warn('dsh-memory: timer 服务不可用,跳过互维维护(mutual.enabled=true 但无 timer)')
183
+ } else {
184
+ const { installMutualMaintenance } = await import('./mutual.js')
185
+ // 双通道 hooks:白箱 base_verify(走 bridge 调灵枢)+ DeepSeek 复核
186
+ installMutualMaintenance(
187
+ ctx as never,
188
+ { heartbeatMs: config.mutual.heartbeatMs },
189
+ {
190
+ verify: async (claim: string) => {
191
+ const r = await bridge.callTool('wisdom_verify', { knowledge: claim, limit: 4 })
192
+ // P1 修复(GPT 审查):结果在 content[].text(JSON),非 .result
193
+ const text = mcpText(r)
194
+ let data: { judgment?: string; best?: { name?: string }; D_norm?: number; record_id?: string } = {}
195
+ try {
196
+ data = JSON.parse(text) as typeof data
197
+ } catch { /* 非 JSON 时用默认 */ }
198
+ return {
199
+ judgment: data.judgment ?? '分析中',
200
+ best: data.best?.name ?? '',
201
+ d_norm: typeof data.D_norm === 'number' ? data.D_norm : -1,
202
+ record_id: data.record_id ?? '',
203
+ }
204
+ },
205
+ review: async (claim: string, w) => {
206
+ // DeepSeek 复核(在白箱判定之上,不重复白箱工作)
207
+ const reviewResult = await bridge.callTool('think', {
208
+ query: `复核以下主张(白箱判定已给出,请独立评估是否同意):${claim.slice(0, 200)}。白箱判定:${w.judgment},best=${w.best}。只输出 同意/质疑/不同意 + 一句话理由`,
209
+ })
210
+ // P1 修复(GPT 审查):文本在 content[].text;结论解析必须先查
211
+ // 「不同意/不通过」再「质疑」再「同意」——「不同意」含子串「同意」,
212
+ // 此前先匹配「同意」→ 不同意被误判为同意
213
+ const text = mcpText(reviewResult)
214
+ const conclusion = text.includes('不同意') || text.includes('不通过')
215
+ ? '不同意'
216
+ : text.includes('质疑') ? '质疑'
217
+ : text.includes('同意') ? '同意' : '不同意'
218
+ return { conclusion, reason: text.slice(0, 120) }
219
+ },
220
+ },
221
+ )
222
+ ctx.logger.info('dsh-memory: 互维维护已启用(心跳 10min + 守护 A + 任务验证双通道)')
223
+ }
224
+ }
225
+ } catch (err) {
226
+ bridge.dispose()
227
+ throw err
228
+ }
229
+
230
+ ctx.effect(() => {
231
+ return () => {
232
+ for (const dispose of disposers) dispose()
233
+ bridge.dispose()
234
+ ctx.logger.info('dsh-memory: 已卸载(工具已注销,灵枢进程已退出)')
235
+ }
236
+ }, 'dsh-memory')
237
+ }
package/src/mutual.ts ADDED
@@ -0,0 +1,401 @@
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
+
19
+ export interface MutualOptions {
20
+ /** 心跳间隔(毫秒),默认 10min */
21
+ heartbeatMs: number
22
+ /** 失联告警阈值(毫秒),默认 25min */
23
+ warnMs: number
24
+ /** 失联重启阈值(毫秒),默认 35min */
25
+ deadMs: number
26
+ /** 任务中豁免倍数,默认 ×2 */
27
+ workingFactor: number
28
+ /** 拉起冷却(毫秒),默认 60s */
29
+ restartCooldownMs: number
30
+ /** 互维网络目录,默认 ~/.lingxu_net */
31
+ netDir: string
32
+ }
33
+
34
+ const DEFAULTS: MutualOptions = {
35
+ heartbeatMs: 10 * 60 * 1000,
36
+ warnMs: 25 * 60 * 1000,
37
+ deadMs: 35 * 60 * 1000,
38
+ workingFactor: 2,
39
+ restartCooldownMs: 60 * 1000,
40
+ netDir: path.join(os.homedir(), '.lingxu_net'),
41
+ }
42
+
43
+ /** 互维网络目录定位 */
44
+ export function netDir(opts: MutualOptions = DEFAULTS): string {
45
+ return opts.netDir
46
+ }
47
+
48
+ // ---------------------------------------------------------------------------
49
+ // 心跳(B 侧写戳)
50
+ // ---------------------------------------------------------------------------
51
+
52
+ export function writeHeartbeat(opts: MutualOptions = DEFAULTS, taskRunning = false): void {
53
+ const dir = netDir(opts)
54
+ fs.mkdirSync(dir, { recursive: true })
55
+ const stamp = {
56
+ ts: Date.now() / 1000,
57
+ pid: process.pid,
58
+ task_running: taskRunning,
59
+ }
60
+ fs.writeFileSync(path.join(dir, 'heartbeat.web.stamp'),
61
+ JSON.stringify(stamp), 'utf-8')
62
+ }
63
+
64
+ export function readHeartbeat(which: 'a' | 'web', opts: MutualOptions = DEFAULTS): {
65
+ ts: number; pid: number; task_running: boolean; ageMs: number
66
+ } | null {
67
+ try {
68
+ const raw = fs.readFileSync(path.join(netDir(opts), `heartbeat.${which}.stamp`), 'utf-8')
69
+ const s = JSON.parse(raw)
70
+ const ageMs = Date.now() - (s.ts as number) * 1000
71
+ return { ts: s.ts, pid: s.pid, task_running: !!s.task_running, ageMs }
72
+ } catch {
73
+ return null
74
+ }
75
+ }
76
+
77
+ /** 失联分级判定(纯函数,A 侧 judge_stamp 的 B 侧镜像) */
78
+ export function judgeStamp(stamp: { ageMs: number; task_running: boolean } | null,
79
+ opts: MutualOptions = DEFAULTS): 'alive' | 'alive_working' | 'warning' | 'dead' | 'no_stamp' {
80
+ if (!stamp) return 'no_stamp'
81
+ const threshold = stamp.task_running ? opts.deadMs * opts.workingFactor : opts.deadMs
82
+ if (stamp.ageMs < opts.warnMs) return 'alive'
83
+ if (stamp.task_running && stamp.ageMs < threshold) return 'alive_working'
84
+ if (stamp.ageMs < threshold) return 'warning'
85
+ return 'dead'
86
+ }
87
+
88
+ // ---------------------------------------------------------------------------
89
+ // 守护 A(检测 harness 进程 + 拉起)
90
+ // ---------------------------------------------------------------------------
91
+
92
+ const HARNESS_PROC = ['python', 'harness.guardian'] // wmic 特征
93
+
94
+ function execP(cmd: string): Promise<string> {
95
+ return new Promise((resolve) => {
96
+ exec(cmd, { windowsHide: true, timeout: 15_000 }, (err, stdout) => {
97
+ resolve(err ? '' : String(stdout))
98
+ })
99
+ })
100
+ }
101
+
102
+ /** 检测 harness 进程是否存在
103
+ * P1 完善(GPT 审查·wmic 兼容):wmic 在 Win11+ 已被移除——失败时
104
+ * fallback PowerShell Get-CimInstance(Win);非 Windows 用 ps 查询。 */
105
+ export async function harnessRunning(): Promise<boolean> {
106
+ if (process.platform === 'win32') {
107
+ // ① wmic(旧 Win10 可用)
108
+ const out = await execP(
109
+ `wmic process where "name='python.exe'" get commandline 2>nul`)
110
+ if (out.includes('harness.guardian') || out.includes('harness.main')) return true
111
+ // ② wmic 不可用(Win11 移除)→ PowerShell
112
+ const psOut = await execP(
113
+ `powershell -NoProfile -Command "Get-CimInstance Win32_Process -Filter \\"name='python.exe'\\" | Select-Object -ExpandProperty CommandLine"`)
114
+ return psOut.includes('harness.guardian') || psOut.includes('harness.main')
115
+ }
116
+ // 非 Windows(Linux/macOS):ps 查询
117
+ const psOut = await execP(`ps -eo command | grep -E 'harness\\.(guardian|main)' | grep -v grep`)
118
+ return !!psOut
119
+ }
120
+
121
+ /** detached 拉起 A 侧 harness.guardian(幂等:先确认不存在) */
122
+ export async function ensureHarness(python = 'python',
123
+ opts: MutualOptions = DEFAULTS): Promise<'started' | 'already' | 'failed'> {
124
+ const running = await harnessRunning()
125
+ if (running) return 'already'
126
+ // P1 修复(GPT 审查):spawn 找不到可执行文件是异步 error 事件,无监听
127
+ // 会直接崩 Node(Unhandled 'error' event)。加监听 + 超时判定拉起失败。
128
+ return new Promise((resolve) => {
129
+ let child: ReturnType<typeof spawn> | null = null
130
+ let failTimer: NodeJS.Timeout | null = null
131
+ let okTimer: NodeJS.Timeout | null = null
132
+ let settled = false
133
+ const finish = (r: 'started' | 'failed'): void => {
134
+ if (settled) return
135
+ settled = true
136
+ if (failTimer) clearTimeout(failTimer)
137
+ if (okTimer) clearTimeout(okTimer)
138
+ resolve(r)
139
+ }
140
+ try {
141
+ child = spawn(python, ['-m', 'harness.guardian'], {
142
+ windowsHide: true,
143
+ detached: true,
144
+ stdio: 'ignore',
145
+ })
146
+ } catch (e) {
147
+ log(opts, `守护失败:${String(e)}`)
148
+ finish('failed')
149
+ return
150
+ }
151
+ // 拉起失败(python 不存在等)→ 记录 + failed,不崩 Node。
152
+ // spawn 的 error 事件是异步的:不能立即判 started——等 50ms error 窗口,
153
+ // 无 error 才算拉起成功(GPT 审查:此前立即返回 started,错误路径也报成功)。
154
+ child.on('error', (err) => {
155
+ log(opts, `守护拉起错误:${err.message}`)
156
+ finish('failed')
157
+ })
158
+ // 拉起成功但立即退出(harness.guardian 不存在)→ failed
159
+ child.on('exit', (code) => {
160
+ if (code !== null && code !== 0) {
161
+ log(opts, `守护进程退出 code=${code}(guardian 可能不可用)`)
162
+ finish('failed')
163
+ }
164
+ })
165
+ okTimer = setTimeout(() => finish('started'), 50)
166
+ failTimer = setTimeout(() => {
167
+ log(opts, `守护拉起超时(10s 无健康确认)`)
168
+ finish('failed')
169
+ }, 10_000)
170
+ child.unref()
171
+ log(opts, `守护动作:拉起 harness.guardian(pid=${child.pid ?? '?'})`)
172
+ })
173
+ }
174
+
175
+ // ---------------------------------------------------------------------------
176
+ // 任务验证邮箱(双通道:白箱 base_verify + DeepSeek 复核)
177
+ // ---------------------------------------------------------------------------
178
+
179
+ export interface VerifyTask {
180
+ id: string
181
+ type: 'verify' | 'knowledge_sync'
182
+ from: 'A' | 'B'
183
+ to: 'B' | 'A'
184
+ payload: { claim: string; evidence?: string; expected?: string; source_ref?: string }
185
+ status: 'pending' | 'processing' | 'done'
186
+ created_at: number
187
+ }
188
+
189
+ export interface VerifyResult {
190
+ task_id: string
191
+ verdict: 'pass' | 'fail' | 'needs_revision'
192
+ whitebox: { judgment: string; best: string; d_norm: number; record_id: string }
193
+ llm_review: { conclusion: string; reason: string }
194
+ reasons: string[]
195
+ evidence: string[]
196
+ verifier: 'B'
197
+ at: number
198
+ }
199
+
200
+ /** 扫描互维目录里 A→B 的 pending 任务 */
201
+ export function scanTasks(opts: MutualOptions = DEFAULTS): VerifyTask[] {
202
+ const dir = path.join(netDir(opts), 'tasks')
203
+ if (!fs.existsSync(dir)) return []
204
+ const out: VerifyTask[] = []
205
+ for (const f of fs.readdirSync(dir)) {
206
+ if (!f.startsWith('task-') || !f.endsWith('.json')) continue
207
+ try {
208
+ const t = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf-8'))
209
+ if (t.to === 'B' && t.status === 'pending') out.push(t)
210
+ } catch { /* 跳过坏文件 */ }
211
+ }
212
+ return out
213
+ }
214
+
215
+ /** 白箱通道:智慧之书 base_verify(通过 bridge 调用,或本地注入) */
216
+ export async function whiteboxVerify(claim: string,
217
+ verifyFn: (c: string) => Promise<{ judgment: string; best: string; d_norm: number; record_id: string }>): Promise<VerifyResult['whitebox']> {
218
+ try {
219
+ return await verifyFn(claim)
220
+ } catch (e) {
221
+ return { judgment: `whitebox_error: ${String(e)}`, best: '', d_norm: -1, record_id: '' }
222
+ }
223
+ }
224
+
225
+ /** 复核通道:DeepSeek 独立复核(在白箱判定之上) */
226
+ export async function llmReview(claim: string, whitebox: VerifyResult['whitebox'],
227
+ reviewFn: (c: string, w: VerifyResult['whitebox']) => Promise<{ conclusion: string; reason: string }>): Promise<VerifyResult['llm_review']> {
228
+ try {
229
+ return await reviewFn(claim, whitebox)
230
+ } catch (e) {
231
+ return { conclusion: `llm_error: ${String(e)}`, reason: '' }
232
+ }
233
+ }
234
+
235
+ /** 综合 verdict(白箱优先) */
236
+ export function combineVerdict(w: VerifyResult['whitebox'],
237
+ l: VerifyResult['llm_review']): VerifyResult['verdict'] {
238
+ const c = l.conclusion || ''
239
+ // P1 修复(GPT 审查):白箱通道异常 → fail-closed(不因复核「同意」而 pass)
240
+ if (w.judgment.startsWith('whitebox_error') || w.judgment.startsWith('llm_error')
241
+ || w.d_norm < 0) {
242
+ return 'needs_revision'
243
+ }
244
+ if (w.judgment.startsWith('采纳')) {
245
+ // 白箱采纳:复核质疑/不同意→needs_revision(白箱优先,记录分歧);否则 pass
246
+ return c.includes('质疑') || c.includes('不同意') || c.includes('不通过')
247
+ ? 'needs_revision' : 'pass'
248
+ }
249
+ if (w.judgment.includes('fail') || w.judgment.includes('不成立')) return 'fail'
250
+ // 证据不足/无法判断 → 白箱不确定,交给复核决定(「不同意」须排除「同意」子串)
251
+ if (c.includes('不同意') || c.includes('不通过')) return 'needs_revision'
252
+ if (c.includes('通过') || c.includes('同意')) return 'pass'
253
+ // P1 修复(GPT 审查):「质疑」是分歧信号——白箱不确定 + 复核质疑 → 需要修订,
254
+ // 此前把「质疑」当 pass 与白箱采纳分支语义矛盾。
255
+ if (c.includes('质疑')) return 'needs_revision'
256
+ return 'needs_revision'
257
+ }
258
+
259
+ /** 任务 ID 安全校验(P1 修复:防路径穿越——task.id 可含 ../../ 写目录外) */
260
+ const TASK_ID_RE = /^[A-Za-z0-9._-]{1,64}$/
261
+
262
+ export function safeTaskId(id: string): boolean {
263
+ return TASK_ID_RE.test(id) && !id.includes('..')
264
+ }
265
+
266
+ /** 处理单个任务:双通道验证 → 写回 result */
267
+ export async function processTask(task: VerifyTask,
268
+ verifyFn: (c: string) => Promise<{ judgment: string; best: string; d_norm: number; record_id: string }>,
269
+ reviewFn: (c: string, w: VerifyResult['whitebox']) => Promise<{ conclusion: string; reason: string }>,
270
+ opts: MutualOptions = DEFAULTS): Promise<VerifyResult | null> {
271
+ const dir = path.join(netDir(opts), 'tasks')
272
+ // P1 修复(GPT 审查):task.id 路径穿越——非法 id 拒绝处理,不写任何文件
273
+ if (!safeTaskId(task.id)) {
274
+ log(opts, `任务 ${JSON.stringify(task.id)} 非法(路径穿越风险),拒绝处理`)
275
+ throw new Error(`非法任务 id: ${task.id}`)
276
+ }
277
+ const taskPath = path.join(dir, `task-${task.id}.json`)
278
+ // P1 完善(GPT 审查·任务竞态):原子 claim——rename task→processing。
279
+ // 多实例同时 scanTasks 读到同一 pending 时,rename 只有一方成功;
280
+ // 失败(文件已被 rename/不存在)= 其他实例正在处理 → 跳过(返回 null)。
281
+ // 此前无锁:多实例都写 processing/result/done,结果互相覆盖。
282
+ const claimPath = path.join(dir, `processing-${task.id}.json`)
283
+ try {
284
+ fs.renameSync(taskPath, claimPath)
285
+ }
286
+ catch {
287
+ return null // 已被其他实例 claim,或文件不存在
288
+ }
289
+ try {
290
+ const w = await whiteboxVerify(task.payload.claim, verifyFn)
291
+ const l = await llmReview(task.payload.claim, w, reviewFn)
292
+ const verdict = combineVerdict(w, l)
293
+ const result: VerifyResult = {
294
+ task_id: task.id,
295
+ verdict,
296
+ whitebox: w,
297
+ llm_review: l,
298
+ reasons: [
299
+ `白箱判定:${w.judgment}(best=${w.best},d_norm=${w.d_norm})`,
300
+ `复核结论:${l.conclusion}`,
301
+ ],
302
+ evidence: [task.payload.source_ref || ''].filter(Boolean),
303
+ verifier: 'B',
304
+ at: Date.now() / 1000,
305
+ }
306
+ // 结果先写 tmp 再 rename(原子,防半写文件)
307
+ const resultTmp = path.join(dir, `result-${task.id}.json.tmp`)
308
+ fs.writeFileSync(resultTmp, JSON.stringify(result, null, 2), 'utf-8')
309
+ fs.renameSync(resultTmp, path.join(dir, `result-${task.id}.json`))
310
+ // 完成:清理 claim 文件(rename 回 done 标记供审计)
311
+ fs.renameSync(claimPath, path.join(dir, `done-${task.id}.json`))
312
+ log(opts, `任务 ${task.id} 验证完成:${verdict}`)
313
+ return result
314
+ }
315
+ catch (e) {
316
+ // 处理失败:释放 claim(rename 回 task 供重试)
317
+ try {
318
+ fs.renameSync(claimPath, taskPath)
319
+ }
320
+ catch { /* 文件可能已不在 */ }
321
+ throw e
322
+ }
323
+ }
324
+
325
+ // ---------------------------------------------------------------------------
326
+ // 日志 / last_contact
327
+ // ---------------------------------------------------------------------------
328
+
329
+ export function log(opts: MutualOptions, msg: string): void {
330
+ try {
331
+ const p = path.join(netDir(opts), 'mutual.log')
332
+ fs.appendFileSync(p, `[B ${new Date().toISOString()}] ${msg}\n`, 'utf-8')
333
+ } catch { /* 日志失败不阻塞 */ }
334
+ }
335
+
336
+ export function writeLastContact(opts: MutualOptions = DEFAULTS): void {
337
+ try {
338
+ fs.writeFileSync(path.join(netDir(opts), 'last_contact.json'),
339
+ JSON.stringify({ last_contact_b: Date.now() / 1000 }), 'utf-8')
340
+ } catch { /* 非阻塞 */ }
341
+ }
342
+
343
+ // ---------------------------------------------------------------------------
344
+ // 安装(ctx.effect 作用域内,卸载时清理)
345
+ // ---------------------------------------------------------------------------
346
+
347
+ export function installMutualMaintenance(
348
+ ctx: { logger: { info(m: string): void }; interval(fn: () => void, ms: number): () => void; effect(fn: () => () => void, name?: string): void },
349
+ config: Partial<MutualOptions> = {},
350
+ hooks: {
351
+ verify?: (c: string) => Promise<{ judgment: string; best: string; d_norm: number; record_id: string }>
352
+ review?: (c: string, w: VerifyResult['whitebox']) => Promise<{ conclusion: string; reason: string }>
353
+ } = {},
354
+ ): void {
355
+ const opts: MutualOptions = { ...DEFAULTS, ...config }
356
+
357
+ // 1. 心跳写戳 + 守护 A(10min 周期)
358
+ // P1 修复(GPT 审查):cordis-plugin-timer 签名是 interval(callback, delay)
359
+ // ——此前 (ms, fn) 写反:数字被当 callback、函数被当 delay,回调永不执行,
360
+ // 互维心跳/任务扫描实际不工作。
361
+ const heartbeatDispose = ctx.interval(() => {
362
+ try {
363
+ writeHeartbeat(opts)
364
+ // 守护 A:harness 不在 → 拉起
365
+ ensureHarness('python', opts).then((r) => {
366
+ if (r === 'started') ctx.logger.info(`mutual: 已拉起 A 侧 harness(${r})`)
367
+ })
368
+ // 读 A 戳分级判定
369
+ const a = readHeartbeat('a', opts)
370
+ const verdict = judgeStamp(a, opts)
371
+ if (verdict === 'warning') ctx.logger.info('mutual: A 侧心跳告警(>25min 未更新)')
372
+ if (verdict === 'dead') ctx.logger.info('mutual: A 侧失联(>35min),等待 guardian 自愈或告警')
373
+ writeLastContact(opts)
374
+ } catch (e) { /* 单次失败不中断 */ }
375
+ }, opts.heartbeatMs)
376
+
377
+ // 2. 任务轮询(30s 周期,检查 A→B 任务)
378
+ const taskDispose = ctx.interval(() => {
379
+ try {
380
+ const tasks = scanTasks(opts)
381
+ for (const t of tasks) {
382
+ if (!hooks.verify || !hooks.review) continue
383
+ processTask(t, hooks.verify, hooks.review, opts).catch((e) => {
384
+ log(opts, `任务 ${t.id} 处理异常:${String(e)}`)
385
+ })
386
+ }
387
+ } catch (e) { /* 单次失败不中断 */ }
388
+ }, 30_000)
389
+
390
+ // 3. effect 作用域清理
391
+ ctx.effect(() => {
392
+ return () => {
393
+ try {
394
+ heartbeatDispose()
395
+ taskDispose()
396
+ } catch { /* 清理失败不阻塞 */ }
397
+ }
398
+ }, 'dsh-memory-mutual')
399
+ }
400
+
401
+ export default { installMutualMaintenance, writeHeartbeat, readHeartbeat, judgeStamp, scanTasks, processTask }