memgate-mcp 0.0.0-stage → 2026.11.21
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 +93 -0
- package/MANIFEST.md +13 -0
- package/README.md +34 -2
- package/VERSIONS.json +9 -0
- package/bin/memgate-mcp.js +9 -0
- package/config/mcp-config-examples.md +31 -0
- package/kernel/activity_telemetry.py +51 -0
- package/kernel/admission.py +208 -0
- package/kernel/calldecay/__init__.py +23 -0
- package/kernel/calldecay/__main__.py +7 -0
- package/kernel/calldecay/_kernel.py +32 -0
- package/kernel/calldecay/adapter.py +126 -0
- package/kernel/calldecay/cli.py +80 -0
- package/kernel/calldecay/gate.py +93 -0
- package/kernel/calldecay/landing.py +1298 -0
- package/kernel/calldecay/metrics.py +37 -0
- package/kernel/calldecay/mock.py +68 -0
- package/kernel/calldecay/pipeline.py +85 -0
- package/kernel/calldecay/proxy.py +220 -0
- package/kernel/calldecay/summarize.py +401 -0
- package/kernel/core/LICENSE +93 -0
- package/kernel/core/__init__.py +0 -0
- package/kernel/core/accept_contract.py +67 -0
- package/kernel/core/chain_probe_world.py +133 -0
- package/kernel/core/concept_ontology.py +2401 -0
- package/kernel/core/concept_opposition.py +291 -0
- package/kernel/core/concept_phase.py +1342 -0
- package/kernel/core/concept_principle.py +2481 -0
- package/kernel/core/concept_pyramid.py +287 -0
- package/kernel/core/concept_space.py +45 -0
- package/kernel/core/concept_space_mixin.py +941 -0
- package/kernel/core/concept_state.py +2748 -0
- package/kernel/core/decision_symbolic.py +245 -0
- package/kernel/core/eco_math_world.py +489 -0
- package/kernel/core/emergence.py +362 -0
- package/kernel/core/events.py +93 -0
- package/kernel/core/hebbian.py +117 -0
- package/kernel/core/llm_arm.py +551 -0
- package/kernel/core/memory_shadow.py +158 -0
- package/kernel/core/mes_layer_base.py +309 -0
- package/kernel/core/mes_vnext.py +540 -0
- package/kernel/core/ontology_core.py +168 -0
- package/kernel/core/phase_field.py +187 -0
- package/kernel/core/reasoning.py +185 -0
- package/kernel/core/rhythm_vnext.py +777 -0
- package/kernel/dashboard_render.py +196 -0
- package/kernel/depscan_probe.py +96 -0
- package/kernel/health_probe.py +186 -0
- package/kernel/hebbian_link.py +34 -0
- package/kernel/knowledge_distiller/README.md +9 -0
- package/kernel/knowledge_distiller/__init__.py +1 -0
- package/kernel/knowledge_distiller/knowledge_distiller.py +196 -0
- package/kernel/m3_judge.py +215 -0
- package/kernel/mechanism_advisor.py +203 -0
- package/kernel/mechanism_learner.py +193 -0
- package/kernel/memory_core.py +81 -0
- package/kernel/quality_gate/README.md +9 -0
- package/kernel/quality_gate/__init__.py +1 -0
- package/kernel/quality_gate/quality_gate.py +7 -0
- package/kernel/registry_gate.py +57 -0
- package/kernel/semantic_recall.py +635 -0
- package/kernel/tiered_decay/README.md +9 -0
- package/kernel/tiered_decay/__init__.py +1 -0
- package/kernel/tiered_decay/tiered_decay.py +17 -0
- package/kernel/tokenizer/README.md +9 -0
- package/kernel/tokenizer/__init__.py +2 -0
- package/kernel/tokenizer/tokenizer.py +14 -0
- package/kernel/version_binding.py +131 -0
- package/mcp_server.py +166 -0
- package/package.json +37 -4
- package/test/test_mcp.py +54 -0
- package//345/216/206/345/217/262/350/204/211/347/273/234.md +19 -0
- package//350/257/264/346/230/216/344/271/246.md +34 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
Elastic License 2.0
|
|
2
|
+
|
|
3
|
+
URL: https://www.elastic.co/licensing/elastic-license
|
|
4
|
+
|
|
5
|
+
## Acceptance
|
|
6
|
+
|
|
7
|
+
By using the software, you agree to all of the terms and conditions below.
|
|
8
|
+
|
|
9
|
+
## Copyright License
|
|
10
|
+
|
|
11
|
+
The licensor grants you a non-exclusive, royalty-free, worldwide,
|
|
12
|
+
non-sublicensable, non-transferable license to use, copy, distribute, make
|
|
13
|
+
available, and prepare derivative works of the software, in each case subject to
|
|
14
|
+
the limitations and conditions below.
|
|
15
|
+
|
|
16
|
+
## Limitations
|
|
17
|
+
|
|
18
|
+
You may not provide the software to third parties as a hosted or managed
|
|
19
|
+
service, where the service provides users with access to any substantial set of
|
|
20
|
+
the features or functionality of the software.
|
|
21
|
+
|
|
22
|
+
You may not move, change, disable, or circumvent the license key functionality
|
|
23
|
+
in the software, and you may not remove or obscure any functionality in the
|
|
24
|
+
software that is protected by the license key.
|
|
25
|
+
|
|
26
|
+
You may not alter, remove, or obscure any licensing, copyright, or other notices
|
|
27
|
+
of the licensor in the software. Any use of the licensor’s trademarks is subject
|
|
28
|
+
to applicable law.
|
|
29
|
+
|
|
30
|
+
## Patents
|
|
31
|
+
|
|
32
|
+
The licensor grants you a license, under any patent claims the licensor can
|
|
33
|
+
license, or becomes able to license, to make, have made, use, sell, offer for
|
|
34
|
+
sale, import and have imported the software, in each case subject to the
|
|
35
|
+
limitations and conditions in this license. This license does not cover any
|
|
36
|
+
patent claims that you cause to be infringed by modifications or additions to
|
|
37
|
+
the software. If you or your company make any written claim that the software
|
|
38
|
+
infringes or contributes to infringement of any patent, your patent license for
|
|
39
|
+
the software granted under these terms ends immediately. If your company makes
|
|
40
|
+
such a claim, your patent license ends immediately for work on behalf of your
|
|
41
|
+
company.
|
|
42
|
+
|
|
43
|
+
## Notices
|
|
44
|
+
|
|
45
|
+
You must ensure that anyone who gets a copy of any part of the software from you
|
|
46
|
+
also gets a copy of these terms.
|
|
47
|
+
|
|
48
|
+
If you modify the software, you must include in any modified copies of the
|
|
49
|
+
software prominent notices stating that you have modified the software.
|
|
50
|
+
|
|
51
|
+
## No Other Rights
|
|
52
|
+
|
|
53
|
+
These terms do not imply any licenses other than those expressly granted in
|
|
54
|
+
these terms.
|
|
55
|
+
|
|
56
|
+
## Termination
|
|
57
|
+
|
|
58
|
+
If you use the software in violation of these terms, such use is not licensed,
|
|
59
|
+
and your licenses will automatically terminate. If the licensor provides you
|
|
60
|
+
with a notice of your violation, and you cease all violation of this license no
|
|
61
|
+
later than 30 days after you receive that notice, your licenses will be
|
|
62
|
+
reinstated retroactively. However, if you violate these terms after such
|
|
63
|
+
reinstatement, any additional violation of these terms will cause your licenses
|
|
64
|
+
to terminate automatically and permanently.
|
|
65
|
+
|
|
66
|
+
## No Liability
|
|
67
|
+
|
|
68
|
+
*As far as the law allows, the software comes as is, without any warranty or
|
|
69
|
+
condition, and the licensor will not be liable to you for any damages arising
|
|
70
|
+
out of these terms or the use or nature of the software, under any kind of
|
|
71
|
+
legal claim.*
|
|
72
|
+
|
|
73
|
+
## Definitions
|
|
74
|
+
|
|
75
|
+
The **licensor** is the entity offering these terms, and the **software** is the
|
|
76
|
+
software the licensor makes available under these terms, including any portion
|
|
77
|
+
of it.
|
|
78
|
+
|
|
79
|
+
**you** refers to the individual or entity agreeing to these terms.
|
|
80
|
+
|
|
81
|
+
**your company** is any legal entity, sole proprietorship, or other kind of
|
|
82
|
+
organization that you work for, plus all organizations that have control over,
|
|
83
|
+
are under the control of, or are under common control with that
|
|
84
|
+
organization. **control** means ownership of substantially all the assets of an
|
|
85
|
+
entity, or the power to direct its management and policies by vote, contract, or
|
|
86
|
+
otherwise. Control can be direct or indirect.
|
|
87
|
+
|
|
88
|
+
**your licenses** are all the licenses granted to you for the software under
|
|
89
|
+
these terms.
|
|
90
|
+
|
|
91
|
+
**use** means anything you do with the software requiring one of your licenses.
|
|
92
|
+
|
|
93
|
+
**trademark** means trademarks, service marks, and similar rights.
|
package/MANIFEST.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# D-MCP版 · 文件清单(2026.11.21)
|
|
2
|
+
|
|
3
|
+
- **mcp_server.py** — MCP stdio 服务器(零第三方依赖)|生产单源
|
|
4
|
+
- **bin/memgate-mcp.js** — npm 启动器(spawn python3 mcp_server.py,stdio 直通)
|
|
5
|
+
- **kernel/** — 随包 kernel(vendor)|可再生
|
|
6
|
+
- **test/test_mcp.py** — 冒烟:握手+四工具+错法码 |验证件
|
|
7
|
+
- **config/mcp-config-examples.md** — 各宿主接入配置片段 |交付文档
|
|
8
|
+
- **README.md / 说明书.md / 历史脉络.md** — 上架说明 / 产品说明书 / 脉络 |交付文档
|
|
9
|
+
- **package.json** — npm 包描述(memgate-mcp,bin=memgate-mcp)
|
|
10
|
+
- **VERSIONS.json** — 版本绑定(产品/协议/工具面/零依赖声明)|绑定源
|
|
11
|
+
- **LICENSE** — Elastic License 2.0(SPDX: Elastic-2.0)
|
|
12
|
+
|
|
13
|
+
语义同源:A-插件版工具面 ≡ B-完整版 REST 面 ≡ D-MCP工具面(deposit/recall/stats/compact)。
|
package/README.md
CHANGED
|
@@ -1,3 +1,35 @@
|
|
|
1
|
-
#
|
|
1
|
+
# MemGate MCP(D-MCP版)说明书
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**一句话**:把治理级记忆(存取留痕/质量门/统计账)接到任何支持 MCP 的 AI 平台——
|
|
4
|
+
Claude Code、Cursor、Copilot Studio、Windsurf、Cline、Zed 一线全收。
|
|
5
|
+
|
|
6
|
+
## 它解决什么
|
|
7
|
+
|
|
8
|
+
AI 助手/编码代理的记忆各自为政:跨项目污染、无审计、忘得快。
|
|
9
|
+
MemGate MCP 提供**治理过的记忆存取**:每个条目带对象-动作-内容三元组签名,过质量门,入统计账。
|
|
10
|
+
|
|
11
|
+
## 快速开始
|
|
12
|
+
|
|
13
|
+
# 1. 冒烟自测(应打印 SMOKE ALL GREEN)
|
|
14
|
+
python3 test/test_mcp.py
|
|
15
|
+
|
|
16
|
+
# 2. 接入宿主(以 Claude Desktop 为例,详见 config/mcp-config-examples.md)
|
|
17
|
+
# 把配置 JSON 填入 claude_desktop_config.json,重启宿主
|
|
18
|
+
# npm 安装后也可以直接用随包启动器:"command": "memgate-mcp"
|
|
19
|
+
|
|
20
|
+
## 工具面(与 A-插件版/B-完整版同源语义)
|
|
21
|
+
|
|
22
|
+
- **memgate_deposit(obj, act, actual, kind, source)** — 存一条治理记忆
|
|
23
|
+
- **memgate_recall(query, top_k)** — 按签名/关键词召回(带分数)
|
|
24
|
+
- **memgate_stats()** — 记忆库统计
|
|
25
|
+
- **memgate_compact()** — 压实(清冗余)
|
|
26
|
+
|
|
27
|
+
## 环境
|
|
28
|
+
|
|
29
|
+
- Python >= 3.9,**零第三方依赖**(stdlib + 随包 kernel)
|
|
30
|
+
- MEMGATE_HOME:记忆库目录(默认 ~/.memgate-mcp)——多项目隔离=每项目配不同目录
|
|
31
|
+
- 与家族关系:工具面与 A-插件版/B-完整版同源语义(deposit/recall/stats/compact)
|
|
32
|
+
|
|
33
|
+
## 版本
|
|
34
|
+
|
|
35
|
+
2026.11.21(2026-11-21,家族 YYYY.MM.DD 制)——MCP 2025-06-18,四工具面,冒烟件随包。
|
package/VERSIONS.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
{
|
|
2
|
+
"product": "memgate-mcp",
|
|
3
|
+
"edition": "D-MCP版",
|
|
4
|
+
"version": "2026.11.21",
|
|
5
|
+
"kernel_source": "../B-完整版/src/kernel (sync_kernel.sh 单源链)",
|
|
6
|
+
"protocol": "MCP 2025-06-18 (stdio, 零依赖手搓实现)",
|
|
7
|
+
"tools": ["memgate_deposit", "memgate_recall", "memgate_stats", "memgate_compact"],
|
|
8
|
+
"compat": { "python": ">=3.9", "third_party_deps": 0 }
|
|
9
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// memgate-mcp launcher: spawns the bundled Python MCP server (stdio passthrough).
|
|
3
|
+
'use strict';
|
|
4
|
+
const { spawn } = require('child_process');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const py = process.env.PYTHON || 'python3';
|
|
7
|
+
const child = spawn(py, [path.join(__dirname, '..', 'mcp_server.py')], { stdio: 'inherit' });
|
|
8
|
+
child.on('error', (err) => { console.error('memgate-mcp: failed to launch ' + py + ': ' + err.message); process.exit(1); });
|
|
9
|
+
child.on('exit', (code, signal) => { if (signal) process.exit(1); process.exit(code == null ? 0 : code); });
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# 宿主接入配置片段(MCP stdio)
|
|
2
|
+
|
|
3
|
+
通用形状(Claude Desktop / Cursor / Cline / Windsurf / Zed 均适用,各家配置文件位置不同):
|
|
4
|
+
|
|
5
|
+
{
|
|
6
|
+
"mcpServers": {
|
|
7
|
+
"memgate": {
|
|
8
|
+
"command": "python3",
|
|
9
|
+
"args": ["/绝对路径/memgate-mcp/mcp_server.py"],
|
|
10
|
+
"env": { "MEMGATE_HOME": "/绝对路径/记忆库目录" }
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
npm 安装后也可用随包启动器(免手填路径):
|
|
16
|
+
|
|
17
|
+
{
|
|
18
|
+
"mcpServers": {
|
|
19
|
+
"memgate": {
|
|
20
|
+
"command": "memgate-mcp",
|
|
21
|
+
"env": { "MEMGATE_HOME": "/绝对路径/记忆库目录" }
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
- Claude Desktop: claude_desktop_config.json(Help → Developer → Edit Config)
|
|
27
|
+
- Cursor: .cursor/mcp.json(项目级)或全局 MCP 设置
|
|
28
|
+
- Cline / Windsurf: 扩展设置里的 MCP Servers 面板
|
|
29
|
+
- 换机器/换宿主零改动:stdio 协议,只要 python3 >= 3.9(npm 启动器另需 node >= 16)
|
|
30
|
+
|
|
31
|
+
工具面:memgate_deposit(存)/ memgate_recall(取)/ memgate_stats(账)/ memgate_compact(压实)。
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import json
|
|
3
|
+
import time
|
|
4
|
+
|
|
5
|
+
_HOME = os.environ.get("CALLDECACY_HOME") or os.path.expanduser("~/.memsteward/landing") # 单源收编 2026-11-19
|
|
6
|
+
"""提取件 v1(2026-11-19 组件提取入册)
|
|
7
|
+
来源:src/bridge_cli.py 行 [(91, 102), (603, 630)]
|
|
8
|
+
状态:未接线提取稿。接线前按本夹 README 的参数化清单补齐。
|
|
9
|
+
"""
|
|
10
|
+
def _telemetry(landing, kind, cur):
|
|
11
|
+
"""good 族观测事件旁路账(JSONL,与账本同目录;观测失败 fail-soft 不阻业务)。"""
|
|
12
|
+
try:
|
|
13
|
+
base = (os.path.dirname(os.path.expanduser(landing)) if landing
|
|
14
|
+
else _HOME)
|
|
15
|
+
os.makedirs(base, exist_ok=True)
|
|
16
|
+
with open(os.path.join(base, "telemetry.jsonl"), "a", encoding="utf-8") as f:
|
|
17
|
+
f.write(json.dumps({"ts": time.strftime("%Y-%m-%dT%H:%M:%S"),
|
|
18
|
+
"kind": kind, "cur": str(cur)[:80]},
|
|
19
|
+
ensure_ascii=False) + "\n")
|
|
20
|
+
except OSError:
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
def _bump_activity(landing=None, sub=None, **kv):
|
|
24
|
+
"""活动计数埋点(2026-11-09 面板):逐子命令计数+末次时刻,kv 累加顶层键。
|
|
25
|
+
fail-soft:埋点永不撑断工具调用。
|
|
26
|
+
落点锚定**账本同目录**(2026-11-12 修:旧锚 $HOME——桥侧 HOME=fakehome 时
|
|
27
|
+
埋点散落假家/静默丢,工具路召回计数缺口即此病)。"""
|
|
28
|
+
try:
|
|
29
|
+
base = (os.path.dirname(os.path.expanduser(landing)) if landing
|
|
30
|
+
else _HOME)
|
|
31
|
+
os.makedirs(base, exist_ok=True)
|
|
32
|
+
p = os.path.join(base, "activity.json")
|
|
33
|
+
d = {}
|
|
34
|
+
try:
|
|
35
|
+
with open(p, encoding="utf-8") as f:
|
|
36
|
+
d = json.load(f)
|
|
37
|
+
except (OSError, ValueError):
|
|
38
|
+
pass
|
|
39
|
+
if sub is not None:
|
|
40
|
+
s = d.setdefault("subs", {}).setdefault(str(sub), {"n": 0})
|
|
41
|
+
s["n"] = int(s.get("n", 0)) + 1
|
|
42
|
+
s["last"] = time.strftime("%Y-%m-%dT%H:%M:%S")
|
|
43
|
+
for k, v in kv.items():
|
|
44
|
+
d[k] = int(d.get(k, 0)) + int(v)
|
|
45
|
+
tmp = p + ".tmp"
|
|
46
|
+
with open(tmp, "w", encoding="utf-8") as f:
|
|
47
|
+
json.dump(d, f, ensure_ascii=False)
|
|
48
|
+
os.replace(tmp, p)
|
|
49
|
+
except Exception:
|
|
50
|
+
pass
|
|
51
|
+
|
|
@@ -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
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""CallDecay —— 决策型智能体的记忆层(LLM 调用衰减中间件)。
|
|
3
|
+
|
|
4
|
+
三行接入:
|
|
5
|
+
from calldecay import CallDecay
|
|
6
|
+
cd = CallDecay()
|
|
7
|
+
d = cd.decide(obj="兔", goal="丰", current="兔", actions=["喂食", "放牧"])
|
|
8
|
+
|
|
9
|
+
许可:全件 Elastic License 2.0 (SPDX: Elastic-2.0)。详见包内 LICENSE。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
__version__ = "0.1.0"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def __getattr__(name):
|
|
16
|
+
# 惰性导入:允许调用方先把 LLM_ARM_HOST 等环境变量设好再取 CallDecay
|
|
17
|
+
if name == "CallDecay":
|
|
18
|
+
from .adapter import CallDecay
|
|
19
|
+
return CallDecay
|
|
20
|
+
if name == "Metrics":
|
|
21
|
+
from .metrics import Metrics
|
|
22
|
+
return Metrics
|
|
23
|
+
raise AttributeError(f"module 'calldecay' has no attribute {name!r}")
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""定位 core 内核并加入模块搜索路径(不改内核源码、不复制内核源码)。
|
|
3
|
+
|
|
4
|
+
查找顺序:
|
|
5
|
+
1. 环境变量 CALLDECAY_CORE(指向包含 core/ 的目录)
|
|
6
|
+
2. calldecay/_kernel/(将来 wheel 捆绑位)
|
|
7
|
+
3. 仓库布局:CallDecay/sdk/calldecay → 上两级 = CallDecay/(内含 core/)
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def bootstrap():
|
|
16
|
+
os.environ.setdefault("LLM_ARM", "1") # 开模型咨询臂(可 env 覆盖)
|
|
17
|
+
os.environ.setdefault("LLM_ARM_CHAT", "1") # 上游默认走 OpenAI 兼容端点
|
|
18
|
+
here = Path(os.path.abspath(__file__)).parent # L09 2026-11-20: abspath 形态
|
|
19
|
+
candidates = []
|
|
20
|
+
env = os.environ.get("CALLDECAY_CORE")
|
|
21
|
+
if env:
|
|
22
|
+
candidates.append(Path(env))
|
|
23
|
+
candidates.append(here / "_kernel")
|
|
24
|
+
candidates.append(here.parent.parent)
|
|
25
|
+
for c in candidates:
|
|
26
|
+
if (c / "core" / "llm_arm.py").exists():
|
|
27
|
+
s = str(c)
|
|
28
|
+
if s not in sys.path:
|
|
29
|
+
sys.path.insert(0, s)
|
|
30
|
+
return c / "core"
|
|
31
|
+
raise ImportError(
|
|
32
|
+
"未找到 core/ 内核。设置环境变量 CALLDECAY_CORE 指向包含 core/ 的目录。")
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""CallDecay SDK —— 决策记忆中间件的库接法(三行接入)。
|
|
3
|
+
|
|
4
|
+
from calldecay import CallDecay
|
|
5
|
+
cd = CallDecay()
|
|
6
|
+
d = cd.decide(obj="兔", goal="丰", current="兔", actions=["喂食", "放牧"])
|
|
7
|
+
cd.learn(obj="兔", act=d["act"], actual="丰", cur="兔")
|
|
8
|
+
|
|
9
|
+
机制本体在 core/(Elastic License 2.0);本文件只是编排层:
|
|
10
|
+
known(查表直连,0 上游调用)→ llm(窄接口咨询)→ explore(回退)。
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from ._kernel import bootstrap
|
|
14
|
+
|
|
15
|
+
bootstrap() # 使 core 可导入;不改内核一行
|
|
16
|
+
|
|
17
|
+
import core.llm_arm as llm_arm # noqa: E402
|
|
18
|
+
from core.concept_space import ConceptSpace # noqa: E402
|
|
19
|
+
from core.decision_symbolic import SymbolicDecision # noqa: E402
|
|
20
|
+
|
|
21
|
+
from .metrics import Metrics
|
|
22
|
+
from .landing import LandingStore, MIN_LIVENESS, _good_direct # noqa: E402
|
|
23
|
+
|
|
24
|
+
import random # noqa: E402
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class CallDecay:
|
|
28
|
+
"""决策记忆中间件实例:一个实例 = 一份本地状态表(概念空间)。"""
|
|
29
|
+
|
|
30
|
+
def __init__(self, gate_open=True, principle_batch_size=3, landing_path=None):
|
|
31
|
+
self.metrics = Metrics()
|
|
32
|
+
self.cs = ConceptSpace()
|
|
33
|
+
# 边精化批间隔(core 统计参数):默认 3 = 决策回路节奏;
|
|
34
|
+
# 约 7 次一致确认后确定性边涌现 → 查表命中(固化阈值语义)
|
|
35
|
+
self.cs._principle_batch_size = principle_batch_size
|
|
36
|
+
self.sd = SymbolicDecision(concept_space=self.cs)
|
|
37
|
+
# A2 落点件(整合施工方案_v1 A段):硬落盘账本——learn 即落盘;
|
|
38
|
+
# 启动时 replay 回灌状态表(进程重启后记忆可回放、可寻址)。
|
|
39
|
+
self.landing = LandingStore(landing_path)
|
|
40
|
+
self._replay_failed = 0
|
|
41
|
+
# 有界回放(2026-11-05 清债):init 成本随账本膨胀(真实账本 2479 条回放
|
|
42
|
+
# 挂死 concept_principle 扫描)——只回放「暖条目+最近 N 条」;冷条目/旧条目
|
|
43
|
+
# 留账本(recall_good/landing.recall 可取,同构复现即回前排),表=暖缓存、
|
|
44
|
+
# 账本=全量真值。上限 CALLDECAY_REPLAY_LIMIT(默认 500)。
|
|
45
|
+
import os as _os
|
|
46
|
+
_limit = int(_os.environ.get("CALLDECAY_REPLAY_LIMIT", "500"))
|
|
47
|
+
_all = len(self.landing.entries)
|
|
48
|
+
_done = 0
|
|
49
|
+
for _e in self.landing.replay(min_liveness=MIN_LIVENESS, limit=_limit):
|
|
50
|
+
try:
|
|
51
|
+
self.sd.learn_from_result(obj=_e.get("obj"), act=_e.get("act"),
|
|
52
|
+
actual=_e.get("actual"), cur=_e.get("cur"))
|
|
53
|
+
_done += 1
|
|
54
|
+
except Exception:
|
|
55
|
+
self._replay_failed += 1 # 单条回放失败不阻启动(账本仍完整)
|
|
56
|
+
self._replay_done = _done
|
|
57
|
+
self._replay_skipped = _all - _done - self._replay_failed
|
|
58
|
+
if gate_open:
|
|
59
|
+
llm_arm.gate_should_call = lambda: True
|
|
60
|
+
|
|
61
|
+
def decide(self, obj, goal, current=None, actions=None, context=None):
|
|
62
|
+
"""决策一步:命中查表直连(0 上游调用),未命中走窄接口咨询,仍无则探索回退。"""
|
|
63
|
+
self.metrics.bump("decisions")
|
|
64
|
+
res = self.sd.decide_symbolic(obj=obj, goal=goal,
|
|
65
|
+
current=current, context=context)
|
|
66
|
+
if res.get("known") or res.get("plan"):
|
|
67
|
+
self.metrics.bump("table_hits")
|
|
68
|
+
out = dict(res)
|
|
69
|
+
out["source"] = "table"
|
|
70
|
+
return out
|
|
71
|
+
sug = llm_arm.suggest(obj=obj, goal=goal, current=current,
|
|
72
|
+
actions=actions, context=context)
|
|
73
|
+
if sug:
|
|
74
|
+
self.metrics.bump("llm_consults")
|
|
75
|
+
return {"act": sug.get("act"), "expected": None, "known": False,
|
|
76
|
+
"plan": [], "is_explore": False,
|
|
77
|
+
"confidence": sug.get("confidence"),
|
|
78
|
+
"reason": "llm:" + str(sug.get("reasoning", ""))[:200],
|
|
79
|
+
"source": "llm"}
|
|
80
|
+
# A14 good 答案模式回落:LLM 未命中且沉淀过 → 零 token 直答
|
|
81
|
+
# (2026-11-05 G/S 系列 A/B 验证:G1 100%vs42.4%,S1 稀疏20=100%)。
|
|
82
|
+
# 灰度只报不直答(缺省只读,2026-11-15 拍板):命中照报(recall_good 计
|
|
83
|
+
# good_shadow_hits 观测计数)但不直答,落 explore;MEMGATE_GOOD_DIRECT=1
|
|
84
|
+
# 开直答(观察一周后)。
|
|
85
|
+
ga = self.landing.recall_good(current) if current is not None else None
|
|
86
|
+
if ga and (not actions or ga in actions) and _good_direct():
|
|
87
|
+
self.metrics.bump("gmem_hits")
|
|
88
|
+
return {"act": ga, "expected": None, "known": False,
|
|
89
|
+
"plan": [], "is_explore": False,
|
|
90
|
+
"reason": "good_pattern", "source": "gmem"}
|
|
91
|
+
self.metrics.bump("explore_fallbacks")
|
|
92
|
+
act = random.choice(actions) if actions else None
|
|
93
|
+
return {"act": act, "expected": None, "known": False, "plan": [],
|
|
94
|
+
"is_explore": True, "reason": "explore_fallback",
|
|
95
|
+
"source": "explore"}
|
|
96
|
+
|
|
97
|
+
def learn(self, obj=None, act=None, actual=None, cur=None, ok=None):
|
|
98
|
+
"""把行动结果写回状态表(蒸馏回灌)——学会的不再问。
|
|
99
|
+
【A2 落点】同时强制落盘(learn→save),进程死记忆不死。
|
|
100
|
+
【A14】ok=True/False 时同步 good 答案模式沉淀/撤销(生产反馈=任务
|
|
101
|
+
奖励/结果确认;A/B 验证:稀疏 20% 反馈即拿满质量,噪声 10%→79.9%)。"""
|
|
102
|
+
self.metrics.bump("learns")
|
|
103
|
+
res = self.sd.learn_from_result(obj=obj, act=act,
|
|
104
|
+
actual=actual, cur=cur)
|
|
105
|
+
self.landing.deposit(obj=obj, act=act, actual=actual, cur=cur)
|
|
106
|
+
if ok is not None and cur is not None and act is not None:
|
|
107
|
+
self.landing.feedback(cur, act, ok=bool(ok))
|
|
108
|
+
return res
|
|
109
|
+
|
|
110
|
+
def feedback(self, cur, act, ok=True):
|
|
111
|
+
"""独立反馈口(不带学习语义时用):good 模式沉淀/撤销。"""
|
|
112
|
+
self.metrics.bump("feedbacks")
|
|
113
|
+
return self.landing.feedback(cur, act, ok=ok)
|
|
114
|
+
|
|
115
|
+
def recall(self, obj=None, act=None, k=8):
|
|
116
|
+
"""签名门控召回(跨重启可查,落点层)。"""
|
|
117
|
+
return self.landing.recall(f"{obj}|{act}", k=k)
|
|
118
|
+
|
|
119
|
+
def stats(self):
|
|
120
|
+
return {"core": self.sd.get_stats(), "metrics": self.metrics.summary(),
|
|
121
|
+
"landing_entries": len(self.landing.entries),
|
|
122
|
+
"good_patterns": len(self.landing.good_patterns),
|
|
123
|
+
"landing_bytes": self.landing.stats().get("bytes", 0),
|
|
124
|
+
"replayed": self._replay_done,
|
|
125
|
+
"replay_skipped": self._replay_skipped,
|
|
126
|
+
"replay_failed": self._replay_failed}
|