@furongjun1999/dsh-memory 0.10.1 → 0.10.3
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/CHANGELOG.en.md +65 -0
- package/CHANGELOG.md +642 -516
- package/README.en.md +1 -1
- package/README.md +2 -2
- package/docs/mdcg/cogmap_ops.md +15 -13
- package/lib/tools.d.ts +2 -2
- package/md_cg/bucketscope.py +36 -18
- package/md_cg/cohesion.py +337 -0
- package/md_cg/config_registry_bulk.py +5 -0
- package/md_cg/constraint_audit.py +231 -0
- package/md_cg/constraint_watch.py +206 -0
- package/md_cg/context_audit.py +240 -0
- package/md_cg/context_plan.py +142 -0
- package/md_cg/distill.py +247 -0
- package/md_cg/dossier.py +151 -0
- package/md_cg/entities.py +133 -0
- package/md_cg/mcp_server.py +60 -7
- package/md_cg/mdcg.py +27 -0
- package/md_cg/mdcos.py +319 -2
- package/md_cg/op_table.py +14 -0
- package/md_cg/profiles.py +298 -0
- package/md_cg/protocol.py +7 -1
- package/md_cg/reldate.py +142 -0
- package/md_cg/selfstmt.py +139 -0
- package/md_cg/state_slots.py +4 -0
- package/md_cg/state_view.py +181 -0
- package/md_cg/sustain.py +28 -2
- package/md_cg/test_alternatives_historical.py +4 -1
- package/md_cg/test_bucket_time_rounds.py +87 -0
- package/md_cg/test_cohesion.py +107 -0
- package/md_cg/test_constraint_audit.py +87 -0
- package/md_cg/test_constraint_watch.py +108 -0
- package/md_cg/test_context_audit.py +110 -0
- package/md_cg/test_context_plan.py +81 -0
- package/md_cg/tokens.py +1 -1
- package/md_cg/version_anchor.py +84 -1
- package/md_cg/whitebox_kb/wisdom/code_solidified.json +6195 -6195
- package/package.json +137 -137
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""约束对账(constraint_audit)——用**操作日志**核对约束,补 H7 的不可测。
|
|
3
|
+
|
|
4
|
+
为什么需要(2026-10-24 第四十六轮):
|
|
5
|
+
第二十四轮判定 H7「无工具」,因为文本检查器测不到行为。
|
|
6
|
+
第四十六轮找到通道:**行为本身不可读,但操作留下的记录可读**——
|
|
7
|
+
工具不在文本层,在日志层。
|
|
8
|
+
|
|
9
|
+
本模块做的是:拿一份约束清单 + 一份操作日志(git log 或任意文本),
|
|
10
|
+
逐条看「这条约束在日志里有没有对应记录」。
|
|
11
|
+
|
|
12
|
+
**三条必须说清的边界**:
|
|
13
|
+
|
|
14
|
+
1. **「无记录」≠「没违反」**(I6 的另一面)
|
|
15
|
+
日志只能证明「发生过」,不能证明「没发生」。
|
|
16
|
+
所以本模块的结论是「有记录 / 无记录」,**不是「遵守 / 违反」**。
|
|
17
|
+
|
|
18
|
+
2. **匹配仍是词面**
|
|
19
|
+
约束是自然语言,日志是提交信息——本模块用实词覆盖做近似匹配。
|
|
20
|
+
所以它会漏掉「说法不同」的记录(第三十九、四十六轮已证:符号不被词频表示)。
|
|
21
|
+
|
|
22
|
+
3. **它不替你想该查什么**
|
|
23
|
+
「这条约束对应查哪类日志」是语义判断(D_meta);
|
|
24
|
+
本模块只执行对账(D_task),不生成检查方法。
|
|
25
|
+
|
|
26
|
+
用一句话定位:
|
|
27
|
+
**它把「让模型自查」换成「查记录」——查的是留痕,不是叙述。**
|
|
28
|
+
|
|
29
|
+
**第四条边界(2026-10-24 第四十八轮实测,最要紧的一条)**:
|
|
30
|
+
|
|
31
|
+
**它的前提不是「有日志」,是「留痕率」。**
|
|
32
|
+
|
|
33
|
+
实测:用本会话 5 条约束去对账 16 条 git 提交,**5/5 全部查不到**——
|
|
34
|
+
而我明知自己违反了其中 2 条(覆盖文件、静默降级)。**漏检率 100%**。
|
|
35
|
+
|
|
36
|
+
根因:那两次违反**从未提交**(覆盖后被 pre-commit 钩子挡住、随即 git checkout
|
|
37
|
+
恢复;静默降级是瞬时缺陷,修了没单独提交)。**日志只记录「已提交」的行为。**
|
|
38
|
+
|
|
39
|
+
所以本模块能验证的是「**留痕行为**的违反率」,不是「所有行为」。
|
|
40
|
+
提升留痕率是前置条件(如「凡改必有提交」),而**对话中的判断永远不留痕**——
|
|
41
|
+
那部分属于 D_meta,任何日志方案都覆盖不到。
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
import re
|
|
45
|
+
|
|
46
|
+
__all__ = ["cross_check", "parse_constraints", "trace_gap", "MATCH_THRESHOLD"]
|
|
47
|
+
|
|
48
|
+
#: 约束与日志的实词覆盖阈值。低于此值视为「日志里没有对应记录」。
|
|
49
|
+
MATCH_THRESHOLD = 0.6
|
|
50
|
+
|
|
51
|
+
_CONSTRAINT_RE = re.compile(r"^[\s\-*•]*([C##]?\d{1,3})[\.、::]?\s+(.+?)\s*$", re.M)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def parse_constraints(list_text):
|
|
55
|
+
"""解析约束清单(形如「C1 不得覆盖旧文件」)。"""
|
|
56
|
+
out = []
|
|
57
|
+
for m in _CONSTRAINT_RE.finditer(str(list_text or "")):
|
|
58
|
+
cid, body = m.group(1), m.group(2).strip()
|
|
59
|
+
if 2 <= len(body) <= 100:
|
|
60
|
+
out.append({"id": cid if cid.upper().startswith("C") else "C" + cid.lstrip("C##"),
|
|
61
|
+
"text": body})
|
|
62
|
+
return out
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _tokens(s):
|
|
66
|
+
s = str(s or "")
|
|
67
|
+
zh = re.findall(r"[\u4e00-\u9fa5]", s)
|
|
68
|
+
bigrams = {"".join(zh[i:i + 2]) for i in range(len(zh) - 1)}
|
|
69
|
+
words = {w.lower() for w in re.findall(r"[A-Za-z_]{2,}", s)}
|
|
70
|
+
return bigrams | words
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def cross_check(constraints, log_text, threshold=MATCH_THRESHOLD):
|
|
74
|
+
"""逐条对账。
|
|
75
|
+
|
|
76
|
+
参数:
|
|
77
|
+
constraints 清单文本或 [{id,text}]
|
|
78
|
+
log_text 操作日志正文(git log 输出或任意文本)
|
|
79
|
+
threshold 实词覆盖阈值
|
|
80
|
+
|
|
81
|
+
返回 dict:
|
|
82
|
+
checked [{id,text,cover,evidence}] 日志里有对应记录
|
|
83
|
+
unchecked [{id,text,cover}] 日志里没找到(**不等于没违反**)
|
|
84
|
+
ok True=全部有记录;False=有未找到的;None=无法判定(无清单/无日志)
|
|
85
|
+
note 边界提示
|
|
86
|
+
"""
|
|
87
|
+
items = constraints
|
|
88
|
+
if isinstance(items, str):
|
|
89
|
+
items = parse_constraints(items)
|
|
90
|
+
items = [it for it in (items or []) if it and it.get("text")]
|
|
91
|
+
log = str(log_text or "")
|
|
92
|
+
|
|
93
|
+
if not items:
|
|
94
|
+
return {"ok": None, "checked": [], "unchecked": [],
|
|
95
|
+
"reason": "没有可对账的约束"}
|
|
96
|
+
if not log.strip():
|
|
97
|
+
return {"ok": None, "checked": [], "unchecked": [],
|
|
98
|
+
"reason": "日志为空,无从对账"}
|
|
99
|
+
|
|
100
|
+
log_tokens = _tokens(log)
|
|
101
|
+
log_lines = [ln for ln in log.splitlines() if ln.strip()]
|
|
102
|
+
checked, unchecked = [], []
|
|
103
|
+
for it in items:
|
|
104
|
+
ct = _tokens(it["text"])
|
|
105
|
+
if not ct:
|
|
106
|
+
unchecked.append({"id": it.get("id", ""), "text": it["text"], "cover": 0.0})
|
|
107
|
+
continue
|
|
108
|
+
cover = len(ct & log_tokens) / float(len(ct))
|
|
109
|
+
row = {"id": it.get("id", ""), "text": it["text"], "cover": round(cover, 3)}
|
|
110
|
+
if cover >= threshold:
|
|
111
|
+
# 找最相关的那一行作为证据
|
|
112
|
+
best, best_c = "", 0.0
|
|
113
|
+
for ln in log_lines:
|
|
114
|
+
lt = _tokens(ln)
|
|
115
|
+
if not lt:
|
|
116
|
+
continue
|
|
117
|
+
c = len(ct & lt) / float(len(ct))
|
|
118
|
+
if c > best_c:
|
|
119
|
+
best, best_c = ln.strip()[:90], c
|
|
120
|
+
row["evidence"] = best
|
|
121
|
+
checked.append(row)
|
|
122
|
+
else:
|
|
123
|
+
unchecked.append(row)
|
|
124
|
+
|
|
125
|
+
return {
|
|
126
|
+
"ok": not unchecked,
|
|
127
|
+
"checked": checked,
|
|
128
|
+
"unchecked": unchecked,
|
|
129
|
+
"counts": {"total": len(items), "checked": len(checked),
|
|
130
|
+
"unchecked": len(unchecked)},
|
|
131
|
+
"note": "「无记录」**不等于**「没违反」(I6):日志只能证明发生过,不能证明没发生。"
|
|
132
|
+
"本结论是「有记录/无记录」,不是「遵守/违反」。",
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def trace_gap(repo=None, paths=None):
|
|
137
|
+
"""留痕缺口检查——找出「有行为但没留痕」的改动。
|
|
138
|
+
|
|
139
|
+
为什么需要(2026-10-24 第四十八轮):H7 首次实测漏检率 100%,
|
|
140
|
+
根因是违反从未提交、故日志无痕。**先能查出「没留痕的改动」,
|
|
141
|
+
才谈得上用日志验证行为。**
|
|
142
|
+
|
|
143
|
+
做法:跑 git status,把未提交的改动列出来——它们就是「尚未留痕的行为」。
|
|
144
|
+
|
|
145
|
+
返回 dict:
|
|
146
|
+
ok True=工作区干净(当前改动都已留痕);False=有未留痕改动
|
|
147
|
+
untracked 未跟踪文件(新文件,行为没进历史)
|
|
148
|
+
modified 已修改未提交
|
|
149
|
+
staged 已暂存未提交
|
|
150
|
+
note 边界提示
|
|
151
|
+
|
|
152
|
+
注意 ok=False **不等于违反约束**——只是「这些改动还没进历史」,
|
|
153
|
+
提交后就留痕了。它是**前置检查**,不是违规判定。
|
|
154
|
+
"""
|
|
155
|
+
import os
|
|
156
|
+
import subprocess
|
|
157
|
+
root = str(repo or os.getcwd())
|
|
158
|
+
try:
|
|
159
|
+
env = dict(os.environ)
|
|
160
|
+
env.setdefault("PYTHONUTF8", "1")
|
|
161
|
+
r = subprocess.run(["git", "status", "--porcelain"],
|
|
162
|
+
capture_output=True, text=True, encoding="utf-8",
|
|
163
|
+
errors="replace", env=env, cwd=root, shell=False)
|
|
164
|
+
except Exception as exc: # noqa: BLE001
|
|
165
|
+
return {"ok": None, "reason": "无法执行 git status:%s" % str(exc)[:80]}
|
|
166
|
+
if r.returncode != 0:
|
|
167
|
+
return {"ok": None, "reason": "git status 返回 %d" % r.returncode}
|
|
168
|
+
|
|
169
|
+
untracked, modified, staged = [], [], []
|
|
170
|
+
for line in (r.stdout or "").splitlines():
|
|
171
|
+
if not line.strip():
|
|
172
|
+
continue
|
|
173
|
+
code, _, path = line[:2], line[2:3], line[3:].strip()
|
|
174
|
+
if paths and not any(pp in path for pp in paths):
|
|
175
|
+
continue
|
|
176
|
+
if code.strip() == "??":
|
|
177
|
+
untracked.append(path)
|
|
178
|
+
elif code[0] not in (" ", "?"):
|
|
179
|
+
staged.append(path)
|
|
180
|
+
else:
|
|
181
|
+
modified.append(path)
|
|
182
|
+
|
|
183
|
+
total = len(untracked) + len(modified) + len(staged)
|
|
184
|
+
return {
|
|
185
|
+
"ok": total == 0,
|
|
186
|
+
"untracked": untracked,
|
|
187
|
+
"modified": modified,
|
|
188
|
+
"staged": staged,
|
|
189
|
+
"counts": {"untracked": len(untracked), "modified": len(modified),
|
|
190
|
+
"staged": len(staged), "total": total},
|
|
191
|
+
"note": "ok=False 只表示「这些改动尚未进历史」,**不等于违反约束**——"
|
|
192
|
+
"提交即留痕。本函数是 H7 的**前置检查**,不是违规判定。",
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def main(argv=None):
|
|
197
|
+
"""CLI:python -m md_cg.constraint_audit <清单文件> <日志文件> [--json]"""
|
|
198
|
+
import json
|
|
199
|
+
import sys
|
|
200
|
+
try:
|
|
201
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
202
|
+
except Exception:
|
|
203
|
+
pass
|
|
204
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
205
|
+
if len(argv) < 2:
|
|
206
|
+
print("用法:python -m md_cg.constraint_audit <清单文件> <日志文件> [--json]")
|
|
207
|
+
return 2
|
|
208
|
+
try:
|
|
209
|
+
with open(argv[0], encoding="utf-8", errors="replace") as fh:
|
|
210
|
+
lst = fh.read()
|
|
211
|
+
with open(argv[1], encoding="utf-8", errors="replace") as fh:
|
|
212
|
+
log = fh.read()
|
|
213
|
+
except OSError as exc:
|
|
214
|
+
print("读文件失败:%s" % exc, file=sys.stderr)
|
|
215
|
+
return 2
|
|
216
|
+
rep = cross_check(lst, log)
|
|
217
|
+
if "--json" in argv:
|
|
218
|
+
print(json.dumps(rep, ensure_ascii=False, indent=1))
|
|
219
|
+
else:
|
|
220
|
+
c = rep.get("counts", {})
|
|
221
|
+
print("约束 %d 条:有记录 %d,无记录 %d"
|
|
222
|
+
% (c.get("total", 0), c.get("checked", 0), c.get("unchecked", 0)))
|
|
223
|
+
for u in rep.get("unchecked", []):
|
|
224
|
+
print(" [无记录] %s %s(覆盖 %.0f%%)" % (u["id"], u["text"], u["cover"] * 100))
|
|
225
|
+
print("")
|
|
226
|
+
print("注:%s" % rep["note"])
|
|
227
|
+
return 0 if rep.get("ok") is not False else 1
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
if __name__ == "__main__":
|
|
231
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""约束巡检(constraint_watch)——把「核对清单」从模型自觉变成管线动作。
|
|
3
|
+
|
|
4
|
+
为什么需要(2026-10-24,上下文管理研究第二十二轮):
|
|
5
|
+
H1 的链路是「约束→清单→可检索→主动核对→发现丢失」。
|
|
6
|
+
前三环已实证(清单可写入、可被内容检索、4/4 top-1),
|
|
7
|
+
**第④环「主动核对」是断点**——没有强制机制,且这是同一病灶的第三次显形:
|
|
8
|
+
第三轮 口头约束不持久 —— 没强制进流程
|
|
9
|
+
第十二轮 验证不发生 —— 没强制进流程
|
|
10
|
+
第二十二轮 清单不会被主动查 —— 没强制进流程
|
|
11
|
+
|
|
12
|
+
所以本模块的立场是:**不依赖模型自觉,由管线定时调用**。
|
|
13
|
+
|
|
14
|
+
与既有机制的关系:
|
|
15
|
+
形态与 sustain.py 的 _tick_tidy 同构(定时巡检),
|
|
16
|
+
但检查对象不同:那边巡检记忆库卫生,这边巡检「当前上下文还撑不撑得住约束」。
|
|
17
|
+
|
|
18
|
+
判据(对齐第二十一轮实测:摘要压缩杀死 80% 约束):
|
|
19
|
+
一条约束「在场」= 当前文本覆盖其实词(中文二字组+英文词)>= COVER_THRESHOLD。
|
|
20
|
+
低于阈值即判缺失——宁可误报,不可漏报(漏报就是静默丢约束)。
|
|
21
|
+
|
|
22
|
+
诚实边界:
|
|
23
|
+
1. 这是**词汇覆盖判定**,不是语义蕴含——覆盖高不代表语义上推得出;
|
|
24
|
+
2. 阈值 0.5 来自第二十一轮同一方法,未做充分验证;
|
|
25
|
+
3. 本模块**不读模型上下文**,当前文本必须由调用方传入;
|
|
26
|
+
4. 它只负责「报缺失」,不负责「回取」——回取是调用方的事。
|
|
27
|
+
6. **字面匹配只认「同样的说法」,不认「同样的意思」**(2026-10-24 自指审计实测):
|
|
28
|
+
清单写「丢弃率等于 1 减 1 除以平均段长」,文档写「1 − 1/平均段长」,
|
|
29
|
+
二字组交集只有 3 个,覆盖率 0.455 → 判缺失,**但内容其实在**。
|
|
30
|
+
同理「0.00 到 0.28」对不上「0.00–0.28」(en dash)。
|
|
31
|
+
这是**假阴性**,比假阳性更危险:会让人以为内容丢了去重复补充。
|
|
32
|
+
识别同义表述需语义理解(数学符号/同义词典/向量),三者都非本模块能做的。
|
|
33
|
+
**故判「不在」时应先怀疑表述差异,再怀疑内容缺失。**
|
|
34
|
+
|
|
35
|
+
5. **它测「表述在不在」,不测「行为守没守」**(2026-10-24 自指实验实测):
|
|
36
|
+
同一次会话里,本模块对 5 条约束报覆盖率 100%(因为归档文档讨论过这些
|
|
37
|
+
约束词),但实际行为违反了其中 2 条(覆盖文件、静默降级)。
|
|
38
|
+
**讨论 ≠ 遵守。** 故本模块只能用于「上下文退化」检测(H1),
|
|
39
|
+
不能用于「行为合规」检测(H7)——后者需要行为观测,不是文本比对。
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
import re
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"parse_constraints", "coverage", "check", "retrieve_for",
|
|
46
|
+
"COVER_THRESHOLD", "CONSTRAINT_RE",
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
#: 实词覆盖阈值:低于此值判为「约束已不在场」。与第二十一轮同法。
|
|
50
|
+
COVER_THRESHOLD = 0.5
|
|
51
|
+
|
|
52
|
+
#: 清单条目形如 "C1 不得覆盖旧文件" 或 "- C1 不得覆盖旧文件" 或 "C1. 不得…"
|
|
53
|
+
CONSTRAINT_RE = re.compile(r"^[\s\-*•]*([C##]?\d{1,3})[\.、::]?\s+(.+?)\s*$", re.M)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _content_words(text):
|
|
57
|
+
"""实词集合:中文二字组 + 英文/标识符词。"""
|
|
58
|
+
s = str(text or "")
|
|
59
|
+
zh = re.findall(r"[\u4e00-\u9fa5]", s)
|
|
60
|
+
bigrams = {"".join(zh[i:i + 2]) for i in range(len(zh) - 1)}
|
|
61
|
+
words = {w.lower() for w in re.findall(r"[A-Za-z_]{2,}", s)}
|
|
62
|
+
return bigrams | words
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def parse_constraints(list_text):
|
|
66
|
+
"""从清单文本里解析约束条目。
|
|
67
|
+
|
|
68
|
+
只认「带编号的短行」——避免把说明文字当成约束。
|
|
69
|
+
返回 [{"id": "C1", "text": "不得覆盖旧文件"}, ...]
|
|
70
|
+
"""
|
|
71
|
+
out = []
|
|
72
|
+
for m in CONSTRAINT_RE.finditer(str(list_text or "")):
|
|
73
|
+
cid, body = m.group(1), m.group(2).strip()
|
|
74
|
+
# 短行才可能是约束;长句多为说明
|
|
75
|
+
if 2 <= len(body) <= 80:
|
|
76
|
+
if not cid.upper().startswith("C") and not cid.isdigit():
|
|
77
|
+
continue
|
|
78
|
+
out.append({"id": ("C" + cid.lstrip("C##")) if not cid.upper().startswith("C") else cid,
|
|
79
|
+
"text": body})
|
|
80
|
+
return out
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def coverage(constraint_text, current_text):
|
|
84
|
+
"""一条约束在当前文本中的实词覆盖率 [0,1]。"""
|
|
85
|
+
cw = _content_words(constraint_text)
|
|
86
|
+
if not cw:
|
|
87
|
+
return 0.0
|
|
88
|
+
return len(cw & _content_words(current_text)) / float(len(cw))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def check(constraints, current_text, threshold=COVER_THRESHOLD):
|
|
92
|
+
"""逐条核对。返回 dict:
|
|
93
|
+
|
|
94
|
+
ok True=全部在场;False=有缺失;None=无法判定(无约束/空文本)
|
|
95
|
+
present [{id,text,cover}]
|
|
96
|
+
missing [{id,text,cover,advice}]
|
|
97
|
+
advice '回取' / '报警' —— 按底稿 C3 三选一给出建议
|
|
98
|
+
|
|
99
|
+
注意 ok=None 与 False 不同:前者是「没东西可查」,后者是「查出缺失」。
|
|
100
|
+
"""
|
|
101
|
+
items = constraints
|
|
102
|
+
if isinstance(items, str):
|
|
103
|
+
items = parse_constraints(items)
|
|
104
|
+
items = [it for it in (items or []) if it and it.get("text")]
|
|
105
|
+
text = str(current_text or "")
|
|
106
|
+
|
|
107
|
+
if not items:
|
|
108
|
+
return {"ok": None, "present": [], "missing": [],
|
|
109
|
+
"reason": "没有可核对的约束"}
|
|
110
|
+
if not text.strip():
|
|
111
|
+
return {"ok": None, "present": [], "missing": [],
|
|
112
|
+
"reason": "当前文本为空,无法核对"}
|
|
113
|
+
|
|
114
|
+
present, missing = [], []
|
|
115
|
+
for it in items:
|
|
116
|
+
c = coverage(it["text"], text)
|
|
117
|
+
row = {"id": it.get("id", ""), "text": it["text"], "cover": round(c, 3)}
|
|
118
|
+
if c >= threshold:
|
|
119
|
+
present.append(row)
|
|
120
|
+
else:
|
|
121
|
+
# 覆盖率介于 0 与阈值之间 → 可能在库里但被压掉了,建议回取;
|
|
122
|
+
# 完全为 0 → 连痕迹都没有,建议报警
|
|
123
|
+
row["advice"] = "回取" if c > 0 else "报警"
|
|
124
|
+
missing.append(row)
|
|
125
|
+
|
|
126
|
+
return {"ok": not missing, "present": present, "missing": missing,
|
|
127
|
+
"threshold": threshold,
|
|
128
|
+
"counts": {"total": len(items), "present": len(present),
|
|
129
|
+
"missing": len(missing)}}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def retrieve_for(constraint_text, cg, k=3):
|
|
133
|
+
"""为一条缺失的约束回取候选原文(框架 v4 第⑤步「三选一」中的「回取」)。
|
|
134
|
+
|
|
135
|
+
为什么需要:本模块此前只做到「报缺失」,没做到「回取」。
|
|
136
|
+
本函数补上这一环:拿约束文本去记忆库检索,返回候选出处。
|
|
137
|
+
|
|
138
|
+
**找不到不等于不存在**(智能论 I6):ok=False 只表示「这次没检索到」,
|
|
139
|
+
不等于「库里没有」,调用方不得据此断言「无出处」。
|
|
140
|
+
"""
|
|
141
|
+
text = str(constraint_text or "").strip()
|
|
142
|
+
if not text:
|
|
143
|
+
return {"ok": None, "candidates": [], "note": "约束文本为空"}
|
|
144
|
+
if cg is None:
|
|
145
|
+
return {"ok": None, "candidates": [],
|
|
146
|
+
"note": "未接入记忆库(cg=None),无法回取"}
|
|
147
|
+
try:
|
|
148
|
+
res = cg.search(text, k=k)
|
|
149
|
+
except Exception as exc: # noqa: BLE001
|
|
150
|
+
return {"ok": None, "candidates": [],
|
|
151
|
+
"note": "检索异常:%s" % str(exc)[:80]}
|
|
152
|
+
hits = res[0] if isinstance(res, tuple) else res
|
|
153
|
+
out = []
|
|
154
|
+
for el in (hits or []):
|
|
155
|
+
node = el[0] if isinstance(el, tuple) else el
|
|
156
|
+
if isinstance(node, dict):
|
|
157
|
+
nid = node.get("id")
|
|
158
|
+
content = (node.get("content") or "")[:120].replace(chr(10), " ")
|
|
159
|
+
if nid:
|
|
160
|
+
out.append({"id": nid, "snippet": content})
|
|
161
|
+
if out:
|
|
162
|
+
return {"ok": True, "candidates": out,
|
|
163
|
+
"note": "检索到 %d 条候选,需判断是否即为出处" % len(out)}
|
|
164
|
+
return {"ok": False, "candidates": [],
|
|
165
|
+
"note": "本次未检索到(不等于库里没有,见 I6)"}
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def main(argv=None):
|
|
169
|
+
"""CLI:从清单文件读约束,从当前文本文件读上下文。
|
|
170
|
+
|
|
171
|
+
用法:python -m md_cg.constraint_watch <清单文件> <当前文本文件> [--json]
|
|
172
|
+
"""
|
|
173
|
+
import json
|
|
174
|
+
import sys
|
|
175
|
+
try:
|
|
176
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
177
|
+
except Exception:
|
|
178
|
+
pass
|
|
179
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
180
|
+
if len(argv) < 2:
|
|
181
|
+
print("用法:python -m md_cg.constraint_watch <清单文件> <当前文本文件> [--json]")
|
|
182
|
+
return 2
|
|
183
|
+
try:
|
|
184
|
+
with open(argv[0], encoding="utf-8", errors="replace") as fh:
|
|
185
|
+
list_text = fh.read()
|
|
186
|
+
with open(argv[1], encoding="utf-8", errors="replace") as fh:
|
|
187
|
+
cur = fh.read()
|
|
188
|
+
except OSError as exc:
|
|
189
|
+
print("读文件失败:%s" % exc, file=sys.stderr)
|
|
190
|
+
return 2
|
|
191
|
+
rep = check(list_text, cur)
|
|
192
|
+
if "--json" in argv:
|
|
193
|
+
print(json.dumps(rep, ensure_ascii=False, indent=1))
|
|
194
|
+
else:
|
|
195
|
+
print("约束 %d 条:在场 %d,缺失 %d"
|
|
196
|
+
% (rep.get("counts", {}).get("total", 0),
|
|
197
|
+
rep.get("counts", {}).get("present", 0),
|
|
198
|
+
rep.get("counts", {}).get("missing", 0)))
|
|
199
|
+
for m in rep.get("missing", []):
|
|
200
|
+
print(" [缺失] %s %s(覆盖 %.0f%%,建议:%s)"
|
|
201
|
+
% (m["id"], m["text"], m["cover"] * 100, m["advice"]))
|
|
202
|
+
return 0 if rep.get("ok") is not False else 1
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
if __name__ == "__main__":
|
|
206
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""上下文审计(context_audit)——一次跑完三种损失的检查。
|
|
3
|
+
|
|
4
|
+
框架 v5 第⑤步要求「三种损失各查一遍」:
|
|
5
|
+
丢弃 → constraint_watch.check (约束表述还在不在)
|
|
6
|
+
稀释 → cohesion.signal_ratio (目标被淹没得多深)
|
|
7
|
+
断裂 → cohesion.seam_ratio (拼装接缝接不接得上)
|
|
8
|
+
|
|
9
|
+
本模块把三者合成一次调用,并给出**一个**判定。三点设计立场:
|
|
10
|
+
|
|
11
|
+
1. **按层级裁剪要求**(框架 v5 第②步):
|
|
12
|
+
L1 任务不要求接缝(并列够用),L3 才要求连续。所以不是所有损失对
|
|
13
|
+
所有任务都算失败——本模块按 plan 出的层级决定哪些检查生效。
|
|
14
|
+
|
|
15
|
+
2. **None 不默认通过,也不判坏**:
|
|
16
|
+
任一检查为 None 且有检查为 True 时,判定为 UNKNOWN——
|
|
17
|
+
「没能核对」既不能当通过,也不能当失败。
|
|
18
|
+
|
|
19
|
+
3. **只报不做**:
|
|
20
|
+
本模块给建议(回取/报警/显式降级),但**不执行**。
|
|
21
|
+
执行要改上下文,那是调用方的事——这条边界与三个底层工具一致。
|
|
22
|
+
|
|
23
|
+
**覆盖范围(2026-10-24 第五十一轮实测补全,重要)**:
|
|
24
|
+
|
|
25
|
+
本模块只覆盖**三种可测失效**:丢弃(约束在场)、稀释(信噪比)、断裂(接缝)。
|
|
26
|
+
|
|
27
|
+
**另外三种失效它测不到**,且实测证明它们能让「三种全过」:
|
|
28
|
+
错位 —— 内容对、接缝对,但**配错了任务/对象/条件**
|
|
29
|
+
过期 —— 内容曾对,但**条件已变**(如引用了旧版本表述)
|
|
30
|
+
失真 —— 内容本身**就是错的**
|
|
31
|
+
|
|
32
|
+
三者全部落在 D_meta 侧(第四十五轮),**任何只读文本的工具都测不到**。
|
|
33
|
+
对策不是改工具,而是制度:
|
|
34
|
+
错位 → 每份 checklist 显式绑定任务,不能跨任务复用
|
|
35
|
+
过期 → 材料带版本锚(纪律第 19 条已要求「版本锚三元」)
|
|
36
|
+
失真 → 证据链与外部裁决(智能论 I14:回执不得自带真值)
|
|
37
|
+
|
|
38
|
+
**所以 verdict=PASS 只意味着「三种可测失效全过」,不意味着「这份上下文一定对」。**
|
|
39
|
+
|
|
40
|
+
**使用规则(2026-10-24 自指审计得出,重要)**:
|
|
41
|
+
|
|
42
|
+
checklist 必须**按任务裁剪**,不能把「会话全部约束」直接塞进去。
|
|
43
|
+
|
|
44
|
+
混用会导致每次审计都 FAIL——不是因为上下文有问题,是因为问了不相干的问题。
|
|
45
|
+
实测:用会话级 5 条约束去审「分析失效机制」这个任务,报出 C3/C4/C5 缺失,
|
|
46
|
+
而这两份文档**本来就不该提**那三条。它报得对,是问错了。
|
|
47
|
+
|
|
48
|
+
**一条真局限(代码解决不了)**:
|
|
49
|
+
|
|
50
|
+
本模块只核对「清单里的约束在不在」,**不判断「这些约束该不该在清单里」**。
|
|
51
|
+
所以它无法区分两种 FAIL:
|
|
52
|
+
① 任务需要 C3 而 C3 丢了 → 真问题
|
|
53
|
+
② 任务不需要 C3 但清单里有 → 误报
|
|
54
|
+
后者要靠调用方按任务裁剪清单来避免——那是语义判断,代码做不了。
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
__all__ = ["audit", "VERDICTS", "LEVEL_REQUIREMENTS"]
|
|
58
|
+
|
|
59
|
+
from . import context_plan as cp
|
|
60
|
+
from . import cohesion as co
|
|
61
|
+
from . import constraint_watch as cw
|
|
62
|
+
|
|
63
|
+
VERDICTS = ("PASS", "FAIL", "UNKNOWN")
|
|
64
|
+
|
|
65
|
+
#: 各层级需要哪些检查。True=必须过;False=不适用
|
|
66
|
+
#: 各层级需要哪些检查。True=必须过;False=不适用
|
|
67
|
+
#:
|
|
68
|
+
#: **为什么 L2 不强制 broken**(2026-10-24 实测修正):
|
|
69
|
+
#: 框架 v4/v5 第②步说 L2 要「半连续」——**步骤要连、章节可断**。
|
|
70
|
+
#: 而 cohesion 测的是块间接缝,对结构化文档(章节并列、靠标题导航)
|
|
71
|
+
#: 本来就低(第十八轮实测:17 份结构化文档中 3 份被误判)。
|
|
72
|
+
#: 若 L2 强制 broken,会把正常的结构化上下文判为失败。
|
|
73
|
+
#: 故 broken 只在 L3(要求连续)与灰区(保守)时强制执行,
|
|
74
|
+
#: L2 给出读数但不判失败。
|
|
75
|
+
LEVEL_REQUIREMENTS = {
|
|
76
|
+
"L1": {"dropped": True, "diluted": True, "broken": False},
|
|
77
|
+
"L2": {"dropped": True, "diluted": True, "broken": False},
|
|
78
|
+
"L3": {"dropped": True, "diluted": False, "broken": True},
|
|
79
|
+
"灰区": {"dropped": True, "diluted": True, "broken": True},
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _verdict_of(required, results):
|
|
84
|
+
"""把三项结果合成一个判定。
|
|
85
|
+
|
|
86
|
+
* 任一 required 项为 False → FAIL(有确凿问题)
|
|
87
|
+
* 否则若有 required 项为 None → UNKNOWN(没能核对)
|
|
88
|
+
* 否则 → PASS
|
|
89
|
+
注意 broken 的语义:cohesion 的 ok 只有 True/False/None 三态。
|
|
90
|
+
"""
|
|
91
|
+
failure = []
|
|
92
|
+
unknown = []
|
|
93
|
+
for key, need in required.items():
|
|
94
|
+
if not need:
|
|
95
|
+
continue
|
|
96
|
+
r = results.get(key) or {}
|
|
97
|
+
ok = r.get("ok")
|
|
98
|
+
if ok is False:
|
|
99
|
+
failure.append(key)
|
|
100
|
+
elif ok is None:
|
|
101
|
+
unknown.append(key)
|
|
102
|
+
if failure:
|
|
103
|
+
return "FAIL", failure, unknown
|
|
104
|
+
if unknown:
|
|
105
|
+
return "UNKNOWN", failure, unknown
|
|
106
|
+
return "PASS", failure, unknown
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def audit(task_text, blocks=None, checklist=None, target_text=None, cg=None, max_lookup=3):
|
|
110
|
+
"""跑完三种损失检查并给出一个判定。
|
|
111
|
+
|
|
112
|
+
参数:
|
|
113
|
+
task_text 任务描述(用于判级)
|
|
114
|
+
blocks 上下文块列表(用于接缝检查)
|
|
115
|
+
checklist 约束清单文本(用于丢弃检查)
|
|
116
|
+
target_text 目标事实文本(用于稀释检查);应包含在 blocks 拼起来的文本里
|
|
117
|
+
cg 认知图实例(可选)。**传了才对缺失约束自动回取候选出处**;
|
|
118
|
+
不传则只报缺失——本模块仍「只报不做」,回取只是**查**,
|
|
119
|
+
不改任何上下文,故不越过「不做」的边界
|
|
120
|
+
max_lookup 最多为几条缺失约束做回取,防止一次审计打爆检索(默认 3)
|
|
121
|
+
|
|
122
|
+
返回 dict:
|
|
123
|
+
verdict PASS / FAIL / UNKNOWN
|
|
124
|
+
level 判出的层级
|
|
125
|
+
losses {dropped, diluted, broken} 各自原始结果
|
|
126
|
+
failed 未通过的检查项
|
|
127
|
+
unknown 无法判定的检查项
|
|
128
|
+
actions 建议动作列表
|
|
129
|
+
note 边界提示
|
|
130
|
+
"""
|
|
131
|
+
p = cp.plan(task_text)
|
|
132
|
+
level = p["level"]
|
|
133
|
+
required = LEVEL_REQUIREMENTS.get(level, LEVEL_REQUIREMENTS["灰区"])
|
|
134
|
+
|
|
135
|
+
joined = "\n".join([b for b in (blocks or []) if b])
|
|
136
|
+
losses = {}
|
|
137
|
+
|
|
138
|
+
# ① 丢弃
|
|
139
|
+
if checklist:
|
|
140
|
+
losses["dropped"] = cw.check(checklist, joined)
|
|
141
|
+
else:
|
|
142
|
+
losses["dropped"] = {"ok": None, "reason": "未提供约束清单,无从核对"}
|
|
143
|
+
|
|
144
|
+
# ② 稀释(需要目标文本)
|
|
145
|
+
if target_text and joined:
|
|
146
|
+
losses["diluted"] = co.signal_ratio(target_text, joined)
|
|
147
|
+
else:
|
|
148
|
+
losses["diluted"] = {"ok": None, "reason": "未提供目标文本或上下文为空"}
|
|
149
|
+
|
|
150
|
+
# ③ 断裂(需要 ≥2 块)
|
|
151
|
+
if blocks and len([b for b in blocks if b]) >= 2:
|
|
152
|
+
rep = co.check(blocks)
|
|
153
|
+
losses["broken"] = {"ok": rep.get("ok"), "ratio": rep.get("ratio"),
|
|
154
|
+
"inner_adj": rep.get("inner_adj"),
|
|
155
|
+
"cross_boundary": rep.get("cross_boundary")}
|
|
156
|
+
else:
|
|
157
|
+
losses["broken"] = {"ok": None, "reason": "块数不足 2,无接缝可言"}
|
|
158
|
+
|
|
159
|
+
verdict, failure, unknown = _verdict_of(required, losses)
|
|
160
|
+
|
|
161
|
+
actions = []
|
|
162
|
+
dropped = losses["dropped"]
|
|
163
|
+
if dropped.get("ok") is False:
|
|
164
|
+
missing = dropped.get("missing", [])
|
|
165
|
+
# 可选回取:只在传了 cg 时做,且限量。回取只**查**不改,故不越过「只报不做」。
|
|
166
|
+
for idx, m in enumerate(missing):
|
|
167
|
+
if cg is not None and idx < max_lookup:
|
|
168
|
+
got = cw.retrieve_for(m.get("text", ""), cg, k=2)
|
|
169
|
+
m["sources"] = got.get("candidates", [])
|
|
170
|
+
if m["sources"]:
|
|
171
|
+
actions.append("丢弃·%s %s → %s;候选出处 %s"
|
|
172
|
+
% (m.get("id", ""), m.get("text", ""),
|
|
173
|
+
m.get("advice", "回取"),
|
|
174
|
+
", ".join(s["id"] for s in m["sources"])))
|
|
175
|
+
continue
|
|
176
|
+
actions.append("丢弃·%s %s → %s(未检索到候选,不等于库里没有)"
|
|
177
|
+
% (m.get("id", ""), m.get("text", ""),
|
|
178
|
+
m.get("advice", "回取")))
|
|
179
|
+
continue
|
|
180
|
+
actions.append("丢弃·%s %s → %s" % (m.get("id", ""), m.get("text", ""),
|
|
181
|
+
m.get("advice", "回取")))
|
|
182
|
+
if losses["diluted"].get("ok") is False:
|
|
183
|
+
actions.append("稀释·目标占比 %s → 提高信噪比(删无关内容),不是单纯缩短"
|
|
184
|
+
% losses["diluted"].get("ratio"))
|
|
185
|
+
if losses["broken"].get("ok") is False:
|
|
186
|
+
actions.append("断裂·接缝比 %s → 连续任务应保原文或用指针,不硬拼"
|
|
187
|
+
% losses["broken"].get("ratio"))
|
|
188
|
+
for key in unknown:
|
|
189
|
+
actions.append("%s·无法判定 → 先补材料再判,不得当作通过" % key)
|
|
190
|
+
# 未强制但读出问题的项也提示(不判失败,只提醒)
|
|
191
|
+
for key, need in required.items():
|
|
192
|
+
if need:
|
|
193
|
+
continue
|
|
194
|
+
r = losses.get(key) or {}
|
|
195
|
+
if r.get("ok") is False:
|
|
196
|
+
actions.append("%s·本层不强制,但读数偏低(%s)→ 若该任务实际需要连续上下文,应升层"
|
|
197
|
+
% (key, r.get("ratio")))
|
|
198
|
+
|
|
199
|
+
return {
|
|
200
|
+
"verdict": verdict,
|
|
201
|
+
"level": level,
|
|
202
|
+
"required": required,
|
|
203
|
+
"losses": losses,
|
|
204
|
+
"failed": failure,
|
|
205
|
+
"unknown": unknown,
|
|
206
|
+
"actions": actions,
|
|
207
|
+
"note": ("本模块只报不做:actions 是建议,执行(写回/降级)由调用方负责。"
|
|
208
|
+
+ ("(本次已为缺失约束检索候选出处,但**只查不改**)"
|
|
209
|
+
if cg is not None else "")
|
|
210
|
+
+ "UNKNOWN 不等于失败,也不等于通过。"),
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def main(argv=None):
|
|
215
|
+
import json
|
|
216
|
+
import sys
|
|
217
|
+
try:
|
|
218
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
219
|
+
except Exception:
|
|
220
|
+
pass
|
|
221
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
222
|
+
if not argv:
|
|
223
|
+
print('用法:python -m md_cg.context_audit "任务描述" [--json]')
|
|
224
|
+
print('(CLI 只做判级与要求裁剪;三种损失需在代码里传材料)')
|
|
225
|
+
return 2
|
|
226
|
+
rep = audit(argv[0])
|
|
227
|
+
if "--json" in argv:
|
|
228
|
+
print(json.dumps(rep, ensure_ascii=False, indent=1))
|
|
229
|
+
else:
|
|
230
|
+
print("判定:%s(层级 %s)" % (rep["verdict"], rep["level"]))
|
|
231
|
+
print("要求:%s" % rep["required"])
|
|
232
|
+
for a in rep["actions"]:
|
|
233
|
+
print(" - %s" % a)
|
|
234
|
+
print("")
|
|
235
|
+
print("注:%s" % rep["note"])
|
|
236
|
+
return 0
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
if __name__ == "__main__":
|
|
240
|
+
raise SystemExit(main())
|