@furongjun1999/dsh-memory 0.5.0 → 0.5.1
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/README.md +552 -465
- package/docs/README.md +1 -0
- package/docs/eval/bench_lingshu_self/bench_self.py +140 -0
- package/docs/eval/bench_lingshu_self/self_bench_result.json +404 -0
- package/docs/eval/bench_lingshu_self//347/201/265/346/236/242/350/207/252/345/272/223/347/253/257/345/210/260/347/253/257/346/243/200/347/264/242/345/256/236/346/265/213_v1.0.md +38 -0
- package/docs/eval//344/270/215/345/217/257/351/235/240/346/200/247/350/220/275/345/234/260_P0_v1.0.md +185 -0
- package/docs/eval//346/225/205/351/232/234/346/263/250/345/205/245/345/256/236/346/265/213_v1.0.md +422 -0
- package/docs/eval//347/253/257/345/210/260/347/253/257LoCoMoQA/345/220/214/345/217/243/345/276/204/345/257/271/347/205/247_v1.0.md +100 -0
- package/docs/eval//347/253/257/345/210/260/347/253/257/345/271/262/346/211/260/346/261/240/350/257/204/346/265/213_/347/241/256/345/256/232/346/200/247/350/243/201/345/206/263vsLLM_judge_v1.1.md +197 -0
- package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v1.md +156 -0
- package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v10.md +210 -0
- package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v11.md +227 -0
- package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v12.md +203 -0
- package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v13.md +233 -0
- package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v14.md +191 -0
- package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v15.md +213 -0
- package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v16.md +214 -0
- package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v17.md +199 -0
- package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v2.md +156 -0
- package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v3.md +152 -0
- package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v4.md +128 -0
- package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v5.md +114 -0
- package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v6.md +192 -0
- package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v7.md +187 -0
- package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v8.md +207 -0
- package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v9.md +203 -0
- package/docs/hive//345/256/211/345/205/250/345/256/241/350/256/241/345/256/236/351/224/232_v0.1.md +202 -0
- package/docs/hive//350/234/202/345/267/242/345/217/214/345/256/236/344/276/213/344/272/222/351/252/214_/350/256/276/350/256/241/345/256/232/347/250/277.md +19 -3
- package/docs/images/lingshu-moonlight-covenant-poster-preview.jpg +0 -0
- package/docs/images/lingshu-moonlight-covenant-poster.png +0 -0
- package/docs/mdcg//345/212/237/350/203/275/350/260/203/347/224/250/346/230/240/345/260/204/350/241/250_v0.1.md +40 -40
- package/docs/theory//344/270/215/345/217/257/351/235/240/345/256/232/347/220/206/344/270/216/345/244/261/346/225/210/344/274/230/345/205/210/346/241/206/346/236/266_v0.3.md +365 -0
- package/docs//344/270/215/345/217/257/351/235/240/346/200/247/347/220/206/350/256/272_v0.1.md +343 -0
- package/lib/bridge.d.ts +9 -0
- package/lib/bridge.js +35 -0
- package/lib/index.js +7 -1
- package/lib/lib/roleplay_web.js +530 -443
- package/lib/lib/token_store.d.ts +7 -1
- package/lib/lib/token_store.js +12 -3
- package/md_cg/audit.py +12 -1
- package/md_cg/backfill.py +16 -15
- package/md_cg/backfill_bucket_zh.py +35 -0
- package/md_cg/bench_e2e_judge.py +532 -0
- package/md_cg/bench_e2e_locomo_qa.py +368 -0
- package/md_cg/bench_e2e_qa.py +256 -0
- package/md_cg/branches.py +18 -2
- package/md_cg/ccgc.py +3 -2
- package/md_cg/chain.py +19 -4
- package/md_cg/consolidate.py +7 -6
- package/md_cg/crosscheck.py +4 -3
- package/md_cg/crypto.py +439 -437
- package/md_cg/datapath.py +395 -335
- package/md_cg/evidence.py +582 -580
- package/md_cg/export.py +3 -1
- package/md_cg/forgetting.py +2 -2
- package/md_cg/fsutil.py +48 -0
- package/md_cg/hotcache.py +255 -238
- package/md_cg/interop.py +161 -22
- package/md_cg/judgment_manifest.py +177 -0
- package/md_cg/links.py +655 -622
- package/md_cg/mcp_server.py +280 -29
- package/md_cg/mdcg.py +616 -125
- package/md_cg/mdcos.py +430 -66
- package/md_cg/mreview/govern.py +5 -4
- package/md_cg/postings.py +4 -2
- package/md_cg/readcache.py +76 -18
- package/md_cg/reconcile.py +228 -0
- package/md_cg/review_cli.py +170 -0
- package/md_cg/routing.py +28 -0
- package/md_cg/run_tests.py +211 -0
- package/md_cg/scrub.py +862 -852
- package/md_cg/security.py +385 -275
- package/md_cg/selfreport.py +3 -2
- package/md_cg/signer.py +565 -562
- package/md_cg/sources.py +3 -2
- package/md_cg/stg.py +6 -0
- package/md_cg/sustain.py +1168 -1138
- package/md_cg/test_access_hints.py +147 -0
- package/md_cg/test_branch_discard_tombstone.py +136 -0
- package/md_cg/test_branches.py +259 -249
- package/md_cg/test_chain_read_isolate.py +168 -0
- package/md_cg/test_datapath_device_name.py +203 -0
- package/md_cg/test_emit_negtail_cache.py +156 -0
- package/md_cg/test_en_pipeline.py +186 -166
- package/md_cg/test_govern_directread.py +421 -0
- package/md_cg/test_i32_hotcache_env_key.py +218 -0
- package/md_cg/test_identity_attribution.py +228 -147
- package/md_cg/test_index_durability.py +238 -224
- package/md_cg/test_interop.py +4 -2
- package/md_cg/test_interop_judgment.py +228 -0
- package/md_cg/test_issue39_utf8_stdio.py +273 -0
- package/md_cg/test_links_concurrent_write.py +188 -0
- package/md_cg/test_merge_upsert.py +168 -0
- package/md_cg/test_n123_derive_expiry_chain.py +205 -0
- package/md_cg/test_n130_verify_falsified_protect.py +185 -0
- package/md_cg/test_n131_merge_gate.py +205 -0
- package/md_cg/test_p1x_ref_root.py +160 -0
- package/md_cg/test_p27_docindex.py +774 -765
- package/md_cg/test_p2_mcp.py +3 -0
- package/md_cg/test_p32_backfill.py +304 -298
- package/md_cg/test_p39_verify_flow.py +90 -50
- package/md_cg/test_p47_session_view.py +60 -25
- package/md_cg/test_propose_tail_index.py +157 -0
- package/md_cg/test_read_scope_b27.py +277 -0
- package/md_cg/test_readcache_default_on.py +168 -0
- package/md_cg/test_readcache_precise_inval.py +270 -0
- package/md_cg/test_readcache_prodpath.py +55 -7
- package/md_cg/test_reconcile_v0.py +294 -0
- package/md_cg/test_retr_s1.py +6 -2
- package/md_cg/test_retr_s1b.py +67 -0
- package/md_cg/test_retr_s7.py +8 -0
- package/md_cg/test_retr_s9_entity_ctx.py +181 -175
- package/md_cg/test_retr_score_once.py +208 -0
- package/md_cg/test_review_onepass.py +170 -0
- package/md_cg/test_rrf_graph_seed_cache.py +154 -0
- package/md_cg/test_security_audit.py +155 -0
- package/md_cg/test_security_audit_b26.py +161 -0
- package/md_cg/test_security_audit_v21.py +250 -0
- package/md_cg/test_semantic_canonical.py +255 -241
- package/md_cg/test_session_isolation.py +168 -0
- package/md_cg/test_snapshot_autoclose.py +187 -0
- package/md_cg/test_tail_watermark_race.py +208 -0
- package/md_cg/test_tenant_env_override_warn.py +139 -0
- package/md_cg/test_tenant_registry_corrupt_warn.py +151 -0
- package/md_cg/test_v14_fixes.py +415 -397
- package/md_cg/test_verify_dirty_reconcile.py +157 -0
- package/md_cg/theory.py +276 -273
- package/md_cg/tokens.py +734 -677
- package/md_cg/units.py +3 -2
- package/md_cg/vision_evidence.py +4 -3
- package/md_cg/whitebox_kb/wisdom/code_solidified.json +6195 -6195
- package/md_cg/whitebox_kb/wisdom/multilang_ir.py +128 -124
- package/md_cg/writepipe.py +554 -550
- package/package.json +6 -2
- package/src/bridge.ts +434 -401
- package/src/index.ts +526 -518
- package/src/lib/roleplay_web.ts +1019 -932
- package/src/lib/token_store.ts +202 -192
package/md_cg/scrub.py
CHANGED
|
@@ -1,853 +1,863 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""md_cg · 记忆自净(记忆 OS #5):抽查 / 联想 / 去污染 / 校准偏差
|
|
3
|
-
|
|
4
|
-
自维持(`sustain.py`)解决「进程还活着」,本模块解决「记忆还干净」。
|
|
5
|
-
四件事构成一个闭环,挂在常驻循环上周期性跑:
|
|
6
|
-
|
|
7
|
-
① **记忆抽查(sample)**
|
|
8
|
-
分层抽样而非随机抽样:风险层(陈旧 / 低置信 / 有反例 / 从未验证 / 孤立)
|
|
9
|
-
+ 对照组(高频 / 随机基线)。对照组是刻意的——只查「看起来有问题」的节点
|
|
10
|
-
会形成确认偏差,永远发现不了「看起来没问题其实有问题」的记忆。
|
|
11
|
-
`seed` 固定 → 同 seed 同样本(可复现、可审计,对齐本仓确定性白箱取向)。
|
|
12
|
-
|
|
13
|
-
② **联想(associate)**
|
|
14
|
-
从抽样节点出发三路邻域合并:
|
|
15
|
-
关系链(`chain.walk`,带条件序列)· 子图层级(`subgraph.expand`)
|
|
16
|
-
· 词法近邻(bigram Jaccard)
|
|
17
|
-
用途是找到「同族节点」——矛盾与重复只能在同族之间判定,孤立地看一个节点
|
|
18
|
-
永远看不出它和谁冲突。
|
|
19
|
-
|
|
20
|
-
③ **去污染(audit → decontaminate)**
|
|
21
|
-
确定性判据(只读、可解释)识别五类污染:
|
|
22
|
-
`contradiction` 同族矛盾(同键不同值 / 极性相反且共享词)
|
|
23
|
-
`expired` 时效过期(`valid_until` / `expires_at` 已过)
|
|
24
|
-
`duplicate` 高冗余(`forgetting.redundancy` ≥ 合并阈值)
|
|
25
|
-
`orphan_noise` 孤立噪音(零访问 + 低重要 + 情境层)
|
|
26
|
-
`unverified` 长期未验证(knowledge 层且零证据)
|
|
27
|
-
处置**只做可逆动作**且复用既有机制:
|
|
28
|
-
· `weaken` → `cg.verify(verdict="weakened")`:反例 +1、置信 -0.15、
|
|
29
|
-
跌破 0.2 自动降级(验证机制天然留痕,不另造一套)
|
|
30
|
-
· `demote` → `cg._move_layer("contextual")`:降出可信层(走保护闸门)
|
|
31
|
-
· `hint` → 只给建议(合并 / 补证据需语义判断,不代劳)
|
|
32
|
-
受保护节点(self/anchor/importance≥0.7/显式保护)**跳过**;**永不删除**。
|
|
33
|
-
幂等:`_scrub.jsonl` 里已处理过的 (节点, 污染类型) 不重复动手。
|
|
34
|
-
|
|
35
|
-
④ **校准偏差(calibrate)**
|
|
36
|
-
用「自报置信 vs 实测正确率」(`metacognition.calibration`)算全局 gap 与
|
|
37
|
-
分桶偏差,给出偏置建议;`apply=True` 才写回(只动有证据的节点,保护节点跳过)。
|
|
38
|
-
|
|
39
|
-
所有动作留痕 `_scrub.jsonl`(payload-free:只记 id / 判据 / 动作,不记内容)。
|
|
40
|
-
零第三方依赖。
|
|
41
|
-
"""
|
|
42
|
-
from __future__ import annotations
|
|
43
|
-
|
|
44
|
-
import os
|
|
45
|
-
import random
|
|
46
|
-
import time
|
|
47
|
-
|
|
48
|
-
from . import forgetting, protect
|
|
49
|
-
from .fsutil import append_jsonl, read_jsonl
|
|
50
|
-
from .mdcg import bigrams
|
|
51
|
-
|
|
52
|
-
SCRUB_LOG = "_scrub.jsonl"
|
|
53
|
-
|
|
54
|
-
DEFAULT_SAMPLE = 12
|
|
55
|
-
DEFAULT_HOPS = 2
|
|
56
|
-
STALE_DAYS = 30.0 # 多久没被访问算「陈旧」
|
|
57
|
-
UNVERIFIED_DAYS = 14.0 # knowledge 层多久没验证算「长期未验证」
|
|
58
|
-
LOW_CONF = 0.35 # 低于此置信算「低置信」
|
|
59
|
-
ORPHAN_IMPORTANCE = 0.30 # 孤立噪音的重要度上限
|
|
60
|
-
MAX_ASSOC_SCAN = 600 # 词法近邻比对上限(全库扫描保护)
|
|
61
|
-
MAX_BINS_REPORT = 4
|
|
62
|
-
MAX_OFFSET = 0.15 # 校准偏置上限(一次最多挪这么多)
|
|
63
|
-
SELF_LAYERS = ("self", "anchor")
|
|
64
|
-
|
|
65
|
-
STRATA = ("stale", "low_conf", "disputed", "unverified", "orphan", "hot", "random")
|
|
66
|
-
STRATUM_WEIGHTS = {"stale": 0.20, "low_conf": 0.20, "disputed": 0.15,
|
|
67
|
-
"unverified": 0.15, "orphan": 0.10, "hot": 0.10,
|
|
68
|
-
"random": 0.10}
|
|
69
|
-
|
|
70
|
-
# 污染类型 → (严重度, 处置动作)
|
|
71
|
-
CONTAMINATION = {
|
|
72
|
-
"contradiction": ("high", ("weaken", "demote")),
|
|
73
|
-
"expired": ("high", ("weaken", "demote")),
|
|
74
|
-
# 未生效(双时间轴另一侧,2026-09-19):**不是错误**——只提示「此刻不适用」,
|
|
75
|
-
# 故 severity=info、处置仅 hint(不 weaken / 不 demote / 不删)。
|
|
76
|
-
"not_yet": ("info", ("hint",)),
|
|
77
|
-
"duplicate": ("medium", ("hint",)),
|
|
78
|
-
"orphan_noise": ("low", ("weaken", "demote")),
|
|
79
|
-
"unverified": ("info", ("hint",)),
|
|
80
|
-
}
|
|
81
|
-
SEVERITY_ORDER = {"high": 3, "medium": 2, "low": 1, "info": 0}
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
# --------------------------------------------------------------------------
|
|
85
|
-
# 工具
|
|
86
|
-
# --------------------------------------------------------------------------
|
|
87
|
-
|
|
88
|
-
# 生效条件:当 cg 的 index 为真且其 "nodes" 为真时返回该值,否则(cg 无 index、index 为假值、缺 "nodes" 或 "nodes" 为假值)返回 {};
|
|
89
|
-
def _nodes(cg) -> dict:
|
|
90
|
-
return (getattr(cg, "index", None) or {}).get("nodes") or {}
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
# 生效条件:cg 与 nid 传入后,若 cache 非 None 且 nid 已在 cache 中则直接返回 cache[nid](即使其值为假值);否则尝试 cg.get(nid),异常或返回假值时按空节点处理,再取其中的 "frontmatter" 真值,若为假值则用 {};cache 非 None 时把结果写入 cache[nid] 后返回;
|
|
94
|
-
def _fm_of(cg, nid, cache=None) -> dict:
|
|
95
|
-
"""取节点 frontmatter(带可选缓存)。不可读(缺密钥 / 已删)→ {}。"""
|
|
96
|
-
if cache is not None and nid in cache:
|
|
97
|
-
return cache[nid]
|
|
98
|
-
node = None
|
|
99
|
-
try:
|
|
100
|
-
node = cg.get(nid)
|
|
101
|
-
except Exception:
|
|
102
|
-
node = None
|
|
103
|
-
fm = (node or {}).get("frontmatter") or {}
|
|
104
|
-
if cache is not None:
|
|
105
|
-
cache[nid] = fm
|
|
106
|
-
return fm
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
# 生效条件:cg.access_counts() 调用成功时返回其结果(访问次数, 最后访问时间);调用抛出任何 Exception 时返回 ({}, {});
|
|
110
|
-
def _access(cg):
|
|
111
|
-
"""(访问次数, 最后访问时间):读访问日志,未 compact 的也算。"""
|
|
112
|
-
try:
|
|
113
|
-
return cg.access_counts()
|
|
114
|
-
except Exception:
|
|
115
|
-
return {}, {}
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
# 生效条件:`from . import chain` 成功且 chain.adjacency(cg) 正常返回时返回该 dict,导入或调用抛任何异常时返回 {}。
|
|
119
|
-
def _adjacency(cg) -> dict:
|
|
120
|
-
try:
|
|
121
|
-
from . import chain
|
|
122
|
-
return chain.adjacency(cg)
|
|
123
|
-
except Exception:
|
|
124
|
-
return {}
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
# 生效条件:float(ts or 0) 抛 TypeError/ValueError 时返回 0.0,转换后为 0(含 ts 为 0/空串/None 等假值)时返回 0.0,否则返回 (now - ts)/86400.0。
|
|
128
|
-
def _days(ts, now) -> float:
|
|
129
|
-
try:
|
|
130
|
-
ts = float(ts or 0)
|
|
131
|
-
except (TypeError, ValueError):
|
|
132
|
-
return 0.0
|
|
133
|
-
return (now - ts) / 86400.0 if ts else 0.0
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
# 生效条件:调用即返回带 t 与 op 的 rec;写 append_jsonl(os.path.join(cg.root, SCRUB_LOG), rec) 抛任何异常都被吞掉,不影响返回值。
|
|
137
|
-
def _log(cg, op: str, **rec) -> dict:
|
|
138
|
-
rec = dict(rec, t=time.time(), op=op)
|
|
139
|
-
try:
|
|
140
|
-
append_jsonl(os.path.join(cg.root, SCRUB_LOG), rec)
|
|
141
|
-
except Exception:
|
|
142
|
-
pass
|
|
143
|
-
return rec
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
# 生效条件:仅当 read_jsonl(cg.root 下 SCRUB_LOG) 的记录 op=="decontaminate" 且 ok 为真时,把 (rec.get("node_id"), rec.get("kind")) 收进返回集合;无此类记录返回空集。
|
|
147
|
-
def _handled(cg) -> set:
|
|
148
|
-
"""已处置过的 (node_id, kind):保证去污染幂等(审计即状态)。"""
|
|
149
|
-
out = set()
|
|
150
|
-
for rec in list(read_jsonl(os.path.join(cg.root, SCRUB_LOG))):
|
|
151
|
-
if rec.get("op") == "decontaminate" and rec.get("ok"):
|
|
152
|
-
out.add((rec.get("node_id"), rec.get("kind")))
|
|
153
|
-
return out
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
# --------------------------------------------------------------------------
|
|
157
|
-
# ① 记忆抽查
|
|
158
|
-
# --------------------------------------------------------------------------
|
|
159
|
-
|
|
160
|
-
# 生效条件:当 cg 的节点/访问/邻接数据可取时,对每个「layer 不在 SELF_LAYERS」的节点(源码仅以 `if layer in SELF_LAYERS: continue` 排除,未要求 layer 非空)按 now、stale_days、unverified_days 判定入池——last 访问时间距今≥stale_days 时入 stale,last 为假值且 created_at 距今≥stale_days 时入 stale,访问计数 acc≥3 入 hot,邻接度 deg==0 且 layer=="contextual" 入 orphan,evidence_count≤0 且 layer=="knowledge" 且 age_d≥unverified_days 入 unverified,evidence_count>0 且 reads<int(max_reads) 且 _fm_of 返回非空前台时按 negative_evidence>0 入 disputed、按 confidence<LOW_CONF(confidence 缺键回落 0.6)入 low_conf(max_reads 为 0 时 int(max_reads)=0,reads<0 恒假,故 disputed/low_conf 不产生),每个节点无条件入 random 池,最后按各池 key 排序返回 pools(片段仅见排序段,未展示抽样阶段);多分支无法一句话覆盖全部分支。
|
|
161
|
-
def _pool_candidates(cg, *, now, stale_days, unverified_days, max_reads=200):
|
|
162
|
-
"""构造各层候选池(不读文件的部分先用索引 + 访问日志)。"""
|
|
163
|
-
nodes = _nodes(cg)
|
|
164
|
-
counts, last = _access(cg)
|
|
165
|
-
adj = _adjacency(cg)
|
|
166
|
-
indeg = {}
|
|
167
|
-
for _src, outs in adj.items():
|
|
168
|
-
for tgt, _e in outs:
|
|
169
|
-
indeg[tgt] = indeg.get(tgt, 0) + 1
|
|
170
|
-
|
|
171
|
-
pools = {s: [] for s in STRATA}
|
|
172
|
-
cache, reads = {}, 0
|
|
173
|
-
for nid, e in nodes.items():
|
|
174
|
-
layer = str(e.get("layer") or "")
|
|
175
|
-
if layer in SELF_LAYERS:
|
|
176
|
-
continue # 自我认知不抽查、不去污染
|
|
177
|
-
created = float(e.get("created_at") or 0)
|
|
178
|
-
age_d = _days(created, now)
|
|
179
|
-
la = float(last.get(nid) or 0)
|
|
180
|
-
acc = int(counts.get(nid) or 0)
|
|
181
|
-
ev = int(e.get("evidence_count") or 0)
|
|
182
|
-
deg = len(adj.get(nid) or []) + indeg.get(nid, 0)
|
|
183
|
-
|
|
184
|
-
if la:
|
|
185
|
-
if _days(la, now) >= stale_days:
|
|
186
|
-
pools["stale"].append((nid, f"距上次访问 {_days(la, now):.0f} 天"))
|
|
187
|
-
elif age_d >= stale_days:
|
|
188
|
-
pools["stale"].append((nid, f"从未访问且已存在 {age_d:.0f} 天"))
|
|
189
|
-
|
|
190
|
-
if acc >= 3:
|
|
191
|
-
pools["hot"].append((nid, f"高频访问 {acc} 次"))
|
|
192
|
-
|
|
193
|
-
if deg == 0 and layer == "contextual":
|
|
194
|
-
pools["orphan"].append((nid, "无任何关系边(孤立)"))
|
|
195
|
-
|
|
196
|
-
if ev <= 0 and layer == "knowledge" and age_d >= unverified_days:
|
|
197
|
-
pools["unverified"].append((nid, f"knowledge 层 {age_d:.0f} 天零验证"))
|
|
198
|
-
|
|
199
|
-
if ev > 0 and reads < int(max_reads):
|
|
200
|
-
fm = _fm_of(cg, nid, cache)
|
|
201
|
-
if fm:
|
|
202
|
-
reads += 1
|
|
203
|
-
neg = int(fm.get("negative_evidence") or 0)
|
|
204
|
-
conf = float(fm.get("confidence", 0.6))
|
|
205
|
-
if neg > 0:
|
|
206
|
-
pools["disputed"].append((nid, f"有 {neg} 条反例"))
|
|
207
|
-
if conf < LOW_CONF:
|
|
208
|
-
pools["low_conf"].append((nid, f"置信 {conf:.2f}"))
|
|
209
|
-
|
|
210
|
-
pools["random"].append((nid, "随机基线"))
|
|
211
|
-
|
|
212
|
-
# 池内排序:风险优先(可复现),抽样时再按 seed 洗牌
|
|
213
|
-
pools["stale"].sort(key=lambda x: (nodes.get(x[0], {}).get("created_at") or 0))
|
|
214
|
-
pools["hot"].sort(key=lambda x: -(int(counts.get(x[0]) or 0)))
|
|
215
|
-
pools["unverified"].sort(
|
|
216
|
-
key=lambda x: (nodes.get(x[0], {}).get("created_at") or 0))
|
|
217
|
-
pools["orphan"].sort(
|
|
218
|
-
key=lambda x: float(nodes.get(x[0], {}).get("importance") or 0.5))
|
|
219
|
-
pools["disputed"].sort(key=lambda x: -len(x[1]))
|
|
220
|
-
pools["low_conf"].sort(key=lambda x: x[1])
|
|
221
|
-
return pools
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
# 生效条件:strategy=="random" 时直接返回 {"random": int(n)};strategy=="risk" 时按剔除 hot/random 后的 STRATUM_WEIGHTS 权重分配;其它策略名走全权重分配,两者都把 int(n) 余量补进已存在的 random 键否则补进 stale。
|
|
225
|
-
def _quota(n: int, strategy: str) -> dict:
|
|
226
|
-
if strategy == "random":
|
|
227
|
-
return {"random": int(n)}
|
|
228
|
-
weights = dict(STRATUM_WEIGHTS)
|
|
229
|
-
if strategy == "risk":
|
|
230
|
-
weights.pop("hot", None)
|
|
231
|
-
weights.pop("random", None)
|
|
232
|
-
total = sum(weights.values()) or 1.0
|
|
233
|
-
out, used = {}, 0
|
|
234
|
-
for s in STRATA:
|
|
235
|
-
if s in weights:
|
|
236
|
-
k = int(round(int(n) * weights[s] / total))
|
|
237
|
-
out[s] = k
|
|
238
|
-
used += k
|
|
239
|
-
rest = int(n) - used
|
|
240
|
-
if rest:
|
|
241
|
-
key = "random" if "random" in out else "stale"
|
|
242
|
-
out[key] = out.get(key, 0) + rest
|
|
243
|
-
return out
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
# 生效条件:k<=0 或 pool 为假值(空池)时返回 [],否则取池前 k*3 项后用 random.Random(f"{seed}:{stratum}") 稳定洗牌并返回前 k 项(池长不足 k*3 时对全池洗牌)。
|
|
247
|
-
def _pick(pool, k: int, seed, stratum: str):
|
|
248
|
-
"""从池中取 k 个:风险最高的 3k 个入池,再按 seed 稳定洗牌。"""
|
|
249
|
-
if k <= 0 or not pool:
|
|
250
|
-
return []
|
|
251
|
-
cand = list(pool)
|
|
252
|
-
if len(cand) > k * 3:
|
|
253
|
-
cand = cand[:k * 3]
|
|
254
|
-
random.Random(f"{seed}:{stratum}").shuffle(cand)
|
|
255
|
-
return cand[:k]
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
# 生效条件:strategy 经 str(strategy or "stratified").lower() 后属于 stratified/risk/random 时返回带分层标签的样本(seed 为 None 时取 0,n 为 0 时 picked 为空),否则抛 ValueError。
|
|
259
|
-
def sample(cg, n: int = DEFAULT_SAMPLE, *, strategy: str = "stratified",
|
|
260
|
-
seed=None, stale_days: float = STALE_DAYS,
|
|
261
|
-
unverified_days: float = UNVERIFIED_DAYS,
|
|
262
|
-
max_reads: int = 200) -> dict:
|
|
263
|
-
"""分层抽查记忆,返回带分层标签的样本。
|
|
264
|
-
|
|
265
|
-
strategy:`stratified`(默认,风险层 + 对照组)· `risk`(只查风险层)
|
|
266
|
-
· `random`(纯随机基线)。seed 固定 → 同样本可复现。
|
|
267
|
-
"""
|
|
268
|
-
strategy = str(strategy or "stratified").lower()
|
|
269
|
-
if strategy not in ("stratified", "risk", "random"):
|
|
270
|
-
raise ValueError(f"未知抽样策略:{strategy}(stratified|risk|random)")
|
|
271
|
-
now = time.time()
|
|
272
|
-
seed = 0 if seed is None else seed
|
|
273
|
-
pools = _pool_candidates(cg, now=now, stale_days=stale_days,
|
|
274
|
-
unverified_days=unverified_days,
|
|
275
|
-
max_reads=max_reads)
|
|
276
|
-
quota = _quota(n, strategy)
|
|
277
|
-
picked, seen = [], set()
|
|
278
|
-
for s in STRATA:
|
|
279
|
-
for nid, reason in _pick(pools.get(s), quota.get(s, 0), seed, s):
|
|
280
|
-
if nid in seen:
|
|
281
|
-
continue
|
|
282
|
-
seen.add(nid)
|
|
283
|
-
picked.append({"node_id": nid, "stratum": s, "reason": reason})
|
|
284
|
-
# 风险层不够时用随机池补足(先剔除已选,避免跳过造成不满额)
|
|
285
|
-
if len(picked) < int(n):
|
|
286
|
-
rest = [x for x in pools["random"] if x[0] not in seen]
|
|
287
|
-
for nid, reason in _pick(rest, int(n) - len(picked), seed,
|
|
288
|
-
"random-fill"):
|
|
289
|
-
seen.add(nid)
|
|
290
|
-
picked.append({"node_id": nid, "stratum": "random",
|
|
291
|
-
"reason": reason})
|
|
292
|
-
return {"ok": True, "strategy": strategy, "seed": seed, "n": len(picked),
|
|
293
|
-
"strata": {s: len(pools.get(s) or []) for s in STRATA},
|
|
294
|
-
"sample": picked, "t": now}
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
# --------------------------------------------------------------------------
|
|
298
|
-
# ② 联想
|
|
299
|
-
# --------------------------------------------------------------------------
|
|
300
|
-
|
|
301
|
-
# 生效条件:a 或 b 为假值(空集)时返回 0.0,否则返回 len(a & b)/len(a | b)。
|
|
302
|
-
def _jaccard(a: set, b: set) -> float:
|
|
303
|
-
if not a or not b:
|
|
304
|
-
return 0.0
|
|
305
|
-
return len(a & b) / len(a | b)
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
# 生效条件:对 node_id 汇总关系链(chain.walk 出边与入边,max_depth=int(hops))、子图层级(subgraph.expand 命中项与父索引逐级上溯 int(hops) 层)以及 lexical 为真时的词法近邻(只在 _nodes 前 int(max_scan) 个节点内比 bigram、sim≥min_sim 者),返回按 weight 降序的 items[:int(limit)]。
|
|
309
|
-
def associate(cg, node_id: str, *, hops: int = DEFAULT_HOPS, limit: int = 30,
|
|
310
|
-
lexical: bool = True, min_sim: float = 0.25,
|
|
311
|
-
max_scan: int = MAX_ASSOC_SCAN) -> dict:
|
|
312
|
-
"""三路邻域联想:关系链 + 子图层级 + 词法近邻。
|
|
313
|
-
|
|
314
|
-
返回按权重降序的 `related`;每条带 `via`(哪一路发现)与 `weight`,
|
|
315
|
-
便于审计「为什么把这两个节点算作同族」。
|
|
316
|
-
"""
|
|
317
|
-
related = {}
|
|
318
|
-
|
|
319
|
-
# 生效条件:nid 为真且 nid != node_id 时,构造 rec={'node_id':nid,'via':via,'weight':round(float(weight),4),'depth':int(depth)} 并并入 extra;仅当 related 中 nid 不存在或 rec['weight'] 大于已有 weight 时更新 related[nid];nid 为假或等于 node_id 时直接返回;
|
|
320
|
-
def put(nid, via, weight, depth=1, **extra):
|
|
321
|
-
if not nid or nid == node_id:
|
|
322
|
-
return
|
|
323
|
-
rec = {"node_id": nid, "via": via, "weight": round(float(weight), 4),
|
|
324
|
-
"depth": int(depth)}
|
|
325
|
-
rec.update(extra)
|
|
326
|
-
cur = related.get(nid)
|
|
327
|
-
if cur is None or rec["weight"] > cur["weight"]:
|
|
328
|
-
related[nid] = rec
|
|
329
|
-
|
|
330
|
-
# 联想是双向的:同族既可能是「我指向的」也可能是「指向我的」,
|
|
331
|
-
# 故关系链同时沿出边与入边展开(`chain_t --causal--> a` 也要能从 a 找到)。
|
|
332
|
-
try:
|
|
333
|
-
from . import chain
|
|
334
|
-
for direction in ("out", "in"):
|
|
335
|
-
for c in chain.walk(cg, node_id,
|
|
336
|
-
relation_types=chain.CHAIN_TYPES_DEFAULT,
|
|
337
|
-
max_depth=int(hops), max_chains=200,
|
|
338
|
-
include_hierarchy=True, direction=direction):
|
|
339
|
-
for i, h in enumerate(c.get("hops") or [], 1):
|
|
340
|
-
put(h["to"], "chain",
|
|
341
|
-
float(h.get("weight") or 1.0) * (0.8 ** (i - 1)),
|
|
342
|
-
depth=i, relation_type=h.get("relation_type"),
|
|
343
|
-
condition=h.get("condition") or "")
|
|
344
|
-
except Exception:
|
|
345
|
-
pass
|
|
346
|
-
|
|
347
|
-
# 子图层级:向下展开子树 + 向上追溯祖先(父边唯一,逐级上溯)。
|
|
348
|
-
try:
|
|
349
|
-
from . import subgraph
|
|
350
|
-
ex = subgraph.expand(cg, node_id, max_depth=int(hops))
|
|
351
|
-
for nid, path in (ex.get("paths") or {}).items():
|
|
352
|
-
d = str(path).count("/")
|
|
353
|
-
put(nid, "subgraph", 1.0 / (1 + d), depth=d)
|
|
354
|
-
pmap = subgraph.parents_index(cg)
|
|
355
|
-
cur, d = node_id, 0
|
|
356
|
-
while d < int(hops):
|
|
357
|
-
ps = pmap.get(cur) or []
|
|
358
|
-
if not ps:
|
|
359
|
-
break
|
|
360
|
-
d += 1
|
|
361
|
-
for pid in ps:
|
|
362
|
-
put(pid, "subgraph", 1.0 / (1 + d), depth=d)
|
|
363
|
-
cur = ps[0]
|
|
364
|
-
except Exception:
|
|
365
|
-
pass
|
|
366
|
-
|
|
367
|
-
if lexical:
|
|
368
|
-
base = None
|
|
369
|
-
try:
|
|
370
|
-
base = cg.get(node_id)
|
|
371
|
-
except Exception:
|
|
372
|
-
base = None
|
|
373
|
-
bg = bigrams((base or {}).get("content") or "")
|
|
374
|
-
if bg:
|
|
375
|
-
cands = []
|
|
376
|
-
for i, nid in enumerate(_nodes(cg)):
|
|
377
|
-
if i >= int(max_scan):
|
|
378
|
-
break
|
|
379
|
-
if nid == node_id or nid in related:
|
|
380
|
-
continue
|
|
381
|
-
try:
|
|
382
|
-
node = cg.get(nid)
|
|
383
|
-
except Exception:
|
|
384
|
-
node = None
|
|
385
|
-
b2 = bigrams((node or {}).get("content") or "")
|
|
386
|
-
sim = _jaccard(bg, b2)
|
|
387
|
-
if sim >= min_sim:
|
|
388
|
-
cands.append((sim, nid))
|
|
389
|
-
cands.sort(key=lambda x: (-x[0], x[1]))
|
|
390
|
-
for sim, nid in cands[:int(limit)]:
|
|
391
|
-
put(nid, "lexical", sim, depth=1, similarity=round(sim, 4))
|
|
392
|
-
|
|
393
|
-
items = sorted(related.values(), key=lambda r: (-r["weight"], r["node_id"]))
|
|
394
|
-
by_via = {}
|
|
395
|
-
for r in items:
|
|
396
|
-
by_via[r["via"]] = by_via.get(r["via"], 0) + 1
|
|
397
|
-
return {"ok": True, "node_id": node_id, "n": len(items),
|
|
398
|
-
"related": items[:int(limit)], "by_via": by_via}
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
# --------------------------------------------------------------------------
|
|
402
|
-
# ③ 去污染:确定性判据
|
|
403
|
-
# --------------------------------------------------------------------------
|
|
404
|
-
|
|
405
|
-
# 已结束键族(2026-09-19 阶段一:补规范名 `effective_until` 与冗余时刻 `expired_at`)。
|
|
406
|
-
# 纪律:`believed_at`(信念时间)**两族都不入**——它既不是「已结束」也不是「尚未开始」,
|
|
407
|
-
# 而是「体系何时确认此条」的取代/审核锚。键族真源见 md_cg/trust.py(FROM_ALIASES/UNTIL_ALIASES),
|
|
408
|
-
# 两侧新增键须同步(交叉守卫 test_validity_filter)。
|
|
409
|
-
_EXPIRY_KEYS = ("effective_until", "valid_until", "expires_at", "expire_at",
|
|
410
|
-
"expiry", "deadline", "expired_at")
|
|
411
|
-
_SKIP_KEYS = ("功能名", "执行", "条件", "来源", "标签", "状态", "备注", "标题",
|
|
412
|
-
"描述", "name", "id", "title", "layer", "tags", "说明")
|
|
413
|
-
_NEG_WORDS = ("禁止", "不得", "不要", "不能", "切勿", "避免", "不应", "不可")
|
|
414
|
-
_POS_WORDS = ("应当", "建议", "必须", "需要", "可以", "允许", "推荐", "宜")
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
# 生效条件:v 为 bool 返回 None;v 为 int/float 时仅 f>1e8 返回 f 否则 None;str(v or "").strip() 为空返回 None;否则按 "%Y-%m-%dT%H:%M:%S"/"%Y-%m-%d %H:%M:%S"/"%Y-%m-%d" 依次取前 19/19/10 字符尝试解析,全失败后再试 float(s),>1e8 返回否则 None,float 亦失败返回 None。
|
|
418
|
-
def _to_ts(v):
|
|
419
|
-
"""宽松时间解析:秒级时间戳 / ISO / `YYYY-MM-DD`。无法识别 → None。"""
|
|
420
|
-
if isinstance(v, bool):
|
|
421
|
-
return None
|
|
422
|
-
if isinstance(v, (int, float)):
|
|
423
|
-
f = float(v)
|
|
424
|
-
return f if f > 1e8 else None
|
|
425
|
-
s = str(v or "").strip()
|
|
426
|
-
if not s:
|
|
427
|
-
return None
|
|
428
|
-
for fmt, n in (("%Y-%m-%dT%H:%M:%S", 19), ("%Y-%m-%d %H:%M:%S", 19),
|
|
429
|
-
("%Y-%m-%d", 10)):
|
|
430
|
-
try:
|
|
431
|
-
return time.mktime(time.strptime(s[:n], fmt))
|
|
432
|
-
except ValueError:
|
|
433
|
-
continue
|
|
434
|
-
try:
|
|
435
|
-
f = float(s)
|
|
436
|
-
return f if f > 1e8 else None
|
|
437
|
-
except ValueError:
|
|
438
|
-
return None
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
# 生效条件:对 (content or "").splitlines() 的每行去 # 后,先试中文全角 ":"、无则试 ":",切出的键长度在 2–12、值非空且键不在 _SKIP_KEYS 时以 setdefault 记录(每键只留首次出现),无合格行返回 {}。
|
|
442
|
-
def _kv_pairs(content) -> dict:
|
|
443
|
-
"""抽 `键:值` 对(中文/英文冒号),跳过结构字段。"""
|
|
444
|
-
out = {}
|
|
445
|
-
for raw in (content or "").splitlines():
|
|
446
|
-
line = raw.strip().lstrip("#").strip()
|
|
447
|
-
if not line:
|
|
448
|
-
continue
|
|
449
|
-
for sep in (":", ":"):
|
|
450
|
-
if sep in line:
|
|
451
|
-
k, _, v = line.partition(sep)
|
|
452
|
-
k, v = k.strip(), v.strip()
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
#
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
and int(
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
continue
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
if
|
|
727
|
-
continue
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
return {"
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""md_cg · 记忆自净(记忆 OS #5):抽查 / 联想 / 去污染 / 校准偏差
|
|
3
|
+
|
|
4
|
+
自维持(`sustain.py`)解决「进程还活着」,本模块解决「记忆还干净」。
|
|
5
|
+
四件事构成一个闭环,挂在常驻循环上周期性跑:
|
|
6
|
+
|
|
7
|
+
① **记忆抽查(sample)**
|
|
8
|
+
分层抽样而非随机抽样:风险层(陈旧 / 低置信 / 有反例 / 从未验证 / 孤立)
|
|
9
|
+
+ 对照组(高频 / 随机基线)。对照组是刻意的——只查「看起来有问题」的节点
|
|
10
|
+
会形成确认偏差,永远发现不了「看起来没问题其实有问题」的记忆。
|
|
11
|
+
`seed` 固定 → 同 seed 同样本(可复现、可审计,对齐本仓确定性白箱取向)。
|
|
12
|
+
|
|
13
|
+
② **联想(associate)**
|
|
14
|
+
从抽样节点出发三路邻域合并:
|
|
15
|
+
关系链(`chain.walk`,带条件序列)· 子图层级(`subgraph.expand`)
|
|
16
|
+
· 词法近邻(bigram Jaccard)
|
|
17
|
+
用途是找到「同族节点」——矛盾与重复只能在同族之间判定,孤立地看一个节点
|
|
18
|
+
永远看不出它和谁冲突。
|
|
19
|
+
|
|
20
|
+
③ **去污染(audit → decontaminate)**
|
|
21
|
+
确定性判据(只读、可解释)识别五类污染:
|
|
22
|
+
`contradiction` 同族矛盾(同键不同值 / 极性相反且共享词)
|
|
23
|
+
`expired` 时效过期(`valid_until` / `expires_at` 已过)
|
|
24
|
+
`duplicate` 高冗余(`forgetting.redundancy` ≥ 合并阈值)
|
|
25
|
+
`orphan_noise` 孤立噪音(零访问 + 低重要 + 情境层)
|
|
26
|
+
`unverified` 长期未验证(knowledge 层且零证据)
|
|
27
|
+
处置**只做可逆动作**且复用既有机制:
|
|
28
|
+
· `weaken` → `cg.verify(verdict="weakened")`:反例 +1、置信 -0.15、
|
|
29
|
+
跌破 0.2 自动降级(验证机制天然留痕,不另造一套)
|
|
30
|
+
· `demote` → `cg._move_layer("contextual")`:降出可信层(走保护闸门)
|
|
31
|
+
· `hint` → 只给建议(合并 / 补证据需语义判断,不代劳)
|
|
32
|
+
受保护节点(self/anchor/importance≥0.7/显式保护)**跳过**;**永不删除**。
|
|
33
|
+
幂等:`_scrub.jsonl` 里已处理过的 (节点, 污染类型) 不重复动手。
|
|
34
|
+
|
|
35
|
+
④ **校准偏差(calibrate)**
|
|
36
|
+
用「自报置信 vs 实测正确率」(`metacognition.calibration`)算全局 gap 与
|
|
37
|
+
分桶偏差,给出偏置建议;`apply=True` 才写回(只动有证据的节点,保护节点跳过)。
|
|
38
|
+
|
|
39
|
+
所有动作留痕 `_scrub.jsonl`(payload-free:只记 id / 判据 / 动作,不记内容)。
|
|
40
|
+
零第三方依赖。
|
|
41
|
+
"""
|
|
42
|
+
from __future__ import annotations
|
|
43
|
+
|
|
44
|
+
import os
|
|
45
|
+
import random
|
|
46
|
+
import time
|
|
47
|
+
|
|
48
|
+
from . import forgetting, nodefile, protect
|
|
49
|
+
from .fsutil import append_jsonl, read_jsonl
|
|
50
|
+
from .mdcg import bigrams
|
|
51
|
+
|
|
52
|
+
SCRUB_LOG = "_scrub.jsonl"
|
|
53
|
+
|
|
54
|
+
DEFAULT_SAMPLE = 12
|
|
55
|
+
DEFAULT_HOPS = 2
|
|
56
|
+
STALE_DAYS = 30.0 # 多久没被访问算「陈旧」
|
|
57
|
+
UNVERIFIED_DAYS = 14.0 # knowledge 层多久没验证算「长期未验证」
|
|
58
|
+
LOW_CONF = 0.35 # 低于此置信算「低置信」
|
|
59
|
+
ORPHAN_IMPORTANCE = 0.30 # 孤立噪音的重要度上限
|
|
60
|
+
MAX_ASSOC_SCAN = 600 # 词法近邻比对上限(全库扫描保护)
|
|
61
|
+
MAX_BINS_REPORT = 4
|
|
62
|
+
MAX_OFFSET = 0.15 # 校准偏置上限(一次最多挪这么多)
|
|
63
|
+
SELF_LAYERS = ("self", "anchor")
|
|
64
|
+
|
|
65
|
+
STRATA = ("stale", "low_conf", "disputed", "unverified", "orphan", "hot", "random")
|
|
66
|
+
STRATUM_WEIGHTS = {"stale": 0.20, "low_conf": 0.20, "disputed": 0.15,
|
|
67
|
+
"unverified": 0.15, "orphan": 0.10, "hot": 0.10,
|
|
68
|
+
"random": 0.10}
|
|
69
|
+
|
|
70
|
+
# 污染类型 → (严重度, 处置动作)
|
|
71
|
+
CONTAMINATION = {
|
|
72
|
+
"contradiction": ("high", ("weaken", "demote")),
|
|
73
|
+
"expired": ("high", ("weaken", "demote")),
|
|
74
|
+
# 未生效(双时间轴另一侧,2026-09-19):**不是错误**——只提示「此刻不适用」,
|
|
75
|
+
# 故 severity=info、处置仅 hint(不 weaken / 不 demote / 不删)。
|
|
76
|
+
"not_yet": ("info", ("hint",)),
|
|
77
|
+
"duplicate": ("medium", ("hint",)),
|
|
78
|
+
"orphan_noise": ("low", ("weaken", "demote")),
|
|
79
|
+
"unverified": ("info", ("hint",)),
|
|
80
|
+
}
|
|
81
|
+
SEVERITY_ORDER = {"high": 3, "medium": 2, "low": 1, "info": 0}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
# --------------------------------------------------------------------------
|
|
85
|
+
# 工具
|
|
86
|
+
# --------------------------------------------------------------------------
|
|
87
|
+
|
|
88
|
+
# 生效条件:当 cg 的 index 为真且其 "nodes" 为真时返回该值,否则(cg 无 index、index 为假值、缺 "nodes" 或 "nodes" 为假值)返回 {};
|
|
89
|
+
def _nodes(cg) -> dict:
|
|
90
|
+
return (getattr(cg, "index", None) or {}).get("nodes") or {}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
# 生效条件:cg 与 nid 传入后,若 cache 非 None 且 nid 已在 cache 中则直接返回 cache[nid](即使其值为假值);否则尝试 cg.get(nid),异常或返回假值时按空节点处理,再取其中的 "frontmatter" 真值,若为假值则用 {};cache 非 None 时把结果写入 cache[nid] 后返回;
|
|
94
|
+
def _fm_of(cg, nid, cache=None) -> dict:
|
|
95
|
+
"""取节点 frontmatter(带可选缓存)。不可读(缺密钥 / 已删)→ {}。"""
|
|
96
|
+
if cache is not None and nid in cache:
|
|
97
|
+
return cache[nid]
|
|
98
|
+
node = None
|
|
99
|
+
try:
|
|
100
|
+
node = cg.get(nid)
|
|
101
|
+
except Exception:
|
|
102
|
+
node = None
|
|
103
|
+
fm = (node or {}).get("frontmatter") or {}
|
|
104
|
+
if cache is not None:
|
|
105
|
+
cache[nid] = fm
|
|
106
|
+
return fm
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# 生效条件:cg.access_counts() 调用成功时返回其结果(访问次数, 最后访问时间);调用抛出任何 Exception 时返回 ({}, {});
|
|
110
|
+
def _access(cg):
|
|
111
|
+
"""(访问次数, 最后访问时间):读访问日志,未 compact 的也算。"""
|
|
112
|
+
try:
|
|
113
|
+
return cg.access_counts()
|
|
114
|
+
except Exception:
|
|
115
|
+
return {}, {}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# 生效条件:`from . import chain` 成功且 chain.adjacency(cg) 正常返回时返回该 dict,导入或调用抛任何异常时返回 {}。
|
|
119
|
+
def _adjacency(cg) -> dict:
|
|
120
|
+
try:
|
|
121
|
+
from . import chain
|
|
122
|
+
return chain.adjacency(cg)
|
|
123
|
+
except Exception:
|
|
124
|
+
return {}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
# 生效条件:float(ts or 0) 抛 TypeError/ValueError 时返回 0.0,转换后为 0(含 ts 为 0/空串/None 等假值)时返回 0.0,否则返回 (now - ts)/86400.0。
|
|
128
|
+
def _days(ts, now) -> float:
|
|
129
|
+
try:
|
|
130
|
+
ts = float(ts or 0)
|
|
131
|
+
except (TypeError, ValueError):
|
|
132
|
+
return 0.0
|
|
133
|
+
return (now - ts) / 86400.0 if ts else 0.0
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
# 生效条件:调用即返回带 t 与 op 的 rec;写 append_jsonl(os.path.join(cg.root, SCRUB_LOG), rec) 抛任何异常都被吞掉,不影响返回值。
|
|
137
|
+
def _log(cg, op: str, **rec) -> dict:
|
|
138
|
+
rec = dict(rec, t=time.time(), op=op)
|
|
139
|
+
try:
|
|
140
|
+
append_jsonl(os.path.join(cg.root, SCRUB_LOG), rec)
|
|
141
|
+
except Exception:
|
|
142
|
+
pass
|
|
143
|
+
return rec
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# 生效条件:仅当 read_jsonl(cg.root 下 SCRUB_LOG) 的记录 op=="decontaminate" 且 ok 为真时,把 (rec.get("node_id"), rec.get("kind")) 收进返回集合;无此类记录返回空集。
|
|
147
|
+
def _handled(cg) -> set:
|
|
148
|
+
"""已处置过的 (node_id, kind):保证去污染幂等(审计即状态)。"""
|
|
149
|
+
out = set()
|
|
150
|
+
for rec in list(read_jsonl(os.path.join(cg.root, SCRUB_LOG))):
|
|
151
|
+
if rec.get("op") == "decontaminate" and rec.get("ok"):
|
|
152
|
+
out.add((rec.get("node_id"), rec.get("kind")))
|
|
153
|
+
return out
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
# --------------------------------------------------------------------------
|
|
157
|
+
# ① 记忆抽查
|
|
158
|
+
# --------------------------------------------------------------------------
|
|
159
|
+
|
|
160
|
+
# 生效条件:当 cg 的节点/访问/邻接数据可取时,对每个「layer 不在 SELF_LAYERS」的节点(源码仅以 `if layer in SELF_LAYERS: continue` 排除,未要求 layer 非空)按 now、stale_days、unverified_days 判定入池——last 访问时间距今≥stale_days 时入 stale,last 为假值且 created_at 距今≥stale_days 时入 stale,访问计数 acc≥3 入 hot,邻接度 deg==0 且 layer=="contextual" 入 orphan,evidence_count≤0 且 layer=="knowledge" 且 age_d≥unverified_days 入 unverified,evidence_count>0 且 reads<int(max_reads) 且 _fm_of 返回非空前台时按 negative_evidence>0 入 disputed、按 confidence<LOW_CONF(confidence 缺键回落 0.6)入 low_conf(max_reads 为 0 时 int(max_reads)=0,reads<0 恒假,故 disputed/low_conf 不产生),每个节点无条件入 random 池,最后按各池 key 排序返回 pools(片段仅见排序段,未展示抽样阶段);多分支无法一句话覆盖全部分支。
|
|
161
|
+
def _pool_candidates(cg, *, now, stale_days, unverified_days, max_reads=200):
|
|
162
|
+
"""构造各层候选池(不读文件的部分先用索引 + 访问日志)。"""
|
|
163
|
+
nodes = _nodes(cg)
|
|
164
|
+
counts, last = _access(cg)
|
|
165
|
+
adj = _adjacency(cg)
|
|
166
|
+
indeg = {}
|
|
167
|
+
for _src, outs in adj.items():
|
|
168
|
+
for tgt, _e in outs:
|
|
169
|
+
indeg[tgt] = indeg.get(tgt, 0) + 1
|
|
170
|
+
|
|
171
|
+
pools = {s: [] for s in STRATA}
|
|
172
|
+
cache, reads = {}, 0
|
|
173
|
+
for nid, e in nodes.items():
|
|
174
|
+
layer = str(e.get("layer") or "")
|
|
175
|
+
if layer in SELF_LAYERS:
|
|
176
|
+
continue # 自我认知不抽查、不去污染
|
|
177
|
+
created = float(e.get("created_at") or 0)
|
|
178
|
+
age_d = _days(created, now)
|
|
179
|
+
la = float(last.get(nid) or 0)
|
|
180
|
+
acc = int(counts.get(nid) or 0)
|
|
181
|
+
ev = int(e.get("evidence_count") or 0)
|
|
182
|
+
deg = len(adj.get(nid) or []) + indeg.get(nid, 0)
|
|
183
|
+
|
|
184
|
+
if la:
|
|
185
|
+
if _days(la, now) >= stale_days:
|
|
186
|
+
pools["stale"].append((nid, f"距上次访问 {_days(la, now):.0f} 天"))
|
|
187
|
+
elif age_d >= stale_days:
|
|
188
|
+
pools["stale"].append((nid, f"从未访问且已存在 {age_d:.0f} 天"))
|
|
189
|
+
|
|
190
|
+
if acc >= 3:
|
|
191
|
+
pools["hot"].append((nid, f"高频访问 {acc} 次"))
|
|
192
|
+
|
|
193
|
+
if deg == 0 and layer == "contextual":
|
|
194
|
+
pools["orphan"].append((nid, "无任何关系边(孤立)"))
|
|
195
|
+
|
|
196
|
+
if ev <= 0 and layer == "knowledge" and age_d >= unverified_days:
|
|
197
|
+
pools["unverified"].append((nid, f"knowledge 层 {age_d:.0f} 天零验证"))
|
|
198
|
+
|
|
199
|
+
if ev > 0 and reads < int(max_reads):
|
|
200
|
+
fm = _fm_of(cg, nid, cache)
|
|
201
|
+
if fm:
|
|
202
|
+
reads += 1
|
|
203
|
+
neg = int(fm.get("negative_evidence") or 0)
|
|
204
|
+
conf = float(fm.get("confidence", 0.6))
|
|
205
|
+
if neg > 0:
|
|
206
|
+
pools["disputed"].append((nid, f"有 {neg} 条反例"))
|
|
207
|
+
if conf < LOW_CONF:
|
|
208
|
+
pools["low_conf"].append((nid, f"置信 {conf:.2f}"))
|
|
209
|
+
|
|
210
|
+
pools["random"].append((nid, "随机基线"))
|
|
211
|
+
|
|
212
|
+
# 池内排序:风险优先(可复现),抽样时再按 seed 洗牌
|
|
213
|
+
pools["stale"].sort(key=lambda x: (nodes.get(x[0], {}).get("created_at") or 0))
|
|
214
|
+
pools["hot"].sort(key=lambda x: -(int(counts.get(x[0]) or 0)))
|
|
215
|
+
pools["unverified"].sort(
|
|
216
|
+
key=lambda x: (nodes.get(x[0], {}).get("created_at") or 0))
|
|
217
|
+
pools["orphan"].sort(
|
|
218
|
+
key=lambda x: float(nodes.get(x[0], {}).get("importance") or 0.5))
|
|
219
|
+
pools["disputed"].sort(key=lambda x: -len(x[1]))
|
|
220
|
+
pools["low_conf"].sort(key=lambda x: x[1])
|
|
221
|
+
return pools
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
# 生效条件:strategy=="random" 时直接返回 {"random": int(n)};strategy=="risk" 时按剔除 hot/random 后的 STRATUM_WEIGHTS 权重分配;其它策略名走全权重分配,两者都把 int(n) 余量补进已存在的 random 键否则补进 stale。
|
|
225
|
+
def _quota(n: int, strategy: str) -> dict:
|
|
226
|
+
if strategy == "random":
|
|
227
|
+
return {"random": int(n)}
|
|
228
|
+
weights = dict(STRATUM_WEIGHTS)
|
|
229
|
+
if strategy == "risk":
|
|
230
|
+
weights.pop("hot", None)
|
|
231
|
+
weights.pop("random", None)
|
|
232
|
+
total = sum(weights.values()) or 1.0
|
|
233
|
+
out, used = {}, 0
|
|
234
|
+
for s in STRATA:
|
|
235
|
+
if s in weights:
|
|
236
|
+
k = int(round(int(n) * weights[s] / total))
|
|
237
|
+
out[s] = k
|
|
238
|
+
used += k
|
|
239
|
+
rest = int(n) - used
|
|
240
|
+
if rest:
|
|
241
|
+
key = "random" if "random" in out else "stale"
|
|
242
|
+
out[key] = out.get(key, 0) + rest
|
|
243
|
+
return out
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
# 生效条件:k<=0 或 pool 为假值(空池)时返回 [],否则取池前 k*3 项后用 random.Random(f"{seed}:{stratum}") 稳定洗牌并返回前 k 项(池长不足 k*3 时对全池洗牌)。
|
|
247
|
+
def _pick(pool, k: int, seed, stratum: str):
|
|
248
|
+
"""从池中取 k 个:风险最高的 3k 个入池,再按 seed 稳定洗牌。"""
|
|
249
|
+
if k <= 0 or not pool:
|
|
250
|
+
return []
|
|
251
|
+
cand = list(pool)
|
|
252
|
+
if len(cand) > k * 3:
|
|
253
|
+
cand = cand[:k * 3]
|
|
254
|
+
random.Random(f"{seed}:{stratum}").shuffle(cand)
|
|
255
|
+
return cand[:k]
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
# 生效条件:strategy 经 str(strategy or "stratified").lower() 后属于 stratified/risk/random 时返回带分层标签的样本(seed 为 None 时取 0,n 为 0 时 picked 为空),否则抛 ValueError。
|
|
259
|
+
def sample(cg, n: int = DEFAULT_SAMPLE, *, strategy: str = "stratified",
|
|
260
|
+
seed=None, stale_days: float = STALE_DAYS,
|
|
261
|
+
unverified_days: float = UNVERIFIED_DAYS,
|
|
262
|
+
max_reads: int = 200) -> dict:
|
|
263
|
+
"""分层抽查记忆,返回带分层标签的样本。
|
|
264
|
+
|
|
265
|
+
strategy:`stratified`(默认,风险层 + 对照组)· `risk`(只查风险层)
|
|
266
|
+
· `random`(纯随机基线)。seed 固定 → 同样本可复现。
|
|
267
|
+
"""
|
|
268
|
+
strategy = str(strategy or "stratified").lower()
|
|
269
|
+
if strategy not in ("stratified", "risk", "random"):
|
|
270
|
+
raise ValueError(f"未知抽样策略:{strategy}(stratified|risk|random)")
|
|
271
|
+
now = time.time()
|
|
272
|
+
seed = 0 if seed is None else seed
|
|
273
|
+
pools = _pool_candidates(cg, now=now, stale_days=stale_days,
|
|
274
|
+
unverified_days=unverified_days,
|
|
275
|
+
max_reads=max_reads)
|
|
276
|
+
quota = _quota(n, strategy)
|
|
277
|
+
picked, seen = [], set()
|
|
278
|
+
for s in STRATA:
|
|
279
|
+
for nid, reason in _pick(pools.get(s), quota.get(s, 0), seed, s):
|
|
280
|
+
if nid in seen:
|
|
281
|
+
continue
|
|
282
|
+
seen.add(nid)
|
|
283
|
+
picked.append({"node_id": nid, "stratum": s, "reason": reason})
|
|
284
|
+
# 风险层不够时用随机池补足(先剔除已选,避免跳过造成不满额)
|
|
285
|
+
if len(picked) < int(n):
|
|
286
|
+
rest = [x for x in pools["random"] if x[0] not in seen]
|
|
287
|
+
for nid, reason in _pick(rest, int(n) - len(picked), seed,
|
|
288
|
+
"random-fill"):
|
|
289
|
+
seen.add(nid)
|
|
290
|
+
picked.append({"node_id": nid, "stratum": "random",
|
|
291
|
+
"reason": reason})
|
|
292
|
+
return {"ok": True, "strategy": strategy, "seed": seed, "n": len(picked),
|
|
293
|
+
"strata": {s: len(pools.get(s) or []) for s in STRATA},
|
|
294
|
+
"sample": picked, "t": now}
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
# --------------------------------------------------------------------------
|
|
298
|
+
# ② 联想
|
|
299
|
+
# --------------------------------------------------------------------------
|
|
300
|
+
|
|
301
|
+
# 生效条件:a 或 b 为假值(空集)时返回 0.0,否则返回 len(a & b)/len(a | b)。
|
|
302
|
+
def _jaccard(a: set, b: set) -> float:
|
|
303
|
+
if not a or not b:
|
|
304
|
+
return 0.0
|
|
305
|
+
return len(a & b) / len(a | b)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
# 生效条件:对 node_id 汇总关系链(chain.walk 出边与入边,max_depth=int(hops))、子图层级(subgraph.expand 命中项与父索引逐级上溯 int(hops) 层)以及 lexical 为真时的词法近邻(只在 _nodes 前 int(max_scan) 个节点内比 bigram、sim≥min_sim 者),返回按 weight 降序的 items[:int(limit)]。
|
|
309
|
+
def associate(cg, node_id: str, *, hops: int = DEFAULT_HOPS, limit: int = 30,
|
|
310
|
+
lexical: bool = True, min_sim: float = 0.25,
|
|
311
|
+
max_scan: int = MAX_ASSOC_SCAN) -> dict:
|
|
312
|
+
"""三路邻域联想:关系链 + 子图层级 + 词法近邻。
|
|
313
|
+
|
|
314
|
+
返回按权重降序的 `related`;每条带 `via`(哪一路发现)与 `weight`,
|
|
315
|
+
便于审计「为什么把这两个节点算作同族」。
|
|
316
|
+
"""
|
|
317
|
+
related = {}
|
|
318
|
+
|
|
319
|
+
# 生效条件:nid 为真且 nid != node_id 时,构造 rec={'node_id':nid,'via':via,'weight':round(float(weight),4),'depth':int(depth)} 并并入 extra;仅当 related 中 nid 不存在或 rec['weight'] 大于已有 weight 时更新 related[nid];nid 为假或等于 node_id 时直接返回;
|
|
320
|
+
def put(nid, via, weight, depth=1, **extra):
|
|
321
|
+
if not nid or nid == node_id:
|
|
322
|
+
return
|
|
323
|
+
rec = {"node_id": nid, "via": via, "weight": round(float(weight), 4),
|
|
324
|
+
"depth": int(depth)}
|
|
325
|
+
rec.update(extra)
|
|
326
|
+
cur = related.get(nid)
|
|
327
|
+
if cur is None or rec["weight"] > cur["weight"]:
|
|
328
|
+
related[nid] = rec
|
|
329
|
+
|
|
330
|
+
# 联想是双向的:同族既可能是「我指向的」也可能是「指向我的」,
|
|
331
|
+
# 故关系链同时沿出边与入边展开(`chain_t --causal--> a` 也要能从 a 找到)。
|
|
332
|
+
try:
|
|
333
|
+
from . import chain
|
|
334
|
+
for direction in ("out", "in"):
|
|
335
|
+
for c in chain.walk(cg, node_id,
|
|
336
|
+
relation_types=chain.CHAIN_TYPES_DEFAULT,
|
|
337
|
+
max_depth=int(hops), max_chains=200,
|
|
338
|
+
include_hierarchy=True, direction=direction):
|
|
339
|
+
for i, h in enumerate(c.get("hops") or [], 1):
|
|
340
|
+
put(h["to"], "chain",
|
|
341
|
+
float(h.get("weight") or 1.0) * (0.8 ** (i - 1)),
|
|
342
|
+
depth=i, relation_type=h.get("relation_type"),
|
|
343
|
+
condition=h.get("condition") or "")
|
|
344
|
+
except Exception:
|
|
345
|
+
pass
|
|
346
|
+
|
|
347
|
+
# 子图层级:向下展开子树 + 向上追溯祖先(父边唯一,逐级上溯)。
|
|
348
|
+
try:
|
|
349
|
+
from . import subgraph
|
|
350
|
+
ex = subgraph.expand(cg, node_id, max_depth=int(hops))
|
|
351
|
+
for nid, path in (ex.get("paths") or {}).items():
|
|
352
|
+
d = str(path).count("/")
|
|
353
|
+
put(nid, "subgraph", 1.0 / (1 + d), depth=d)
|
|
354
|
+
pmap = subgraph.parents_index(cg)
|
|
355
|
+
cur, d = node_id, 0
|
|
356
|
+
while d < int(hops):
|
|
357
|
+
ps = pmap.get(cur) or []
|
|
358
|
+
if not ps:
|
|
359
|
+
break
|
|
360
|
+
d += 1
|
|
361
|
+
for pid in ps:
|
|
362
|
+
put(pid, "subgraph", 1.0 / (1 + d), depth=d)
|
|
363
|
+
cur = ps[0]
|
|
364
|
+
except Exception:
|
|
365
|
+
pass
|
|
366
|
+
|
|
367
|
+
if lexical:
|
|
368
|
+
base = None
|
|
369
|
+
try:
|
|
370
|
+
base = cg.get(node_id)
|
|
371
|
+
except Exception:
|
|
372
|
+
base = None
|
|
373
|
+
bg = bigrams((base or {}).get("content") or "")
|
|
374
|
+
if bg:
|
|
375
|
+
cands = []
|
|
376
|
+
for i, nid in enumerate(_nodes(cg)):
|
|
377
|
+
if i >= int(max_scan):
|
|
378
|
+
break
|
|
379
|
+
if nid == node_id or nid in related:
|
|
380
|
+
continue
|
|
381
|
+
try:
|
|
382
|
+
node = cg.get(nid)
|
|
383
|
+
except Exception:
|
|
384
|
+
node = None
|
|
385
|
+
b2 = bigrams((node or {}).get("content") or "")
|
|
386
|
+
sim = _jaccard(bg, b2)
|
|
387
|
+
if sim >= min_sim:
|
|
388
|
+
cands.append((sim, nid))
|
|
389
|
+
cands.sort(key=lambda x: (-x[0], x[1]))
|
|
390
|
+
for sim, nid in cands[:int(limit)]:
|
|
391
|
+
put(nid, "lexical", sim, depth=1, similarity=round(sim, 4))
|
|
392
|
+
|
|
393
|
+
items = sorted(related.values(), key=lambda r: (-r["weight"], r["node_id"]))
|
|
394
|
+
by_via = {}
|
|
395
|
+
for r in items:
|
|
396
|
+
by_via[r["via"]] = by_via.get(r["via"], 0) + 1
|
|
397
|
+
return {"ok": True, "node_id": node_id, "n": len(items),
|
|
398
|
+
"related": items[:int(limit)], "by_via": by_via}
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
# --------------------------------------------------------------------------
|
|
402
|
+
# ③ 去污染:确定性判据
|
|
403
|
+
# --------------------------------------------------------------------------
|
|
404
|
+
|
|
405
|
+
# 已结束键族(2026-09-19 阶段一:补规范名 `effective_until` 与冗余时刻 `expired_at`)。
|
|
406
|
+
# 纪律:`believed_at`(信念时间)**两族都不入**——它既不是「已结束」也不是「尚未开始」,
|
|
407
|
+
# 而是「体系何时确认此条」的取代/审核锚。键族真源见 md_cg/trust.py(FROM_ALIASES/UNTIL_ALIASES),
|
|
408
|
+
# 两侧新增键须同步(交叉守卫 test_validity_filter)。
|
|
409
|
+
_EXPIRY_KEYS = ("effective_until", "valid_until", "expires_at", "expire_at",
|
|
410
|
+
"expiry", "deadline", "expired_at")
|
|
411
|
+
_SKIP_KEYS = ("功能名", "执行", "条件", "来源", "标签", "状态", "备注", "标题",
|
|
412
|
+
"描述", "name", "id", "title", "layer", "tags", "说明")
|
|
413
|
+
_NEG_WORDS = ("禁止", "不得", "不要", "不能", "切勿", "避免", "不应", "不可")
|
|
414
|
+
_POS_WORDS = ("应当", "建议", "必须", "需要", "可以", "允许", "推荐", "宜")
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
# 生效条件:v 为 bool 返回 None;v 为 int/float 时仅 f>1e8 返回 f 否则 None;str(v or "").strip() 为空返回 None;否则按 "%Y-%m-%dT%H:%M:%S"/"%Y-%m-%d %H:%M:%S"/"%Y-%m-%d" 依次取前 19/19/10 字符尝试解析,全失败后再试 float(s),>1e8 返回否则 None,float 亦失败返回 None。
|
|
418
|
+
def _to_ts(v):
|
|
419
|
+
"""宽松时间解析:秒级时间戳 / ISO / `YYYY-MM-DD`。无法识别 → None。"""
|
|
420
|
+
if isinstance(v, bool):
|
|
421
|
+
return None
|
|
422
|
+
if isinstance(v, (int, float)):
|
|
423
|
+
f = float(v)
|
|
424
|
+
return f if f > 1e8 else None
|
|
425
|
+
s = str(v or "").strip()
|
|
426
|
+
if not s:
|
|
427
|
+
return None
|
|
428
|
+
for fmt, n in (("%Y-%m-%dT%H:%M:%S", 19), ("%Y-%m-%d %H:%M:%S", 19),
|
|
429
|
+
("%Y-%m-%d", 10)):
|
|
430
|
+
try:
|
|
431
|
+
return time.mktime(time.strptime(s[:n], fmt))
|
|
432
|
+
except ValueError:
|
|
433
|
+
continue
|
|
434
|
+
try:
|
|
435
|
+
f = float(s)
|
|
436
|
+
return f if f > 1e8 else None
|
|
437
|
+
except ValueError:
|
|
438
|
+
return None
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
# 生效条件:对 (content or "").splitlines() 的每行去 # 后,先试中文全角 ":"、无则试 ":",切出的键长度在 2–12、值非空且键不在 _SKIP_KEYS 时以 setdefault 记录(每键只留首次出现),无合格行返回 {}。
|
|
442
|
+
def _kv_pairs(content) -> dict:
|
|
443
|
+
"""抽 `键:值` 对(中文/英文冒号),跳过结构字段。"""
|
|
444
|
+
out = {}
|
|
445
|
+
for raw in (content or "").splitlines():
|
|
446
|
+
line = raw.strip().lstrip("#").strip()
|
|
447
|
+
if not line:
|
|
448
|
+
continue
|
|
449
|
+
for sep in (":", ":"):
|
|
450
|
+
if sep in line:
|
|
451
|
+
k, _, v = line.partition(sep)
|
|
452
|
+
k, v = k.strip(), v.strip()
|
|
453
|
+
# CCG 六要素行(`# 功能名:` / `# 不适用条件:` …)是**逐节点声明**,
|
|
454
|
+
# 不是可跨节点比对的断言值。把「不适用条件」当键会让语义无关的节点
|
|
455
|
+
# 互为「同键不同值」矛盾(实测 12 抽样里 9 条 high 全是这类误报,
|
|
456
|
+
# 且 apply 会把好节点 weaken+demote 并跨层移动文件)。
|
|
457
|
+
if (2 <= len(k) <= 12 and v and k not in _SKIP_KEYS
|
|
458
|
+
and not nodefile.is_ccg_mark(k)):
|
|
459
|
+
out.setdefault(k, v)
|
|
460
|
+
break
|
|
461
|
+
return out
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
# 生效条件:c 取 content or "",含 _NEG_WORDS 任一返回 -1 分量、含 _POS_WORDS 任一返回 +1 分量,结果为两者之和(都不含时为 0)。
|
|
465
|
+
def _polarity(content) -> int:
|
|
466
|
+
c = content or ""
|
|
467
|
+
return (-1 if any(w in c for w in _NEG_WORDS) else 0) + \
|
|
468
|
+
(1 if any(w in c for w in _POS_WORDS) else 0)
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
# 生效条件:按 _EXPIRY_KEYS 顺序遍历 fm,返回首个满足「键在 fm 中且 _to_ts 非 None 且 ts<now」的 (k, fm.get(k));该键解析为 None 或 ts≥now 时继续检查后续键,全不满足返回 None。
|
|
472
|
+
def _expired(fm, now):
|
|
473
|
+
for k in _EXPIRY_KEYS:
|
|
474
|
+
if k in fm:
|
|
475
|
+
ts = _to_ts(fm.get(k))
|
|
476
|
+
if ts is not None and ts < now:
|
|
477
|
+
return k, fm.get(k)
|
|
478
|
+
return None
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
# 未生效键(双时间轴的起点,2026-09-19 · 真源 md_cg/trust.py)。
|
|
482
|
+
# 纪律一:`valid_from` **绝不并入 `_EXPIRY_KEYS`**——两者语义相反(「尚未开始」vs
|
|
483
|
+
# 「已经结束」),并入会让「未来才生效」被误判为「已失效」并触发 weaken/demote。
|
|
484
|
+
# 纪律二:`believed_at`(信念时间)同上,**两族都不入**——第三类语义(体系何时确认)。
|
|
485
|
+
_NOT_YET_KEYS = ("valid_from", "valid_since", "effective_from", "starts_at")
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
# 生效条件:按 _NOT_YET_KEYS 顺序遍历 fm,返回首个满足「键在 fm 中且 _to_ts 非 None 且 ts>now」的 (k, fm.get(k));全不满足返回 None。
|
|
489
|
+
def _not_yet(fm, now):
|
|
490
|
+
"""宽松判定「尚未生效」(与 `_expired` 同口径,方向相反)。"""
|
|
491
|
+
for k in _NOT_YET_KEYS:
|
|
492
|
+
if k in fm:
|
|
493
|
+
ts = _to_ts(fm.get(k))
|
|
494
|
+
if ts is not None and ts > now:
|
|
495
|
+
return k, fm.get(k)
|
|
496
|
+
return None
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
# 生效条件:对 content 取 kv_pairs、bigrams 和 polarity,遍历 related(若 related 为假值则视为空)的前 int(max_compare) 个 r,以 r["node_id"] 调 cg.get;若某 oid 节点可读非空,先在其 content 与 content 的共同键中找到值不同者并返回 {'with':oid,'via':r.get('via'),'why':'同键不同值:...'};否则若极性乘积 <0 且双方 bigram 非空,且共享 bigram 数 >=3 且 ratio>=0.15,返回 {'with':oid,'via':r.get('via'),'why':'极性相反且共享内容:...'};全部遍历完无命中则返回 None;
|
|
500
|
+
def _contradiction(cg, content, related, max_compare=10):
|
|
501
|
+
"""与同族节点比对:同键不同值 / 极性相反且共享 bigram。"""
|
|
502
|
+
kv_a = _kv_pairs(content)
|
|
503
|
+
bg_a, pol_a = bigrams(content or ""), _polarity(content)
|
|
504
|
+
for r in (related or [])[:int(max_compare)]:
|
|
505
|
+
oid = r["node_id"]
|
|
506
|
+
try:
|
|
507
|
+
onode = cg.get(oid)
|
|
508
|
+
except Exception:
|
|
509
|
+
onode = None
|
|
510
|
+
if not onode:
|
|
511
|
+
continue
|
|
512
|
+
oc = onode.get("content") or ""
|
|
513
|
+
kv_b = _kv_pairs(oc)
|
|
514
|
+
for k in sorted(set(kv_a) & set(kv_b)):
|
|
515
|
+
if kv_a[k] != kv_b[k]:
|
|
516
|
+
return {"with": oid, "via": r.get("via"),
|
|
517
|
+
"why": f"同键不同值:{k}={kv_a[k]} vs {kv_b[k]}"}
|
|
518
|
+
bg_b = bigrams(oc)
|
|
519
|
+
if pol_a * _polarity(oc) < 0 and bg_a and bg_b:
|
|
520
|
+
shared = bg_a & bg_b
|
|
521
|
+
ratio = len(shared) / max(1, min(len(bg_a), len(bg_b)))
|
|
522
|
+
if len(shared) >= 3 and ratio >= 0.15:
|
|
523
|
+
return {"with": oid, "via": r.get("via"),
|
|
524
|
+
"why": "极性相反且共享内容:" + "、".join(
|
|
525
|
+
sorted(shared)[:5])}
|
|
526
|
+
return None
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
# 生效条件:ids 在 node_ids 为 None 时取索引全部键、为 str 时取单元素列表、否则取 list(node_ids),limit 为真值时截断为前 int(limit) 个;跳过 layer 在 SELF_LAYERS 的节点和 cg.get 取不到正文的节点,对剩余每个节点按 min_severity 门限累加 expired/unverified/orphan_noise/duplicate/contradiction,返回 ok=无 high 且无 medium 的结果。
|
|
530
|
+
def audit(cg, node_ids=None, *, hops: int = 1, min_severity: str = "info",
|
|
531
|
+
limit=None, unverified_days: float = UNVERIFIED_DAYS,
|
|
532
|
+
lexical: bool = True, min_sim: float = 0.15) -> dict:
|
|
533
|
+
"""对指定节点(默认全库)做污染体检。**只读**,不改动任何节点。"""
|
|
534
|
+
nodes = _nodes(cg)
|
|
535
|
+
ids = list(nodes.keys()) if node_ids is None else (
|
|
536
|
+
[node_ids] if isinstance(node_ids, str) else list(node_ids))
|
|
537
|
+
if limit:
|
|
538
|
+
ids = ids[:int(limit)]
|
|
539
|
+
counts, _last = _access(cg)
|
|
540
|
+
adj = _adjacency(cg)
|
|
541
|
+
indeg = {}
|
|
542
|
+
for _src, outs in adj.items():
|
|
543
|
+
for tgt, _e in outs:
|
|
544
|
+
indeg[tgt] = indeg.get(tgt, 0) + 1
|
|
545
|
+
now = time.time()
|
|
546
|
+
issues, checked = [], 0
|
|
547
|
+
|
|
548
|
+
for nid in ids:
|
|
549
|
+
e = nodes.get(nid)
|
|
550
|
+
if not e:
|
|
551
|
+
continue
|
|
552
|
+
layer = str(e.get("layer") or "")
|
|
553
|
+
if layer in SELF_LAYERS:
|
|
554
|
+
continue
|
|
555
|
+
try:
|
|
556
|
+
node = cg.get(nid)
|
|
557
|
+
except Exception:
|
|
558
|
+
node = None
|
|
559
|
+
if not node:
|
|
560
|
+
continue
|
|
561
|
+
checked += 1
|
|
562
|
+
fm = node.get("frontmatter") or {}
|
|
563
|
+
content = node.get("content") or ""
|
|
564
|
+
age_d = _days(fm.get("created_at") or e.get("created_at"), now)
|
|
565
|
+
|
|
566
|
+
# 生效条件:kind 是 CONTAMINATION 的键(否则 KeyError)且 CONTAMINATION[kind] 取出的 sev 在 SEVERITY_ORDER 中的值(缺键按 0)不小于闭包变量 min_severity 在 SEVERITY_ORDER 中的值(缺键按 0)时,把 {node_id, layer, kind, severity, detail, fix} 用 **extra 覆盖更新后追加到闭包 issues;sev 的值更小则直接 return 不追加(该函数无返回值)。
|
|
567
|
+
def add(kind, detail, **extra):
|
|
568
|
+
sev, actions = CONTAMINATION[kind]
|
|
569
|
+
if SEVERITY_ORDER.get(sev, 0) < SEVERITY_ORDER.get(min_severity, 0):
|
|
570
|
+
return
|
|
571
|
+
rec = {"node_id": nid, "layer": layer, "kind": kind,
|
|
572
|
+
"severity": sev, "detail": detail, "fix": list(actions)}
|
|
573
|
+
rec.update(extra)
|
|
574
|
+
issues.append(rec)
|
|
575
|
+
|
|
576
|
+
hit = _expired(fm, now)
|
|
577
|
+
if hit:
|
|
578
|
+
add("expired", f"时效已过:{hit[0]}={hit[1]}", evidence=hit[0])
|
|
579
|
+
|
|
580
|
+
# 双时间轴另一侧(2026-09-19):尚未生效**不是错误**——只提示「此刻不适用」,
|
|
581
|
+
# 处置由 CONTAMINATION["not_yet"] 定为 info 级 + 仅 hint(不 weaken / 不 demote)。
|
|
582
|
+
ny = _not_yet(fm, now)
|
|
583
|
+
if ny:
|
|
584
|
+
add("not_yet", f"尚未生效:{ny[0]}={ny[1]}", evidence=ny[0])
|
|
585
|
+
|
|
586
|
+
if (layer == "knowledge" and age_d >= unverified_days
|
|
587
|
+
and int(e.get("evidence_count") or 0) <= 0):
|
|
588
|
+
add("unverified", f"knowledge 层 {age_d:.0f} 天零验证")
|
|
589
|
+
|
|
590
|
+
if ((len(adj.get(nid) or []) + indeg.get(nid, 0)) == 0
|
|
591
|
+
and layer == "contextual"
|
|
592
|
+
and int(counts.get(nid) or 0) == 0
|
|
593
|
+
and float(fm.get("importance") or e.get("importance") or 0.5)
|
|
594
|
+
< ORPHAN_IMPORTANCE):
|
|
595
|
+
add("orphan_noise", "孤立且零访问、低重要(情境噪音)")
|
|
596
|
+
|
|
597
|
+
try:
|
|
598
|
+
red = forgetting.redundancy(cg, content, layer=layer, exclude=nid)
|
|
599
|
+
except Exception:
|
|
600
|
+
red = None
|
|
601
|
+
if red and float(red.get("max") or 0) >= float(forgetting.DUP_MERGE):
|
|
602
|
+
add("duplicate", f"冗余 {red['max']:.2f}(与 {red.get('with')})",
|
|
603
|
+
duplicate_with=red.get("with"))
|
|
604
|
+
|
|
605
|
+
rel = associate(cg, nid, hops=max(1, int(hops)), limit=10,
|
|
606
|
+
lexical=lexical, min_sim=min_sim)["related"]
|
|
607
|
+
bad = _contradiction(cg, content, rel)
|
|
608
|
+
if bad:
|
|
609
|
+
add("contradiction", bad["why"], conflict_with=bad.get("with"))
|
|
610
|
+
|
|
611
|
+
by_kind = {}
|
|
612
|
+
for i in issues:
|
|
613
|
+
by_kind[i["kind"]] = by_kind.get(i["kind"], 0) + 1
|
|
614
|
+
high = sum(1 for i in issues if i["severity"] == "high")
|
|
615
|
+
med = sum(1 for i in issues if i["severity"] == "medium")
|
|
616
|
+
return {"ok": not (high or med), "n_checked": checked,
|
|
617
|
+
"n_issues": len(issues), "issues": issues, "by_kind": by_kind,
|
|
618
|
+
"stats": {"checked": checked, "high": high, "medium": med,
|
|
619
|
+
"low": sum(1 for i in issues if i["severity"] == "low")},
|
|
620
|
+
"t": now}
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
# 生效条件:循环 max(1, int(times)) 次调用 cg.verify(nid, "scrub:"+kind+":"+str(detail)[:120], "weakened"),返回最后一次调用结果(times≤0 时按 1 次执行)。
|
|
624
|
+
def _weaken(cg, nid, kind, detail, times=1):
|
|
625
|
+
res = None
|
|
626
|
+
for _ in range(max(1, int(times))):
|
|
627
|
+
res = cg.verify(nid, f"scrub:{kind}:{str(detail)[:120]}", "weakened")
|
|
628
|
+
return res
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
# 生效条件:kinds 为真且 issue 的 kind 不在其中则跳过;kind 为 duplicate/unverified 记 hint,已出现在 _handled 记 skip,protect.is_protected 为真且 override 为假记 skip_protected,dry_run 为真记 planned;仅 dry_run 为假时对余下 issue 执行 _weaken,并在 demote 为真、severity 为 high 或 low 且当前层非 contextual 时降级到 contextual,返回计数与 actions。
|
|
632
|
+
def decontaminate(cg, node_ids=None, *, kinds=None, dry_run: bool = True,
|
|
633
|
+
min_severity: str = "medium", hops: int = 1, actor=None,
|
|
634
|
+
override: bool = False, weaken_times: int = 1,
|
|
635
|
+
demote: bool = True) -> dict:
|
|
636
|
+
"""按体检结果处置污染。**默认 dry_run**;实修只做可逆动作。
|
|
637
|
+
|
|
638
|
+
动作:`weaken`(verify weakened → 反例+1、置信-0.15、跌破 0.2 自动降级)、
|
|
639
|
+
`demote`(降级到情境层)、`hint`(只建议,不改)。保护节点跳过;永不删除。
|
|
640
|
+
"""
|
|
641
|
+
rep = audit(cg, node_ids, hops=hops, min_severity=min_severity)
|
|
642
|
+
handled = _handled(cg)
|
|
643
|
+
actions = []
|
|
644
|
+
n_applied = n_prot = n_done = n_hint = 0
|
|
645
|
+
|
|
646
|
+
for issue in rep["issues"]:
|
|
647
|
+
nid, kind = issue["node_id"], issue["kind"]
|
|
648
|
+
if kinds and kind not in kinds:
|
|
649
|
+
continue
|
|
650
|
+
# 只给建议的动作必须按 CONTAMINATION 的**声明**判定,不能靠 kind 白名单:
|
|
651
|
+
# `not_yet` 声明 fix=("hint",),原实现只排除 duplicate/unverified,
|
|
652
|
+
# 于是它会落到 _weaken 分支(实测 min_severity="info" 时 confidence
|
|
653
|
+
# 0.6→0.45、negative_evidence 0→1),声明与实修不一致。
|
|
654
|
+
_declared = CONTAMINATION.get(kind, (None, ()))[1]
|
|
655
|
+
if kind in ("duplicate", "unverified") or _declared == ("hint",):
|
|
656
|
+
n_hint += 1
|
|
657
|
+
actions.append({"node_id": nid, "kind": kind, "action": "hint",
|
|
658
|
+
"detail": issue["detail"], "applied": False})
|
|
659
|
+
continue
|
|
660
|
+
if (nid, kind) in handled:
|
|
661
|
+
n_done += 1
|
|
662
|
+
actions.append({"node_id": nid, "kind": kind, "action": "skip",
|
|
663
|
+
"detail": "已处置过(幂等)", "applied": False})
|
|
664
|
+
continue
|
|
665
|
+
prot, why = protect.is_protected(cg, nid)
|
|
666
|
+
if prot and not override:
|
|
667
|
+
n_prot += 1
|
|
668
|
+
actions.append({"node_id": nid, "kind": kind,
|
|
669
|
+
"action": "skip_protected", "detail": why,
|
|
670
|
+
"applied": False})
|
|
671
|
+
continue
|
|
672
|
+
if dry_run:
|
|
673
|
+
actions.append({"node_id": nid, "kind": kind,
|
|
674
|
+
"action": "planned",
|
|
675
|
+
"planned": list(CONTAMINATION[kind][1]),
|
|
676
|
+
"detail": issue["detail"], "applied": False})
|
|
677
|
+
continue
|
|
678
|
+
|
|
679
|
+
done = []
|
|
680
|
+
try:
|
|
681
|
+
_weaken(cg, nid, kind, issue["detail"], weaken_times)
|
|
682
|
+
done.append("weaken")
|
|
683
|
+
except Exception as exc: # noqa: BLE001
|
|
684
|
+
done.append(f"weaken_failed:{type(exc).__name__}")
|
|
685
|
+
if demote and issue["severity"] in ("high", "low"):
|
|
686
|
+
try:
|
|
687
|
+
fm = _fm_of(cg, nid, None)
|
|
688
|
+
if str(fm.get("layer") or "") != "contextual":
|
|
689
|
+
cg._move_layer(nid, "contextual", reason=f"scrub:{kind}")
|
|
690
|
+
# 层降级 = 生命周期降级(②):状态同批推进(负路由,失败不抛)
|
|
691
|
+
_st = cg.set_state(nid, "demoted", reason=f"scrub:{kind}",
|
|
692
|
+
actor=actor or "scrub")
|
|
693
|
+
done.append("demote" if _st.get("ok") else
|
|
694
|
+
f"demote_state:{_st.get('error')}")
|
|
695
|
+
except Exception as exc: # noqa: BLE001
|
|
696
|
+
done.append(f"demote_failed:{type(exc).__name__}")
|
|
697
|
+
n_applied += 1
|
|
698
|
+
_log(cg, "decontaminate", node_id=nid, kind=kind, ok=True,
|
|
699
|
+
actions=done, severity=issue["severity"], actor=actor)
|
|
700
|
+
actions.append({"node_id": nid, "kind": kind, "action": "applied",
|
|
701
|
+
"done": done, "detail": issue["detail"],
|
|
702
|
+
"applied": True})
|
|
703
|
+
|
|
704
|
+
if not dry_run:
|
|
705
|
+
_log(cg, "decontaminate_batch", ok=True, applied=n_applied,
|
|
706
|
+
skipped_protected=n_prot, skipped_done=n_done, hints=n_hint,
|
|
707
|
+
actor=actor)
|
|
708
|
+
return {"ok": True, "dry_run": dry_run, "n_issues": rep["n_issues"],
|
|
709
|
+
"applied": n_applied, "skipped_protected": n_prot,
|
|
710
|
+
"skipped_done": n_done, "hints": n_hint, "actions": actions,
|
|
711
|
+
"audit": rep, "t": time.time()}
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
# --------------------------------------------------------------------------
|
|
715
|
+
# ④ 校准偏差
|
|
716
|
+
# --------------------------------------------------------------------------
|
|
717
|
+
|
|
718
|
+
# 生效条件:对 cg 中每个「layer 不在 SELF_LAYERS」且 evidence_count≥int(min_evidence)(min_evidence=0 时该比较恒假而不早退)的节点,若 protect.is_protected 为假或 override 为真,且 cg.get(nid) 未抛异常并返回真值节点,则取 fm.get("confidence", 0.6)(缺键才回落 0.6,键存在为 None/假值不回落)为 old,算出 round(max(0.0, min(0.99, old+float(offset))),4),与 old 差<1e-9 时跳过,否则写 fm["confidence"] 与 fm["calibration"] 并调用 cg._write_node 成功时 adjusted+1(写回异常被吞掉不计数),返回 (adjusted, skipped),其中 skipped 只累计「layer 属 SELF_LAYERS」或被 protect 拦下且非 override 的节点。
|
|
719
|
+
def _apply_offset(cg, offset, *, override=False, min_evidence=1):
|
|
720
|
+
nodes = _nodes(cg)
|
|
721
|
+
adjusted = skipped = 0
|
|
722
|
+
for nid, e in nodes.items():
|
|
723
|
+
if str(e.get("layer") or "") in SELF_LAYERS:
|
|
724
|
+
skipped += 1
|
|
725
|
+
continue
|
|
726
|
+
if int(e.get("evidence_count") or 0) < int(min_evidence):
|
|
727
|
+
continue
|
|
728
|
+
prot, _why = protect.is_protected(cg, nid)
|
|
729
|
+
if prot and not override:
|
|
730
|
+
skipped += 1
|
|
731
|
+
continue
|
|
732
|
+
try:
|
|
733
|
+
node = cg.get(nid)
|
|
734
|
+
except Exception:
|
|
735
|
+
node = None
|
|
736
|
+
if not node:
|
|
737
|
+
continue
|
|
738
|
+
fm = node.get("frontmatter") or {}
|
|
739
|
+
old = float(fm.get("confidence", 0.6))
|
|
740
|
+
new = round(max(0.0, min(0.99, old + float(offset))), 4)
|
|
741
|
+
if abs(new - old) < 1e-9:
|
|
742
|
+
continue
|
|
743
|
+
fm["confidence"] = new
|
|
744
|
+
fm["calibration"] = {"t": time.time(), "offset": round(float(offset), 4),
|
|
745
|
+
"from": old, "to": new}
|
|
746
|
+
try:
|
|
747
|
+
cg._write_node(nid, os.path.join(cg.root, e["path"]), fm,
|
|
748
|
+
node.get("content") or "")
|
|
749
|
+
adjusted += 1
|
|
750
|
+
except Exception: # noqa: BLE001
|
|
751
|
+
pass
|
|
752
|
+
return adjusted, skipped
|
|
753
|
+
|
|
754
|
+
|
|
755
|
+
# 生效条件:cg 和 apply/override/actor/max_offset/min_evidence 传入后,若 metacognition.calibration(cg) 返回 ok 假,则返回 {'ok':False,'reason':cal.get('reason') or 'insufficient_data',...};若 ok 真,则用 gap=float(cal.get('gap') or 0.0) 和 max_offset 计算 offset=round(max(-max_offset,min(max_offset,-gap)),4),对 cal.get('bins') or [] 中 accuracy 非 None 的 bin 生成 bins_bias 并排序;仅当 apply 为真且 abs(offset)>1e-9 时调用 _apply_offset(cg,offset,override=override,min_evidence=min_evidence) 并写日志,最后返回 ok True 及 verdict/gap/建议 offset 等字段;
|
|
756
|
+
def calibrate(cg, *, apply: bool = False, override: bool = False, actor=None,
|
|
757
|
+
max_offset: float = MAX_OFFSET, min_evidence: int = 1) -> dict:
|
|
758
|
+
"""校准偏差:自报置信 vs 实测正确率 → 偏置建议(`apply=True` 才写回)。"""
|
|
759
|
+
from . import metacognition
|
|
760
|
+
cal = metacognition.calibration(cg)
|
|
761
|
+
if not cal.get("ok"):
|
|
762
|
+
return {"ok": False, "reason": cal.get("reason") or "insufficient_data",
|
|
763
|
+
"calibration": cal, "applied": False, "n_adjusted": 0,
|
|
764
|
+
"hint": "先 verify() 积累证据,校准才有样本"}
|
|
765
|
+
gap = float(cal.get("gap") or 0.0)
|
|
766
|
+
offset = round(max(-float(max_offset), min(float(max_offset), -gap)), 4)
|
|
767
|
+
bins_bias = []
|
|
768
|
+
for b in cal.get("bins") or []:
|
|
769
|
+
if b.get("accuracy") is None:
|
|
770
|
+
continue
|
|
771
|
+
bins_bias.append({"bin": b["bin"], "n_nodes": b["n_nodes"],
|
|
772
|
+
"confidence": b["confidence"],
|
|
773
|
+
"accuracy": b["accuracy"],
|
|
774
|
+
"bias": round(float(b["confidence"])
|
|
775
|
+
- float(b["accuracy"]), 4)})
|
|
776
|
+
bins_bias.sort(key=lambda x: -abs(x["bias"]))
|
|
777
|
+
adjusted = skipped = 0
|
|
778
|
+
if apply and abs(offset) > 1e-9:
|
|
779
|
+
adjusted, skipped = _apply_offset(cg, offset, override=override,
|
|
780
|
+
min_evidence=min_evidence)
|
|
781
|
+
_log(cg, "calibrate", ok=True, offset=offset, gap=gap,
|
|
782
|
+
adjusted=adjusted, actor=actor)
|
|
783
|
+
blind = 0
|
|
784
|
+
try:
|
|
785
|
+
blind = int(metacognition.blindspots(cg, limit=1)
|
|
786
|
+
.get("unresolved_count") or 0)
|
|
787
|
+
except Exception:
|
|
788
|
+
pass
|
|
789
|
+
return {"ok": True, "verdict": cal.get("verdict"), "gap": gap,
|
|
790
|
+
"expected_accuracy": cal.get("expected_accuracy"),
|
|
791
|
+
"actual_accuracy": cal.get("actual_accuracy"),
|
|
792
|
+
"ece": cal.get("ece"), "n_nodes": cal.get("n_nodes"),
|
|
793
|
+
"suggested_offset": offset, "applied": bool(apply),
|
|
794
|
+
"n_adjusted": adjusted, "skipped_protected": skipped,
|
|
795
|
+
"bins_bias": bins_bias[:MAX_BINS_REPORT], "blindspots": blind,
|
|
796
|
+
"hint": ("整体偏过度自信" if gap > 0.05 else
|
|
797
|
+
"整体偏保守" if gap < -0.05 else "校准良好")}
|
|
798
|
+
|
|
799
|
+
|
|
800
|
+
# --------------------------------------------------------------------------
|
|
801
|
+
# 一轮完整自净 + 审计
|
|
802
|
+
# --------------------------------------------------------------------------
|
|
803
|
+
|
|
804
|
+
# 生效条件:cg 与 n/seed/dry_run/hops/strategy/apply_calibration/actor 传入后,按 n 与 strategy、seed 调 sample;对 sample 结果前 8 个 node_id 按 hops 调 associate;按 dry_run/hops/actor 调 decontaminate;按 apply_calibration/actor 调 calibrate;若 decontaminate 的 audit.issues 中存在 severity 为 high 或 medium 的项则 out.ok 为 False,否则为 True,并返回含 sample/associate/audit/decontaminate/calibration/t 的 out;
|
|
805
|
+
def sweep(cg, *, n: int = DEFAULT_SAMPLE, seed=None, dry_run: bool = True,
|
|
806
|
+
hops: int = DEFAULT_HOPS, strategy: str = "stratified",
|
|
807
|
+
apply_calibration: bool = False, actor=None) -> dict:
|
|
808
|
+
"""一轮自净闭环:抽查 → 联想 → 体检 → 去污染 → 校准偏差。"""
|
|
809
|
+
smp = sample(cg, n, strategy=strategy, seed=seed)
|
|
810
|
+
ids = [s["node_id"] for s in smp["sample"]]
|
|
811
|
+
assoc = {}
|
|
812
|
+
for nid in ids[:8]:
|
|
813
|
+
assoc[nid] = [r["node_id"] for r in associate(
|
|
814
|
+
cg, nid, hops=hops, lexical=False, limit=5)["related"]]
|
|
815
|
+
dec = decontaminate(cg, ids, dry_run=dry_run, hops=hops, actor=actor)
|
|
816
|
+
rep = dec["audit"]
|
|
817
|
+
cal = calibrate(cg, apply=apply_calibration, actor=actor)
|
|
818
|
+
hi = [i for i in rep["issues"] if i["severity"] in ("high", "medium")]
|
|
819
|
+
out = {"ok": not hi, "dry_run": dry_run, "n_high_medium": len(hi),
|
|
820
|
+
"sample": smp, "associate": assoc, "audit": rep,
|
|
821
|
+
"decontaminate": dec, "calibration": cal, "t": time.time()}
|
|
822
|
+
_log(cg, "sweep", n_sample=smp["n"], n_issues=rep["n_issues"],
|
|
823
|
+
n_high_medium=len(hi), applied=dec["applied"], dry_run=dry_run,
|
|
824
|
+
calibration=(cal.get("verdict") if cal.get("ok")
|
|
825
|
+
else cal.get("reason")))
|
|
826
|
+
return out
|
|
827
|
+
|
|
828
|
+
|
|
829
|
+
# 生效条件:返回 cg.root 下 SCRUB_LOG 的全部记录条数 n 与 recs[-int(limit):](limit=0 时切片为 recs[0:] 即返回全部记录)。
|
|
830
|
+
def history(cg, limit: int = 100) -> dict:
|
|
831
|
+
recs = list(read_jsonl(os.path.join(cg.root, SCRUB_LOG)))
|
|
832
|
+
return {"n": len(recs), "records": recs[-int(limit):]}
|
|
833
|
+
|
|
834
|
+
|
|
835
|
+
# 生效条件:读取 cg.root 下 SCRUB_LOG 的 JSONL 记录,过滤 op=="sweep" 得 sweeps、op=="decontaminate" 且 ok 为真得 decs;last 为 sweeps 最后一项或 None;返回 {'sweeps':len(sweeps),'decontaminated':len(decs),'last_sweep':last 的 t/n_issues/n_high_medium/applied/dry_run/calibration 或 None};
|
|
836
|
+
def summary(cg) -> dict:
|
|
837
|
+
"""给 health_os / 自维持循环用的只读摘要。"""
|
|
838
|
+
recs = list(read_jsonl(os.path.join(cg.root, SCRUB_LOG)))
|
|
839
|
+
sweeps = [r for r in recs if r.get("op") == "sweep"]
|
|
840
|
+
decs = [r for r in recs if r.get("op") == "decontaminate" and r.get("ok")]
|
|
841
|
+
last = sweeps[-1] if sweeps else None
|
|
842
|
+
return {"sweeps": len(sweeps), "decontaminated": len(decs),
|
|
843
|
+
"last_sweep": ({"t": last.get("t"),
|
|
844
|
+
"n_issues": last.get("n_issues"),
|
|
845
|
+
"n_high_medium": last.get("n_high_medium"),
|
|
846
|
+
"applied": last.get("applied"),
|
|
847
|
+
"dry_run": last.get("dry_run"),
|
|
848
|
+
"calibration": last.get("calibration")}
|
|
849
|
+
if last else None)}
|
|
850
|
+
|
|
851
|
+
|
|
852
|
+
# 生效条件:无入参调用即返回固定的 actions 列表、STRATA 列表、CONTAMINATION 映射(每项取 severity 与 actions)与 STALE_DAYS/UNVERIFIED_DAYS/LOW_CONF/ORPHAN_IMPORTANCE/MAX_OFFSET 阈值字典。
|
|
853
|
+
def catalog() -> dict:
|
|
854
|
+
return {"actions": ["sample", "associate", "audit", "decontaminate",
|
|
855
|
+
"calibrate", "sweep", "history", "summary", "catalog"],
|
|
856
|
+
"strata": list(STRATA),
|
|
857
|
+
"contamination": {k: {"severity": v[0], "actions": list(v[1])}
|
|
858
|
+
for k, v in CONTAMINATION.items()},
|
|
859
|
+
"thresholds": {"stale_days": STALE_DAYS,
|
|
860
|
+
"unverified_days": UNVERIFIED_DAYS,
|
|
861
|
+
"low_conf": LOW_CONF,
|
|
862
|
+
"orphan_importance": ORPHAN_IMPORTANCE,
|
|
853
863
|
"max_offset": MAX_OFFSET}}
|