memgate 0.0.0-stage → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +12 -0
- package/README.md +52 -2
- package/VERSIONS.json +17 -0
- package/dist/index.js +726 -0
- package/index.ts +25 -0
- package/openclaw.plugin.json +53 -0
- package/package.json +37 -3
- package/src/admission.py +208 -0
- package/src/bridge.ts +205 -0
- package/src/bridge_cli.py +600 -0
- package/src/context-engine.ts +373 -0
- package/src/hebbian_link.py +34 -0
- package/src/kernel/activity_telemetry.py +51 -0
- package/src/kernel/admission.py +208 -0
- package/src/kernel/calldecay/__init__.py +24 -0
- package/src/kernel/calldecay/__main__.py +7 -0
- package/src/kernel/calldecay/_kernel.py +32 -0
- package/src/kernel/calldecay/adapter.py +126 -0
- package/src/kernel/calldecay/cli.py +80 -0
- package/src/kernel/calldecay/gate.py +93 -0
- package/src/kernel/calldecay/landing.py +1298 -0
- package/src/kernel/calldecay/metrics.py +37 -0
- package/src/kernel/calldecay/mock.py +68 -0
- package/src/kernel/calldecay/pipeline.py +85 -0
- package/src/kernel/calldecay/proxy.py +220 -0
- package/src/kernel/calldecay/summarize.py +401 -0
- package/src/kernel/core/LICENSE +228 -0
- package/src/kernel/core/__init__.py +0 -0
- package/src/kernel/core/accept_contract.py +67 -0
- package/src/kernel/core/chain_probe_world.py +133 -0
- package/src/kernel/core/concept_ontology.py +2401 -0
- package/src/kernel/core/concept_opposition.py +291 -0
- package/src/kernel/core/concept_phase.py +1342 -0
- package/src/kernel/core/concept_principle.py +2481 -0
- package/src/kernel/core/concept_pyramid.py +287 -0
- package/src/kernel/core/concept_space.py +45 -0
- package/src/kernel/core/concept_space_mixin.py +941 -0
- package/src/kernel/core/concept_state.py +2748 -0
- package/src/kernel/core/decision_symbolic.py +245 -0
- package/src/kernel/core/eco_math_world.py +489 -0
- package/src/kernel/core/emergence.py +362 -0
- package/src/kernel/core/events.py +93 -0
- package/src/kernel/core/hebbian.py +117 -0
- package/src/kernel/core/llm_arm.py +551 -0
- package/src/kernel/core/memory_shadow.py +158 -0
- package/src/kernel/core/mes_layer_base.py +309 -0
- package/src/kernel/core/mes_vnext.py +540 -0
- package/src/kernel/core/ontology_core.py +168 -0
- package/src/kernel/core/phase_field.py +187 -0
- package/src/kernel/core/reasoning.py +185 -0
- package/src/kernel/core/rhythm_vnext.py +777 -0
- package/src/kernel/dashboard_render.py +196 -0
- package/src/kernel/depscan_probe.py +96 -0
- package/src/kernel/health_probe.py +186 -0
- package/src/kernel/hebbian_link.py +34 -0
- package/src/kernel/knowledge_distiller/README.md +9 -0
- package/src/kernel/knowledge_distiller/__init__.py +1 -0
- package/src/kernel/knowledge_distiller/knowledge_distiller.py +196 -0
- package/src/kernel/m3_judge.py +215 -0
- package/src/kernel/mechanism_advisor.py +203 -0
- package/src/kernel/mechanism_learner.py +193 -0
- package/src/kernel/memory_core.py +81 -0
- package/src/kernel/quality_gate/README.md +9 -0
- package/src/kernel/quality_gate/__init__.py +1 -0
- package/src/kernel/quality_gate/quality_gate.py +7 -0
- package/src/kernel/registry_gate.py +57 -0
- package/src/kernel/semantic_recall.py +635 -0
- package/src/kernel/tiered_decay/README.md +9 -0
- package/src/kernel/tiered_decay/__init__.py +1 -0
- package/src/kernel/tiered_decay/tiered_decay.py +17 -0
- package/src/kernel/tokenizer/README.md +9 -0
- package/src/kernel/tokenizer/__init__.py +2 -0
- package/src/kernel/tokenizer/tokenizer.py +14 -0
- package/src/kernel/version_binding.py +131 -0
- package/src/knowledge_distiller.py +196 -0
- package/src/m3_collector.py +247 -0
- package/src/m3_judge.py +215 -0
- package/src/memory-capability.ts +44 -0
- package/src/semantic_recall.py +635 -0
- package/src/thinking_stub.ts +141 -0
- package/src/toolface_hook.ts +69 -0
- package/src/tools.ts +98 -0
- package/src/vendor/calldecay-sdk/calldecay/__init__.py +24 -0
- package/src/vendor/calldecay-sdk/calldecay/__main__.py +7 -0
- package/src/vendor/calldecay-sdk/calldecay/_kernel.py +32 -0
- package/src/vendor/calldecay-sdk/calldecay/adapter.py +126 -0
- package/src/vendor/calldecay-sdk/calldecay/cli.py +80 -0
- package/src/vendor/calldecay-sdk/calldecay/gate.py +93 -0
- package/src/vendor/calldecay-sdk/calldecay/landing.py +1298 -0
- package/src/vendor/calldecay-sdk/calldecay/metrics.py +37 -0
- package/src/vendor/calldecay-sdk/calldecay/mock.py +68 -0
- package/src/vendor/calldecay-sdk/calldecay/pipeline.py +85 -0
- package/src/vendor/calldecay-sdk/calldecay/proxy.py +220 -0
- package/src/vendor/calldecay-sdk/calldecay/summarize.py +401 -0
- package/src/vendor/core/LICENSE +228 -0
- package/src/vendor/core/__init__.py +0 -0
- package/src/vendor/core/accept_contract.py +67 -0
- package/src/vendor/core/chain_probe_world.py +133 -0
- package/src/vendor/core/concept_ontology.py +2401 -0
- package/src/vendor/core/concept_opposition.py +291 -0
- package/src/vendor/core/concept_phase.py +1342 -0
- package/src/vendor/core/concept_principle.py +2481 -0
- package/src/vendor/core/concept_pyramid.py +287 -0
- package/src/vendor/core/concept_space.py +45 -0
- package/src/vendor/core/concept_space_mixin.py +941 -0
- package/src/vendor/core/concept_state.py +2748 -0
- package/src/vendor/core/decision_symbolic.py +245 -0
- package/src/vendor/core/eco_math_world.py +489 -0
- package/src/vendor/core/emergence.py +362 -0
- package/src/vendor/core/events.py +93 -0
- package/src/vendor/core/hebbian.py +117 -0
- package/src/vendor/core/llm_arm.py +551 -0
- package/src/vendor/core/memory_shadow.py +158 -0
- package/src/vendor/core/mes_layer_base.py +309 -0
- package/src/vendor/core/mes_vnext.py +540 -0
- package/src/vendor/core/ontology_core.py +168 -0
- package/src/vendor/core/phase_field.py +187 -0
- package/src/vendor/core/reasoning.py +185 -0
- package/src/vendor/core/rhythm_vnext.py +777 -0
- package/src/vendor/pvs-sdk/pvs/__init__.py +0 -0
- package/src/vendor/pvs-sdk/pvs/adapters/__init__.py +0 -0
- package/src/vendor/pvs-sdk/pvs/adapters/llm_backends.py +69 -0
- package/src/vendor/pvs-sdk/pvs/core/__init__.py +0 -0
- package/src/vendor/pvs-sdk/pvs/core/budget.py +84 -0
- package/src/vendor/pvs-sdk/pvs/core/llm_gate.py +149 -0
- package/src/vendor/pvs-sdk/pvs/core/memory.py +143 -0
- package/src/vendor/pvs-sdk/pvs/core/pvs.py +175 -0
- package/src/vendor/pvs-sdk/pvs/core/verifier.py +77 -0
- package/src/vendor/pvs-sdk/pvs/eval/__init__.py +3 -0
- package/src/vendor/pvs-sdk/pvs/eval/coverage.py +82 -0
- package/src/vendor/pvs-sdk/pvs/gate/__init__.py +5 -0
- package/src/vendor/pvs-sdk/pvs/gate/__main__.py +3 -0
- package/src/vendor/pvs-sdk/pvs/gate/boot.py +68 -0
- package/src/vendor/pvs-sdk/pvs/gate/ledger.py +157 -0
- package/src/vendor/pvs-sdk/pvs/gate/preflight.py +342 -0
- package/src/vendor/pvs-sdk/pvs/harness/__init__.py +0 -0
package/index.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// index.ts — 通用治理中间件 OpenClaw 插件入口(骨架 v0.1)
|
|
2
|
+
// 三面注册:context-engine(三层记忆)+ memory(账本摘要)+ tools(治理四件)。
|
|
3
|
+
// 单源原则:业务逻辑全在 Python(LandingStore/pvs.gate/accept_contract),TS 只做调用面。
|
|
4
|
+
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
|
5
|
+
import type { OpenClawPluginApi } from "openclaw/plugin-sdk/core";
|
|
6
|
+
import { registerGovernanceTools } from "./src/tools.js";
|
|
7
|
+
import { registerGovernanceContextEngine } from "./src/context-engine.js";
|
|
8
|
+
import { registerGovernanceMemory } from "./src/memory-capability.js";
|
|
9
|
+
import { registerToolfaceHook } from "./src/toolface_hook.js";
|
|
10
|
+
import type { BridgeConfig } from "./src/bridge.js";
|
|
11
|
+
|
|
12
|
+
export default definePluginEntry({
|
|
13
|
+
id: "memgate",
|
|
14
|
+
name: "MemGate",
|
|
15
|
+
description:
|
|
16
|
+
"Three-layer memory (hot/warm/cold) + governance gate tools, bridged to the Python single-source.",
|
|
17
|
+
register(api: OpenClawPluginApi) {
|
|
18
|
+
// 插件配置面(sdk-setup.md: 配置经 api.pluginConfig 下发;形状对齐 manifest configSchema)
|
|
19
|
+
const cfg = ((api as any).pluginConfig ?? {}) as BridgeConfig;
|
|
20
|
+
registerGovernanceTools(api, cfg);
|
|
21
|
+
registerGovernanceContextEngine(api, cfg);
|
|
22
|
+
registerGovernanceMemory(api, cfg);
|
|
23
|
+
registerToolfaceHook(api, cfg); // P4 动态工具面(gate.toolfaceHook 开关,默认关)
|
|
24
|
+
},
|
|
25
|
+
});
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "memgate",
|
|
3
|
+
"name": "MemGate",
|
|
4
|
+
"description": "Three-layer memory (hot/warm/cold) + governance gate tools, bridged to the Python single-source (CallDecay LandingStore + pvs.gate + accept_contract). Delegating compaction mode: official engine is the safety net.",
|
|
5
|
+
"version": "0.1.2",
|
|
6
|
+
"kind": [
|
|
7
|
+
"memory",
|
|
8
|
+
"context-engine"
|
|
9
|
+
],
|
|
10
|
+
"categories": [
|
|
11
|
+
"memory"
|
|
12
|
+
],
|
|
13
|
+
"contracts": {
|
|
14
|
+
"tools": [
|
|
15
|
+
"governance_preflight",
|
|
16
|
+
"governance_ledger",
|
|
17
|
+
"governance_deposit",
|
|
18
|
+
"governance_recall"
|
|
19
|
+
]
|
|
20
|
+
},
|
|
21
|
+
"activation": {
|
|
22
|
+
"onStartup": true
|
|
23
|
+
},
|
|
24
|
+
"configSchema": {
|
|
25
|
+
"type": "object",
|
|
26
|
+
"additionalProperties": false,
|
|
27
|
+
"properties": {
|
|
28
|
+
"pythonBin": {
|
|
29
|
+
"type": "string",
|
|
30
|
+
"default": "python3"
|
|
31
|
+
},
|
|
32
|
+
"workspaceRoot": {
|
|
33
|
+
"type": "string"
|
|
34
|
+
},
|
|
35
|
+
"landingPath": {
|
|
36
|
+
"type": "string"
|
|
37
|
+
},
|
|
38
|
+
"bridgePath": {
|
|
39
|
+
"type": "string"
|
|
40
|
+
},
|
|
41
|
+
"hotWindowMessages": {
|
|
42
|
+
"type": "integer",
|
|
43
|
+
"default": 12,
|
|
44
|
+
"minimum": 1
|
|
45
|
+
},
|
|
46
|
+
"coldStartTokenBudget": {
|
|
47
|
+
"type": "integer",
|
|
48
|
+
"default": 20000,
|
|
49
|
+
"minimum": 2000
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "memgate",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.2",
|
|
4
|
+
"description": "OpenClaw governance middleware: three-layer memory (hot/warm/cold) + gate tools, bridged to the Python single-source (CallDecay LandingStore / pvs.gate / accept_contract).",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "SEE LICENSE IN LICENSE",
|
|
7
|
+
"files": [
|
|
8
|
+
"index.ts",
|
|
9
|
+
"dist/",
|
|
10
|
+
"openclaw.plugin.json",
|
|
11
|
+
"src/",
|
|
12
|
+
"VERSIONS.json",
|
|
13
|
+
"README.md",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"typebox": "1.3.18"
|
|
18
|
+
},
|
|
19
|
+
"peerDependencies": {
|
|
20
|
+
"openclaw": ">=2026.9.4"
|
|
21
|
+
},
|
|
22
|
+
"openclaw": {
|
|
23
|
+
"extensions": [
|
|
24
|
+
"./index.ts"
|
|
25
|
+
],
|
|
26
|
+
"compat": {
|
|
27
|
+
"pluginApi": ">=2026.9.4",
|
|
28
|
+
"minGatewayVersion": "2026.9.4"
|
|
29
|
+
},
|
|
30
|
+
"build": {
|
|
31
|
+
"openclawVersion": "2026.9.4",
|
|
32
|
+
"pluginSdkVersion": "2026.9.4"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"repository": {
|
|
36
|
+
"type": "git",
|
|
37
|
+
"url": "git+https://github.com/lipin007/memsteward.git"
|
|
38
|
+
},
|
|
39
|
+
"homepage": "https://github.com/lipin007/memsteward"
|
|
6
40
|
}
|
package/src/admission.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""admission —— MemGate 写入侧准入过滤(五病成熟度缺口 #1:治「回声污染合格面」)。
|
|
3
|
+
|
|
4
|
+
设计原则
|
|
5
|
+
- 不注≠删:**绝不删除任何既有条目**。本模块只判新写入(拒收/隔离);
|
|
6
|
+
既有条目只由 `quarantine-mark` 子命令**显式 opt-in** 打标记(默认 dry-run)。
|
|
7
|
+
- 拒收(reject)=确定性横幅/信封残片——剥掉已知传输铬后残余 < REJECT_RESIDUAL_MAX,
|
|
8
|
+
这类文本不是记忆内容而是传输外壳,写入即污染,返回明确原因。
|
|
9
|
+
- 隔离(quarantine)=疑似回声/污染——收下写入但打 `admit="quarantine"` 标记,
|
|
10
|
+
默认出召回合格面;审计面(--include-transcripts / --audit-quarantine)可查。
|
|
11
|
+
|
|
12
|
+
垃圾模式清单(全部实据锚定,见 experiments/对照臂_20261112/ledger_copy.json;
|
|
13
|
+
计数可由 experiments/写入准入_20261112/pattern_scan.py 重跑):
|
|
14
|
+
inter_session_envelope [Inter-session message] 传输信封头
|
|
15
|
+
实据 b6b9f025 / 9fa9ac6e / d08e657f / c2184276(summary 体)
|
|
16
|
+
exec_completion_banner [OpenClaw exec completion] 运行横幅
|
|
17
|
+
实据 318ae811(body=「OpenClaw」即该横幅的词汤摘要)
|
|
18
|
+
session_event_banner [OpenClaw session event] 会话事件横幅
|
|
19
|
+
实据 5d53c6d0 / b7e9974e(commitTurn/ingest 转录)
|
|
20
|
+
subagent_context_banner [Subagent Context] 子代理上下文横幅
|
|
21
|
+
实据 807432dd / 5d2db2bc
|
|
22
|
+
internal_context_tag <<<BEGIN/END_OPENCLAW_INTERNAL_CONTEXT>>> 信封头尾标签
|
|
23
|
+
实据 ffe0d935(body 词汤含 BEGIN_/END_ 残片)
|
|
24
|
+
prompt_data_tag <prompt-data> 传输信封标签(任务给定;
|
|
25
|
+
账本字面 0 命中——负结果照登,防御性收录)
|
|
26
|
+
section_banner ===X=== 分节横幅(===GAMEARG=== / ===END=== 实据
|
|
27
|
+
aca974bc / 0825ca4e;===LOG===/===CURL===/===GIT===
|
|
28
|
+
同族但账本 0 命中——负结果照登)
|
|
29
|
+
envelope_header_fields sourceSession=/sourceChannel=/sourceTool=/isUser= 信封字段
|
|
30
|
+
实据同 inter_session 族
|
|
31
|
+
envelope_key_token sourceSession 等裸键名词汤(无 = 值)
|
|
32
|
+
实据 b6b9f025 body 词汤
|
|
33
|
+
routed_boilerplate This content was routed by OpenClaw… 路由样板句
|
|
34
|
+
实据 probe_gap24 qi38 题源 / b6b9f025 族
|
|
35
|
+
chrome_word_soup 横幅词序打乱后的词汤(无 CJK 且全部单词落在已知横幅
|
|
36
|
+
词集内)实据 318ae811 signature=「completion OpenClaw exec」
|
|
37
|
+
echo_fragment 超短回声碎片(≤ ECHO_MAX_CHARS 字符)
|
|
38
|
+
实据 0504f503=「测」/ 92626deb=「好」/ 1935b2f8=「那就开测吧」
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
import json
|
|
42
|
+
import re
|
|
43
|
+
import time
|
|
44
|
+
|
|
45
|
+
# 剥铬后残余 < 该值 ⇒ 拒收(确定性残片);≥ 该值 ⇒ 隔离(混了实质内容)
|
|
46
|
+
REJECT_RESIDUAL_MAX = 20
|
|
47
|
+
# 超短回声碎片阈(实据最大 5 字符「那就开测吧」,留 1 字符余量)
|
|
48
|
+
ECHO_MAX_CHARS = 6
|
|
49
|
+
|
|
50
|
+
CHROME_RULES = [
|
|
51
|
+
("inter_session_envelope", re.compile(r"\[Inter-session message\]")),
|
|
52
|
+
("exec_completion_banner", re.compile(r"\[OpenClaw exec completion\]")),
|
|
53
|
+
("session_event_banner", re.compile(r"\[OpenClaw session event\]")),
|
|
54
|
+
("subagent_context_banner", re.compile(r"\[Subagent Context\]")),
|
|
55
|
+
("internal_context_tag",
|
|
56
|
+
re.compile(r"<<<(?:BEGIN|END)_OPENCLAW_INTERNAL_CONTEXT>>>|"
|
|
57
|
+
r"(?:BEGIN|END)_OPENCLAW_INTERNAL_CONTEXT")),
|
|
58
|
+
("prompt_data_tag", re.compile(r"</?prompt-data>")),
|
|
59
|
+
("section_banner", re.compile(r"===\w+===")),
|
|
60
|
+
("envelope_header_fields",
|
|
61
|
+
re.compile(r"(?:sourceSession|sourceChannel|sourceTool|isUser)=\S+")),
|
|
62
|
+
("envelope_key_token",
|
|
63
|
+
re.compile(r"\b(?:sourceSession|sourceChannel|sourceTool|sessions_send|isUser)\b")),
|
|
64
|
+
("routed_boilerplate", re.compile(r"This content was routed by OpenClaw[^\n]*")),
|
|
65
|
+
]
|
|
66
|
+
|
|
67
|
+
# 词汤判据的横幅词集(chrome_word_soup:文本单词全部落在某一横幅词集内)
|
|
68
|
+
CHROME_PHRASES = [
|
|
69
|
+
"[OpenClaw exec completion]",
|
|
70
|
+
"[Inter-session message]",
|
|
71
|
+
"[Subagent Context]",
|
|
72
|
+
"[OpenClaw session event]",
|
|
73
|
+
"This content was routed by OpenClaw from another session",
|
|
74
|
+
]
|
|
75
|
+
CHROME_WORDSETS = [frozenset(re.findall(r"[a-z]+", p.lower())) for p in CHROME_PHRASES]
|
|
76
|
+
|
|
77
|
+
_STRIP_RESIDUAL = re.compile(
|
|
78
|
+
r"[\s,。;:、,.:;|/\\()\[\]{}<>\"'`~!??!…—\-+*=#@$%^&]+")
|
|
79
|
+
_CJK = re.compile(r"[\u4e00-\u9fff]")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def strip_chrome(text):
|
|
83
|
+
"""剥掉已知传输铬(横幅/信封/标签/字段/样板句)→ (残余长度, 命中模式名列表)。"""
|
|
84
|
+
s = str(text or "")
|
|
85
|
+
hits = []
|
|
86
|
+
for name, rx in CHROME_RULES:
|
|
87
|
+
if rx.search(s):
|
|
88
|
+
hits.append(name)
|
|
89
|
+
s = rx.sub(" ", s)
|
|
90
|
+
residual = _STRIP_RESIDUAL.sub("", s)
|
|
91
|
+
return len(residual), hits
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _word_soup(text):
|
|
95
|
+
"""词汤判据(实据 318ae811):纯 ASCII 且全部单词落在某一横幅词集内。"""
|
|
96
|
+
s = str(text or "")
|
|
97
|
+
if not s.strip() or _CJK.search(s):
|
|
98
|
+
return False
|
|
99
|
+
words = set(re.findall(r"[a-z]+", s.lower()))
|
|
100
|
+
return bool(words) and any(words <= cw for cw in CHROME_WORDSETS)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def classify_text(text, echo=False, soup_text=None):
|
|
104
|
+
"""对自由文本下准入判定。
|
|
105
|
+
|
|
106
|
+
echo=True 时启用超短回声碎片规则(observe 轮次/摘要正文这类对话文本);
|
|
107
|
+
soup_text 覆盖词汤判据的输入(条目分类时排除 base 骨架词干扰)。"""
|
|
108
|
+
s = str(text or "")
|
|
109
|
+
if not s.strip():
|
|
110
|
+
return {"verdict": "ok", "patterns": [], "reason": None, "residual_len": 0}
|
|
111
|
+
residual, hits = strip_chrome(s)
|
|
112
|
+
if hits:
|
|
113
|
+
if residual < REJECT_RESIDUAL_MAX:
|
|
114
|
+
return {"verdict": "reject", "patterns": hits,
|
|
115
|
+
"reason": (f"传输横幅/信封残片({','.join(hits)}),"
|
|
116
|
+
f"剥除后残余 {residual} 字符 < {REJECT_RESIDUAL_MAX}"),
|
|
117
|
+
"residual_len": residual}
|
|
118
|
+
return {"verdict": "quarantine", "patterns": hits,
|
|
119
|
+
"reason": (f"传输铬混实质内容({','.join(hits)})→ 疑似回声污染,"
|
|
120
|
+
f"收下隔离(残余 {residual} 字符)"),
|
|
121
|
+
"residual_len": residual}
|
|
122
|
+
if _word_soup(soup_text if soup_text is not None else s):
|
|
123
|
+
return {"verdict": "quarantine", "patterns": ["chrome_word_soup"],
|
|
124
|
+
"reason": "横幅词汤(单词全部落在已知横幅词集)→ 疑似横幅回声",
|
|
125
|
+
"residual_len": residual}
|
|
126
|
+
if echo and len(s.strip()) <= ECHO_MAX_CHARS:
|
|
127
|
+
return {"verdict": "quarantine", "patterns": ["echo_fragment"],
|
|
128
|
+
"reason": (f"超短回声碎片({len(s.strip())} 字符 "
|
|
129
|
+
f"≤ {ECHO_MAX_CHARS})→ 疑似对话回声"),
|
|
130
|
+
"residual_len": residual}
|
|
131
|
+
return {"verdict": "ok", "patterns": [], "reason": None, "residual_len": residual}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def classify_entry(e):
|
|
135
|
+
"""对账本条目下准入判定(quarantine-mark 复核用;不改条目)。
|
|
136
|
+
|
|
137
|
+
chrome 判据看全字段(含 base 词面);词汤判据只看内容字段(base 骨架词会
|
|
138
|
+
干扰子集判定——实据 318ae811 的 base 含 decision/number 等骨架键);
|
|
139
|
+
回声判据只看 body(实据 0504f503/92626deb/1935b2f8 均为短 body 摘要)。"""
|
|
140
|
+
content = " ".join(str(e.get(k) or "")
|
|
141
|
+
for k in ("obj", "act", "actual", "signature", "topic", "body"))
|
|
142
|
+
blob = content
|
|
143
|
+
b = e.get("base")
|
|
144
|
+
if b:
|
|
145
|
+
try:
|
|
146
|
+
blob += " " + json.dumps(b, ensure_ascii=False)
|
|
147
|
+
except (TypeError, ValueError):
|
|
148
|
+
pass
|
|
149
|
+
v = classify_text(blob, echo=False, soup_text=content)
|
|
150
|
+
if v["verdict"] != "ok":
|
|
151
|
+
return v
|
|
152
|
+
body = str(e.get("body") or "").strip()
|
|
153
|
+
if body and len(body) <= ECHO_MAX_CHARS:
|
|
154
|
+
return {"verdict": "quarantine", "patterns": ["echo_fragment"],
|
|
155
|
+
"reason": (f"疑似回声碎片(body {len(body)} 字符 "
|
|
156
|
+
f"≤ {ECHO_MAX_CHARS})"),
|
|
157
|
+
"residual_len": v.get("residual_len", 0)}
|
|
158
|
+
return v
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def is_quarantined(e):
|
|
162
|
+
"""隔离标记判定(recall 合格面过滤用)。"""
|
|
163
|
+
return str((e or {}).get("admit") or "") == "quarantine"
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def mark_quarantine(store, entry, reason, by="admission", save=True):
|
|
167
|
+
"""打隔离标记(标记≠删除;原字段逐字保留)。"""
|
|
168
|
+
entry["admit"] = "quarantine"
|
|
169
|
+
entry["admit_reason"] = str(reason or "")[:200]
|
|
170
|
+
entry["admit_ts"] = time.strftime("%Y-%m-%dT%H:%M:%S")
|
|
171
|
+
entry["admit_by"] = by
|
|
172
|
+
if save:
|
|
173
|
+
store.save()
|
|
174
|
+
return entry
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def scan_quarantine(store, apply=False, sample_limit=20):
|
|
178
|
+
"""既有条目复核(quarantine-mark 子命令后端)。
|
|
179
|
+
|
|
180
|
+
默认 dry-run:只报告,零写入;apply=True 才打标记(只加字段,不删不改)。"""
|
|
181
|
+
report = {"scanned": 0, "matched": 0, "applied": 0, "already": 0,
|
|
182
|
+
"by_pattern": {}, "samples": []}
|
|
183
|
+
matches = []
|
|
184
|
+
for e in store.entries.values():
|
|
185
|
+
report["scanned"] += 1
|
|
186
|
+
if is_quarantined(e):
|
|
187
|
+
report["already"] += 1
|
|
188
|
+
continue
|
|
189
|
+
v = classify_entry(e)
|
|
190
|
+
if v["verdict"] == "ok":
|
|
191
|
+
continue
|
|
192
|
+
report["matched"] += 1
|
|
193
|
+
for p in (v["patterns"] or ["unknown"]):
|
|
194
|
+
report["by_pattern"][p] = report["by_pattern"].get(p, 0) + 1
|
|
195
|
+
if len(report["samples"]) < sample_limit:
|
|
196
|
+
report["samples"].append({
|
|
197
|
+
"id": str(e.get("id"))[:16],
|
|
198
|
+
"verdict": v["verdict"], "patterns": v["patterns"],
|
|
199
|
+
"excerpt": str(e.get("body") or e.get("signature") or "")[:80]})
|
|
200
|
+
matches.append((e, v))
|
|
201
|
+
if apply:
|
|
202
|
+
for e, v in matches:
|
|
203
|
+
mark_quarantine(store, e, "reclass:" + (v["reason"] or ""),
|
|
204
|
+
by="quarantine-mark", save=False)
|
|
205
|
+
report["applied"] += 1
|
|
206
|
+
if matches:
|
|
207
|
+
store.save() # 只增标记字段;条目数/原字段零变化(不注≠删)
|
|
208
|
+
return report
|
package/src/bridge.ts
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// bridge.ts — TS→Python 唯一桥客户端(业务逻辑单源在 Python,本层零业务逻辑)
|
|
2
|
+
// 形状钉自 openclaw 2026.9.4;双通道:
|
|
3
|
+
// bridgeCall 同步单发(--oneshot):请求载荷经 stdin 传 JSON
|
|
4
|
+
// ——execve 单参上限(MAX_ARG_STRLEN≈128KiB)整类绕开,旧 ARG_CAP 截断已删
|
|
5
|
+
// bridgeCallAsync 常驻 worker(--serve):逐行 JSON-RPC over stdio,进程复用+崩溃自愈
|
|
6
|
+
// 业务帽仍在 Python 侧(ingest 存储 ≤200 字符);TS 不做业务截断。
|
|
7
|
+
import { execFileSync, spawn, type ChildProcess } from "node:child_process";
|
|
8
|
+
import { readFileSync } from "node:fs";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
10
|
+
|
|
11
|
+
export interface BridgeConfig {
|
|
12
|
+
pythonBin?: string;
|
|
13
|
+
bridgePath?: string;
|
|
14
|
+
landingPath?: string;
|
|
15
|
+
workspaceRoot?: string;
|
|
16
|
+
hotWindowMessages?: number;
|
|
17
|
+
coldStartTokenBudget?: number;
|
|
18
|
+
/** S2 远程桥(2026-11-10 拍板「2切换」):显式守护端点;缺省时读 config/daemon_forward.json
|
|
19
|
+
* 的 bridgeRemote+endpoint。命中走守护 /bridge,失败 fail-soft 回落本地 worker(零中断)。 */
|
|
20
|
+
remoteEndpoint?: string;
|
|
21
|
+
remoteBridge?: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const DEFAULT_BRIDGE = fileURLToPath(new URL("./bridge_cli.py", import.meta.url));
|
|
25
|
+
|
|
26
|
+
function flagTail(cfg: BridgeConfig, args: string[]): string[] {
|
|
27
|
+
const tail: string[] = [];
|
|
28
|
+
if (cfg.landingPath) tail.push("--landing", cfg.landingPath);
|
|
29
|
+
if (cfg.workspaceRoot) tail.push("--ws", cfg.workspaceRoot);
|
|
30
|
+
return tail.concat(args.map(String));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 同步调 Python 桥(--oneshot):返回解析后 JSON。失败抛错(写路径由调用方定 fail 语义)。 */
|
|
34
|
+
export function bridgeCall(cfg: BridgeConfig, sub: string, args: string[] = []): any {
|
|
35
|
+
const bin = cfg.pythonBin ?? "python3";
|
|
36
|
+
const bridge = cfg.bridgePath ?? DEFAULT_BRIDGE;
|
|
37
|
+
const out = execFileSync(bin, [bridge, "--oneshot"], {
|
|
38
|
+
input: JSON.stringify({ sub, args: flagTail(cfg, args) }),
|
|
39
|
+
encoding: "utf-8",
|
|
40
|
+
timeout: 5_000, // 同步面仅 promptBuilder(实测 warm 10–20ms ⇒ 250×余量);python 挂死最坏卡事件循环 5s 而非 30s,保登录页可用
|
|
41
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
42
|
+
});
|
|
43
|
+
return JSON.parse(out);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// ── 常驻 worker(--serve)────────────────────────────────────────────────
|
|
47
|
+
interface Pending {
|
|
48
|
+
resolve: (v: any) => void;
|
|
49
|
+
reject: (e: Error) => void;
|
|
50
|
+
timer: ReturnType<typeof setTimeout>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
class BridgeWorker {
|
|
54
|
+
private proc: ChildProcess | null = null;
|
|
55
|
+
private nextId = 1;
|
|
56
|
+
private pending = new Map<number, Pending>();
|
|
57
|
+
private buf = "";
|
|
58
|
+
constructor(private readonly cfg: BridgeConfig) {}
|
|
59
|
+
|
|
60
|
+
private ensure(): ChildProcess {
|
|
61
|
+
if (this.proc && this.proc.exitCode === null) return this.proc;
|
|
62
|
+
const bin = this.cfg.pythonBin ?? "python3";
|
|
63
|
+
const bridge = this.cfg.bridgePath ?? DEFAULT_BRIDGE;
|
|
64
|
+
const proc = spawn(bin, [bridge, "--serve"], { stdio: ["pipe", "pipe", "pipe"] });
|
|
65
|
+
this.buf = "";
|
|
66
|
+
proc.stdout!.on("data", (d: Buffer) => this.onData(d));
|
|
67
|
+
proc.stderr!.on("data", (d: Buffer) => {
|
|
68
|
+
const s = d.toString().trim();
|
|
69
|
+
if (s) console.error("[memgate] worker stderr:", s.slice(0, 500));
|
|
70
|
+
});
|
|
71
|
+
proc.on("exit", () => this.onExit(proc));
|
|
72
|
+
proc.on("error", (err) => this.onError(proc, err));
|
|
73
|
+
this.proc = proc;
|
|
74
|
+
return proc;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
private onData(d: Buffer): void {
|
|
78
|
+
this.buf += d.toString("utf-8");
|
|
79
|
+
let nl: number;
|
|
80
|
+
while ((nl = this.buf.indexOf("\n")) >= 0) {
|
|
81
|
+
const line = this.buf.slice(0, nl).trim();
|
|
82
|
+
this.buf = this.buf.slice(nl + 1);
|
|
83
|
+
if (!line) continue;
|
|
84
|
+
let msg: any;
|
|
85
|
+
try { msg = JSON.parse(line); } catch { continue; }
|
|
86
|
+
const p = this.pending.get(msg.id);
|
|
87
|
+
if (!p) continue;
|
|
88
|
+
this.pending.delete(msg.id);
|
|
89
|
+
clearTimeout(p.timer);
|
|
90
|
+
if (msg.ok) p.resolve(msg.result);
|
|
91
|
+
else p.reject(new Error(String(msg.error ?? "bridge worker error")));
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
private onExit(proc: ChildProcess): void {
|
|
96
|
+
if (this.proc === proc) this.proc = null;
|
|
97
|
+
for (const [, p] of this.pending) {
|
|
98
|
+
clearTimeout(p.timer);
|
|
99
|
+
p.reject(new Error("bridge worker exited"));
|
|
100
|
+
}
|
|
101
|
+
this.pending.clear();
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
private onError(proc: ChildProcess, err: Error): void {
|
|
105
|
+
if (this.proc === proc) this.proc = null;
|
|
106
|
+
for (const [, p] of this.pending) {
|
|
107
|
+
clearTimeout(p.timer);
|
|
108
|
+
p.reject(new Error(`bridge worker spawn: ${err.message}`));
|
|
109
|
+
}
|
|
110
|
+
this.pending.clear();
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
call(sub: string, tail: string[]): Promise<any> {
|
|
114
|
+
return new Promise((resolve, reject) => {
|
|
115
|
+
const proc = this.ensure();
|
|
116
|
+
const id = this.nextId++;
|
|
117
|
+
const timer = setTimeout(() => {
|
|
118
|
+
this.pending.delete(id);
|
|
119
|
+
this.dispose();
|
|
120
|
+
reject(new Error(`bridge worker timeout: ${sub}`));
|
|
121
|
+
}, 30_000);
|
|
122
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
123
|
+
proc.stdin!.write(JSON.stringify({ id, sub, args: tail }) + "\n", (err) => {
|
|
124
|
+
if (!err) return;
|
|
125
|
+
const p = this.pending.get(id);
|
|
126
|
+
if (p) {
|
|
127
|
+
this.pending.delete(id);
|
|
128
|
+
clearTimeout(p.timer);
|
|
129
|
+
this.dispose();
|
|
130
|
+
p.reject(new Error(`bridge worker write: ${err.message}`));
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
dispose(): void {
|
|
137
|
+
const proc = this.proc;
|
|
138
|
+
this.proc = null;
|
|
139
|
+
for (const [, p] of this.pending) {
|
|
140
|
+
clearTimeout(p.timer);
|
|
141
|
+
p.reject(new Error("bridge worker disposed"));
|
|
142
|
+
}
|
|
143
|
+
this.pending.clear();
|
|
144
|
+
if (proc && proc.exitCode === null) proc.kill("SIGTERM");
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const GATE_CFG = fileURLToPath(new URL("../config/daemon_forward.json", import.meta.url));
|
|
149
|
+
|
|
150
|
+
function remoteFor(cfg: BridgeConfig): string | null {
|
|
151
|
+
// 显式 opt-out(remoteBridge:false)压过 gate 文件——测试/旁路场景强制本地路径
|
|
152
|
+
if (cfg.remoteBridge === false) return null;
|
|
153
|
+
if (cfg.remoteEndpoint) return cfg.remoteEndpoint;
|
|
154
|
+
try {
|
|
155
|
+
const g = JSON.parse(readFileSync(GATE_CFG, "utf-8"));
|
|
156
|
+
if (g && g.bridgeRemote && typeof g.endpoint === "string") return g.endpoint;
|
|
157
|
+
} catch { /* 无 gate 文件=原路径 */ }
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function remoteCall(endpoint: string, sub: string, tail: string[]): Promise<any> {
|
|
162
|
+
const ac = new AbortController();
|
|
163
|
+
const timer = setTimeout(() => ac.abort(), 25_000);
|
|
164
|
+
try {
|
|
165
|
+
const res = await fetch(endpoint.replace(/\/$/, "") + "/bridge", {
|
|
166
|
+
method: "POST",
|
|
167
|
+
headers: { "content-type": "application/json" },
|
|
168
|
+
body: JSON.stringify({ sub, args: tail }),
|
|
169
|
+
signal: ac.signal,
|
|
170
|
+
});
|
|
171
|
+
const body = await res.json();
|
|
172
|
+
if (!res.ok || (body && body.ok === false && body.error)) {
|
|
173
|
+
throw new Error(String(body?.error ?? `HTTP ${res.status}`));
|
|
174
|
+
}
|
|
175
|
+
// 形状契约对齐(2026-11-12 修复):守护 /bridge 回的是 worker 信封
|
|
176
|
+
// {id,ok,result},而本地 worker 路径 resolve 的是 msg.result——双通道
|
|
177
|
+
// 必须同形。旧代码把信封原样上抛:工具层 details.entry/引擎 r.hits 全
|
|
178
|
+
// 空、commit 幂等口把 duplicate 显示成 committed(daemon 在跑即触发,
|
|
179
|
+
// daemon 死走 worker 兜底反而正常 ⇒ 长期潜伏)。裸结果无 "result" 键
|
|
180
|
+
// 原样返回(preflight 顶层自带 ok 字段——不可用 ok 判信封,只认键)。
|
|
181
|
+
return (body && typeof body === "object" && body.ok === true && "result" in body)
|
|
182
|
+
? body.result : body;
|
|
183
|
+
} finally { clearTimeout(timer); }
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const workers = new Map<string, BridgeWorker>();
|
|
187
|
+
|
|
188
|
+
function workerFor(cfg: BridgeConfig): BridgeWorker {
|
|
189
|
+
const key = `${cfg.pythonBin ?? "python3"}|${cfg.bridgePath ?? DEFAULT_BRIDGE}`;
|
|
190
|
+
let w = workers.get(key);
|
|
191
|
+
if (!w) {
|
|
192
|
+
w = new BridgeWorker(cfg);
|
|
193
|
+
workers.set(key, w);
|
|
194
|
+
}
|
|
195
|
+
return w;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** 异步调 Python 桥(常驻 worker):进程复用,崩溃后下次调用自动重建。失败抛错。
|
|
199
|
+
* S2 远程桥命中时先走守护 /bridge,失败 fail-soft 回落本地 worker。 */
|
|
200
|
+
export function bridgeCallAsync(cfg: BridgeConfig, sub: string, args: string[] = []): Promise<any> {
|
|
201
|
+
const tail = flagTail(cfg, args);
|
|
202
|
+
const ep = remoteFor(cfg);
|
|
203
|
+
if (ep) return remoteCall(ep, sub, tail).catch(() => workerFor(cfg).call(sub, tail));
|
|
204
|
+
return workerFor(cfg).call(sub, tail);
|
|
205
|
+
}
|