memgate-mcp 0.0.0-stage → 2026.11.24

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.
Files changed (74) hide show
  1. package/FEATURES.md +81 -0
  2. package/HISTORY.md +23 -0
  3. package/LICENSE +93 -0
  4. package/MANIFEST.md +13 -0
  5. package/MANUAL.md +32 -0
  6. package/README.md +28 -2
  7. package/VERSIONS.json +9 -0
  8. package/bin/memgate-mcp.js +9 -0
  9. package/config/mcp-config-examples.md +31 -0
  10. package/kernel/activity_telemetry.py +51 -0
  11. package/kernel/admission.py +208 -0
  12. package/kernel/calldecay/__init__.py +23 -0
  13. package/kernel/calldecay/__main__.py +7 -0
  14. package/kernel/calldecay/_kernel.py +32 -0
  15. package/kernel/calldecay/adapter.py +126 -0
  16. package/kernel/calldecay/cli.py +80 -0
  17. package/kernel/calldecay/gate.py +93 -0
  18. package/kernel/calldecay/landing.py +1298 -0
  19. package/kernel/calldecay/metrics.py +37 -0
  20. package/kernel/calldecay/mock.py +68 -0
  21. package/kernel/calldecay/pipeline.py +85 -0
  22. package/kernel/calldecay/proxy.py +220 -0
  23. package/kernel/calldecay/summarize.py +401 -0
  24. package/kernel/core/LICENSE +93 -0
  25. package/kernel/core/__init__.py +0 -0
  26. package/kernel/core/accept_contract.py +67 -0
  27. package/kernel/core/chain_probe_world.py +133 -0
  28. package/kernel/core/concept_ontology.py +2401 -0
  29. package/kernel/core/concept_opposition.py +291 -0
  30. package/kernel/core/concept_phase.py +1342 -0
  31. package/kernel/core/concept_principle.py +2481 -0
  32. package/kernel/core/concept_pyramid.py +287 -0
  33. package/kernel/core/concept_space.py +45 -0
  34. package/kernel/core/concept_space_mixin.py +941 -0
  35. package/kernel/core/concept_state.py +2748 -0
  36. package/kernel/core/decision_symbolic.py +245 -0
  37. package/kernel/core/eco_math_world.py +489 -0
  38. package/kernel/core/emergence.py +362 -0
  39. package/kernel/core/events.py +93 -0
  40. package/kernel/core/hebbian.py +117 -0
  41. package/kernel/core/llm_arm.py +551 -0
  42. package/kernel/core/memory_shadow.py +158 -0
  43. package/kernel/core/mes_layer_base.py +309 -0
  44. package/kernel/core/mes_vnext.py +540 -0
  45. package/kernel/core/ontology_core.py +168 -0
  46. package/kernel/core/phase_field.py +187 -0
  47. package/kernel/core/reasoning.py +185 -0
  48. package/kernel/core/rhythm_vnext.py +777 -0
  49. package/kernel/dashboard_render.py +196 -0
  50. package/kernel/depscan_probe.py +96 -0
  51. package/kernel/health_probe.py +186 -0
  52. package/kernel/hebbian_link.py +34 -0
  53. package/kernel/knowledge_distiller/README.md +9 -0
  54. package/kernel/knowledge_distiller/__init__.py +1 -0
  55. package/kernel/knowledge_distiller/knowledge_distiller.py +196 -0
  56. package/kernel/m3_judge.py +215 -0
  57. package/kernel/mechanism_advisor.py +203 -0
  58. package/kernel/mechanism_learner.py +193 -0
  59. package/kernel/memory_core.py +81 -0
  60. package/kernel/quality_gate/README.md +9 -0
  61. package/kernel/quality_gate/__init__.py +1 -0
  62. package/kernel/quality_gate/quality_gate.py +7 -0
  63. package/kernel/registry_gate.py +57 -0
  64. package/kernel/semantic_recall.py +635 -0
  65. package/kernel/tiered_decay/README.md +9 -0
  66. package/kernel/tiered_decay/__init__.py +1 -0
  67. package/kernel/tiered_decay/tiered_decay.py +17 -0
  68. package/kernel/tokenizer/README.md +9 -0
  69. package/kernel/tokenizer/__init__.py +2 -0
  70. package/kernel/tokenizer/tokenizer.py +14 -0
  71. package/kernel/version_binding.py +131 -0
  72. package/mcp_server.py +166 -0
  73. package/package.json +44 -3
  74. package/test/test_mcp.py +54 -0
package/FEATURES.md ADDED
@@ -0,0 +1,81 @@
1
+ # MemGate / MemSteward — Feature Guide
2
+
3
+ Governed memory for LLM agents: the agent remembers, the memory stays clean, and everything is auditable. One kernel, four deployment shapes.
4
+
5
+ ## 1. Memory core (LandingStore)
6
+
7
+ - **Triple-signature entries** — every memory is an (object, action, actual) triple with kind/source metadata, so recall is structured, not fuzzy string matching.
8
+ - **Write path** — admission quality gate -> single-writer protocol -> hard persistence (JSON on disk, crash-safe, survives restart). No background rewrite of your data.
9
+ - **Read path** — **signature-gated recall** (query by object|action keys), hybrid semantic + BM25 retrieval, plus a liveness gate: cold entries are not injected into context, never silently deleted.
10
+ - **Timeline queries** — recall_recent(hours), recall_by_time(start, end), timeline() digest.
11
+ - **Embeddings** — pluggable local embedding backend with a KV cache (EmbedCache) so repeated queries cost nothing.
12
+
13
+ ## 2. Quality pipeline (why "governance-grade")
14
+
15
+ - **Admission gate** — echo fragments, ultra-short and junk writes are quarantined automatically before they ever land in the store.
16
+ - **Quarantine + verdicts** — suspicious entries are flagged, not deleted; verification criteria score outcomes.
17
+ - **Feedback loop** — good-mode feedback lands in LandingStore.feedback with revoke support.
18
+ - **Ledger** — every write is traceable through the governance ledger tool. Better to remember less than to remember wrong.
19
+
20
+ ## 3. Liveness decay (memories age)
21
+
22
+ - Entries carry a liveness value that decays over time (default decay factor 0.9, configurable floor).
23
+ - Older memories fade from recall automatically instead of piling up forever.
24
+ - hold(entry) keeps an entry alive (liveness = 1.0) when it matters.
25
+
26
+ ## 4. Governance tool surface (OpenClaw plugin)
27
+
28
+ Four tools out of the box: governance_preflight / governance_ledger / governance_deposit / governance_recall. Plus a Python bridge with 13 subcommands (deposit, recall, digest, ingest, commit, preflight, ledger, constraints, depscan, version, compact, restore, ping) usable from CLI, oneshot, or serve mode. The plugin wires two OpenClaw slots (memory + contextEngine) and ships a three-tier (hot/warm/cold) memory ingest.
29
+
30
+ ## 5. MCP tool surface (memgate-mcp)
31
+
32
+ One MCP server, any host: Claude Code, Cursor, Copilot Studio, Windsurf, Cline, Zed.
33
+
34
+ - memgate_deposit(obj, act, actual, kind, source) — store one governed memory
35
+ - memgate_recall(query, top_k) — signature/keyword recall with scores
36
+ - memgate_stats() — store statistics
37
+ - memgate_compact() — drop redundancy
38
+
39
+ Python >= 3.9, **zero third-party dependencies** (stdlib + shipped kernel). Config: one JSON block in your host config (see config/mcp-config-examples.md).
40
+
41
+ ## 6. Python SDK
42
+
43
+ from memsteward import Memory
44
+ mem = Memory('memory.json')
45
+ mem.deposit('player', 'mining', 'found diamond', kind='experience')
46
+ hits = mem.recall('mining', top_k=5)
47
+ mem.recall_recent(hours=24); mem.timeline(hours=24)
48
+ mem.decay(0.99) # liveness aging
49
+ mem.hold(entry_id) # keep alive
50
+ mem.quarantine(entry_id) # flag low quality
51
+
52
+ Advanced surface (MemStewardLocal): quarantine, distillation, concept space, panoramic/rolling planners, mechanism learner/advisor, zero-intrusion observation wrapper.
53
+
54
+ ## 7. Performance (measured)
55
+
56
+ | Metric | MemSteward | Mem0 | Zep | LangChain |
57
+ |---|---|---|---|---|
58
+ | write | **0.01ms** | 50ms | 100ms | 20ms |
59
+ | retrieve | **<1ms** | 200ms | 300ms | 100ms |
60
+ | quality gate | yes | no | no | no |
61
+ | liveness decay | yes | no | partial | no |
62
+ | fully local | yes | yes | no | partial |
63
+ | Chinese-native tokenizer | yes | partial | partial | partial |
64
+
65
+ ## 8. Privacy and security
66
+
67
+ - All data stays on your machine (MEMSTEWARD_HOME, default ~/.memsteward/). No cloud sync, no telemetry upload.
68
+ - Every write passes the quality gate; single-writer protocol prevents concurrent pollution.
69
+ - Contract first: out-of-contract writes stop for review instead of landing silently.
70
+
71
+ ## 9. Versions and compatibility
72
+
73
+ - Product family: CalVer (YYYY.MM.DD, one release line for all editions). SDK: SemVer (0.x = API may change; 1.0 freezes).
74
+ - VERSIONS.json binds plugin/sdk/bridge protocol/embedding fingerprint; verify with: python3 src/bridge_cli.py version
75
+ - OpenClaw pluginApi >= 2026.9.4; bridge protocol 3; Python >= 3.9.
76
+
77
+ ## 10. License
78
+
79
+ Elastic License 2.0 (SPDX: Elastic-2.0): free for internal and commercial use; do not offer the software itself as a hosted/managed service to third parties; patents licensed with the software (suit terminates); trademarks not licensed with the code. Patent boundaries: PATENTS.md.
80
+
81
+ Deeper documentation: each edition ships a MANUAL.md (promise list + verification contract), a HISTORY.md, and a MANIFEST.md (parts list). The local edition also ships a full capability index (CAPABILITY_INDEX.md).
package/HISTORY.md ADDED
@@ -0,0 +1,23 @@
1
+ # D-MCP Edition · History
2
+
3
+ - **Project opened 2026-11-21 22:40** (decision: "start, manage the platform well, no mess"): strategic call = MCP is the de-facto standard for AI coding platforms (Claude Code / Cursor / Copilot / Windsurf / Cline / Zed all covered); one MCP surface unlocks the whole ecosystem — more leverage than one plugin per host.
4
+ - Shape decision: join the **middleware family** (alongside A/B/C, family management), no separate stovepipe — reuse the family production/listing separation, VERSIONS binding, and registration gate.
5
+ - Implementation decision: **zero third-party dependencies**, hand-rolled MCP stdio (family self-sufficiency philosophy); kernel driven in-process (works offline); semantics mirror the B edition REST surface.
6
+ - 2026-11-21 23:0x smoke all green (handshake / four tools / error code -32601), see test/test_mcp.py.
7
+
8
+ ## Correction record (2026-11-21 22:5x, opened after the question "0.1.0 does not look right")
9
+
10
+ - **Original text**: VERSIONS.json / server version = 0.1.0
11
+ - **Root cause**: opening the project casually started a new semver line, violating the family versioning rule (VERSIONS-3tier.md, decided 2026-11-17: version format YYYY.MM.DD, three lines increment independently); the same day the A/B lines were already drifting (npm 0.2.x forced by re-release, GHCR 0.1.2 an ad-hoc in-tree number) — three lines, three eras = confirmed version drift
12
+ - **Current ruling**: the D edition first number = **2026.11.21** (family scheme, and legal semver for npm); **all lines standardize on YYYY.MM.DD going forward** — published npm 0.2.x / GHCR 0.1.2 are immutable; from the next release they rejoin the line
13
+ - **Impact**: all D management files (VERSIONS.json / mcp_server.py / manual) updated; A/B listing artifacts unchanged
14
+ - **Open items**: the B line next release uses 2026.11.x; the npm line next release likewise rejoins (the version jump is the drift zero point)
15
+ - **2026-11-22 listing package built**: 73 files + memgate-mcp-2026.11.21.tgz (350KB), smoke all green; added package.json + bin/memgate-mcp.js launcher; MANIFEST version corrected 0.1.0 -> 2026.11.21.
16
+
17
+ ## Correction record (2026-11-22)
18
+
19
+ - License statement corrected: the top-level LICENSE had mistakenly held old commercial-license text; that day it first rejoined the unified statement, then switched to Elastic License 2.0 per plan A (see next entry).
20
+
21
+ ## Correction record (2026-11-22)
22
+
23
+ - License switched again: everything under **Elastic License 2.0** (SPDX: Elastic-2.0) — standard terms, free internal and commercial use, no offering the software itself as a hosted/managed service to third parties, patents licensed with the software (suit terminates), trademarks not licensed with code. The previous Unified Statement v1.3 wording is retired.
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/MANUAL.md ADDED
@@ -0,0 +1,32 @@
1
+ # MemGate MCP (D-MCP Edition) Manual
2
+
3
+ **In one line**: connect governed memory (audited writes/reads, quality gates, statistical ledgers) to any MCP-capable AI platform — Claude Code, Cursor, Copilot Studio, Windsurf, Cline, Zed, one surface for all.
4
+
5
+ ## What it solves
6
+
7
+ AI assistants and coding agents keep scattered memories: cross-project pollution, no audit, fast forgetting. MemGate MCP provides **governed memory access**: every entry carries an object-action-content triple signature, passes the quality gate, and enters the statistical ledger.
8
+
9
+ ## Quick start
10
+
11
+ # 1. smoke self-test (should print SMOKE ALL GREEN)
12
+ python3 test/test_mcp.py
13
+
14
+ # 2. connect a host (Claude Desktop example; see config/mcp-config-examples.md)
15
+ # paste the config JSON into claude_desktop_config.json, restart the host
16
+
17
+ ## Tool surface (same-source semantics with the Plugin Edition (A) / Complete Edition (B))
18
+
19
+ - **memgate_deposit(obj, act, actual, kind, source)** — store one governed memory
20
+ - **memgate_recall(query, top_k)** — recall by signature/keyword (with scores)
21
+ - **memgate_stats()** — memory store statistics
22
+ - **memgate_compact()** — compact (drop redundancy)
23
+
24
+ ## Environment
25
+
26
+ - Python >= 3.9, **zero third-party dependencies** (stdlib + shipped kernel)
27
+ - MEMGATE_HOME: memory store directory (default ~/.memgate-mcp) — multi-project isolation = one directory per project
28
+ - family relationship: the kernel is single-source with the Complete Edition (B) (sync_kernel.sh link); production changes go back to the family single source
29
+
30
+ ## Version
31
+
32
+ 2026.11.21 (2026-11-21, family YYYY.MM.DD scheme) — MCP 2025-06-18, four-tool surface, smoke test shipped.
package/README.md CHANGED
@@ -1,3 +1,29 @@
1
- # Temporary Holding Version
1
+ # MemGate MCP (D-MCP Edition)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **In one line**: connect governed memory (audited writes/reads, quality gates, statistical ledgers) to any MCP-capable AI platform — Claude Code, Cursor, Copilot Studio, Windsurf, Cline, Zed, one surface for all.
4
+
5
+ ## Quick start
6
+
7
+ # 1. smoke self-test (should print SMOKE ALL GREEN)
8
+ python3 test/test_mcp.py
9
+
10
+ # 2. connect a host (Claude Desktop example; see config/mcp-config-examples.md)
11
+ # paste the config JSON into claude_desktop_config.json, restart the host
12
+ # after npm install the shipped launcher works too: "command": "memgate-mcp"
13
+
14
+ ## Tool surface (same-source semantics with the Plugin Edition (A) / Complete Edition (B))
15
+
16
+ - **memgate_deposit(obj, act, actual, kind, source)** — store one governed memory
17
+ - **memgate_recall(query, top_k)** — recall by signature/keyword (with scores)
18
+ - **memgate_stats()** — memory store statistics
19
+ - **memgate_compact()** — compact (drop redundancy)
20
+
21
+ ## Environment
22
+
23
+ - Python >= 3.9, **zero third-party dependencies** (stdlib + shipped kernel)
24
+ - MEMGATE_HOME: memory store directory (default ~/.memgate-mcp) — multi-project isolation = one directory per project
25
+ - family relationship: tool semantics are same-source with the Plugin Edition (A) / Complete Edition (B) (deposit/recall/stats/compact)
26
+
27
+ ## Version
28
+
29
+ 2026.11.21 (2026-11-21, family YYYY.MM.DD scheme) — MCP 2025-06-18, four-tool surface, smoke test shipped.
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,7 @@
1
+ # -*- coding: utf-8 -*-
2
+ """python -m calldecay 入口。"""
3
+
4
+ from .cli import main
5
+
6
+ if __name__ == "__main__":
7
+ main()