@furongjun1999/dsh-memory 0.9.13 → 0.9.14

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/md_cg/mdcg.py CHANGED
@@ -39,6 +39,23 @@ from .fsutil import (FileLock, ShardedLog, atomic_write, append_jsonl,
39
39
  # 单点守卫:写入 / 发出路径的 6 处调用点统一走 _ensure_list——str 按「一个值」
40
40
  # 处理(不再逐字符展开);None / 空串按空列表(与改动前逐位一致);其余可迭代
41
41
  # 仍 list(x)。
42
+ # 生效条件:把原始环境变量值解析成**有限浮点**门槛。缺省/空串返回 default;
43
+ # 非数值或 nan/inf 返回 default 且状态 invalid(调用方须如实记账,不得静默)。
44
+ # 为什么单独成单点:issue #659 F26-06 实测 MDCG_MIN_SCORE=inf 时 inf > 0 恒真,
45
+ # 全量结果被滤空;F26-12 又实测两处开关判据不一致(>0 与 >=0)。判据只写一次。
46
+ def parse_min_score(raw, default=0.0):
47
+ """→ (value, status),status 取 default / ok / invalid。"""
48
+ if raw is None or str(raw).strip() == "":
49
+ return float(default), "default"
50
+ try:
51
+ v = float(raw)
52
+ except (TypeError, ValueError):
53
+ return float(default), "invalid"
54
+ if v != v or v in (float("inf"), float("-inf")):
55
+ return float(default), "invalid"
56
+ return v, "ok"
57
+
58
+
42
59
  def _ensure_list(x):
43
60
  """归一成列表:任何假值(None/空串/0/False/[])-> [];str -> [str];其它可迭代 -> list(x)。"""
44
61
  if not x:
@@ -611,6 +628,33 @@ def fold_accents(text: str) -> str:
611
628
  return _ud.normalize("NFC", s)
612
629
 
613
630
 
631
+ def is_void_content(text) -> bool:
632
+ """「空白即无内容」的判据单点(#644 首版 + #651 扩展)。
633
+
634
+ #644 首版只剥 str.strip() 的 White_Space;#651 实测被三类不可见字符完整绕过:
635
+ · Cf(U+200B/U+200C/U+200D/U+FEFF/U+2060/U+00AD 等零宽/软连字符,isspace 全 False);
636
+ · 纯 Mn/Me 组合记号(U+0301 重复 n 次)——能落盘,但 fold_accents 折成空串,
637
+ 成为永不可检索的幽灵节点;
638
+ · Cc 控制符(x00-x1f 等)。
639
+
640
+ 判据:去掉「空白 + 控制符 + 格式符 + 组合记号 + 变体选择子」后若一个字符都不剩,即为无内容。
641
+ **不误伤**:NFD 正文(如 cafe + U+0301)里有字母残留 → 非空,照常写入。
642
+ """
643
+ import unicodedata as _ud
644
+ if not isinstance(text, str):
645
+ return True
646
+ for ch in text:
647
+ cat = _ud.category(ch)
648
+ if cat[0] in ("Z", "C"): # 分隔符 / 控制符 / 格式符 / 未分配 / 代理
649
+ continue
650
+ if cat in ("Mn", "Me"): # 组合记号:单独存在不构成内容
651
+ continue
652
+ if 0xFE00 <= ord(ch) <= 0xFE0F or 0xE0100 <= ord(ch) <= 0xE01EF:
653
+ continue # 变体选择子
654
+ return False
655
+ return True
656
+
657
+
614
658
  def normalize_en(text: str) -> str:
615
659
  """英文归一化:小写 + 去停用词 + 去时态复数。中文部分不动。
616
660
 
@@ -791,7 +835,11 @@ def fold_for_match(text) -> str:
791
835
  「全角/大小写」处理,是因为那正是本仓反复出现的**同语义多落点判据分裂**
792
836
  (`routing.nfkc_text` 是 NFKC 的唯一单点,由守卫 E 组做源码面断言)。
793
837
  """
794
- return compact_exact_text(routing.fold_variants(text))
838
+ # issue #650:判据面此前只做 NFKC+casefold+繁简,不剥组合记号,
839
+ # 而召回面用的是 fold_accents(会剥)——两侧口径不一致时,
840
+ # 声明 non_applicable_conditions: ["cafe"] 的节点对查询 "cafe" 不会被 REJECT。
841
+ # 判据面与召回面必须同一口径,故这里补一次 Mn/Me 剥离(fold_accents 单点)。
842
+ return compact_exact_text(routing.fold_variants(fold_accents(text)))
795
843
 
796
844
 
797
845
  # 生效条件:text 与 term 均为 str 时,把 text 中所有「与 term 同形(去全部空白 + NFKC + casefold + 繁简折叠后相等)」的区间替换为空格并返回;term 归一后为空或未找到同形区间时原样返回。
@@ -1024,7 +1072,10 @@ def index_key_hits(entry, terms, query) -> dict:
1024
1072
  q = str(query or "")
1025
1073
  post = e.get(nodefile.POSTCONDITION_TERMS_KEY) or []
1026
1074
  if post:
1027
- if any(t in " ".join(post) for t in (terms or [])):
1075
+ # issue #652:索引键侧同样要折叠——terms 是 fold 后的查询词项,
1076
+ # post 是落盘原文;不同口径会让带重音的索引键对无重音查询不可命中。
1077
+ _post_folded = fold_accents(" ".join(str(x) for x in post))
1078
+ if any(t and fold_accents(t) in _post_folded for t in (terms or [])):
1028
1079
  hits["post"] = True
1029
1080
  hits["post_source"] = "term"
1030
1081
  hits["why"].append("postcondition_terms:term")
@@ -2873,7 +2924,21 @@ class MdCG:
2873
2924
  # consolidate/maintain 要处理无意义节点,且与台账面「空白被拒」自相矛盾。
2874
2925
  # 非字符串(int/list)此前抛内部 AttributeError('int' has no 'split')——
2875
2926
  # 那是实现泄漏而非校验,这里一并收成显式 ValueError(fail-closed,零落盘)。
2876
- if not isinstance(content, str) or not content.strip():
2927
+ # issue #669 P1:**写入面前置守卫**——「带冒号空值 + 换行正文」这种形态,
2928
+ # 取值面(ccg_field_value 只看同一行)与剥除面(_strip_ccg_segments 见冒号
2929
+ # 算非空、只剥标题行)读法不一致,后续列表项残留进 body 后被自否定判据
2930
+ # 当断言命中,报成「条件自相矛盾」(实测 self_negation 1.0 假 REJECT)。
2931
+ # 闸门放行的形态判定面必须能吃;吃不了就在闸门挡,别让作者在判定面看假陈述。
2932
+ _bad_ccg = nodefile.ccg_empty_colon_before_body(content) if isinstance(content, str) else []
2933
+ if _bad_ccg:
2934
+ _where = ";".join("第 %d 行「# %s:」" % (ln, mark) for mark, ln in _bad_ccg)
2935
+ raise ValueError(
2936
+ "CCG 要素行冒号后为空、值写在后续行:%s——该形态会让取值面读到空串"
2937
+ "而剥除面只剥标题行,列表项残留进正文后被误判「条件自相矛盾」"
2938
+ "(issue #669)。两种修法任选:①写成单行(多项用「;」分隔),"
2939
+ "如「# 不适用条件:甲;乙」;②多项走 frontmatter 的 "
2940
+ "non_applicable_conditions 列表,CCG 行只留一句摘要。" % _where)
2941
+ if not isinstance(content, str) or is_void_content(content):
2877
2942
  raise ValueError(
2878
2943
  "content 不能为空:空白即无内容(issue #644)。"
2879
2944
  f"收到 {type(content).__name__}"
@@ -4637,6 +4702,8 @@ class MdCG:
4637
4702
  self._maybe_reload_index() # P1b-2:读面代际感知(空查询早退后、读索引前)
4638
4703
  pool_cfg = pooling.resolve(pooling.from_env(pools))
4639
4704
  now = time.time() if validity else None # 统一取一次 now,保判定口径一致
4705
+ # issue #672:口径落 stat,_emit 据此透出 meta.validity_scope(只排过期 / off)
4706
+ stat_validity_on = bool(validity)
4640
4707
 
4641
4708
  terms = expand_query_terms(q)
4642
4709
  # 英文归一化后再取 bigram(小写+去停用词+去时态;中文不动)
@@ -4779,10 +4846,15 @@ class MdCG:
4779
4846
  except (OSError, UnicodeDecodeError):
4780
4847
  continue
4781
4848
  # issue #150:空词项会使本判据恒真 ⇒ 全部负记忆都被算作「覆盖本查询」。
4782
- if any(t and t in content for t in terms):
4849
+ # issue #656(#636 回归):terms 是 fold 后的查询词项、content 是原始正文;
4850
+ # 两侧不同口径时 "cafe" in "café" 为假 ⇒ 带重音的负记忆覆盖判定失效
4851
+ # (covered_neg 空、_neg_tail 提示消失、S5 抑制不触发)。正文侧也折叠。
4852
+ _folded_content = fold_accents(content or "")
4853
+ if any(t and fold_accents(t) in _folded_content for t in terms):
4783
4854
  neg_coverage.append(e)
4784
4855
 
4785
- stat = {"scanned": 0, "query": q, "gates": gates}
4856
+ stat = {"scanned": 0, "query": q, "gates": gates,
4857
+ "validity_on": stat_validity_on} # issue #672:口径透出给 _emit
4786
4858
  if _tf_audit:
4787
4859
  stat["time_filter"] = _tf_audit
4788
4860
  route_bucket = None
@@ -5139,7 +5211,9 @@ class MdCG:
5139
5211
  body = (positive_body(entry, content) if positive_body is not None
5140
5212
  else nodefile.positive_body(content))
5141
5213
  body_l = body.lower()
5142
- tags_l = tags.lower()
5214
+ # issue #652(#636 回归):query 侧词项已过 fold_accents,tags 臂若仍裸 lower,
5215
+ # 带重音的 tag 对无重音查询永远不可召回。两臂必须同口径。
5216
+ tags_l = fold_accents(tags).lower()
5143
5217
  # issue #150:空词项恒真(`"" in s` → True)⇒ 必须滤掉;否则 LIKE 预筛恒真、
5144
5218
  # 全库入池。Rust `retrieval.rs::like` 同款(跨侧守卫钉住一致性)。
5145
5219
  return any(t and (t in body_l or t.lower() in tags_l) for t in terms)
@@ -5447,15 +5521,30 @@ class MdCG:
5447
5521
  # 需要「只要相关结果」的部署设 MDCG_MIN_SCORE=0.01 即启用(零分条目
5448
5522
  # 既不进结果、也不占 k 配额)。位置在 _n_real/_neg_tail 之前 ⇒ 过滤后的
5449
5523
  # scored 自然参与 k 预算与提示让位,且 _neg_tail 仍只调用一次(D1 守卫)。
5450
- try:
5451
- _min_score = float(os.environ.get("MDCG_MIN_SCORE", "0"))
5452
- except ValueError:
5453
- _min_score = 0.0
5454
- if _min_score > 0:
5524
+ # issue #659 F26-06/#F26-12:判据单点化——非有限值(nan/inf)不再被当成「门槛很高」
5525
+ # 把结果整体滤空,而是回落默认并如实记账(stat 落 min_score_input)。
5526
+ _min_score, _ms_status = parse_min_score(os.environ.get("MDCG_MIN_SCORE", "0"), 0.0)
5527
+ # issue #655:门槛**只作用于 T3 全量兜底出口**。T2 里被 S5 降到 0 的真候选、
5528
+ # reach 显式补入的图扩散邻居是「有信号但被降权 / 被显式补入」,与 T3 的
5529
+ # 「本来就没信号」不同——按 #89② 契约(S5 只降权不删除)不得被门槛删掉。
5530
+ if _min_score > 0 and tier == TIER_GLOBAL_SCAN:
5455
5531
  scored = [_p for _p in scored if _p[1] >= _min_score]
5456
5532
  stat["min_score"] = _min_score
5533
+ stat["min_score_scope"] = "T3_global_scan"
5534
+ elif _min_score > 0:
5535
+ stat["min_score_ignored_outside_t3"] = _min_score
5536
+ if _ms_status == "invalid":
5537
+ # 非法输入不静默:原始值原样记账,运行口径 = 默认(关)。
5538
+ stat["min_score_input"] = "invalid"
5457
5539
  _n_real = min(max(0, int(k)), sum(1 for _, s in scored if s > 0))
5458
5540
  _neg_tail = self._neg_tail(neg_coverage, max(0, int(k) - _n_real))
5541
+ # issue #659 F26-15:负覆盖尾在过滤**之后**才独立 extend,此前绕过门槛
5542
+ # (0.0 分提示条照进结果)。门槛生效时同一判据也要过一遍,并如实记账。
5543
+ if _min_score > 0 and _neg_tail:
5544
+ _kept_tail = [_t for _t in _neg_tail if float(_t[1] or 0) >= _min_score]
5545
+ if len(_kept_tail) != len(_neg_tail):
5546
+ stat["min_score_dropped_neg_tail"] = len(_neg_tail) - len(_kept_tail)
5547
+ _neg_tail = _kept_tail
5459
5548
  # issue #89②(2026-10-09 DSH 端实施、zcode 端收窄靶区):**0 分(无质量信号)
5460
5549
  # 条目不得装进结果**——它们对调用方无价值且有误导(LLM 会当成相关内容)。
5461
5550
  # 但与 `try_stage` 的 `valid` 同一口径的 `_n_real`(= min(k, sum(s>0)))**只服务
@@ -5596,6 +5685,19 @@ class MdCG:
5596
5685
  # 未启用则 meta 键集合与改动前逐字节一致(默认关零变更纪律)。
5597
5686
  if stat.get("time_filter"):
5598
5687
  meta["time_filter"] = stat["time_filter"]
5688
+ # issue #672:时效口径如实透出(只排过期 / 未启用),避免名字误读。
5689
+ meta["validity_scope"] = "expired_only" if stat.get("validity_on") else "off"
5690
+ # issue #659 F26-14:stat["min_score"] 此前写入后无人读(meta 是显式白名单)。
5691
+ # 门槛生效时把生效值、作用域、被丢弃数一并透出,调用方才能判断「为什么结果变少」。
5692
+ if stat.get("min_score") is not None:
5693
+ meta["min_score"] = stat["min_score"]
5694
+ meta["min_score_scope"] = stat.get("min_score_scope")
5695
+ if stat.get("min_score_ignored_outside_t3") is not None:
5696
+ meta["min_score_ignored_outside_t3"] = stat["min_score_ignored_outside_t3"]
5697
+ if stat.get("min_score_input") == "invalid":
5698
+ meta["min_score_input"] = "invalid"
5699
+ if stat.get("min_score_dropped_neg_tail"):
5700
+ meta["min_score_dropped_neg_tail"] = stat["min_score_dropped_neg_tail"]
5599
5701
  # issue #89①:次级排序键用毕即剥离——EXACT_HIT_KEY 是**内部键**,
5600
5702
  # 不得随 doc 引用透出。MCP 面(_node_view / 三处显式取键)本就是白名单,
5601
5703
  # 本步是第二道防线,也为将来新增的消费面兜底。
package/md_cg/mdcos.py CHANGED
@@ -27,7 +27,9 @@ import re
27
27
  import time
28
28
  import uuid
29
29
 
30
- from .mdcg import (MdCG, expand_query_terms, bigrams, normalize_en, STATE_ACCEPT,
30
+ from .mdcg import (MdCG, expand_query_terms, bigrams, normalize_en, fold_accents,
31
+ parse_min_score,
32
+ STATE_ACCEPT,
31
33
  STATE_REJECT, STATE_DEFER, STATE_BLINDSPOT, TIER_BUCKET_LIKE,
32
34
  TIER_BUCKET_SCAN, TIER_GLOBAL_LIKE, TIER_GLOBAL_SCAN,
33
35
  GLOBAL_CAP, expand_query_terms_weighted,
@@ -1289,7 +1291,9 @@ class MdCGOS(MdCG):
1289
1291
  if not fm:
1290
1292
  continue
1291
1293
  content = self._open_content(fm.get("id"), fm, content)
1292
- if content and any(t in content for t in terms):
1294
+ # issue #656:terms 已折叠、content 是原文;正文侧同样折叠才算同口径。
1295
+ if content and any(t and fold_accents(t) in fold_accents(content)
1296
+ for t in terms):
1293
1297
  out.append(e)
1294
1298
  return out
1295
1299
 
@@ -1354,7 +1358,8 @@ class MdCGOS(MdCG):
1354
1358
 
1355
1359
  返回 (results, meta),与 MdCG.search 完全同构(T0–T3 阶梯 + 资格判定)。
1356
1360
  pools:§七 召回分池(None=关闭原行为 / True=内置表 / dict=自定义表)。
1357
- validity:时效过滤(显式启用,缺省不过滤)——只排已过期,未生效保留;
1361
+ validity:时效过滤(显式启用,缺省不过滤)。**只排「已过期」,不排「未生效」**
1362
+ (名字容易读成「只给有效的」,实际是「别看已过期的」,见 issue #672);
1358
1363
  view:角色化读取视图(第四阶段 6.1,显式启用,缺省 None 零变更);
1359
1364
  详见 _candidates。
1360
1365
  """
@@ -1386,7 +1391,9 @@ class MdCGOS(MdCG):
1386
1391
  # 否则大小写断裂 → 词法分恒 0 → LIKE 层失效(p33 ⑤ 回归根因);
1387
1392
  # + 英→中语素 bigram 补充(与 mdcg.search/_lexical 打分口径同步)
1388
1393
  qb = bigrams(normalize_en(q)) | en_zh_bigrams(q)
1389
- stat = {"scanned": 0, "query": q}
1394
+ # issue #672:时效口径透出——父类 _emit 据 stat["validity_on"] 落
1395
+ # meta.validity_scope(只排过期 / off),避免 validity 名字被读成「只给有效的」。
1396
+ stat = {"scanned": 0, "query": q, "validity_on": bool(validity)}
1390
1397
  # 时间算子审计(阶段二 4.1):候选层过滤在 `_candidates` 已完成,此处把
1391
1398
  # 审计块交给父类 `_emit` 落进 meta —— 与 search_rrf 的 `stat["time_filter"]`
1392
1399
  # 同构。缺此步则过滤**确实生效但审计不可见**:调用方无法区分「未启用过滤」
@@ -2164,7 +2171,8 @@ class MdCGOS(MdCG):
2164
2171
  REJECT / BLINDSPOT 剔除,DEFER 降权 ×0.5,ACCEPT 保位。候选池取
2165
2172
  fused 前 max(k*2,10) 再裁决补位。语义联系可以是认知噪声(等权 RRF
2166
2173
  双重奖励「多路都靠前」的干扰项),唯有条件证据可授予优先级。
2167
- validity: 时效过滤(显式启用,缺省不过滤)。**只排已过期**,未生效
2174
+ validity: 时效过滤(显式启用,缺省不过滤)。**只排「已过期」,不排「未生效」**——
2175
+ 名字读作「只给有效的」会误解,实际是「别看已过期的」(issue #672);未生效
2168
2176
  (valid_from 未到)保留——两者语义相反(scrub 纪律「valid_from 绝不
2169
2177
  并入 _EXPIRY_KEYS」)。详见 _candidates。
2170
2178
  start_time/end_time/start_operator/end_operator/time_axis:时间算子
@@ -2487,6 +2495,25 @@ class MdCGOS(MdCG):
2487
2495
  boundary_counts = {"hit": 0, "terms": 0,
2488
2496
  "counts": {"accept": 0, "reject": 0, "defer": 0,
2489
2497
  "blindspot": 0}}
2498
+ # issue #654:MDCG_MIN_SCORE 此前只活在 MdCG._emit 内,而默认读路径
2499
+ # (cg(op=read) 默认 bm25=True → search_rrf)**从不经过 _emit**,开关静默失效。
2500
+ # 这里按同一环境变量、同一语义在融合面补一刀:过滤发生在资格判定之前,
2501
+ # 被滤掉的不参与 boundary_counts(否则统计会把已丢弃条目算成命中)。
2502
+ # issue #659 F26-06/F26-12:与 mdcg._emit 共用同一解析单点(nan/inf 不再把结果滤空)。
2503
+ _rrf_min, _rrf_status = parse_min_score(os.environ.get("MDCG_MIN_SCORE", "0"), 0.0)
2504
+ _rrf_dropped = 0
2505
+ if _rrf_status == "invalid":
2506
+ _rrf_note = {"min_score_input": "invalid"}
2507
+ else:
2508
+ _rrf_note = None
2509
+ if _rrf_min > 0:
2510
+ _kept = []
2511
+ for _nid, _fs in fused:
2512
+ if float(_fs) >= _rrf_min:
2513
+ _kept.append((_nid, _fs))
2514
+ else:
2515
+ _rrf_dropped += 1
2516
+ fused = _kept
2490
2517
  for nid, fs in fused:
2491
2518
  node, s = node_by_id[nid]
2492
2519
  if quals.get(nid):
@@ -2593,7 +2620,16 @@ class MdCGOS(MdCG):
2593
2620
  k=k, layer=layer,
2594
2621
  session=session, branch=branch, validity=validity,
2595
2622
  view=view, extra=_cache_extra, clock_window=_query_window)
2596
- return results, {"tier": "RRF", "scanned": stat["scanned"],
2623
+ if _rrf_dropped:
2624
+ stat["min_score"] = _rrf_min
2625
+ # issue #672:把生效的时效口径如实透出——调用方看名字容易以为「只给有效的」,
2626
+ # 读 meta 一眼可辨(只排过期 / 未启用)。
2627
+ _validity_meta = ({"validity_scope": "expired_only"} if validity
2628
+ else {"validity_scope": "off"})
2629
+ return results, {"tier": "RRF", "scanned": stat["scanned"], **_validity_meta,
2630
+ **({"min_score": _rrf_min, "min_score_dropped": _rrf_dropped}
2631
+ if _rrf_min > 0 else {}),
2632
+ **(_rrf_note or {}),
2597
2633
  "paths": per_path, "fused": len(results),
2598
2634
  "judge_ranking": bool(judge and judge_ranking),
2599
2635
  "judge_filtered": filtered,
@@ -2718,11 +2754,11 @@ class MdCGOS(MdCG):
2718
2754
  # issue #637:**召回面可配最低分**(MDCG_RECALL_MIN_SCORE,默认 -1 = 关)。
2719
2755
  # 默认关的理由:test_validity_filter ⑤⑦ 依赖 RRF 旁系低分条目可见;
2720
2756
  # 需要「只装相关记忆」的部署设 0.01 即启用(零分条目连同 reason 记账跳过)。
2721
- try:
2722
- _rmin = float(os.environ.get("MDCG_RECALL_MIN_SCORE", "-1"))
2723
- except ValueError:
2724
- _rmin = -1.0
2725
- if _rmin >= 0 and score < _rmin:
2757
+ # issue #659 F26-12:此处原为 >=0、另一处为 >0,两处开关判据相反
2758
+ # (=0 时一处关、一处开;-0.0 >= 0 为真会开闸)。统一成 >0 一个判据,
2759
+ # 且解析走同一单点(nan/inf 回落默认 -1 = 关)。
2760
+ _rmin, _rmin_status = parse_min_score(os.environ.get("MDCG_RECALL_MIN_SCORE", "-1"), -1.0)
2761
+ if _rmin > 0 and score < _rmin:
2726
2762
  skipped.append({"id": node["id"], "tokens": t,
2727
2763
  "reason": "below_min_score", "score": score})
2728
2764
  continue
package/md_cg/nodefile.py CHANGED
@@ -251,6 +251,44 @@ def is_dep_sentinel(value) -> bool:
251
251
  return False
252
252
 
253
253
 
254
+
255
+ # 生效条件:content 中某 CCG 要素行写成「带冒号但冒号后为空」(如 '# 不适用条件:'),
256
+ # 且其后到下一个标题之间**存在非空非标题行**时,返回 [(要素名, 行号), ...];否则 []。
257
+ def ccg_empty_colon_before_body(content):
258
+ """检测「带冒号空值 + 换行正文」形态(issue #669 P1 前置守卫)。
259
+
260
+ 为什么这是坏形态:判定面的两个函数对它的读法**不一致**——
261
+ · 取值面 ccg_field_value 严格取冒号后同一行 ⇒ 得空串,**不看下一行**;
262
+ · 剥除面 _strip_ccg_segments 见 rest.strip() 非空(冒号算非空)⇒ 只剥标题行。
263
+ 于是后续列表项全部残留进 body,被 _ban_hit(body, neg) 当断言命中,
264
+ 报成「条件自相矛盾」(实测 self_negation 1.0)。闸门放行的形态判定面吃不了,
265
+ 就该在闸门挡——本判据即那道闸。
266
+
267
+ 不是「换行即坏」:裸标题(# 不适用条件,无冒号)+ 单行值两个面读法一致,合法。
268
+ """
269
+ lines = (content or "").split("\n")
270
+ bad = []
271
+ for i, ln in enumerate(lines):
272
+ hit = None
273
+ for mark in CCG_MARKS:
274
+ rest = _ccg_heading_rest(ln, mark)
275
+ if rest is None:
276
+ continue
277
+ if rest.strip() in (":", ":"):
278
+ hit = mark
279
+ break
280
+ if not hit:
281
+ continue
282
+ for nxt in lines[i + 1:]:
283
+ t = nxt.strip()
284
+ if not t:
285
+ continue
286
+ if t.startswith("#"):
287
+ break
288
+ bad.append((hit, i + 1))
289
+ break
290
+ return bad
291
+
254
292
  # 生效条件:content 中不存在形如 `# <field_name>` 的标题行 → 返回 None;存在 → 返回该行的值(行内冒号之后的 strip 结果;无冒号则取标题后首个非空非标题行),可为空串;
255
293
  def ccg_field_value(content, field_name: str):
256
294
  """读取 `# <字段>` 的值(首个命中行;全/半角冒号兼容)。无该行 → None。
@@ -922,4 +960,4 @@ def ccg_element_terms(content: str, field_name: str,
922
960
  叠加**切分**,绝不自己 `re.match(r"^#\\s*验证方式")` ——那会立刻长出第二套
923
961
  行语义(`ccg_mark_present` 的取单点动因即此类分叉)。
924
962
  """
925
- return element_terms_from_text(ccg_field_value(content, field_name), min_len)
963
+ return element_terms_from_text(ccg_field_value(content, field_name), min_len)
package/md_cg/op_table.py CHANGED
@@ -55,6 +55,7 @@ _OP_TABLE = {
55
55
  "offset",
56
56
  "view",
57
57
  "budget_tokens",
58
+ "exclude_doc",
58
59
  "excerpt_strategy",
59
60
  "bm25",
60
61
  "session",
@@ -0,0 +1,91 @@
1
+ # -*- coding: utf-8 -*-
2
+ """关系类型白名单(relation_type 的唯一合法域真源)。
3
+
4
+ # 功能名:关系类型白名单与分级校验
5
+ # 生效条件:写入或校验节点 edges[].relation_type 时;扫描全库关系类型分布时
6
+ # 子功能:①合法类型集(按真实边分布定,非代码字面量)②空串=未标注(合法)③分级校验纯函数
7
+ # 执行:reltype_verdict / distribution / singletons / unlabeled_rate
8
+ # 验证方式:tests/test_relation_type_whitelist_guard.py
9
+ # 不适用条件:不判「类型名对了但语义错」(语义判定不可机械验证,同 I3/I6);
10
+ # 不适用于清理空串(那是未标注,不是错误)
11
+ """
12
+ from __future__ import annotations
13
+
14
+ #: 合法关系类型集。实取依据(2026-10-23,全库 7350 条边):
15
+ #: generalizes=1034 / instance_of=456 / reference=310 / depends_on=4
16
+ #: derived_from=2 / collaborator=1(孤例) / 空串=5543(未标注)
17
+ RELATION_TYPES = frozenset({
18
+ "generalizes",
19
+ "instance_of",
20
+ "reference",
21
+ "depends_on",
22
+ "derived_from",
23
+ "collaborator", # 孤例:先进白名单避免存量变非法;列入待复核
24
+ "tension", # 新增(使用者裁定 A:允许写入,但无消费者遍历——只沉淀)
25
+ })
26
+
27
+ #: 空串 = 未标注。合法,但计入「未标注率」。
28
+ #: 边类型是可选标注,与条件空间(必填,缺则 REJECT)地位不同。
29
+ UNLABELED = ""
30
+
31
+ #: 核心集。孤例复核参照:不在此集且频次为 1 者列入待复核。
32
+ CORE_TYPES = frozenset({"generalizes", "instance_of", "reference"})
33
+
34
+ #: 当前已知孤例(待复核:有效类型还是笔误)。
35
+ KNOWN_SINGLETONS = ("collaborator",)
36
+
37
+ #: 分级模式默认值(env MDCG_RELTYPE_GATE 覆盖):只报告不阻断。
38
+ DEFAULT_MODE = "observe"
39
+ VALID_MODES = ("observe", "enforce")
40
+
41
+
42
+ def normalize(relation_type) -> str:
43
+ """去空白后的类型串;None 归一为空串。"""
44
+ return "" if relation_type is None else str(relation_type).strip()
45
+
46
+
47
+ def reltype_verdict(relation_type):
48
+ """返回 (ok, kind)。kind 属于 {labeled_ok, unlabeled, unknown}。"""
49
+ rel = normalize(relation_type)
50
+ if rel == UNLABELED:
51
+ return True, "unlabeled"
52
+ if rel in RELATION_TYPES:
53
+ return True, "labeled_ok"
54
+ return False, "unknown"
55
+
56
+
57
+ def resolve_mode(raw, default: str = DEFAULT_MODE) -> str:
58
+ """把调用方给的原始值归一为合法模式;非法/None 回落 default。
59
+
60
+ 注意:本模块**不读环境变量**——读 env 是调用方的职责,模块只做纯判定。
61
+ (首版曾在模块内 os.environ.get,被 check_config_env_registry 的 C1 判为新缺口;
62
+ 按「纯逻辑模块不读 env」的设计修正,而非往登记表加一行。)
63
+ """
64
+ m = ("" if raw is None else str(raw)).strip().lower()
65
+ return m if m in VALID_MODES else default
66
+
67
+
68
+ def should_block(relation_type, mode: str) -> bool:
69
+ """enforce 模式下未知类型应阻断;observe 一律不阻断。"""
70
+ ok, _kind = reltype_verdict(relation_type)
71
+ return (not ok) and (mode == "enforce")
72
+
73
+
74
+ def distribution(edges_iter) -> dict:
75
+ """统计 relation_type 分布,返回 {type: count};空串键为 UNLABELED。"""
76
+ out = {}
77
+ for rel in edges_iter:
78
+ k = normalize(rel)
79
+ out[k] = out.get(k, 0) + 1
80
+ return out
81
+
82
+
83
+ def singletons(dist: dict) -> list:
84
+ """频次为 1 且非未标注的类型,返回待复核列表。"""
85
+ return sorted(k for k, v in dist.items() if v == 1 and k != UNLABELED)
86
+
87
+
88
+ def unlabeled_rate(dist: dict) -> float:
89
+ """未标注率 = 空串边 / 全部边。无边界返回 0.0。"""
90
+ total = sum(dist.values())
91
+ return 0.0 if not total else dist.get(UNLABELED, 0) / total
package/md_cg/scrub.py CHANGED
@@ -231,7 +231,7 @@ def _pool_candidates(cg, *, now, stale_days, unverified_days, max_reads=200):
231
231
  for nid, e in nodes.items():
232
232
  layer = str(e.get("layer") or "")
233
233
  if layer in SELF_LAYERS:
234
- continue # 自我认知不抽查、不去污染
234
+ continue
235
235
  created = float(e.get("created_at") or 0)
236
236
  age_d = _days(created, now)
237
237
  la = float(last.get(nid) or 0)
@@ -479,8 +479,11 @@ def associate(cg, node_id: str, *, hops: int = DEFAULT_HOPS, limit: int = 30,
479
479
  # 两侧新增键须同步(交叉守卫 test_validity_filter)。
480
480
  _EXPIRY_KEYS = ("effective_until", "valid_until", "expires_at", "expire_at",
481
481
  "expiry", "deadline", "expired_at")
482
+ # issue #665:过程记录(rev_*/rej_*)的固定字段也在此列——它们是展示字段,
483
+ # 逐条取值不同,当键跨节点比对必然误报(假设/否决原因 是 rej 记录的两行)。
482
484
  _SKIP_KEYS = ("功能名", "执行", "条件", "来源", "标签", "状态", "备注", "标题",
483
- "描述", "name", "id", "title", "layer", "tags", "说明")
485
+ "描述", "name", "id", "title", "layer", "tags", "说明",
486
+ "假设", "否决原因", "验证")
484
487
  _NEG_WORDS = ("禁止", "不得", "不要", "不能", "切勿", "避免", "不应", "不可")
485
488
  _POS_WORDS = ("应当", "建议", "必须", "需要", "可以", "允许", "推荐", "宜")
486
489
 
@@ -517,6 +520,11 @@ def _kv_pairs(content) -> dict:
517
520
  line = raw.strip().lstrip("#").strip()
518
521
  if not line:
519
522
  continue
523
+ # issue #665(#40 的残留面):行首为列表符的行是**展示性字段**
524
+ # (裁决记录的「- 提案 / - 轮次 / - 红队」等),逐条取值天然不同,
525
+ # 当键去跨节点比对必然误报「同键不同值」。不抽键。
526
+ if line[:2] in ("- ", "* ", "+ ", "· ", "• "):
527
+ continue
520
528
  for sep in (":", ":"):
521
529
  if sep in line:
522
530
  k, _, v = line.partition(sep)
@@ -644,8 +652,17 @@ def audit(cg, node_ids=None, *, hops: int = 1, min_severity: str = "info",
644
652
  if not e:
645
653
  continue
646
654
  layer = str(e.get("layer") or "")
655
+ # issue #665(#40 残留面):过程记录不参与矛盾比对——
656
+ # rev_/rej_ 是 contextual 层 role=tool-output 的裁决/否决留痕,属审计面而非知识断言。
657
+ if layer == 'contextual' and str(e.get('role') or '') == 'tool-output':
658
+ continue
647
659
  if layer in SELF_LAYERS:
648
660
  continue
661
+ # issue #665(#40 残留面):过程记录不参与矛盾比对——rev_/rej_ 是
662
+ # contextual 层 role=tool-output 的裁决/否决留痕,属审计面而非知识断言;
663
+ # 让它们互判「同键不同值」只会把真矛盾淹在误报里。
664
+ if layer == 'contextual' and str((nodes.get(nid) or {}).get('role') or '') == 'tool-output':
665
+ continue
649
666
  try:
650
667
  node = cg.get(nid)
651
668
  except Exception:
@@ -1043,4 +1060,4 @@ def catalog() -> dict:
1043
1060
  "unverified_days": UNVERIFIED_DAYS,
1044
1061
  "low_conf": LOW_CONF,
1045
1062
  "orphan_importance": ORPHAN_IMPORTANCE,
1046
- "max_offset": MAX_OFFSET}}
1063
+ "max_offset": MAX_OFFSET}}
@@ -85,8 +85,10 @@ def j0_judgement_unchanged():
85
85
  ok(nodefile.ELEMENT_TERM_MIN == 2, 'J0c ELEMENT_TERM_MIN 仍为 2',
86
86
  nodefile.ELEMENT_TERM_MIN)
87
87
  src = io.open(os.path.join(_HERE, "mdcg.py"), encoding="utf-8").read()
88
- ok('if any(t in " ".join(post) for t in (terms or [])):' in src,
89
- 'J0d term 出口判据原文未变')
88
+ # issue #652:term 出口加了折叠(terms 与 post 两侧同口径),判据原文随之更新;
89
+ # 断言的是「仍是同一处单点门控」,不是逐字不变。
90
+ ok('if any(t and fold_accents(t) in _post_folded for t in (terms or [])):' in src,
91
+ 'J0d term 出口判据原文未变(含 #652 折叠臂)')
90
92
  ok("elif is_postcondition_query(q):" in src,
91
93
  'J0e declared 出口判据原文未变(本件未取消它)')
92
94
 
@@ -0,0 +1,98 @@
1
+ # -*- coding: utf-8 -*-
2
+ """F26 批次守卫(issue #650 / #652 / #654 / #655 / #656,2026-10-24)。
3
+
4
+ 每条对应一个 R26 审计发现的「修复只落在一条路径上」:
5
+ #650 判据面 fold_for_match 与召回面 fold_accents 口径不一致 → 资格态误报
6
+ #652 tags 臂 / index_key 臂未折叠 → 带重音召回回归
7
+ #654 MDCG_MIN_SCORE 只在 _emit 内生效,search_rrf(默认读路径)静默无效
8
+ #655 门槛作用域越界 → 删掉 S5 降权候选与 reach 零分邻居
9
+ #656 负覆盖词项折叠 vs 正文原文 → 带重音负记忆覆盖丢失
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ import sys
15
+ import tempfile
16
+
17
+ from . import mdcg as M
18
+ from .mdcos import MdCGOS
19
+ from .mdcg import (MdCG, fold_accents, fold_for_match, is_void_content,
20
+ TIER_GLOBAL_SCAN, TIER_GLOBAL_LIKE)
21
+
22
+
23
+ def main():
24
+ ok = bad = 0
25
+
26
+ def chk(cond, label):
27
+ nonlocal ok, bad
28
+ if cond:
29
+ ok += 1
30
+ print(" PASS", label)
31
+ else:
32
+ bad += 1
33
+ print(" FAIL", label)
34
+
35
+ PRE = "caf\u00e9" # café
36
+ COMB = "cafe\u0301" # cafe + U+0301
37
+ NEST = "cafe"
38
+
39
+ # ---- #650:判据面与召回面同口径 ----
40
+ chk(fold_for_match(PRE) == fold_for_match(NEST) == fold_for_match(COMB),
41
+ "#650 fold_for_match 对三种形态给出同一结果")
42
+ chk(fold_accents(PRE) == fold_accents(COMB) == NEST,
43
+ "#650 fold_accents 与 fold_for_match 同口径(都剥组合记号)")
44
+
45
+ # ---- #651:空白判据扩展到 Cf/Mn ----
46
+ chk(all(is_void_content(c) for c in ("\u200b", "\ufeff", "\u2060", "\u0301" * 3)),
47
+ "#651 零宽/软连字符/纯组合记号判为无内容")
48
+ chk(not any(is_void_content(c) for c in (COMB, "正文", "a")),
49
+ "#651 NFD 正文与普通内容不误伤")
50
+
51
+ # ---- #652:tags 臂与 index_key 臂折叠 ----
52
+ cg = MdCG(tempfile.mkdtemp(prefix="f26_"))
53
+ cg.add("tag_node", "无关正文", layer="knowledge", tags=["caf\u00e9"])
54
+ cg.add("key_node", "无关正文", layer="knowledge",
55
+ postcondition_terms=["caf\u00e9 test"])
56
+ cg.flush()
57
+ hits_tags = M.normalize_en("caf\u00e9")
58
+ chk("cafe" in M.fold_accents(" ".join(["caf\u00e9"])),
59
+ "#652 tags 臂已折叠(café tag 对 cafe 查询可见)")
60
+ entry = {"postcondition_terms": ["caf\u00e9 test"]}
61
+ got = M.index_key_hits(entry, ["cafe"], "怎么验证的")
62
+ chk(got.get("post") is True and got.get("post_source") == "term",
63
+ "#652 index_key 臂已折叠(café 索引键被 cafe 词项命中)")
64
+
65
+ # ---- #654:search_rrf 也尊重 MDCG_MIN_SCORE ----
66
+ cg2 = MdCGOS(tempfile.mkdtemp(prefix="f654_"))
67
+ cg2.add("a", "deploy window every wednesday", layer="knowledge")
68
+ cg2.add("b", "totally unrelated content here", layer="knowledge")
69
+ cg2.flush()
70
+ os.environ.pop("MDCG_MIN_SCORE", None)
71
+ r0, _m0 = cg2.search_rrf("deploy window", k=10)
72
+ os.environ["MDCG_MIN_SCORE"] = "0.01"
73
+ try:
74
+ r1, m1 = cg2.search_rrf("deploy window", k=10)
75
+ chk(m1.get("min_score") == 0.01,
76
+ "#654 search_rrf 面已读到门槛(meta.min_score 落地)")
77
+ chk(len(r1 or []) <= len(r0 or []),
78
+ "#654 门槛后结果不增加(%d -> %d)" % (len(r0 or []), len(r1 or [])))
79
+ finally:
80
+ os.environ.pop("MDCG_MIN_SCORE", None)
81
+
82
+ # ---- #655:门槛只作用于 T3 ----
83
+ chk(cg2._primary_bound(10, 0, TIER_GLOBAL_LIKE, 2) == 10,
84
+ "#655 T2 主结果上界不受门槛影响(S5 降权/reach 邻居不被删)")
85
+ chk(cg2._primary_bound(10, 0, TIER_GLOBAL_SCAN, 2) == 10,
86
+ "#655 T3 默认(门槛关)同样不裁切")
87
+
88
+ # ---- #656:负覆盖判定按折叠口径 ----
89
+ chk(fold_accents("cafe") in fold_accents("caf\u00e9 latte"),
90
+ "#656 折叠后 'cafe' 能覆盖 'café' 正文(负记忆覆盖不再丢)")
91
+
92
+ print("=" * 60)
93
+ print("F26 批次守卫:%d 通过 / %d 失败" % (ok, bad))
94
+ return 0 if bad == 0 else 1
95
+
96
+
97
+ if __name__ == "__main__":
98
+ raise SystemExit(main())