@furongjun1999/dsh-memory 0.9.22 → 0.9.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.en.md +404 -0
- package/CHANGELOG.md +45 -0
- package/README.en.md +240 -0
- package/README.md +3 -1
- package/docs/README.md +2 -0
- package/docs/en/README.md +190 -0
- package/docs/en/TRANSLATION.md +78 -0
- package/docs/en/TRANSLATION_MANIFEST.json +170 -0
- package/docs/en/TRANSLATION_REPORT.md +11 -0
- package/docs/en/dev/README.md +10 -0
- package/docs/en/dev/coding-testing.md +72 -0
- package/docs/en/dev/switch-matrix.md +10 -0
- package/docs/en/glossary.md +97 -0
- package/docs/en/harnesses/claude.md +100 -0
- package/docs/en/harnesses/codebuddy.md +93 -0
- package/docs/en/harnesses/codex.md +88 -0
- package/docs/en/harnesses/dsh.md +84 -0
- package/docs/en/harnesses/zcode.md +42 -0
- package/docs/en/mdcg/ccg.md +32 -0
- package/docs/en/mdcg/generated-docs.md +20 -0
- package/docs/en/mdcg/guardrail-charter.md +170 -0
- package/docs/en/mdcg/mcp-tool-names.md +43 -0
- package/docs/en/mdcg/multi-harness.md +43 -0
- package/docs/en/mdcg/recall-metadata.md +30 -0
- package/docs/en/mdcg/world-model-endpoint.md +379 -0
- package/docs/en/mdcg/write-aliases.md +130 -0
- package/docs/en/ops/README.md +11 -0
- package/docs/en/ops/environment-known-issues.md +244 -0
- package/docs/en/ops/install.md +72 -0
- package/docs/en/ops/operations-troubleshooting.md +86 -0
- package/docs/en/ops/permissions-review.md +79 -0
- package/docs/en/ops/release-governance.md +49 -0
- package/docs/en/ops/tool-name-migration.md +30 -0
- package/docs/en/ops/ui-install-troubleshooting.md +53 -0
- package/docs/en/standards/ai-coding-standard-checklist.md +71 -0
- package/docs/en/standards/ai-coding-standard-lingshu.md +47 -0
- package/docs/en/standards/ai-coding-standard.md +185 -0
- package/docs/en/ui/minimal.md +62 -0
- package/docs/mdcg/cogmap_ops.md +15 -15
- package/lib/hooks.d.ts +22 -0
- package/lib/hooks.js +124 -32
- package/lib/index.js +19 -3
- package/lib/lib/console_web.mjs +30 -3
- package/lib/lib/hook_audit.d.ts +3 -2
- package/lib/lib/hook_audit.js +14 -4
- package/lib/lib/mdcg_client.d.ts +5 -2
- package/lib/lib/mdcg_client.js +8 -4
- package/lib/lib/prompt_safety.d.ts +24 -0
- package/lib/lib/prompt_safety.js +77 -1
- package/lib/lib/token_store.js +5 -2
- package/lib/tools.js +5 -3
- package/md_cg/fsutil.py +80 -25
- package/md_cg/mcp_server.py +5761 -5557
- package/md_cg/mdcg.py +570 -73
- package/md_cg/mdcos.py +36 -11
- package/md_cg/nodefile.py +147 -23
- package/md_cg/op_table.py +14 -4
- package/md_cg/reconcile.py +9 -11
- package/md_cg/rollback.py +16 -1
- package/md_cg/scrub.py +94 -14
- package/md_cg/security.py +4 -2
- package/md_cg/test_cond_term_fold.py +183 -0
- package/md_cg/test_cond_terms_colon.py +348 -0
- package/md_cg/test_generation_guard.py +63 -42
- package/md_cg/test_issue362_neg_condition.py +44 -7
- package/md_cg/test_issue39_utf8_stdio.py +3 -3
- package/md_cg/test_issue444_scrub_evidence_plaintext.py +14 -8
- package/md_cg/test_issue677_flush_batch_io.py +139 -0
- package/md_cg/test_issue677_info_fast.py +82 -0
- package/md_cg/test_issue677_remember_dedupe.py +106 -0
- package/md_cg/test_issue712_tokens_sessions_read.py +199 -0
- package/md_cg/test_issue722_strict_conditions.py +96 -0
- package/md_cg/test_issue730_narrowing_audit.py +121 -0
- package/md_cg/test_issue733_verify_override.py +193 -0
- package/md_cg/test_issue733_verify_override_and_overwrite_inherit.py +315 -0
- package/md_cg/test_issue740_filelock_fd_leak.py +218 -0
- package/md_cg/test_issue741_content_hash_same_source.py +158 -0
- package/md_cg/test_issue747_slot_contradiction.py +125 -0
- package/md_cg/test_issue754_nested_root_guard.py +197 -0
- package/md_cg/test_issue757_index_hash_compare.py +85 -0
- package/md_cg/test_issue758_disk_hash_single.py +67 -0
- package/md_cg/test_issue759_twophase_hash.py +67 -0
- package/md_cg/test_n204_n205_n226_n227_n228_n229_exit_gates.py +545 -542
- package/md_cg/test_n209_verify_write_face_gates.py +5 -2
- package/md_cg/test_neg_condition_hits.py +336 -333
- package/md_cg/test_scrub_source_line_false_positive.py +64 -0
- package/md_cg/test_twophase.py +286 -286
- package/md_cg/tokens.py +55 -7
- package/md_cg/twophase.py +15 -6
- package/md_cg/writepipe.py +35 -3
- package/package.json +137 -134
- package/scripts/workspace_index.py +2 -0
- package/src/hooks.ts +139 -33
- package/src/index.ts +19 -3
- package/src/lib/console_web.mjs +30 -3
- package/src/lib/hook_audit.ts +15 -5
- package/src/lib/mdcg_client.ts +8 -4
- package/src/lib/prompt_safety.ts +73 -1
- package/src/lib/token_store.ts +5 -2
- package/src/tools.ts +5 -3
- package/ui/minimal/integrity.json +2 -2
- package/ui/minimal/payload/lib/lib/console_web.mjs +30 -3
- package/ui/minimal/payload/src/lib/console_web.mjs +30 -3
package/md_cg/mdcg.py
CHANGED
|
@@ -26,6 +26,7 @@ import atexit
|
|
|
26
26
|
import weakref
|
|
27
27
|
import hashlib
|
|
28
28
|
import secrets
|
|
29
|
+
import collections
|
|
29
30
|
import threading
|
|
30
31
|
|
|
31
32
|
from . import (nodefile, protect, routing, subgraph, chain, provenance, pooling,
|
|
@@ -349,6 +350,46 @@ VERIFICATION_BASIS = nodefile.VERIFICATION_BASIS
|
|
|
349
350
|
# 检验强度(多主体世界模型对齐 v0.1 §2 L1;真源 nodefile.CHECK_STRENGTHS)
|
|
350
351
|
CHECK_STRENGTHS = nodefile.CHECK_STRENGTHS
|
|
351
352
|
|
|
353
|
+
#: 覆写(同 node_id 再写)时应**继承**而非重置的元数据列(issue #732)。
|
|
354
|
+
#: `add()` 是全量重建 fm:除 lifecycle_state / verification_state / depends_on /
|
|
355
|
+
#: check_strength 已各有显式继承逻辑外,其余键一律按缺省值或重算值落盘。于是
|
|
356
|
+
#: 「同 id 覆写正文」会顺手把 created_at 改成现在、session 变成 unattributed、
|
|
357
|
+
#: evidence_log / protected 直接消失。下列字段表达的是「这条记忆的历史与证据」,
|
|
358
|
+
#: 不是「这次写什么」,故覆写时继承;调用方**显式**给出同名键才覆盖。
|
|
359
|
+
#: 注:importance 不在此列——它是 recalc 派生物,正文变了本就该重算;但保护位
|
|
360
|
+
#: (protected)在此列内,故「重要性重算跌破 0.70」不会连带撤销既有保护
|
|
361
|
+
#: (保护是单向的:打上就不再自动取消)。
|
|
362
|
+
#: `untrusted` / `untrusted_markers` **不在此列**(#742 复核):它们是「这份正文」的
|
|
363
|
+
#: 判定结果,若无条件继承,「干净节点被覆写成含注入短语的正文」会继承旧的
|
|
364
|
+
#: untrusted=False 而吃掉写入面 classify 的命中标记(安全向 fail-open)。
|
|
365
|
+
INHERIT_ON_OVERWRITE = (
|
|
366
|
+
"session", "writer",
|
|
367
|
+
"evidence_count", "positive_evidence", "negative_evidence", "evidence_log",
|
|
368
|
+
"verified_at", "verification_history",
|
|
369
|
+
"access_count", "last_access",
|
|
370
|
+
"protected", "protection_reason", "immutable",
|
|
371
|
+
)
|
|
372
|
+
|
|
373
|
+
#: 正文**逐字未变**时才继承的列:它们描述的是「这份正文」的属性,正文没动就没理由
|
|
374
|
+
#: 重算或丢弃。
|
|
375
|
+
#:
|
|
376
|
+
#: - `edges`:写入侧 auto:linkref 只在正文含 @<id> 时派生一次,覆写既不继承也不
|
|
377
|
+
#: 重派生,等于把自动血缘一并抹掉(实测 mem_1793461027725_714001 改写前 edges
|
|
378
|
+
#: 有 1 条 auto:linkref,改写后为空)。
|
|
379
|
+
#: - `confidence` / `verification_basis` / `non_applicable_conditions` / `modality`:
|
|
380
|
+
#: 证据累积值与条件面三列(#742 复核:retag / 元数据补丁复用 add() 时若不继承,
|
|
381
|
+
#: confidence 回落 0.6、verification_basis 清空、拒绝域与 modality 一并丢失)。
|
|
382
|
+
#: - `importance_source`:与 `importance` 配对(importance 走「传 None 才继承」的
|
|
383
|
+
#: 形参缺省口径,其派生来源必须同进同退)。
|
|
384
|
+
#: - `untrusted` / `untrusted_markers`:见上(安全向,必须在正文不变时才继承)。
|
|
385
|
+
#:
|
|
386
|
+
#: ⚠️ 本表与 add() 的 `importance=None` 形参缺省是**同一判据的两半**(正文未变才
|
|
387
|
+
#: 继承),改一处必须同步另一处。
|
|
388
|
+
INHERIT_ON_OVERWRITE_BODY_SAME = (
|
|
389
|
+
"edges", "confidence", "verification_basis", "non_applicable_conditions",
|
|
390
|
+
"modality", "importance_source", "untrusted", "untrusted_markers",
|
|
391
|
+
)
|
|
392
|
+
|
|
352
393
|
|
|
353
394
|
# 英→中语素召回中的代词黑名单(超泛词,进召回词只添噪声)
|
|
354
395
|
_EN_ZH_PRONOUNS = {"我", "你", "他", "她", "它", "我们", "你们", "他们"}
|
|
@@ -859,6 +900,29 @@ NEG_LINK_CHARS = frozenset("是这那该此种个些的了在为之其")
|
|
|
859
900
|
NEG_SCOPE_WINDOW = 6
|
|
860
901
|
|
|
861
902
|
|
|
903
|
+
# 生效条件:text 为任意对象(None 按空串)时返回**保空白**的匹配面归一串(fold_accents → routing.fold_variants,顺序与 fold_for_match 逐字一致);只归一去空白。
|
|
904
|
+
_SceneNorm = collections.namedtuple("_SceneNorm", "compact keep") # (紧凑归一串, 保空白归一串)
|
|
905
|
+
|
|
906
|
+
|
|
907
|
+
def fold_for_match_keep(text) -> str:
|
|
908
|
+
"""匹配面归一(**保空白**)——`fold_for_match` 与 `_cond_scene_norm` 的公共单点。
|
|
909
|
+
|
|
910
|
+
**本函数不是独立判据**:匹配面归一必须经 `fold_for_match` 或 `_cond_scene_norm`;
|
|
911
|
+
直接调用只允许「需要保空白判词边界」的场合(`_term_in_scene_norm` 与词边界正则)。
|
|
912
|
+
text 为 str 或 None(None 按空串,沿用 main 归一链的既有处理)——不是「任意对象」。
|
|
913
|
+
|
|
914
|
+
issue #753/#755:正条件面补字符归一时若自己拼 `fold_accents(routing.fold_variants(x))`,
|
|
915
|
+
就是仓内**第三份**归一链,且**顺序与原式相反**——BMP 实测有 8 个码点因此分叉
|
|
916
|
+
(希腊下加点区:`ᾀ`(U+1F80) 正序 → `α`、反序 → `αι`;casefold 会把下加点展开成 iota,
|
|
917
|
+
正序已先剥掉 Mn)。这正是 #362 E 组「单点收口、禁止两份实现」要防的漂移。故归一收进本函数:
|
|
918
|
+
· `fold_for_match` = 本函数 + `compact_exact_text`(去空白);
|
|
919
|
+
· `_cond_scene_norm` = 本函数 + 去空白/保空白两态。
|
|
920
|
+
顺序**不得交换**:fold_accents 先(NFKC→NFD→剥拉丁 Mn→NFC),fold_variants 后
|
|
921
|
+
(NFKC→casefold→繁简折叠)。
|
|
922
|
+
"""
|
|
923
|
+
return routing.fold_variants(fold_accents(text))
|
|
924
|
+
|
|
925
|
+
|
|
862
926
|
# 生效条件:text 为任意对象(None 按空串)时返回其匹配面归一串(去全部空白 + NFKC + casefold + 繁简折叠,繁简表当前为空);归一口径复用 routing.fold_variants 单点。
|
|
863
927
|
def fold_for_match(text) -> str:
|
|
864
928
|
"""匹配面归一人(#362b/c)——**复用路由面的同一份口径**,不新造第二份。
|
|
@@ -872,7 +936,7 @@ def fold_for_match(text) -> str:
|
|
|
872
936
|
# 而召回面用的是 fold_accents(会剥)——两侧口径不一致时,
|
|
873
937
|
# 声明 non_applicable_conditions: ["cafe"] 的节点对查询 "cafe" 不会被 REJECT。
|
|
874
938
|
# 判据面与召回面必须同一口径,故这里补一次 Mn/Me 剥离(fold_accents 单点)。
|
|
875
|
-
return compact_exact_text(
|
|
939
|
+
return compact_exact_text(fold_for_match_keep(text))
|
|
876
940
|
|
|
877
941
|
|
|
878
942
|
# 生效条件:text 与 term 均为 str 时,把 text 中所有「与 term 同形(去全部空白 + NFKC + casefold + 繁简折叠后相等)」的区间替换为空格并返回;term 归一后为空或未找到同形区间时原样返回。
|
|
@@ -2682,6 +2746,10 @@ class MdCG:
|
|
|
2682
2746
|
for _nid, _e in batch:
|
|
2683
2747
|
if _nid not in self._dirty:
|
|
2684
2748
|
self._dirty[_nid] = _e
|
|
2749
|
+
# #677 C 复核:`_dirty.clear()` 会连 superseded_ids 一起清(见 _DirtyDict),
|
|
2750
|
+
# 失败回填若不恢复它,下一轮会把「已判陈旧」的记录当新记录写进分片
|
|
2751
|
+
# ⇒ 旧版本覆盖新版本(内容错误,比重复更严重)。
|
|
2752
|
+
self._dirty.superseded_ids |= superseded
|
|
2685
2753
|
raise
|
|
2686
2754
|
|
|
2687
2755
|
# 生效条件:batch 为 [(nid, entry)] 快照、superseded 为「已判陈旧」的 id 集合(两者都取自 _flush_locked 的锁内快照)时,在 FileLock(index_path) 下按需新建 ShardedLog、登记本进程分片(_own_shard)后逐条 append(跳过 superseded 中的 id),最后关闭分片句柄并返回 None;self._log 为假值时跳过关闭;
|
|
@@ -2699,12 +2767,18 @@ class MdCG:
|
|
|
2699
2767
|
# 否则「分片文件已存在但 _own_shard 未登记」的窗口里,本进程自己的
|
|
2700
2768
|
# 追加会被自家探活当成他进程变化(多线程下白重载一次)。
|
|
2701
2769
|
self._own_shard = self._log.path
|
|
2702
|
-
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
|
|
2707
|
-
|
|
2770
|
+
# issue #80 残留面(C 案):被判定陈旧(重放时已放行盘面)的条目
|
|
2771
|
+
# **不得**落分片日志——落了就成『索引侧旧盖新』且跨重启存活。
|
|
2772
|
+
_recs = [{"id": nid, "e": e} for nid, e in batch if nid not in superseded]
|
|
2773
|
+
# #677 C 根治:**一次 write + 一次 flush**(原实现每条 append 都 flush,
|
|
2774
|
+
# 锁内 IO 次数 = 脏集条数;大库下一批上千条就是上千次 flush——这正是
|
|
2775
|
+
# 「写成功但应答超时」的持锁来源)。原子性不变:整批仍在同一把 FileLock 内。
|
|
2776
|
+
_app = getattr(self._log, "append_many", None)
|
|
2777
|
+
if callable(_app):
|
|
2778
|
+
_app(_recs)
|
|
2779
|
+
else: # 兼容旧 ShardedLog(无 append_many)
|
|
2780
|
+
for _r in _recs:
|
|
2781
|
+
self._log.append(_r)
|
|
2708
2782
|
# 写完立即关分片句柄:Windows 上「被本进程打开的文件」无法删除,
|
|
2709
2783
|
# 若持有句柄,rebuild_index 的 ShardedLog.clear 会静默失败,已并进
|
|
2710
2784
|
# 快照的旧记录被永久重放(旧条目反而覆盖新快照)。append 内部已
|
|
@@ -3020,9 +3094,31 @@ class MdCG:
|
|
|
3020
3094
|
# ---------- 写 ----------
|
|
3021
3095
|
|
|
3022
3096
|
# 生效条件:node_id/content 必填;node_id 不匹配 _NODE_ID_RE(^[A-Za-z0-9_.@-]{1,128}$)或含 ".."、或整串精确等值于 _NODE_ID_FORBIDDEN("None"/"null",空语义值字符串化污染形态,P3 None.md 缺陷禁写)、或落盘 realpath 越出 self.root 时抛 ValueError(P0-1 白名单+纵深闸);layer 不在 LAYERS 内、或 verification_basis 非 None 且不在 VERIFICATION_BASIS 内时抛 ValueError;consistency 为真且 _cons.check 判 REJECT 时,on_conflict="reject" 抛 ConsistencyError、on_conflict="defer" 返回 None;判 BLINDSPOT(comparable==0,检测前提不存在)时**恒放行**(与 writepipe._gate_consistency 的 issue #26 同口径,落盘并把 vd 并进 extra["consistency"]);其余情形完成写盘/入索引后返回 node_id;consistency_out 为 dict 时把本次判定回填 consistency_out["consistency"](#361:三条出口都可追溯)。
|
|
3097
|
+
# 生效条件:prev_entry 为索引条目、content 为本次写入正文;返回 True 表示「正文变了,验证态须降级」。
|
|
3098
|
+
# issue #757:优先用**索引条目的 content_hash**(与盘面同源,见 #741/#756),省一次读盘;
|
|
3099
|
+
# 缺 hash 时才回退读盘、并用**同一个** nodefile.content_hash 归一(不引入第二口径)。
|
|
3100
|
+
# 失败面:索引陈旧只会多判「变了」→ 降 doubted(安全方向);反向不可能(陈旧值来自更早正文)。
|
|
3101
|
+
@staticmethod
|
|
3102
|
+
def _vstate_body_changed(cg, node_id: str, prev_entry, content) -> bool:
|
|
3103
|
+
if not prev_entry:
|
|
3104
|
+
return False
|
|
3105
|
+
prev_hash = prev_entry.get("content_hash")
|
|
3106
|
+
if not prev_hash:
|
|
3107
|
+
try:
|
|
3108
|
+
prev_hash = nodefile.content_hash(
|
|
3109
|
+
(cg.get(node_id) or {}).get("content") or "")
|
|
3110
|
+
except Exception: # noqa: BLE001 —— 读面失败按未变处置
|
|
3111
|
+
return False
|
|
3112
|
+
try:
|
|
3113
|
+
new_hash = nodefile.content_hash(content or "")
|
|
3114
|
+
except Exception: # noqa: BLE001 —— 非 str 正文按未变处置(不打断写入)
|
|
3115
|
+
return False
|
|
3116
|
+
return bool(prev_hash) and prev_hash != new_hash
|
|
3117
|
+
|
|
3118
|
+
|
|
3023
3119
|
def add(self, node_id: str, content: str, layer: str = "knowledge",
|
|
3024
|
-
tags=None, condition_space=None, importance
|
|
3025
|
-
confidence: float =
|
|
3120
|
+
tags=None, condition_space=None, importance=None,
|
|
3121
|
+
confidence: float = None, edges=None, verification_basis: str = None,
|
|
3026
3122
|
non_applicable_conditions=None, override: bool = False,
|
|
3027
3123
|
consistency: bool = False, on_conflict: str = "reject",
|
|
3028
3124
|
consistency_out: dict = None,
|
|
@@ -3165,8 +3261,28 @@ class MdCG:
|
|
|
3165
3261
|
# 故 MdCGOS 的既有语义(非法值回落文档缺省)一字不变。
|
|
3166
3262
|
# 判据单点在模块级 `_require_unit_number`(同仓单点判据纪律:判据只写
|
|
3167
3263
|
# 一份,写侧读侧共用;守卫可对其做定点变异自证)。
|
|
3264
|
+
# importance 缺省 None = 「调用方没声明」⇒ 覆写时继承旧值,新节点回落 0.5。
|
|
3265
|
+
# 必须在**写侧数值闸(#151②)之前**解析:那道闸对 None 是 fail-closed,
|
|
3266
|
+
# 解析晚一步就变成「合法调用被判非法落盘」。与同函数里 check_strength 的
|
|
3267
|
+
# 「传入优先;否则取旧值」同一口径——不能拿 0.5 当缺省,否则一次普通覆写
|
|
3268
|
+
# 就把 0.8 的节点打回 0.5(#732 的另一面)。
|
|
3269
|
+
_prev_fm = {}
|
|
3270
|
+
_prev_body = None
|
|
3271
|
+
if (self.index.get("nodes") or {}).get(node_id) is not None:
|
|
3272
|
+
try:
|
|
3273
|
+
_pn = self.get(node_id) or {}
|
|
3274
|
+
_prev_fm = dict(_pn.get("frontmatter") or {})
|
|
3275
|
+
_prev_body = _pn.get("content")
|
|
3276
|
+
except Exception:
|
|
3277
|
+
_prev_fm, _prev_body = {}, None
|
|
3278
|
+
if importance is None:
|
|
3279
|
+
# 旧库可能有「键存在但值为 None」的节点:dict.get(k, default) 此时返回
|
|
3280
|
+
# None(不是 default)⇒ 下游 _require_unit_number fail-closed 抛错。
|
|
3281
|
+
_pi = _prev_fm.get("importance")
|
|
3282
|
+
importance = _pi if _pi is not None else 0.5
|
|
3168
3283
|
_require_unit_number("importance", importance)
|
|
3169
|
-
|
|
3284
|
+
if confidence is not None:
|
|
3285
|
+
_require_unit_number("confidence", confidence)
|
|
3170
3286
|
if verification_basis is not None and verification_basis not in VERIFICATION_BASIS:
|
|
3171
3287
|
raise ValueError(f"未知验证基底:{verification_basis}(允许:{VERIFICATION_BASIS})")
|
|
3172
3288
|
if check_strength is not None and check_strength not in CHECK_STRENGTHS:
|
|
@@ -3336,13 +3452,36 @@ class MdCG:
|
|
|
3336
3452
|
# (`MdCGSecure.add` 的 `sensitivity or DEFAULT_SENSITIVITY` 把两者
|
|
3337
3453
|
# 归一成同一个值,闸便看不见差异)。本键只是判据载体,**不落 fm**。
|
|
3338
3454
|
_declared_sens = extra.pop("declared_sensitivity", None)
|
|
3455
|
+
_created_given = "created_at" in extra
|
|
3339
3456
|
created_at = extra.pop("created_at", time.time())
|
|
3457
|
+
if not _created_given and _prev_fm.get("created_at"):
|
|
3458
|
+
created_at = _prev_fm["created_at"] # 出生时间只写一次
|
|
3340
3459
|
# 条件论「观测时间」栏:写入时必须记录观测时间窗。
|
|
3341
3460
|
# 调用方未提供 time_window 时,以写入时刻为锚、默认窗口 OBSERVATION_WINDOW_SEC。
|
|
3342
3461
|
cs = dict(condition_space or {})
|
|
3343
3462
|
tw = cs.get("time_window")
|
|
3344
3463
|
if not (isinstance(tw, (list, tuple)) and len(tw) == 2):
|
|
3345
3464
|
cs["time_window"] = [created_at, created_at + OBSERVATION_WINDOW_SEC]
|
|
3465
|
+
# BODY_SAME 继承不得覆盖**显式给出**的键(#742 复核):形参缺省无法区分
|
|
3466
|
+
# 「没给」与「给了缺省值」,故以 None 为哨兵;confidence 的 0.6 在继承
|
|
3467
|
+
# 之后才补(显式传入 0.6 也会进 _explicit)。modality 走 extra.pop,
|
|
3468
|
+
# 必须在 pop 之前取「是否显式给了」。
|
|
3469
|
+
_modality_given = "modality" in extra
|
|
3470
|
+
_explicit = set(extra)
|
|
3471
|
+
if _modality_given:
|
|
3472
|
+
_explicit.add("modality")
|
|
3473
|
+
if confidence is None:
|
|
3474
|
+
confidence = 0.6
|
|
3475
|
+
else:
|
|
3476
|
+
_explicit.add("confidence")
|
|
3477
|
+
for _pk, _pv in (('verification_basis', verification_basis),
|
|
3478
|
+
('non_applicable_conditions', non_applicable_conditions),
|
|
3479
|
+
('importance_source', importance_source)):
|
|
3480
|
+
if _pv is not None:
|
|
3481
|
+
_explicit.add(_pk)
|
|
3482
|
+
if edges is not None:
|
|
3483
|
+
_explicit.add("edges") # edges 是形参:显式给了就不能被旧值覆盖
|
|
3484
|
+
|
|
3346
3485
|
fm = {
|
|
3347
3486
|
"id": node_id, "layer": layer,
|
|
3348
3487
|
"modality": extra.pop("modality", "text"),
|
|
@@ -3356,6 +3495,29 @@ class MdCG:
|
|
|
3356
3495
|
"evidence_count": 0, "positive_evidence": 0, "negative_evidence": 0,
|
|
3357
3496
|
}
|
|
3358
3497
|
fm.update(extra)
|
|
3498
|
+
# 覆写继承(issue #732):调用方显式给出的键才覆盖,否则沿用旧值。
|
|
3499
|
+
# 位置在 update(extra) 之后、各闸之前——既有闸(保护/密级/生命周期)
|
|
3500
|
+
# 读的就是这份 fm,故继承值必须在此之前就位。
|
|
3501
|
+
for _k in INHERIT_ON_OVERWRITE:
|
|
3502
|
+
if _k not in extra and _k in _prev_fm:
|
|
3503
|
+
fm[_k] = _prev_fm[_k]
|
|
3504
|
+
# 正文逐字未变(retag / 纯元数据改写)⇒ 自动血缘不必重算。
|
|
3505
|
+
# **只在调用方没给 edges 时继承**:`edges` 是形参不是 extra,若无条件继承
|
|
3506
|
+
# 会把调用方刚算好的新边覆盖回旧值(实测 p17_predict 的「命中 → 因果边
|
|
3507
|
+
# 置信度 +0.05」正是这样被吃掉的)。同理 importance 已改为「传 None 才继承」
|
|
3508
|
+
# 的缺省口径(见上方 S1),不再走本白名单。
|
|
3509
|
+
if _prev_body is not None and _prev_fm:
|
|
3510
|
+
# 判据与 #756 的 content_hash 同源(normalize_body 是它的输入规范化单点):
|
|
3511
|
+
# 单尾换行差异视为「未变」,多尾换行差异视为「变了」。此前用 rstrip("\n")
|
|
3512
|
+
# 是第二份文本等价判据(与 #756 不同源,≥2 尾换行会误判「未变」)。
|
|
3513
|
+
_same_body = (nodefile.normalize_body(_prev_body)
|
|
3514
|
+
== nodefile.normalize_body(content))
|
|
3515
|
+
if _same_body:
|
|
3516
|
+
for _k in INHERIT_ON_OVERWRITE_BODY_SAME:
|
|
3517
|
+
if _k not in _explicit and _k in _prev_fm:
|
|
3518
|
+
fm[_k] = _prev_fm[_k]
|
|
3519
|
+
if edges is None and _prev_fm.get("edges"):
|
|
3520
|
+
fm["edges"] = _prev_fm["edges"]
|
|
3359
3521
|
# 写入面信任标记(使用者裁定 2026-10-21:「未验证、未信任的信息本来就不应该执行」):
|
|
3360
3522
|
# 文本里出现伪装系统消息/指令式短语 ⇒ 落 untrusted 标记 + 命中词,供检索面与
|
|
3361
3523
|
# 上层(注入前)据此把它当**数据**而不是指令;不改正文(数据无损)。
|
|
@@ -3506,24 +3668,20 @@ class MdCG:
|
|
|
3506
3668
|
# 「已验证」。证据针对的是**旧正文**,故只在正文真的变了时才降
|
|
3507
3669
|
# (verified→doubted 是 TRANSITIONS 里的合法迁移,不需 override)。
|
|
3508
3670
|
# 边界:无 principal 的裸库 / ops 未声明(`Principal()` 缺省)⇒
|
|
3509
|
-
# `allows_op`
|
|
3510
|
-
#
|
|
3511
|
-
#
|
|
3671
|
+
# `allows_op` 为真,逐位继承,既有语义零变化。
|
|
3672
|
+
# issue #757:正文比对改用**索引条目的 content_hash**(不再读盘回正文)。
|
|
3673
|
+
# 前提已由 #741/#756 建立:content_hash 内部 normalize_body 是唯一真源,
|
|
3674
|
+
# 直调 add / 重建扫描 / 两级提交写入的条目都同源;两级提交保证「同 id 的
|
|
3675
|
+
# 上一次成功写入」此时已在内存索引里(不依赖是否 flush)。
|
|
3676
|
+
# 失败面是**保守的**:索引若陈旧只会多判「正文变过」→ 降 doubted(安全方向)。
|
|
3512
3677
|
_inherit = prev_vstate
|
|
3513
3678
|
if prev_vstate == "verified" and prev_entry is not None:
|
|
3514
3679
|
_principal = getattr(self, "principal", None)
|
|
3515
3680
|
_may_verify = (not callable(getattr(_principal, "allows_op", None))
|
|
3516
3681
|
or _principal.allows_op("verify"))
|
|
3517
|
-
if not _may_verify
|
|
3518
|
-
|
|
3519
|
-
|
|
3520
|
-
except Exception: # noqa: BLE001 —— 读面失败按未变处置
|
|
3521
|
-
_prev_body = None
|
|
3522
|
-
_new_body = content or ""
|
|
3523
|
-
if not _new_body.endswith("\n"):
|
|
3524
|
-
_new_body += "\n"
|
|
3525
|
-
if _prev_body is not None and _prev_body != _new_body:
|
|
3526
|
-
_inherit = "doubted"
|
|
3682
|
+
if not _may_verify and MdCG._vstate_body_changed(
|
|
3683
|
+
self, node_id, prev_entry, content):
|
|
3684
|
+
_inherit = "doubted"
|
|
3527
3685
|
fm[trust.STATE_FIELD] = _inherit
|
|
3528
3686
|
else:
|
|
3529
3687
|
_pe_v = prev_entry or {}
|
|
@@ -3692,7 +3850,7 @@ class MdCG:
|
|
|
3692
3850
|
rejection_index_terms(fm, sealed),
|
|
3693
3851
|
"access_count": fm.get("access_count", 0),
|
|
3694
3852
|
"last_access": fm.get("last_access", 0),
|
|
3695
|
-
"content_hash":
|
|
3853
|
+
"content_hash": nodefile.content_hash(sealed),
|
|
3696
3854
|
"temporal": fm.get("temporal"),
|
|
3697
3855
|
"spatial": fm.get("spatial"),
|
|
3698
3856
|
"time_window": cs.get("time_window"),
|
|
@@ -4363,6 +4521,83 @@ class MdCG:
|
|
|
4363
4521
|
# 生效条件:dry_run 为真时只统计不改盘;否则遍历 index["nodes"],get(nid) 取不到(无密钥/文件缺失)计入 unreadable,
|
|
4364
4522
|
# fm 已有 big_domain 计入 already,content 为 None 计入 unreadable,routing.classify_text(content) 为 None 计入 no_signal,
|
|
4365
4523
|
# 其余写 fm["big_domain"] → _write_node → 同步索引 entry["big_domain"];limit 为真值时 written 达 limit 即停;写完 flush();返回统计 dict。
|
|
4524
|
+
def retag(self, node_id: str, tags_add=None, tags_remove=None,
|
|
4525
|
+
condition_space_patch=None, depends_on=None,
|
|
4526
|
+
dry_run: bool = True) -> dict: # 库层缺省 True:直接调库也安全
|
|
4527
|
+
"""**只改元数据**(tags / condition_space / depends_on),正文与证据链原样。
|
|
4528
|
+
|
|
4529
|
+
为何需要它:给存量节点补 `domain:` 标签以迁出 `knowledge/orphan/`
|
|
4530
|
+
(`routing.route_key` 只认 tags 的 `domain:` 前缀,其次
|
|
4531
|
+
`condition_space.observation_position`),此前唯一通道是同 id 覆写
|
|
4532
|
+
`add()`——而 `add()` 是全量重建 fm,会重置 created_at / session 并丢
|
|
4533
|
+
evidence_log / edges(见 issue #732 与 INHERIT_ON_OVERWRITE)。
|
|
4534
|
+
|
|
4535
|
+
本函数不改判据、不新造写盘点:它**复用 add() 的既有写链**(换桶清理、
|
|
4536
|
+
索引 _stage、密级与保护闸全部照旧),只是把「正文逐字不变」这件事显式
|
|
4537
|
+
保证下来,从而命中 `INHERIT_ON_OVERWRITE_BODY_SAME` 的继承分支——
|
|
4538
|
+
edges 与 importance 也一并保住。
|
|
4539
|
+
|
|
4540
|
+
dry_run=True 只算不写,返回将要落到的桶与路径,供调用方先确认。
|
|
4541
|
+
**库层缺省 True**(#742 复核:直接调库默认落盘与「预演优先」相反);
|
|
4542
|
+
工具面 maintain(action=retag, apply=True) 才落盘,且 apply=False 时
|
|
4543
|
+
即便显式 dry_run=False 也不写(见 mdcos.maintain 的双开关收敛)。
|
|
4544
|
+
"""
|
|
4545
|
+
node = self.get(node_id)
|
|
4546
|
+
if not node:
|
|
4547
|
+
return {"ok": False, "error": "node_not_found", "node_id": node_id}
|
|
4548
|
+
fm = dict(node.get("frontmatter") or {})
|
|
4549
|
+
content = node.get("content") or ""
|
|
4550
|
+
layer = str(fm.get("layer") or "knowledge")
|
|
4551
|
+
old_rel = node.get("path") or ""
|
|
4552
|
+
tags = [str(t) for t in (fm.get("tags") or []) if str(t).strip()]
|
|
4553
|
+
rem = {str(t).strip() for t in _ensure_list(tags_remove)
|
|
4554
|
+
if str(t).strip()}
|
|
4555
|
+
new_tags = [t for t in tags if t not in rem]
|
|
4556
|
+
for t in _ensure_list(tags_add):
|
|
4557
|
+
t = str(t).strip()
|
|
4558
|
+
if t and t not in new_tags:
|
|
4559
|
+
new_tags.append(t)
|
|
4560
|
+
cs = dict(fm.get("condition_space") or {})
|
|
4561
|
+
if isinstance(condition_space_patch, dict):
|
|
4562
|
+
cs.update(condition_space_patch)
|
|
4563
|
+
deps = trust.as_deps(depends_on) if depends_on is not None else None
|
|
4564
|
+
bucket = None
|
|
4565
|
+
if layer in BUCKETED_LAYERS:
|
|
4566
|
+
bucket = routing.bucket_dir(routing.route_key(cs, new_tags))
|
|
4567
|
+
ahead = os.path.join(self.root, layer, bucket)
|
|
4568
|
+
else:
|
|
4569
|
+
ahead = os.path.dirname(os.path.join(self.root, old_rel))
|
|
4570
|
+
new_rel = os.path.relpath(os.path.join(ahead, "%s.md" % node_id),
|
|
4571
|
+
self.root).replace("\\", "/")
|
|
4572
|
+
plan = {
|
|
4573
|
+
"ok": True, "dry_run": bool(dry_run), "node_id": node_id,
|
|
4574
|
+
"layer": layer, "tags": new_tags, "condition_space": cs,
|
|
4575
|
+
"depends_on": deps, "bucket": bucket,
|
|
4576
|
+
"from_path": old_rel, "to_path": new_rel,
|
|
4577
|
+
"moved": os.path.abspath(os.path.join(self.root, new_rel))
|
|
4578
|
+
!= os.path.abspath(os.path.join(self.root, old_rel)),
|
|
4579
|
+
"tags_changed": new_tags != tags,
|
|
4580
|
+
"cs_changed": cs != dict(fm.get("condition_space") or {}),
|
|
4581
|
+
}
|
|
4582
|
+
if dry_run:
|
|
4583
|
+
return plan
|
|
4584
|
+
# 走**同一条写链**(与 cg(op=write) 的元数据补丁路径同一实现):置
|
|
4585
|
+
# `_meta_patch` 后,正文闸/冲突闸/档位闸按「正文没变」放行,而层闸、
|
|
4586
|
+
# 写保护闸、换桶清理、索引 _stage 仍由既有单点负责。这样 admin 面的
|
|
4587
|
+
# maintain retag 与 token 面的 write 补丁行为一致,不会两条路两种结果。
|
|
4588
|
+
from .writepipe import default_pipeline
|
|
4589
|
+
_a = {"op": "write", "node_id": node_id, "layer": layer,
|
|
4590
|
+
"content": content, "tags": new_tags, "condition_space": cs,
|
|
4591
|
+
"_meta_patch": True}
|
|
4592
|
+
if deps is not None:
|
|
4593
|
+
_a["depends_on"] = deps
|
|
4594
|
+
_out = default_pipeline().execute(self, _a)
|
|
4595
|
+
plan["committed"] = bool((_out or {}).get("committed"))
|
|
4596
|
+
if not plan["committed"]:
|
|
4597
|
+
plan["ok"] = False
|
|
4598
|
+
plan["write_out"] = _out
|
|
4599
|
+
return plan
|
|
4600
|
+
|
|
4366
4601
|
def backfill_big_domain(self, dry_run: bool = False, limit: int = None) -> dict:
|
|
4367
4602
|
"""为缺 `big_domain` 的节点补域标签(S1 大域收敛的前置元数据;幂等)。
|
|
4368
4603
|
|
|
@@ -4660,36 +4895,109 @@ class MdCG:
|
|
|
4660
4895
|
parts = [str(v)]
|
|
4661
4896
|
return ";".join(parts)
|
|
4662
4897
|
|
|
4898
|
+
# 条件空间的槽标签 / 首尾标点**不在这里另立名字**:真源只有 nodefile 一处,
|
|
4899
|
+
# 本类通过 `nodefile.COND_SLOT_LABELS` / `nodefile.COND_EDGE_PUNCT` 直接引用。
|
|
4900
|
+
#
|
|
4901
|
+
# 为什么不保留 `MdCG._SLOT_LABELS` / `MdCG._EDGE_PUNCT` 这两个别名
|
|
4902
|
+
# (2026-11-02 review 后收敛):它们是**零读点**——委托化之后
|
|
4903
|
+
# `_cond_terms` / `_cond_terms_diag` 都直接调 nodefile,生产路径一次也不读;
|
|
4904
|
+
# `_EDGE_PUNCT` 连测试都没有。留着等于多出两个可漂移的入口名,
|
|
4905
|
+
# 与「单点收口」的主张自相矛盾。测试 L2 只验 `is` 同一性,
|
|
4906
|
+
# 那验的是「别名没被抄一份」,删掉别名后该断言自然失去对象,一并移除。
|
|
4907
|
+
#
|
|
4908
|
+
# 真源漂移守卫也不用类体 `assert`:`tuple(l for _k, l in CONDITION_SLOTS)`
|
|
4909
|
+
# 与 `COND_SLOT_LABELS` 两边都由 CONDITION_SLOTS 派生(见 nodefile 的
|
|
4910
|
+
# `COND_SLOT_LABELS = tuple(label for _key, label in CONDITION_SLOTS)`),
|
|
4911
|
+
# 恒真;且 `python -O` 会把它整个剥离,防护力为 0。真正有守卫价值的是
|
|
4912
|
+
# 「不是另抄一份」这件事,它已由 `COND_SLOT_LABELS` 的单一定义天然保证。
|
|
4913
|
+
|
|
4663
4914
|
@staticmethod
|
|
4664
|
-
# 生效条件:cond_text
|
|
4915
|
+
# 生效条件:cond_text 为假值时 terms 为空列表且各计数为 0;否则返回 nodefile.condition_terms_diag 的完整诊断字典(切分单点在 nodefile,本方法只是包内别名)。
|
|
4916
|
+
def _cond_terms_diag(cond_text: str):
|
|
4917
|
+
"""条件文本 → {terms, n_empty, n_digit, n_short,
|
|
4918
|
+
n_time_sentinel, n_decl_sentinel}。
|
|
4919
|
+
|
|
4920
|
+
**切分单点在 `nodefile.condition_terms_diag`**,本方法只是别名 ——
|
|
4921
|
+
早先 `nodefile.cond_terms` 是第二份实现、补丁后两份行为分叉,
|
|
4922
|
+
属潜伏风险(零调用点,未成当下缺陷)。改为单点后不可能再分叉。
|
|
4923
|
+
"""
|
|
4924
|
+
return nodefile.condition_terms_diag(cond_text)
|
|
4925
|
+
|
|
4926
|
+
@staticmethod
|
|
4927
|
+
# 生效条件:cond_text 为假值时按空串返回空列表;否则返回 nodefile.cond_terms 的短语列表(规则同 condition_terms_diag)。
|
|
4665
4928
|
def _cond_terms(cond_text: str):
|
|
4666
|
-
"""生效条件声明 → 匹配短语列表(确定性切分,无语义猜测)。
|
|
4929
|
+
"""生效条件声明 → 匹配短语列表(确定性切分,无语义猜测)。"""
|
|
4930
|
+
return nodefile.cond_terms(cond_text)
|
|
4931
|
+
|
|
4932
|
+
@staticmethod
|
|
4933
|
+
# 生效条件:term 为任意值、scene 为字符串;当 term 是「纯 ASCII 字母词」(api/app/core/UTC 这类)时按词边界匹配(左右不得紧邻其他 ASCII 字母),其余形态保持子串匹配;任一路径命中即返回 True。
|
|
4934
|
+
def _term_in_scene(term, scene: str) -> bool:
|
|
4935
|
+
"""条件短语是否在情境串里成立 —— ASCII 词按词边界,中文按子串。
|
|
4936
|
+
|
|
4937
|
+
为什么纯 ASCII 字母词必须走词边界(PR #735 head 实测):
|
|
4667
4938
|
|
|
4668
|
-
|
|
4669
|
-
|
|
4670
|
-
|
|
4671
|
-
|
|
4939
|
+
"capital".find("api") == 1 ⇒ 子串命中,但问句讲的是「capital 结构」
|
|
4940
|
+
"mapping".find("app") == 1 ⇒ 子串命中,但问句讲的是「mapping 对不对」
|
|
4941
|
+
"score".find("core") == 4 ⇒ 子串命中,但问句讲的是「计算 score 的方式」
|
|
4942
|
+
|
|
4943
|
+
条件文本里 `app`/`api`/`core` 来自 `backend/app/core/...`、
|
|
4944
|
+
`/api/uzi/...` 这类路径切开后的碎片;用子串匹配时,任何含这几个
|
|
4945
|
+
字母的词都会误命中,于是「条件未确认」被误判成「已确认」,节点被
|
|
4946
|
+
错误放行(PR #735 已把切分修好,这一类碎片因此才真正暴露出来)。
|
|
4947
|
+
|
|
4948
|
+
只对**纯 ASCII 字母词**收紧,中文仍走子串:中文没有词边界概念,
|
|
4949
|
+
且短语本身已是切分结果,再收紧会大面积漏命中;非字母 ASCII
|
|
4950
|
+
(`9:00` / `3:1` / `dsh-memory` 的连字符)也不收紧 —— 那不是
|
|
4951
|
+
「短词误咬」的形态。
|
|
4952
|
+
|
|
4953
|
+
归一与 `_term_in_scene_norm` 共用 `fold_for_match_keep`(#753/#755 复核);
|
|
4954
|
+
**循环内请改用 `_term_in_scene_norm` + 预归一场**,否则每个词项都会重算场景归一。
|
|
4672
4955
|
"""
|
|
4673
|
-
|
|
4674
|
-
|
|
4675
|
-
|
|
4676
|
-
|
|
4677
|
-
|
|
4678
|
-
|
|
4679
|
-
|
|
4680
|
-
|
|
4681
|
-
|
|
4682
|
-
|
|
4683
|
-
|
|
4684
|
-
|
|
4685
|
-
|
|
4686
|
-
|
|
4687
|
-
|
|
4688
|
-
return
|
|
4956
|
+
return MdCG._term_in_scene_norm(term, MdCG._cond_scene_norm(scene))
|
|
4957
|
+
|
|
4958
|
+
@staticmethod
|
|
4959
|
+
# 生效条件:scene 为任意值(None 按空串)时返回二元组 (紧凑归一串, 保空白归一串);归一口径=fold_for_match_keep(fold_accents → routing.fold_variants)+ compact_exact_text 去空白,与 fold_for_match 同一份单点。
|
|
4960
|
+
def _cond_scene_norm(scene):
|
|
4961
|
+
"""场景串 → `_SceneNorm(compact, keep)`(紧凑归一串 / 保空白归一串)。**一次归一,多处复用**。
|
|
4962
|
+
|
|
4963
|
+
为什么要拆出来:判据在一个节点的 5~6 个词项上**共用同一个场景串**,不拆就是
|
|
4964
|
+
同一份归一连算 6 遍(O(词项数) 倍;具体微秒数随机器与库规模而变,本条不做数字承诺)。
|
|
4965
|
+
不做 memo —— `routing.set_trad_to_simp()` 运行时可改繁简表,缓存会返回改表前的旧值。
|
|
4966
|
+
|
|
4967
|
+
归一链复用 `fold_for_match_keep`(#753/#755):顺序与 fold_for_match 逐字一致,
|
|
4968
|
+
不另拼第三份实现。
|
|
4969
|
+
"""
|
|
4970
|
+
keep = fold_for_match_keep(scene or "")
|
|
4971
|
+
return _SceneNorm(compact_exact_text(keep), keep)
|
|
4972
|
+
|
|
4973
|
+
@staticmethod
|
|
4974
|
+
# 生效条件:term 为任意值、norm_scene 为 _cond_scene_norm 的返回值时,纯 ASCII 字母词按词边界(判在保空白串上)匹配、其余按紧凑串子串匹配;任一路径命中即 True。
|
|
4975
|
+
def _term_in_scene_norm(term, norm_scene) -> bool:
|
|
4976
|
+
"""条件短语是否在**已归一**的场景里成立(口径见 `_term_in_scene`)。"""
|
|
4977
|
+
t = "" if term is None else str(term)
|
|
4978
|
+
if not t:
|
|
4979
|
+
return False
|
|
4980
|
+
# 与负条件面(neg_condition_hits)**同口径归一**:此前这里两侧都是裸原文,
|
|
4981
|
+
# 于是「条件写 PE、问句打 pe」永不命中,而同一个词在负条件面却能命中 ——
|
|
4982
|
+
# 同一份判据的两个面口径分裂。
|
|
4983
|
+
t_keep = fold_for_match_keep(t)
|
|
4984
|
+
t_fold = compact_exact_text(t_keep)
|
|
4985
|
+
if not t_fold:
|
|
4986
|
+
return False
|
|
4987
|
+
if t_fold.isascii() and t_fold.isalpha():
|
|
4988
|
+
# 词边界必须判在**保空白**的归一串上:紧凑串把
|
|
4989
|
+
# `"fdata financials"` 拼成 `"fdatafinancials"`,再判「左右不得紧邻
|
|
4990
|
+
# ASCII 字母」就会把合法的 `fdata` 误杀。
|
|
4991
|
+
pat = (r"(?<![A-Za-z])"
|
|
4992
|
+
+ r"\s*".join(re.escape(p) for p in t_keep.split())
|
|
4993
|
+
+ r"(?![A-Za-z])")
|
|
4994
|
+
return re.search(pat, norm_scene.keep) is not None
|
|
4995
|
+
return t_fold in norm_scene.compact
|
|
4689
4996
|
|
|
4690
4997
|
@staticmethod
|
|
4691
4998
|
# 生效条件:node_dict 的 content 经 ccg_completeness 判为不完整 → BLINDSPOT;否则由 query 与 context(仅当 context 为 dict 时并入)合成情境串,命中 frontmatter 的任一 non_applicable_conditions 词 → REJECT;否则情境非空(query 去空白后非空,或 context 为真)且「生效条件」文本非空、非"无条件"、其词项全未命中且词项非空 → DEFER;否则无 verification_basis → DEFER;否则 ACCEPT;
|
|
4692
|
-
def judge_qualification(node_dict, query: str, context=None
|
|
4999
|
+
def judge_qualification(node_dict, query: str, context=None,
|
|
5000
|
+
strict_conditions: bool = True):
|
|
4693
5001
|
"""四态判定(白箱第 1/2 篇)。
|
|
4694
5002
|
|
|
4695
5003
|
输入:节点 + 查询 + 当前情境
|
|
@@ -4738,36 +5046,109 @@ class MdCG:
|
|
|
4738
5046
|
# 情境为空(无 query 且无 context)→ 无可判定依据,跳过本段不降级:
|
|
4739
5047
|
# 「无情境」不能被误判成「不适用」。
|
|
4740
5048
|
cond_hit = None
|
|
5049
|
+
relaxed = False # #722:未确认条件被放宽(state 仍 DEFER)
|
|
4741
5050
|
has_scene = bool((query or "").strip()) or bool(context)
|
|
5051
|
+
# 正条件段「跳过比对」的原因(review 5b 可观测性):不记录的话,
|
|
5052
|
+
# 「没写条件」「写了空值声明」「写了全时窗哨兵」三者在日志上完全同形。
|
|
5053
|
+
# 取值:None(没跳过)/ "no_condition"(没写)/ "sentinel_decl"(空值声明)/
|
|
5054
|
+
# "sentinel_time"(时间维全时窗)。
|
|
5055
|
+
exempt = None
|
|
4742
5056
|
if has_scene:
|
|
4743
5057
|
cond_text = MdCG._ccg_line(content, "生效条件")
|
|
4744
5058
|
if not cond_text and fm.get("condition_space"):
|
|
4745
5059
|
cond_text = nodefile.condition_space_text(fm["condition_space"])
|
|
4746
|
-
if cond_text
|
|
4747
|
-
|
|
4748
|
-
|
|
4749
|
-
|
|
4750
|
-
|
|
4751
|
-
|
|
4752
|
-
|
|
4753
|
-
|
|
5060
|
+
if not cond_text or cond_text.strip() == "无条件":
|
|
5061
|
+
exempt = "no_condition"
|
|
5062
|
+
else:
|
|
5063
|
+
diag = MdCG._cond_terms_diag(cond_text)
|
|
5064
|
+
terms_ = diag["terms"]
|
|
5065
|
+
if not terms_:
|
|
5066
|
+
# 「写了条件却切不出可用短语」≠「本来就没写条件」:
|
|
5067
|
+
# 后者跳过比对是对的,前者是条件不可用,不能静默放行。
|
|
5068
|
+
#
|
|
5069
|
+
# 但两类残段是**合法空值声明**,不是「切不出」:
|
|
5070
|
+
# · 时间维哨兵(全时窗/任意时刻)—— 文档口径「不因其未命中而降级」
|
|
5071
|
+
# · 空值语义哨兵(无/不适用)—— 「约束:无」声明的是「无约束」,
|
|
5072
|
+
# 是完整声明,不是坏条件(旧实现靠 len<2 把它静默滤掉,
|
|
5073
|
+
# 恰好得到 ACCEPT;本补丁若只用 len 判定会把它误判成 DEFER)
|
|
5074
|
+
# 判据是**析取式**:残段全部落在合法声明桶 → 豁免;
|
|
5075
|
+
# 只要有一段落在硬不可用桶(纯标点/纯数字/单字碎片)→ 不豁免。
|
|
5076
|
+
unusable = diag["n_empty"] + diag["n_digit"] + diag["n_short"]
|
|
5077
|
+
if not unusable:
|
|
5078
|
+
# 残段全部落在合法声明桶 -> 豁免。再按桶分因:
|
|
5079
|
+
# 时间维哨兵与空值语义哨兵是不同口径的声明,日志里必须分开。
|
|
5080
|
+
if diag["n_time_sentinel"] and not diag["n_decl_sentinel"]:
|
|
5081
|
+
exempt = "sentinel_time"
|
|
5082
|
+
else:
|
|
5083
|
+
exempt = "sentinel_decl"
|
|
5084
|
+
if unusable:
|
|
5085
|
+
bits = []
|
|
5086
|
+
if diag["n_empty"]:
|
|
5087
|
+
bits.append(f"纯标点 {diag['n_empty']}")
|
|
5088
|
+
if diag["n_digit"]:
|
|
5089
|
+
bits.append(f"纯数字 {diag['n_digit']}")
|
|
5090
|
+
if diag["n_short"]:
|
|
5091
|
+
bits.append(f"单字碎片 {diag['n_short']}")
|
|
5092
|
+
return {"state": STATE_DEFER,
|
|
5093
|
+
"reason": ("生效条件切不出可用短语("
|
|
5094
|
+
+ "、".join(bits)
|
|
5095
|
+
+ "):" + cond_text.strip()[:40]
|
|
5096
|
+
+ ";请改写为 2 字以上的实词短语")}
|
|
5097
|
+
else:
|
|
5098
|
+
# 命中判据统一走 _term_in_scene:纯 ASCII 字母词按词边界,
|
|
5099
|
+
# 其余按子串。直接 `t in scene_str` 会让 `api` 咬住
|
|
5100
|
+
# `capital`、`app` 咬住 `mapping`、`core` 咬住 `score`。
|
|
5101
|
+
# 场景归一**只算一次**(同一节点的所有词项共用一个场景串)
|
|
5102
|
+
_norm_scene = MdCG._cond_scene_norm(scene_str)
|
|
5103
|
+
cond_hit = next((t for t in terms_
|
|
5104
|
+
if MdCG._term_in_scene_norm(t, _norm_scene)), None)
|
|
5105
|
+
if cond_hit is None:
|
|
5106
|
+
if strict_conditions:
|
|
5107
|
+
return {"state": STATE_DEFER,
|
|
5108
|
+
"reason": ("生效条件未在情境确认(未命中任何声明条件:"
|
|
5109
|
+
+ "、".join(terms_[:3])
|
|
5110
|
+
+ ");可补充情境或条件词面后重判")}
|
|
5111
|
+
# issue #722(Q2=A):放宽**只到 usable**——state 仍是 DEFER,
|
|
5112
|
+
# 不稀释 ACCEPT=已确认 的语义;切不出可用短语不放宽(坏条件)。
|
|
5113
|
+
relaxed = True
|
|
4754
5114
|
|
|
4755
5115
|
# 4) DEFER:节点无 verification_basis → 信任根基不足
|
|
4756
5116
|
if not fm.get("verification_basis"):
|
|
4757
5117
|
return {"state": STATE_DEFER,
|
|
4758
5118
|
"reason": "未声明验证基底,需补充才能继续判定"}
|
|
4759
5119
|
|
|
5120
|
+
# 5) 放宽出口(#722 Q2=A):state 仍 DEFER,usable=True + code/relaxed 供下游分流。
|
|
5121
|
+
if relaxed:
|
|
5122
|
+
return {"state": STATE_DEFER,
|
|
5123
|
+
"code": "relaxed_condition",
|
|
5124
|
+
"condition_status": "unconfirmed",
|
|
5125
|
+
"relaxed": True,
|
|
5126
|
+
"usable": True,
|
|
5127
|
+
"reason": ("生效条件未在情境确认;strict_conditions=false 放宽:"
|
|
5128
|
+
"可参考使用,但未冒充已确认(原判 DEFER)")}
|
|
4760
5129
|
# 5) ACCEPT:默认——reason 诚实标注正条件是否经情境确认
|
|
4761
5130
|
acc = "5 要素齐全 + 不适用条件未命中 + 验证基底已声明"
|
|
4762
5131
|
if cond_hit:
|
|
4763
5132
|
acc = f"生效条件已确认(命中「{cond_hit}」)+ " + acc
|
|
4764
5133
|
elif not has_scene:
|
|
4765
5134
|
acc = "无情境可比(未做正条件确认)+ " + acc
|
|
5135
|
+
else:
|
|
5136
|
+
# 走到这里说明「有情境、但没命中任何短语」而仍然 ACCEPT。
|
|
5137
|
+
# 以前这条与「根本没写条件」共用同一句 reason,日志上无法区分
|
|
5138
|
+
# (2026-11-02 review 5b:本 PR 最该抓的可观测性缺口)。
|
|
5139
|
+
# 按 `exempt` 记录的**跳过原因**逐一分因——三种语义不能合并成一句。
|
|
5140
|
+
_EXEMPT_TEXT = {
|
|
5141
|
+
"no_condition": "未声明生效条件(跳过正条件比对)",
|
|
5142
|
+
"sentinel_decl": "生效条件为空值声明(已豁免)",
|
|
5143
|
+
"sentinel_time": "生效条件为时间维全时窗(已豁免)",
|
|
5144
|
+
}
|
|
5145
|
+
acc = _EXEMPT_TEXT.get(exempt, "生效条件未做正条件确认") + " + " + acc
|
|
4766
5146
|
return {"state": STATE_ACCEPT, "reason": acc}
|
|
4767
5147
|
|
|
4768
5148
|
# 生效条件:node_dict 为 {frontmatter, content}(缺键按空处理)、query 为字符串、context 为 dict 或 None;无条件先算边界命中(boundary_hit),再算资格判定——边界命中**且** query 为边界问句(is_boundary_query)时,资格判定改以「摘掉命中拒绝域条目后的 query」重跑(并在返回体的 qualification 上标 boundary_suppressed=True),其余情形资格判定原样跑 judge_qualification(node_dict, query, context);返回 {"qualification","boundary","counts","recallable","reason"}——counts 内 reject 与 boundary_hit **分开计数**,recallable 为「可召回可展示」(边界命中恒真;无边界命中时 = 资格态不是 REJECT);#362d 案②:抑制确实发生且未摘词面原判 REJECT 时,把该证据并入顶层 reason(键集与 state 不动)。
|
|
4769
5149
|
@staticmethod
|
|
4770
|
-
def judge_with_boundary(node_dict, query: str, context=None
|
|
5150
|
+
def judge_with_boundary(node_dict, query: str, context=None,
|
|
5151
|
+
strict_conditions: bool = True) -> dict:
|
|
4771
5152
|
"""资格判定 + 拒绝域命中——**分开计数、分开呈现**(§5.2 / P0-4)。
|
|
4772
5153
|
|
|
4773
5154
|
返回形状(P2 的检索面直接消费)::
|
|
@@ -4816,10 +5197,12 @@ class MdCG:
|
|
|
4816
5197
|
qual = dict(MdCG.judge_qualification(
|
|
4817
5198
|
node_dict,
|
|
4818
5199
|
strip_boundary_terms(query, bh["terms"]) if suppressed else query,
|
|
4819
|
-
context
|
|
5200
|
+
context,
|
|
5201
|
+
strict_conditions=strict_conditions))
|
|
4820
5202
|
qual["boundary_suppressed"] = suppressed
|
|
4821
5203
|
# #362d 案②(零破坏子形态):另算一次**未摘词面**的判定作证据,见下方 reason 段。
|
|
4822
|
-
raw = (dict(MdCG.judge_qualification(node_dict, query, context
|
|
5204
|
+
raw = (dict(MdCG.judge_qualification(node_dict, query, context,
|
|
5205
|
+
strict_conditions=strict_conditions))
|
|
4823
5206
|
if suppressed else qual)
|
|
4824
5207
|
# 非边界问句下 raw 即 qual 本身,**不产生第二次判定**(默认口径零位移);
|
|
4825
5208
|
# 该证据只并入顶层 reason——键集与 state 一字不动,§5.2 的不变量保持成立;
|
|
@@ -4842,9 +5225,14 @@ class MdCG:
|
|
|
4842
5225
|
why += (";**摘词面前原判 %s**(查询逐字含本节点的拒绝域条目,该 REJECT "
|
|
4843
5226
|
"被边界问句的摘词面抑制;边界命中使其可召回可展示)"
|
|
4844
5227
|
% STATE_REJECT)
|
|
4845
|
-
|
|
4846
|
-
|
|
4847
|
-
|
|
5228
|
+
_q = {"state": qual.get("state"),
|
|
5229
|
+
"reason": qual.get("reason"),
|
|
5230
|
+
"boundary_suppressed": qual["boundary_suppressed"]}
|
|
5231
|
+
# issue #722:放宽标记必须随 qualification 透出(否则调用方只能看 reason 文案)。
|
|
5232
|
+
for _k in ("usable", "relaxed", "code", "condition_status"):
|
|
5233
|
+
if _k in qual:
|
|
5234
|
+
_q[_k] = qual[_k]
|
|
5235
|
+
return {"qualification": _q,
|
|
4848
5236
|
"boundary": {"hit": bh["hit"], "terms": bh["terms"],
|
|
4849
5237
|
"marker": bh["marker"], "reason": bh["reason"]},
|
|
4850
5238
|
"counts": counts, "recallable": recallable,
|
|
@@ -4858,7 +5246,8 @@ class MdCG:
|
|
|
4858
5246
|
include_neg: bool = True, judge: bool = True, pools=None,
|
|
4859
5247
|
session=None, branch=None, validity=None,
|
|
4860
5248
|
start_time=None, end_time=None, start_operator=None,
|
|
4861
|
-
end_operator=None, time_axis=None, view=None
|
|
5249
|
+
end_operator=None, time_axis=None, view=None,
|
|
5250
|
+
strict_conditions: bool = True):
|
|
4862
5251
|
"""返回 (results, meta)。results = [(node_dict, score, qualification)]。
|
|
4863
5252
|
|
|
4864
5253
|
validity:**只排除「已过期」(expired),不排除「未生效」(not_yet)**。
|
|
@@ -5100,7 +5489,8 @@ class MdCG:
|
|
|
5100
5489
|
if valid >= min_results:
|
|
5101
5490
|
return self._emit(scored, k, tier, stat, route_bucket, record,
|
|
5102
5491
|
len(docs), judge, context, neg_coverage,
|
|
5103
|
-
big_domain, big_scores, pool_cfg
|
|
5492
|
+
big_domain, big_scores, pool_cfg,
|
|
5493
|
+
strict_conditions=strict_conditions)
|
|
5104
5494
|
return None
|
|
5105
5495
|
|
|
5106
5496
|
# T0/T1:路由桶内
|
|
@@ -5295,7 +5685,8 @@ class MdCG:
|
|
|
5295
5685
|
self.record_access([r[0]["id"] for r in _merged[:k]], TIER_SPREAD)
|
|
5296
5686
|
return self._emit(_merged, k, TIER_SPREAD, stat, route_bucket,
|
|
5297
5687
|
record, len(_merged), judge, context,
|
|
5298
|
-
neg_coverage, big_domain, big_scores, pool_cfg
|
|
5688
|
+
neg_coverage, big_domain, big_scores, pool_cfg,
|
|
5689
|
+
strict_conditions=strict_conditions)
|
|
5299
5690
|
else:
|
|
5300
5691
|
gates["s3"] = {"seeds": len(_seeds), "expanded": 0,
|
|
5301
5692
|
"hops": _s3_hops, "reason": "no_edges"}
|
|
@@ -5333,7 +5724,8 @@ class MdCG:
|
|
|
5333
5724
|
scored = self._score(picked, q, qb, pool_cfg)
|
|
5334
5725
|
return self._emit(scored, k, TIER_GLOBAL_SCAN, stat, route_bucket,
|
|
5335
5726
|
record, len(picked), judge,
|
|
5336
|
-
context, neg_coverage, big_domain, big_scores, pool_cfg
|
|
5727
|
+
context, neg_coverage, big_domain, big_scores, pool_cfg,
|
|
5728
|
+
strict_conditions=strict_conditions)
|
|
5337
5729
|
|
|
5338
5730
|
# 生效条件:无条件按 hits 的 path 与 allowed 集合做双向邻接扩散(只读 index["nodes"] 的 edges/target,不读节点文件),
|
|
5339
5731
|
# hops<=0 或无命中/无 allowed 时返回 ({}, seeds);否则返回 ({被扩散节点 path: decay**跳数}, seeds),不含种子自身;
|
|
@@ -5655,7 +6047,7 @@ class MdCG:
|
|
|
5655
6047
|
# 生效条件:scored 按 (-分数, -importance) 排序,真实命中数 n_real = min(max(0,k), scored 中 s>0 的条数),负覆盖提示条数 = len(_neg_tail(neg_coverage, max(0,k-n_real))) = min(NEG_COVERAGE_MAX, max(0,k-n_real))(H10 修订:真实命中优先,提示不再按 min(3,k) 先占位——改前 k=2/3 时主结果配额被算成 0、一条真实命中都不返回),主结果取 scored[:max(0,k-提示数)](#89② 收窄:tier==TIER_GLOBAL_SCAN 且 n_real==0 时取 0 条;单点见 _primary_bound/_zero_filler_only)后逐条判定(judge 为真值时调 judge_qualification(r[0], stat["query"] 或 "", context),否则 qual={"state":None,"reason":"judge_disabled"}),再把提示条目 extend 到 out 末尾;record 为真且主结果非空时调 record_access;pool_plan 以 pooling.plan(stat["cap"] 或模块级 GLOBAL_CAP, pools) 生成,stat["pool_taken"] 为真时并入 taken/cands/lost;返回 (out, 含 tier/scanned/bucket/candidates/pre_cap/cap/cut_order/pools/covered_neg/big_domain 的审计 dict);
|
|
5656
6048
|
def _emit(self, scored, k, tier, stat, bucket, record, candidates,
|
|
5657
6049
|
judge, context, neg_coverage, big_domain=None, big_scores=None,
|
|
5658
|
-
pools=None):
|
|
6050
|
+
pools=None, strict_conditions: bool = True):
|
|
5659
6051
|
# ---- S5 负记忆抑制(契约 §3 S5;flag 控、默认关)----
|
|
5660
6052
|
# 现状:rejected/unresolved 命中只会被「附加」到结果里(sensing),对正候选毫无影响。
|
|
5661
6053
|
# 这里把它变成**抑制信号**:与负记忆「边相邻」或「词面高度重叠」的正候选按
|
|
@@ -5829,7 +6221,8 @@ class MdCG:
|
|
|
5829
6221
|
for r in results:
|
|
5830
6222
|
if judge:
|
|
5831
6223
|
_jw = MdCG.judge_with_boundary(r[0], stat.get("query") or "",
|
|
5832
|
-
context
|
|
6224
|
+
context,
|
|
6225
|
+
strict_conditions=strict_conditions)
|
|
5833
6226
|
qual = dict(_jw["qualification"])
|
|
5834
6227
|
_b = boundary_mark(r[0], stat.get("query") or "", context)
|
|
5835
6228
|
if _b.get("hit"):
|
|
@@ -6109,22 +6502,110 @@ class MdCG:
|
|
|
6109
6502
|
"path": rel, "reason": reason}
|
|
6110
6503
|
|
|
6111
6504
|
# 生效条件:verdict 不在 {confirmed,weakened,falsified} 时抛 ValueError;node_id 取不到节点返回 None;verdict=="falsified" 时先经 protect.guard_forget(受保护节点需显式 override=True——旧版本自动快照+留痕;拒绝抛 ProtectionError 且无任何副作用),通过后以 content[:200] 为假设写入 rejected 层、删除原文件并 _unstage,返回 {"action":"falsified","new_id":None,"evidence_count":None,"demoted":None};confirmed/weakened 时 confidence 分别 +0.05 / -0.15(夹到 [0,0.99] 并 round 2)、evidence_count 与 positive_evidence/negative_evidence 各 +1、追加 evidence_log,且仅当 weakened 后 confidence < DEMOTE_CONFIDENCE 且 layer=="knowledge" 时调 _move_layer 到 contextual 并 set_state("demoted"),否则 _write_node 回写并同步索引 evidence_count;
|
|
6505
|
+
def _verify_superseded(self, node_id: str, node: dict, evidence: str,
|
|
6506
|
+
superseded_by: str = None,
|
|
6507
|
+
override: bool = False) -> dict:
|
|
6508
|
+
"""把节点标记为「已被新版本取代」(`lifecycle.superseded`)。
|
|
6509
|
+
|
|
6510
|
+
与 `falsified` 的关键区别:**不删除、不进 trash、不动 verification_state**。
|
|
6511
|
+
「它现在成不成立」与「它是否还是当前版本」是正交的两件事——前者归
|
|
6512
|
+
`trust.verification_state`,后者归 `lifecycle.lifecycle_state`。`superseded`
|
|
6513
|
+
早在 2026-10-18 就进了 lifecycle 状态机(`active/converged/demoted →
|
|
6514
|
+
superseded`,且 `superseded → active` 可回滚),并经 `is_retired()`
|
|
6515
|
+
退出默认检索面。缺的只是**工具面入口**,本函数补的就是这一环——不新增
|
|
6516
|
+
状态、不改判据、不复制第二份迁移表。
|
|
6517
|
+
|
|
6518
|
+
为何 superseded_by 必填而非用 override:护栏的目的不是「多按一次确认」,
|
|
6519
|
+
而是「取代关系要能指名替代者」。裸 override 允许随手退役;指名替代者
|
|
6520
|
+
则同时产出血缘与可追溯依据。
|
|
6521
|
+
"""
|
|
6522
|
+
by = str(superseded_by or "").strip()
|
|
6523
|
+
if not by:
|
|
6524
|
+
raise ValueError(
|
|
6525
|
+
"superseded 必须给 superseded_by=<取代它的节点 id>:"
|
|
6526
|
+
"取代关系要能指名替代者,空值等于「随手退役」")
|
|
6527
|
+
if by == node_id:
|
|
6528
|
+
raise ValueError("superseded_by 不能是节点自身")
|
|
6529
|
+
if not self.get(by):
|
|
6530
|
+
raise ValueError(
|
|
6531
|
+
"superseded_by 指向的节点不存在:%r(取代关系必须可追溯)" % by)
|
|
6532
|
+
fm = dict(node.get("frontmatter") or {})
|
|
6533
|
+
_orig_fm = dict(fm) # 回滚点(set_state 失败时还原)
|
|
6534
|
+
fm["superseded_by"] = by
|
|
6535
|
+
fm["superseded_at"] = time.time()
|
|
6536
|
+
# 先把「被谁取代」写进 fm,再走 lifecycle 的唯一推进入口(它会重读盘面
|
|
6537
|
+
# 再写一次,故顺序不能倒——先 set_state 后写 fm 会被覆盖回去)。
|
|
6538
|
+
self._write_node(node_id, os.path.join(self.root, node["path"]), fm,
|
|
6539
|
+
node.get("content") or "")
|
|
6540
|
+
# 保护位同样会拦「降级出去」(active→superseded 在 lifecycle._RANK 上加 3 档,
|
|
6541
|
+
# 被 is_downgrade 判为降级)。这里**自动带 override**,理由与 superseded_by
|
|
6542
|
+
# 必填是同一件事:护栏要防的是「随手丢弃」,不是「有序退役」——本操作不删
|
|
6543
|
+
# 数据、不改验证态、且 superseded→active 可回滚,同时必须指名替代者。
|
|
6544
|
+
# 强制情况回填进返回体(forced_protected),审计面看得见这一次是按保护位破的。
|
|
6545
|
+
# **两类更硬的保护不吃自动 override**(#742 复核):
|
|
6546
|
+
# · `immutable`:语义比 protected 更硬,退役必须显式声明;
|
|
6547
|
+
# · self/anchor 层:is_retired() 会让它退出默认检索面,等价于「软删出
|
|
6548
|
+
# 模型视野」——正是保护闸要防的效果,故必须显式 override。
|
|
6549
|
+
_immutable = bool(fm.get("immutable"))
|
|
6550
|
+
_layer = str(fm.get("layer") or node.get("layer") or "")
|
|
6551
|
+
if _immutable and not override:
|
|
6552
|
+
return {"action": "superseded", "ok": False, "error": "immutable",
|
|
6553
|
+
"superseded_by": by,
|
|
6554
|
+
"hint": "节点标记 immutable:退役必须显式 override=True"}
|
|
6555
|
+
if _layer in ("self", "anchor") and not override:
|
|
6556
|
+
return {"action": "superseded", "ok": False, "error": "protected_layer",
|
|
6557
|
+
"superseded_by": by,
|
|
6558
|
+
"hint": "self/anchor 层退役必须显式 override=True"
|
|
6559
|
+
"(自动 override 只覆盖 protected / importance 档)"}
|
|
6560
|
+
_prot = bool(fm.get("protected") or _immutable)
|
|
6561
|
+
_audit = (" [override:immutable]" if _immutable else
|
|
6562
|
+
(" [override:protected]" if _prot else ""))
|
|
6563
|
+
lc = lifecycle.set_state(
|
|
6564
|
+
self, node_id, "superseded",
|
|
6565
|
+
reason=f"被 {by} 取代:{str(evidence)[:80]}{_audit}",
|
|
6566
|
+
actor=getattr(self, "actor", None) or "verify:superseded",
|
|
6567
|
+
override=_prot)
|
|
6568
|
+
if not (lc or {}).get("ok"):
|
|
6569
|
+
# 原子性(#742 复核):set_state 失败 ⇒ 回滚已写进 fm 的两个键,
|
|
6570
|
+
# 不让盘面留下「有 superseded_by 但 lifecycle 仍是 active」的不自洽态。
|
|
6571
|
+
try:
|
|
6572
|
+
self._write_node(node_id, os.path.join(self.root, node["path"]),
|
|
6573
|
+
_orig_fm, node.get("content") or "")
|
|
6574
|
+
except Exception: # noqa: BLE001 —— 回滚失败不掩盖原始失败
|
|
6575
|
+
pass
|
|
6576
|
+
return {"action": "superseded", "ok": False,
|
|
6577
|
+
"superseded_by": by, "lifecycle": lc}
|
|
6578
|
+
try:
|
|
6579
|
+
propagation = trust.mark_dependents(
|
|
6580
|
+
self, node_id,
|
|
6581
|
+
reason=f"上游 {node_id} 已被 {by} 取代——引用方需复核是否仍以旧版为准",
|
|
6582
|
+
actor="verify:superseded", trigger="verify_superseded")
|
|
6583
|
+
except Exception: # noqa: BLE001 —— 传播失败不推翻已完成的退役
|
|
6584
|
+
propagation = {"ok": False, "changed": 0,
|
|
6585
|
+
"reason": "propagation_failed"}
|
|
6586
|
+
return {"action": "superseded", "ok": True, "superseded_by": by,
|
|
6587
|
+
"forced_protected": _prot, "lifecycle": lc,
|
|
6588
|
+
"propagation": propagation, "demoted": None}
|
|
6589
|
+
|
|
6112
6590
|
def verify(self, node_id: str, evidence: str, verdict: str,
|
|
6113
|
-
override: bool = False):
|
|
6591
|
+
override: bool = False, superseded_by: str = None):
|
|
6114
6592
|
"""验证单元(白箱第 3 篇第 13 章):对节点做一次外部验证裁决。
|
|
6115
6593
|
|
|
6116
|
-
verdict ∈ {"confirmed", "weakened", "falsified"}
|
|
6594
|
+
verdict ∈ {"confirmed", "weakened", "falsified", "superseded"}
|
|
6117
6595
|
- confirmed:positive_evidence+1,confidence 上调 +0.05
|
|
6118
6596
|
- weakened:negative_evidence+1,confidence 下调 -0.15(反例权重更大)
|
|
6119
6597
|
- falsified:节点移入 rejected/(幂等:相同 hypothesis 不重复);
|
|
6120
6598
|
受保护节点(self/anchor 层、protected 标记、importance≥0.7)
|
|
6121
6599
|
不可一键证伪删除——需显式 override=True(先快照+留痕)
|
|
6600
|
+
- superseded:**被新版本取代**(需 superseded_by=<替代者 id>)。与
|
|
6601
|
+
falsified 的区别是「不删除、不进 trash、不动 verification_state」:
|
|
6602
|
+
「还成不成立」归 trust,「是否还是当前版本」归 lifecycle,两者正交。
|
|
6122
6603
|
|
|
6123
6604
|
每次裁决累加 evidence_count(白箱第 5 篇第 4 章)。
|
|
6124
6605
|
weakened 后 confidence 跌破 DEMOTE_CONFIDENCE 且原属 knowledge 层 →
|
|
6125
6606
|
降级为 contextual(假设层),返回 demoted 审计记录。
|
|
6126
6607
|
"""
|
|
6127
|
-
if verdict not in ("confirmed", "weakened", "falsified"):
|
|
6608
|
+
if verdict not in ("confirmed", "weakened", "falsified", "superseded"):
|
|
6128
6609
|
raise ValueError(f"未知裁决:{verdict}")
|
|
6129
6610
|
node = self.get(node_id)
|
|
6130
6611
|
if not node:
|
|
@@ -6184,6 +6665,9 @@ class MdCG:
|
|
|
6184
6665
|
return {"action": "falsified", "new_id": None,
|
|
6185
6666
|
"evidence_count": None, "demoted": None,
|
|
6186
6667
|
"propagation": propagation}
|
|
6668
|
+
if verdict == "superseded":
|
|
6669
|
+
return self._verify_superseded(node_id, node, evidence,
|
|
6670
|
+
superseded_by, override=override)
|
|
6187
6671
|
# confirmed/weakened:调整 confidence(白箱第 5 篇:
|
|
6188
6672
|
# 反例的权重应该比正例大——这里用非对称步长实现)
|
|
6189
6673
|
fm = node["frontmatter"]
|
|
@@ -6228,7 +6712,7 @@ class MdCG:
|
|
|
6228
6712
|
# 搬过去的内容与回执同源(顺序依据见交付汇报)。
|
|
6229
6713
|
_land_fm()
|
|
6230
6714
|
demoted = self._move_layer(
|
|
6231
|
-
node_id, "contextual",
|
|
6715
|
+
node_id, "contextual", override=override,
|
|
6232
6716
|
reason=f"confidence {fm['confidence']} < {DEMOTE_CONFIDENCE}")
|
|
6233
6717
|
# 层降级 = 生命周期降级(②):knowledge→contextual 即 state→demoted。
|
|
6234
6718
|
# 受保护节点已被 `guard_move` 拦在上一层(走不到这里);此处仍按负路由
|
|
@@ -6243,17 +6727,30 @@ class MdCG:
|
|
|
6243
6727
|
# weakened → doubted(证据被削弱 ⇒ 存疑,待复核)
|
|
6244
6728
|
# 受保护节点不接受降级——负路由 ok=False 只说明「不可降」,不回滚已完成的
|
|
6245
6729
|
# 证据计数(与上方 lifecycle 降级同风格:不假装成功,也不推翻既成事实)。
|
|
6730
|
+
#
|
|
6731
|
+
# issue #733:`override` 必须透传到验证态推进。此前它只透传给了
|
|
6732
|
+
# falsified 分支的 `protect.guard_forget`,两条正常裁决分支整段没带。
|
|
6733
|
+
# 而它们落到的 `trust.set_state` → `stamp` 对**受保护节点**的降级迁移
|
|
6734
|
+
# 会直接拒绝(`ok=False, error="protected"`),提示语正是
|
|
6735
|
+
# 「确需降级请显式 override=True」——调用方照做却仍被拒 ⇒ 受保护节点的
|
|
6736
|
+
# weakened 裁决**永远无法生效**:回执 ok=False、verification_state 停在
|
|
6737
|
+
# 原值,而 confidence / evidence_count / evidence_log 已按 weakened 扣减
|
|
6738
|
+
# 并落盘,形成「证据记了、结论没落地」的盘面不自洽态。
|
|
6739
|
+
# 该面与 falsified 分支同属「verify 覆盖受保护节点」的唯一合法通路,
|
|
6740
|
+
# 故 override 在两条分支同源透传(缺省 False,既有调用方行为逐位不变)。
|
|
6246
6741
|
if verdict == "confirmed":
|
|
6247
6742
|
ver = self.set_verification(
|
|
6248
6743
|
node_id, "verified",
|
|
6249
6744
|
reason=f"外部裁决 confirmed:{str(evidence)[:80]}",
|
|
6250
6745
|
actor="verify:confirmed", evidence=evidence,
|
|
6251
|
-
method=fm.get("verification_basis"), trigger="verify"
|
|
6746
|
+
method=fm.get("verification_basis"), trigger="verify",
|
|
6747
|
+
override=override)
|
|
6252
6748
|
else:
|
|
6253
6749
|
ver = self.set_verification(
|
|
6254
6750
|
node_id, "doubted",
|
|
6255
6751
|
reason=f"外部裁决 weakened:{str(evidence)[:80]}",
|
|
6256
|
-
actor="verify:weakened", evidence=evidence, trigger="verify"
|
|
6752
|
+
actor="verify:weakened", evidence=evidence, trigger="verify",
|
|
6753
|
+
override=override)
|
|
6257
6754
|
# 结论已变 ⇒ 下游的「地基动了」:同步一跳传播(永不抛,降级不阻断)
|
|
6258
6755
|
propagation = trust.mark_dependents(
|
|
6259
6756
|
self, node_id, reason=f"上游验证结论变为 {verdict}",
|