@furongjun1999/dsh-memory 0.9.22 → 0.10.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/CHANGELOG.en.md +450 -0
- package/CHANGELOG.md +112 -0
- package/README.en.md +244 -0
- package/README.md +272 -260
- package/codebuddy/CODEBUDDY.md +1 -1
- package/docs/README.md +2 -0
- package/docs/discipline/templates/full.md.tmpl +1 -1
- package/docs/discipline/templates/rules.mdc.tmpl +1 -1
- 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 +16 -15
- package/lib/client.js +29 -3
- package/lib/hooks.d.ts +34 -0
- package/lib/hooks.js +167 -33
- 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/bucketindex.py +231 -0
- package/md_cg/bucketscope.py +339 -0
- package/md_cg/config_registry_bulk.py +19 -10
- package/md_cg/config_validate.py +14 -2
- package/md_cg/detrerank.py +137 -0
- package/md_cg/fsutil.py +215 -25
- package/md_cg/govern/__init__.py +23 -0
- package/md_cg/iface/__init__.py +46 -0
- package/md_cg/iface/_verify.py +609 -0
- package/md_cg/iface/contracts.py +337 -0
- package/md_cg/judgment_manifest.py +14 -0
- package/md_cg/kernel/__init__.py +27 -0
- package/md_cg/mcp_server.py +457 -23
- package/md_cg/mdcg.py +1034 -79
- package/md_cg/mdcos.py +263 -21
- package/md_cg/metacognition.py +66 -13
- package/md_cg/mutate_extract_shipped.py +126 -0
- package/md_cg/mutate_ledger_e2e.py +100 -0
- package/md_cg/nodefile.py +147 -23
- package/md_cg/op_table.py +22 -4
- package/md_cg/probe_c_ledger_integrity.py +258 -0
- package/md_cg/probe_d_retirement_discipline.py +263 -0
- package/md_cg/reconcile.py +9 -11
- package/md_cg/review_cli.py +6 -1
- package/md_cg/rollback.py +16 -1
- package/md_cg/run_tests.py +30 -1
- package/md_cg/scopeselect.py +214 -0
- package/md_cg/scrub.py +160 -23
- package/md_cg/security.py +4 -2
- package/md_cg/state_extract.py +149 -0
- package/md_cg/state_slots.py +58 -10
- package/md_cg/structboost.py +179 -0
- package/md_cg/test_alternatives_historical.py +162 -0
- package/md_cg/test_b2_sensitivity_landing.py +226 -223
- package/md_cg/test_b3_merge_keeps_content.py +608 -583
- package/md_cg/test_bucket_cards.py +85 -0
- package/md_cg/test_bucket_day_order.py +74 -0
- package/md_cg/test_bucket_quota.py +79 -0
- package/md_cg/test_bucket_recency_guards.py +75 -0
- package/md_cg/test_bucket_three_causes.py +83 -0
- package/md_cg/test_bucketindex.py +130 -0
- package/md_cg/test_bucketscope_early.py +71 -0
- package/md_cg/test_cond_term_fold.py +183 -0
- package/md_cg/test_cond_term_fold_gate.py +1210 -0
- package/md_cg/test_cond_term_neg_scope.py +147 -0
- package/md_cg/test_cond_terms_colon.py +348 -0
- package/md_cg/test_detrerank.py +157 -0
- package/md_cg/test_gate_four_kpi.py +136 -0
- package/md_cg/test_generation_guard.py +76 -43
- package/md_cg/test_issue192_move_layer_indices_guard.py +48 -0
- package/md_cg/test_issue362_neg_condition.py +44 -7
- package/md_cg/test_issue39_utf8_stdio.py +572 -572
- package/md_cg/test_issue413_preimage_failclosed.py +147 -9
- 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_issue768_overwrite_time_window_anchor.py +135 -0
- package/md_cg/test_issue789_log_plaintext_probe.py +100 -0
- package/md_cg/test_issue790_verb_negation.py +77 -0
- package/md_cg/test_issue810_root_guard.py +71 -0
- package/md_cg/test_issue812_info_index_stale.py +78 -0
- package/md_cg/test_issue827_weaken_dedup.py +361 -0
- package/md_cg/test_issue829_calibration_positive_gate.py +473 -0
- package/md_cg/test_kernel_iface_contracts.py +18 -0
- package/md_cg/test_md_cg_no_hive_dep.py +238 -17
- 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_probe_cd_shipped.py +385 -0
- package/md_cg/test_recent_tail.py +93 -0
- package/md_cg/test_run_tests_entry_gates.py +110 -0
- package/md_cg/test_scopeselect.py +70 -0
- package/md_cg/test_scopeselect_clock.py +70 -0
- package/md_cg/test_scrub_source_line_false_positive.py +64 -0
- package/md_cg/test_session_attribution_consistency.py +835 -813
- package/md_cg/test_state_extract_shipped.py +162 -0
- package/md_cg/test_state_ledger_chain.py +207 -0
- package/md_cg/test_state_ledger_e2e.py +145 -0
- package/md_cg/test_structboost.py +102 -0
- package/md_cg/test_timeboost.py +83 -0
- package/md_cg/test_timeboost_relativedate.py +71 -0
- package/md_cg/test_topicagg.py +129 -0
- package/md_cg/test_twophase.py +286 -286
- package/md_cg/timeboost.py +223 -0
- package/md_cg/tokens.py +55 -7
- package/md_cg/topicagg.py +142 -0
- package/md_cg/twophase.py +15 -6
- package/md_cg/whitebox_kb/wisdom/code_compose.py +33 -5
- package/md_cg/whitebox_kb/wisdom/compose_engine.py +5 -1
- package/md_cg/whitebox_kb/wisdom/role_compose.py +271 -268
- package/md_cg/writepipe.py +35 -3
- package/package.json +4 -1
- package/scripts/workspace_index.py +2 -0
- package/src/hooks.ts +182 -34
- 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/build-ui.mjs +41 -2
- package/ui/minimal/payload/lib/client.js +29 -3
- package/ui/minimal/payload/lib/lib/console_web.mjs +30 -3
- package/ui/minimal/payload/src/lib/console_web.mjs +30 -3
- package/ui/minimal/payload/web/app.js +3 -1
- package/ui/minimal/payload/web/client.js +30 -3
- package/web/app.js +3 -1
- package/web/client.js +30 -3
- package/zcode/AGENTS.md +1 -1
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 = {"我", "你", "他", "她", "它", "我们", "你们", "他们"}
|
|
@@ -854,11 +895,44 @@ NEG_CUES = ("不属于", "不是", "没有", "并非", "并无", "未有",
|
|
|
854
895
|
#: 那是过度收紧方向(由守卫 `--mutate` 的 M3 定点变异钉住)。
|
|
855
896
|
NEG_LINK_CHARS = frozenset("是这那该此种个些的了在为之其")
|
|
856
897
|
|
|
898
|
+
#: 否定词与被否定成分之间的**动词性虚化字**(`未使用X` / `不是采用X` / `没有用X`)。
|
|
899
|
+
#: 与 `NEG_LINK_CHARS`(连接字:的/这/种/是…)**分表存放**,因为二者词性不同:
|
|
900
|
+
#: 连接字不承载语义,动词承载——合并会掩盖「否定词作用于动作、动作的宾语才是词项」
|
|
901
|
+
#: 这一层结构。判据仍是一条:`_negated_at` 里两表**并集**逐字符检查。
|
|
902
|
+
#: 只收高频、几乎不单独作实义词的虚化用法;`做`/`看`/`走` 这类实义动词不收。
|
|
903
|
+
NEG_VERB_CHARS = frozenset("使用采")
|
|
904
|
+
|
|
905
|
+
#: `_negated_at` 的字符准入集=连接字 ∪ 虚化动词字(单点,勿在别处另拼)。
|
|
906
|
+
NEG_SCOPE_CHARS = NEG_LINK_CHARS | NEG_VERB_CHARS
|
|
907
|
+
|
|
857
908
|
#: 否定作用域窗口(向前最多回看的字符数):6 够「不是」+「这样的」(2+3),
|
|
858
909
|
#: 又不足以跨过 `不适合X` 里的实义词。窗口两端都有 K 组对照——缩到 1 即红(M2)。
|
|
859
910
|
NEG_SCOPE_WINDOW = 6
|
|
860
911
|
|
|
861
912
|
|
|
913
|
+
# 生效条件:text 为任意对象(None 按空串)时返回**保空白**的匹配面归一串(fold_accents → routing.fold_variants,顺序与 fold_for_match 逐字一致);只归一去空白。
|
|
914
|
+
_SceneNorm = collections.namedtuple("_SceneNorm", "compact keep raw") # (紧凑归一串, 保空白归一串, 原文串)
|
|
915
|
+
|
|
916
|
+
|
|
917
|
+
def fold_for_match_keep(text) -> str:
|
|
918
|
+
"""匹配面归一(**保空白**)——`fold_for_match` 与 `_cond_scene_norm` 的公共单点。
|
|
919
|
+
|
|
920
|
+
**本函数不是独立判据**:匹配面归一必须经 `fold_for_match` 或 `_cond_scene_norm`;
|
|
921
|
+
直接调用只允许「需要保空白判词边界」的场合(`_term_in_scene_norm` 与词边界正则)。
|
|
922
|
+
text 为 str 或 None(None 按空串,沿用 main 归一链的既有处理)——不是「任意对象」。
|
|
923
|
+
|
|
924
|
+
issue #753/#755:正条件面补字符归一时若自己拼 `fold_accents(routing.fold_variants(x))`,
|
|
925
|
+
就是仓内**第三份**归一链,且**顺序与原式相反**——BMP 实测有 8 个码点因此分叉
|
|
926
|
+
(希腊下加点区:`ᾀ`(U+1F80) 正序 → `α`、反序 → `αι`;casefold 会把下加点展开成 iota,
|
|
927
|
+
正序已先剥掉 Mn)。这正是 #362 E 组「单点收口、禁止两份实现」要防的漂移。故归一收进本函数:
|
|
928
|
+
· `fold_for_match` = 本函数 + `compact_exact_text`(去空白);
|
|
929
|
+
· `_cond_scene_norm` = 本函数 + 去空白/保空白两态。
|
|
930
|
+
顺序**不得交换**:fold_accents 先(NFKC→NFD→剥拉丁 Mn→NFC),fold_variants 后
|
|
931
|
+
(NFKC→casefold→繁简折叠)。
|
|
932
|
+
"""
|
|
933
|
+
return routing.fold_variants(fold_accents(text))
|
|
934
|
+
|
|
935
|
+
|
|
862
936
|
# 生效条件:text 为任意对象(None 按空串)时返回其匹配面归一串(去全部空白 + NFKC + casefold + 繁简折叠,繁简表当前为空);归一口径复用 routing.fold_variants 单点。
|
|
863
937
|
def fold_for_match(text) -> str:
|
|
864
938
|
"""匹配面归一人(#362b/c)——**复用路由面的同一份口径**,不新造第二份。
|
|
@@ -872,7 +946,7 @@ def fold_for_match(text) -> str:
|
|
|
872
946
|
# 而召回面用的是 fold_accents(会剥)——两侧口径不一致时,
|
|
873
947
|
# 声明 non_applicable_conditions: ["cafe"] 的节点对查询 "cafe" 不会被 REJECT。
|
|
874
948
|
# 判据面与召回面必须同一口径,故这里补一次 Mn/Me 剥离(fold_accents 单点)。
|
|
875
|
-
return compact_exact_text(
|
|
949
|
+
return compact_exact_text(fold_for_match_keep(text))
|
|
876
950
|
|
|
877
951
|
|
|
878
952
|
# 生效条件:text 与 term 均为 str 时,把 text 中所有「与 term 同形(去全部空白 + NFKC + casefold + 繁简折叠后相等)」的区间替换为空格并返回;term 归一后为空或未找到同形区间时原样返回。
|
|
@@ -917,11 +991,75 @@ def _negated_at(s: str, i: int) -> bool:
|
|
|
917
991
|
continue
|
|
918
992
|
for cue in NEG_CUES:
|
|
919
993
|
if j + len(cue) <= i and s.startswith(cue, j):
|
|
920
|
-
if all(ch in
|
|
994
|
+
if all(ch in NEG_SCOPE_CHARS for ch in s[j + len(cue):i]):
|
|
921
995
|
return True
|
|
922
996
|
return False
|
|
923
997
|
|
|
924
998
|
|
|
999
|
+
#: #790 方案 C:原文路径只认这四个否定词。`别`/`莫`/`非`/`无` 等单字 cue 在
|
|
1000
|
+
#: 「分别采用」「特别使用」「莫非使用」里会误伤(2026-11-06 实测),故不纳入。
|
|
1001
|
+
_NEG_VERB_CUES = ("没有", "未", "不", "没")
|
|
1002
|
+
|
|
1003
|
+
#: 双重否定判据:cue 前一字符也属否定字 ⇒ 不判否定(`不得不`/`不能不`/`不是不`)。
|
|
1004
|
+
_NEG_DOUBLE_CHARS = frozenset("不没未无非莫别")
|
|
1005
|
+
|
|
1006
|
+
#: 双重否定之间允许出现的情态字(`不`+`得`+`不`)。
|
|
1007
|
+
_NEG_MODAL_CHARS = frozenset("得能会可要想须该")
|
|
1008
|
+
|
|
1009
|
+
|
|
1010
|
+
def _double_negated_before(s: str, j: int) -> bool:
|
|
1011
|
+
"""#790:`s[j]` 处的否定词是否处于双重否定里(`不得不`/`不能不`/`未必不`)。
|
|
1012
|
+
|
|
1013
|
+
只看 cue 之前**一个字**挡不住 `不得不采用`——第二次「不」前面是「得」。故向前最多跨 2 个
|
|
1014
|
+
情态字,若遇到否定字则判为双重否定(语义=必须),不当作否定。
|
|
1015
|
+
"""
|
|
1016
|
+
k = j - 1
|
|
1017
|
+
for _ in range(3):
|
|
1018
|
+
if k < 0:
|
|
1019
|
+
return False
|
|
1020
|
+
ch = s[k]
|
|
1021
|
+
if ch in _NEG_DOUBLE_CHARS:
|
|
1022
|
+
return True
|
|
1023
|
+
if ch not in _NEG_MODAL_CHARS:
|
|
1024
|
+
return False
|
|
1025
|
+
k -= 1
|
|
1026
|
+
return False
|
|
1027
|
+
|
|
1028
|
+
# 生效条件:s 为归一串、i 为 0 <= i < len(s) 的匹配起址时返回 True 当且仅当「否定词与匹配之间含至少一个虚化动词字」
|
|
1029
|
+
# (未使用X / 未采用X / 没有使用X / 不采用X)且 gap 全由连接字或空白构成;其余情形一律 False。
|
|
1030
|
+
def _verb_negated_at(s: str, i: int) -> bool:
|
|
1031
|
+
"""#790(方案 C):只拦「否定词 + (连接字|空白) + **虚化动词** + 宾语」这一支。
|
|
1032
|
+
|
|
1033
|
+
为什么不在原文路径直接用 `_negated_at`:#790 的诉求是「未使用 PE」不该判条件已确认,
|
|
1034
|
+
但把原文路径交给 `_negated_at` 会把 base 本来就命中的「不是 PE」「不是 api」一并变
|
|
1035
|
+
DEFER——族枚举 recall_loss 2340(见 `_fold_hit_unnagated` docstring 的登记)。
|
|
1036
|
+
本判据额外要求 gap 里**含虚化动词字**(`NEG_VERB_CHARS`),故:
|
|
1037
|
+
|
|
1038
|
+
· `未使用 PE` gap=「使用 」→ 含动词字 ⇒ 否定(DEFER)
|
|
1039
|
+
· `没有使用 PE` gap=「使用 」→ 同上
|
|
1040
|
+
· `未使用这种 PE` gap=「使用这种 」→ 全为连接字 ⇒ 否定
|
|
1041
|
+
· `不是 PE` gap=「是 」 → 无动词字 ⇒ **不判否定**(base 判定一字不动)
|
|
1042
|
+
"""
|
|
1043
|
+
for back in range(1, NEG_SCOPE_WINDOW + 1):
|
|
1044
|
+
j = i - back
|
|
1045
|
+
if j < 0:
|
|
1046
|
+
break
|
|
1047
|
+
for cue in _NEG_VERB_CUES:
|
|
1048
|
+
if j + len(cue) <= i and s.startswith(cue, j):
|
|
1049
|
+
# A-not-A(正反问):「是不是」「有没有」里的否定词是正反叠用标记,
|
|
1050
|
+
# 与 `_negated_at` 的同名豁免同源(多字 cue 用「前字 == cue 尾字」判)。
|
|
1051
|
+
if j >= 1 and s[j - 1] == (s[j + 1] if len(cue) == 1 else cue[-1]):
|
|
1052
|
+
continue
|
|
1053
|
+
# 双重否定:「不得不采用」「不能不使用」语义是「必须用」,不能判否定。
|
|
1054
|
+
# 要跨过情态字(得/能/会/可/要/想)再往前看一个字是否定字。
|
|
1055
|
+
if _double_negated_before(s, j):
|
|
1056
|
+
continue
|
|
1057
|
+
gap = s[j + len(cue):i]
|
|
1058
|
+
if any(ch in NEG_VERB_CHARS for ch in gap) and all(
|
|
1059
|
+
ch in NEG_SCOPE_CHARS or ch.isspace() for ch in gap):
|
|
1060
|
+
return True
|
|
1061
|
+
return False
|
|
1062
|
+
|
|
925
1063
|
# 生效条件:hay 与 needle 均为 str 时返回 needle 在 hay 中的全部出现起始下标(左对齐、按升序,含重叠出现);needle 为空串返回空列表。
|
|
926
1064
|
def _occurrences(hay: str, needle: str) -> list:
|
|
927
1065
|
"""needle 在 hay 中的全部出现起址(#362a:逐次出现各自判否定作用域)。"""
|
|
@@ -1985,7 +2123,7 @@ def _usable_index_snapshot(value):
|
|
|
1985
2123
|
# 生效条件:构造须传入 root,经 os.path.abspath 后以 exist_ok=True 创建该目录及 LAYERS 各层子目录;autoflush 无论取值(默认 64)都原样赋给实例。
|
|
1986
2124
|
class MdCG:
|
|
1987
2125
|
# 生效条件:root 传参即被 os.path.abspath 绝对化并 makedirs(exist_ok=True) 建立 root 与模块级 LAYERS 各层目录,autoflush(默认 64,含 0 等假值)原样存入 self.autoflush,随后 _load_index() 载入索引并以 _index_signature() 记录 _index.json 签名到 self._index_sig(跨进程读面代际感知的基线,P1b-2)、sweep_stale_temps(self.root) 清扫,并把 self 登记进模块级 _LIVE_CGS,最后按 MDCG_READ_CACHE 装配读缓存(#370:readcache.install_default——自动装配的唯一入口,env 门 + 幂等,MDCG_READ_CACHE=0 时不装配);
|
|
1988
|
-
def __init__(self, root: str, autoflush: int = 64):
|
|
2126
|
+
def __init__(self, root: str, autoflush: int = 64, async_flush=None):
|
|
1989
2127
|
self.root = os.path.abspath(root)
|
|
1990
2128
|
os.makedirs(self.root, exist_ok=True)
|
|
1991
2129
|
for L in LAYERS:
|
|
@@ -2000,6 +2138,16 @@ class MdCG:
|
|
|
2000
2138
|
# 近期事件滚动窗口(白箱第 5 篇第 3 章「近期事件」)
|
|
2001
2139
|
self.recent_log = os.path.join(self.root, "_recent.jsonl")
|
|
2002
2140
|
self.autoflush = autoflush
|
|
2141
|
+
# 生效条件:async_flush 为 None 时本实例随 env `MDCG_ASYNC_FLUSH` 走(缺省异步,
|
|
2142
|
+
# 与 #677 P2 逐位一致);为 True/False 时**钉死**本实例的落盘模式,不再读 env。
|
|
2143
|
+
# 为什么需要实例级开关(2026-11-08,issue #831):`autoflush=1` 的既有承诺是
|
|
2144
|
+
# 「写毕即落分片日志」——`review_cli._cg` 的注释据此写「任意退出形态下写入对
|
|
2145
|
+
# 其它进程立即可见」,`test_review_cli_visibility` ③ 也据此断言。但 #677 P2
|
|
2146
|
+
# 把 flush 改到后台线程后,`_request_flush` 只 `ev.set()` 即返回,写入**只是被
|
|
2147
|
+
# 调度**、并未落盘;短命进程(review_cli 这类)在被 kill / `os._exit` 时后台
|
|
2148
|
+
# 线程未必跑过 ⇒ 承诺失效。实例级开关让「我要同步语义」的调用点显式声明,
|
|
2149
|
+
# 不必依赖进程级 env(env 是全局的,改它会波及同进程其它库实例)。
|
|
2150
|
+
self._async_flush_forced = async_flush
|
|
2003
2151
|
# issue #677 P2:后台索引落盘的状态(锁 / 事件 / 线程 / 停止标志)。
|
|
2004
2152
|
# 锁在 __init__ 就绪——flush 可能在写路径、后台线程、close 三处被调。
|
|
2005
2153
|
self._flush_lock = threading.RLock()
|
|
@@ -2040,6 +2188,13 @@ class MdCG:
|
|
|
2040
2188
|
# 由下次访问重建。占用面:1.7 万节点 ≈ 三张小表 + 位序/分类两表(内存派生,
|
|
2041
2189
|
# 不改磁盘格式)。
|
|
2042
2190
|
self._stg_index = None
|
|
2191
|
+
# issue #766(W3 增量化):增量重载的**物化基线**三元组——必须与
|
|
2192
|
+
# `self.index` 分开存,否则调用方就地改写索引条目会把基线一起污染,
|
|
2193
|
+
# 下次增量便携带这份脏值(全量路径不会,它从盘上重读)。
|
|
2194
|
+
self._index_baseline = None # 私有 nodes 拷贝(条目顶层已隔离)
|
|
2195
|
+
self._baseline_cursor = None # 该基线已消费到的分片日志字节水位
|
|
2196
|
+
self._baseline_snap_sig = None # 该基线对应 _index.json 的 (mtime_ns,size)
|
|
2197
|
+
self._baseline_dir_fp = None # 该基线对应盘面目录指纹(不依赖快照带该键)
|
|
2043
2198
|
self.index = self._load_index()
|
|
2044
2199
|
# P1b-2(2026-09-26,DSH 在役复验):索引只在本行装载一次,此后
|
|
2045
2200
|
# read/get/search 全走内存态——其它进程(review_cli autoflush=1)
|
|
@@ -2066,8 +2221,209 @@ class MdCG:
|
|
|
2066
2221
|
|
|
2067
2222
|
# ---------- 索引(派生物,可重建) ----------
|
|
2068
2223
|
|
|
2224
|
+
# 生效条件:idx 为一份**刚落盘/刚装载**的完整索引(dict,含 nodes)时,把增量基线三元组重置为「该 idx 私有拷贝 + 当前日志水位 + 当前快照签名」;恒返回 None。
|
|
2225
|
+
def _reset_baseline(self, idx):
|
|
2226
|
+
"""重置增量基线三元组(单点——构造 / 全量装载 / compact / rebuild 共用)。
|
|
2227
|
+
|
|
2228
|
+
**为什么存私有拷贝**:调用方会就地改写 `self.index` 的条目(仓内测试与
|
|
2229
|
+
bench 多处这么做),共享同一批条目对象会让基线携带脏值;全量路径每次
|
|
2230
|
+
从盘上重读、不会,故基线必须自己留一份。
|
|
2231
|
+
|
|
2232
|
+
**为什么水位在拷贝之后再取**(安全方向):先取水位再去重放日志,水位里
|
|
2233
|
+
记的东西可能**尚未**被应用;反过来(先重放、后取水位)则水位一定 ⊆ 已
|
|
2234
|
+
消费集合,下次至多重放幂等记录,不会漏。本函数取在水位之前即调用方
|
|
2235
|
+
之后还要 apply_log 的情形也保持一致——宁可重复,不可漏。
|
|
2236
|
+
"""
|
|
2237
|
+
nodes = idx.get("nodes") if isinstance(idx, dict) else None
|
|
2238
|
+
if not isinstance(nodes, dict):
|
|
2239
|
+
self._index_baseline = None
|
|
2240
|
+
self._baseline_cursor = None
|
|
2241
|
+
self._baseline_snap_sig = None
|
|
2242
|
+
return
|
|
2243
|
+
self._index_baseline = {
|
|
2244
|
+
"schema": SCHEMA,
|
|
2245
|
+
"nodes": {k: dict(v) for k, v in nodes.items() if isinstance(v, dict)},
|
|
2246
|
+
"_fingerprint": idx.get("_fingerprint"),
|
|
2247
|
+
}
|
|
2248
|
+
try:
|
|
2249
|
+
self._baseline_cursor = ShardedLog.committed_cursor(self.index_log_dir)
|
|
2250
|
+
except (OSError, ValueError):
|
|
2251
|
+
self._baseline_cursor = None
|
|
2252
|
+
# 目录指纹:增量正确性的 ④ 前提。**自存**而非依赖快照的 _fingerprint
|
|
2253
|
+
# 键——后者只在 compact 过之后才有,而生产常态(MCP serve autoflush=1
|
|
2254
|
+
# 只 flush 不 close)根本不会写快照,读那条会把增量永久挡在门外
|
|
2255
|
+
# (实测踩过:probe read 臂重载仍 200/200)。
|
|
2256
|
+
try:
|
|
2257
|
+
self._baseline_dir_fp = self._dir_fingerprint()
|
|
2258
|
+
except (OSError, ValueError):
|
|
2259
|
+
self._baseline_dir_fp = None
|
|
2260
|
+
try:
|
|
2261
|
+
_st = os.stat(self.index_path)
|
|
2262
|
+
self._baseline_snap_sig = (_st.st_mtime_ns, _st.st_size)
|
|
2263
|
+
except OSError:
|
|
2264
|
+
self._baseline_snap_sig = None
|
|
2265
|
+
|
|
2266
|
+
# 生效条件:仅当「快照文件签名与上次装载时逐位相同」**且**「上次已把该快照对应那一刻的全部分片日志消费到水位」时,返回在现有内存索引上叠加日志新增尾部后的新索引(新对象,条目不共享);任一条证不出(无基线、快照签名变过、游标缺失、分片消失/被截断、盘面指纹变化)一律返回 None,交由 _load_index 走全量路径。
|
|
2267
|
+
def _try_incremental_index(self):
|
|
2268
|
+
"""索引**增量重载**(issue #766 / W3):只重放日志新增尾部,不重读快照。
|
|
2269
|
+
|
|
2270
|
+
为什么需要(先量后改的读数):`flush()` 只 append 分片、从不清;只有
|
|
2271
|
+
`close()`→`compact_index` 才 `ShardedLog.clear`。长期存活写方(MCP serve
|
|
2272
|
+
本体即 `autoflush=1 只 flush 不 close`)的分片日志**只增不减**,而
|
|
2273
|
+
`_load_index` 每次都把全部记录重读重解析一遍:
|
|
2274
|
+
· 300 节点、日志 2000→12000 条:单次 `_load_index` 65→258 ms(斜率
|
|
2275
|
+
约 18ms/千条)——成本 ∝ **该库历史写入总量**,不是本次增量;
|
|
2276
|
+
· 10000 节点:单次重载 258 ms 里 `json.load` 177 ms + `read_all` 160 ms。
|
|
2277
|
+
两者叠加就是 §6 注实测的「读 P95 放大 16.6–21.0x」。故可拆物是
|
|
2278
|
+
**重载本身的成本**,不是锁(读路径取锁 0 次)。
|
|
2279
|
+
|
|
2280
|
+
**为什么可以只叠尾部而不重读快照**(充要条件,缺一即回退):
|
|
2281
|
+
① 快照签名(mtime_ns,size)逐位未变 ⇒ `_index.json` 字节没被改写过
|
|
2282
|
+
⇒ 它描述的那份 nodes 与上次装载时是同**一份**,无需重读;
|
|
2283
|
+
② 上次装载后**已消费**该快照对应时刻的全部分片记录(`_log_cursor`
|
|
2284
|
+
与索引同代)⇒ 内存索引 == 快照 ⊕ 已消费记录,再叠加新尾部即
|
|
2285
|
+
等于「快照 ⊕ 全部记录」= 全量路径的结果;
|
|
2286
|
+
③ 期间无 compact 发生:compact 会 `ShardedLog.clear` 使部分分片
|
|
2287
|
+
消失、并重写快照使签名变化——两条中任一条都已被 ①② 或返回
|
|
2288
|
+
`(None,None)` 挡住;
|
|
2289
|
+
④ 盘面目录指纹仍可信(`_snapshot_trusted` 同一判据):防非合作写者
|
|
2290
|
+
在快照写入后改了盘面(改名/换目录/删加),此时路径映射可能已陈旧。
|
|
2291
|
+
三者同时成立时,增量结果与全量路径**逐位一致**,不是近似。
|
|
2292
|
+
|
|
2293
|
+
**不看 `_dirty`**:脏集属于「本实例未落盘写入」,由调用方
|
|
2294
|
+
`_maybe_reload_index` 在拿到新索引后按其见证判据重放;本函数只负责
|
|
2295
|
+
重建「盘面 + 日志」这一面,与既有分工一致。
|
|
2296
|
+
"""
|
|
2297
|
+
base = getattr(self, "_index_baseline", None)
|
|
2298
|
+
cursor = getattr(self, "_baseline_cursor", None)
|
|
2299
|
+
if base is None or cursor is None:
|
|
2300
|
+
return None
|
|
2301
|
+
snap = getattr(self, "_baseline_snap_sig", None)
|
|
2302
|
+
# ① 快照签名逐位未变(双侧 None 也算一致:库从未 compact 过)
|
|
2303
|
+
try:
|
|
2304
|
+
st = os.stat(self.index_path)
|
|
2305
|
+
cur_snap = (st.st_mtime_ns, st.st_size)
|
|
2306
|
+
except OSError:
|
|
2307
|
+
cur_snap = None
|
|
2308
|
+
if cur_snap != snap:
|
|
2309
|
+
return None
|
|
2310
|
+
# ④ 盘面变化判据:**与全量路径同一判据**(`_load_index` 里
|
|
2311
|
+
# `_changed <= _log_dirs` + `_covers_disk` 那两步),不另造更严的口径。
|
|
2312
|
+
# 为什么不能要求「目录指纹一位不变」:合作写入每次 `add` 都走
|
|
2313
|
+
# atomic_write(建临时文件再改名),必然改所在目录的 mtime ⇒ 那条
|
|
2314
|
+
# 判据会把**正常写入本身**判成不可增量,增量被永久挡在门外(实测:
|
|
2315
|
+
# 探针 read 臂重载仍 200/200、P95 仍是 16.58x,改动等于没生效)。
|
|
2316
|
+
try:
|
|
2317
|
+
cur_fp = self._dir_fingerprint()
|
|
2318
|
+
except (OSError, ValueError):
|
|
2319
|
+
return None
|
|
2320
|
+
old_fp = getattr(self, "_baseline_dir_fp", None)
|
|
2321
|
+
if old_fp is None:
|
|
2322
|
+
return None
|
|
2323
|
+
changed = {d for d, m in cur_fp.items() if old_fp.get(d) != m}
|
|
2324
|
+
changed |= {d for d in old_fp if d not in cur_fp}
|
|
2325
|
+
|
|
2326
|
+
# ② / ③ 读日志新增尾部(分片消失/被截断时 read_tails 返回 (None,None))
|
|
2327
|
+
try:
|
|
2328
|
+
recs, new_cursor = ShardedLog.read_tails(self.index_log_dir, cursor)
|
|
2329
|
+
except (OSError, ValueError):
|
|
2330
|
+
return None
|
|
2331
|
+
if recs is None:
|
|
2332
|
+
return None
|
|
2333
|
+
|
|
2334
|
+
# ④' 变过的目录必须都在「日志新增/改写记录所在目录」里——非合作写者
|
|
2335
|
+
# (改名/换目录/对调/删一加一)不改 .md 计数却改路径映射,它们在日志
|
|
2336
|
+
# 里没有对应 path,必被这条挡住而回退全量。
|
|
2337
|
+
if changed:
|
|
2338
|
+
log_dirs = set()
|
|
2339
|
+
for _r in recs:
|
|
2340
|
+
_e = _r.get("e") if isinstance(_r, dict) else None
|
|
2341
|
+
_p = _e.get("path") if isinstance(_e, dict) else None
|
|
2342
|
+
if _p:
|
|
2343
|
+
log_dirs.add(os.path.dirname(str(_p).replace("\\", "/")))
|
|
2344
|
+
if not changed <= log_dirs:
|
|
2345
|
+
return None
|
|
2346
|
+
|
|
2347
|
+
# ④'' **不在此处判**:盘面覆盖闸要在重放之后才判得准(见下方 `_covers_disk`
|
|
2348
|
+
# 调用点)。此处留注释只为标明④' 不是最后一道闸。
|
|
2349
|
+
if not recs:
|
|
2350
|
+
# 无新增:**仍须返回新对象**。调用方 `_maybe_reload_index` 会在
|
|
2351
|
+
# 拿到的 idx["nodes"] 上就地重放 `_dirty`(`idx["nodes"][nid] = e`),
|
|
2352
|
+
# 若把基线本身交出去,本实例未落盘的脏值就会写进基线,下次增量
|
|
2353
|
+
# 便把它当成盘面事实携带下去。
|
|
2354
|
+
self._baseline_cursor = new_cursor
|
|
2355
|
+
self._baseline_snap_sig = snap
|
|
2356
|
+
# 指纹推进到**本次已核对过的当前盘面**(上面 ④' 已判「变过的目录
|
|
2357
|
+
# 全在日志新增目录里」,即这些变化已被本次重放覆盖)。不推进则下
|
|
2358
|
+
# 一轮会把同一批已核销的变化再判一次,无限回退全量。
|
|
2359
|
+
self._baseline_dir_fp = cur_fp
|
|
2360
|
+
_n = dict(base.get("nodes") or {})
|
|
2361
|
+
# ④'' 同上:无新增日志时也必须判盘面覆盖(孤儿形态同样存在于
|
|
2362
|
+
# 「零新增 + 盘上多一个 .md」这条路径上)。
|
|
2363
|
+
if not self._covers_disk(_n):
|
|
2364
|
+
return None
|
|
2365
|
+
_idx = {"schema": SCHEMA, "nodes": _n,
|
|
2366
|
+
"buckets": self._count_buckets(_n)}
|
|
2367
|
+
if "_fingerprint" in base:
|
|
2368
|
+
_idx["_fingerprint"] = base["_fingerprint"]
|
|
2369
|
+
return _idx
|
|
2370
|
+
|
|
2371
|
+
nodes = dict(base.get("nodes") or {}) # 外层新 dict;条目对象随后逐条替换
|
|
2372
|
+
skips = []
|
|
2373
|
+
for rec in recs:
|
|
2374
|
+
nid, e = rec.get("id"), rec.get("e")
|
|
2375
|
+
if not nid:
|
|
2376
|
+
continue
|
|
2377
|
+
nid = str(nid)
|
|
2378
|
+
if e is not None and not isinstance(e, dict):
|
|
2379
|
+
skips.append((self.index_log_dir, nid, e))
|
|
2380
|
+
continue
|
|
2381
|
+
if e is None:
|
|
2382
|
+
nodes.pop(nid, None)
|
|
2383
|
+
else:
|
|
2384
|
+
nodes[nid] = e
|
|
2385
|
+
if skips:
|
|
2386
|
+
note_bad_payload_rows(skips)
|
|
2387
|
+
# ④'' 盘面覆盖闸:**必须复用全量路径的 `_covers_disk`**,不得只靠目录
|
|
2388
|
+
# 指纹。独立复核实测到的缺陷(改前可见 / 改后不可见):
|
|
2389
|
+
# 「他实例写已落盘、其索引增量还在其 `_dirty`」——盘上多出一个 .md,
|
|
2390
|
+
# 日志里没有它。若它恰好和一条合作写入落在**同一子目录**,则
|
|
2391
|
+
# `changed == log_dirs` 成立、④' 放行,而快照里没有该节点 ⇒ 增量
|
|
2392
|
+
# 继承快照的旧节点集 ⇒ **该节点在存活读者上要等到下次全量才可见**。
|
|
2393
|
+
# 全量路径正是靠本闸挡住这种形态(`_covers_disk` 不过 ⇒ 宁重扫)。
|
|
2394
|
+
# 不调它 = 两条路径对「盘面覆盖」各执一套口径,正好回到 #409 要消灭
|
|
2395
|
+
# 的形态(该 issue 的收口纪律是判据单点)。
|
|
2396
|
+
# 位置在**重放之后**:要判的是「重放完的节点集是否覆盖当前盘面」。
|
|
2397
|
+
if not self._covers_disk(nodes):
|
|
2398
|
+
return None
|
|
2399
|
+
idx = {"schema": SCHEMA, "nodes": nodes, "buckets": {}}
|
|
2400
|
+
idx["buckets"] = self._count_buckets(nodes)
|
|
2401
|
+
# 保留快照的指纹(④ 已判其仍与当前盘面一致,故逐位不变)
|
|
2402
|
+
if "_fingerprint" in base:
|
|
2403
|
+
idx["_fingerprint"] = base["_fingerprint"]
|
|
2404
|
+
# 推进基线(同一代四元组):下次继续从新水位往后读。指纹一并推进到
|
|
2405
|
+
# 本次已核对过的盘面——上面的 ④' 已判「变过的目录全在日志新增目录
|
|
2406
|
+
# 里」,这些变化已被本次重放覆盖,不推进会让下一轮把同一批已核销的
|
|
2407
|
+
# 变化再判一次,无限回退全量。
|
|
2408
|
+
self._index_baseline = {"schema": SCHEMA,
|
|
2409
|
+
"nodes": {k: dict(v) for k, v in nodes.items()
|
|
2410
|
+
if isinstance(v, dict)},
|
|
2411
|
+
"_fingerprint": base.get("_fingerprint")}
|
|
2412
|
+
self._baseline_cursor = new_cursor
|
|
2413
|
+
self._baseline_snap_sig = snap
|
|
2414
|
+
self._baseline_dir_fp = cur_fp
|
|
2415
|
+
return idx
|
|
2416
|
+
|
|
2069
2417
|
# 生效条件:os.path.exists(self.index_path) 为真、json.load 成功、解析结果为 dict(顶层非对象=null/[]/123/"abc" 视同损坏)且其 "schema" 等于模块级 SCHEMA、且其 "_fingerprint"(目录树 mtime 指纹)等于当前 self._dir_fingerprint() 时以该快照为基底;快照缺失/损坏/顶层非对象/无指纹/指纹不符(盘面在快照写入后有增删——其它存活实例未 flush 的写入或外部改盘)均回退 self._scan_nodes() 全库扫描为基底;随后经 self._apply_log 重放分片日志(N225 补强:与 compact 面**同一实现**——无 id 跳过、e 为 None 则 pop 该 nid(tombstone)、e 非 dict 且非 None 则跳过并记账、其余覆盖),最终 buckets 由 _count_buckets 重算;
|
|
2070
2418
|
def _load_index(self):
|
|
2419
|
+
# issue #766(W3 增量化):先试**增量**重载——快照未变就只重放日志新增
|
|
2420
|
+
# 尾部,不重读快照、不重放历史记录。任一前提证不出即回退下面的全量
|
|
2421
|
+
# 路径(`_try_incremental_index` 返回 None 的全部情形)。
|
|
2422
|
+
_incr = self._try_incremental_index()
|
|
2423
|
+
if _incr is not None:
|
|
2424
|
+
return _incr
|
|
2425
|
+
# 全量路径:先试增量,不可行再整库重装(`_reset_baseline` 在返回前
|
|
2426
|
+
# 重建基线,见该函数与 `_try_incremental_index` 的水位顺序说明)。
|
|
2071
2427
|
idx = None
|
|
2072
2428
|
if os.path.exists(self.index_path):
|
|
2073
2429
|
try:
|
|
@@ -2132,6 +2488,9 @@ class MdCG:
|
|
|
2132
2488
|
idx = {"schema": SCHEMA, "nodes": self._scan_nodes(), "buckets": {}}
|
|
2133
2489
|
self._apply_log(idx["nodes"])
|
|
2134
2490
|
idx["buckets"] = self._count_buckets(idx["nodes"])
|
|
2491
|
+
# 记录物化基线,供下次增量使用。**水位取在此刻**(apply_log 之后)是
|
|
2492
|
+
# 安全方向:水位 ⊆ 已消费集合 ⇒ 下次至多重放幂等记录,不会漏。
|
|
2493
|
+
self._reset_baseline(idx)
|
|
2135
2494
|
return idx
|
|
2136
2495
|
|
|
2137
2496
|
# 生效条件:nodes 为可 pop / 可赋值的映射(dict 或 _DirtyDict)时,对 ShardedLog.read_all(self.index_log_dir) 的每条记录逐条重放——无 id(假值)跳过;有 id 时 str 归一(legacy P3 自愈腿:旧版本 _stage 落下的 {"id": 123} 不得让 int 键进索引);e 为 None(tombstone)⇒ nodes.pop(nid, None),语义一字不改;e 非 dict 且非 None("[]"/123/"abc" 等合法 JSON 载荷)⇒ **跳过**并经 fsutil.note_bad_payload_rows 记账 + stderr 告警(容忍 ≠ 静默,且不得让非 dict 载荷进 nodes——下游 _count_buckets 对元素裸调 .get,不做类型检查);其余(dict 载荷)⇒ nodes[nid] = e 覆盖;函数返回传入的 nodes。
|
|
@@ -2564,6 +2923,13 @@ class MdCG:
|
|
|
2564
2923
|
atomic_write(self.index_path, json.dumps(idx, ensure_ascii=False))
|
|
2565
2924
|
ShardedLog.clear(self.index_log_dir)
|
|
2566
2925
|
self.index = idx
|
|
2926
|
+
# issue #766:compact 重写了快照并**清空分片日志** ⇒ 旧基线(旧快照 +
|
|
2927
|
+
# 旧水位)描述的盘面已不存在。此处**立即重建**基线(而不是留 None 等
|
|
2928
|
+
# 下次重载):compact 手里就有刚落盘的 idx,日志刚清空(水位全 0),
|
|
2929
|
+
# 是重建基线最廉价的一刻。留 None 会让「刚 compact 完的进程」在下次
|
|
2930
|
+
# 全量重载之前一直无法增量——那是静默的性能回退(正确性无碍,但
|
|
2931
|
+
# 收益归零,实测踩过)。
|
|
2932
|
+
self._reset_baseline(idx)
|
|
2567
2933
|
# 第 3 层结构索引随快照替换失效(快照重建过,旧表与它的划分关系不再
|
|
2568
2934
|
# 有据可依):下次 stg 访问重建;不在此处立即重算——compact 是收尾路
|
|
2569
2935
|
# 径,重建成本挪到真正需要索引的那次读(惰性失效重建,同一选)。
|
|
@@ -2573,8 +2939,11 @@ class MdCG:
|
|
|
2573
2939
|
self._index_sig = self._index_signature()
|
|
2574
2940
|
return idx
|
|
2575
2941
|
|
|
2576
|
-
#
|
|
2942
|
+
# 生效条件:本实例以 async_flush= 显式钉死模式时返回该值(True 异步 / False 同步),否则读 env MDCG_ASYNC_FLUSH(缺省开;=0 关)——关闭时 _request_flush 退回同步 flush。
|
|
2577
2943
|
def _async_flush_on(self):
|
|
2944
|
+
forced = getattr(self, "_async_flush_forced", None)
|
|
2945
|
+
if forced is not None:
|
|
2946
|
+
return bool(forced)
|
|
2578
2947
|
return (os.environ.get("MDCG_ASYNC_FLUSH", "1") or "1").strip() != "0"
|
|
2579
2948
|
|
|
2580
2949
|
# 生效条件:请求一次后台落盘——异步开时置事件并确保守护线程在跑(首次创建),重复请求合并为一次;
|
|
@@ -2682,6 +3051,10 @@ class MdCG:
|
|
|
2682
3051
|
for _nid, _e in batch:
|
|
2683
3052
|
if _nid not in self._dirty:
|
|
2684
3053
|
self._dirty[_nid] = _e
|
|
3054
|
+
# #677 C 复核:`_dirty.clear()` 会连 superseded_ids 一起清(见 _DirtyDict),
|
|
3055
|
+
# 失败回填若不恢复它,下一轮会把「已判陈旧」的记录当新记录写进分片
|
|
3056
|
+
# ⇒ 旧版本覆盖新版本(内容错误,比重复更严重)。
|
|
3057
|
+
self._dirty.superseded_ids |= superseded
|
|
2685
3058
|
raise
|
|
2686
3059
|
|
|
2687
3060
|
# 生效条件:batch 为 [(nid, entry)] 快照、superseded 为「已判陈旧」的 id 集合(两者都取自 _flush_locked 的锁内快照)时,在 FileLock(index_path) 下按需新建 ShardedLog、登记本进程分片(_own_shard)后逐条 append(跳过 superseded 中的 id),最后关闭分片句柄并返回 None;self._log 为假值时跳过关闭;
|
|
@@ -2699,12 +3072,18 @@ class MdCG:
|
|
|
2699
3072
|
# 否则「分片文件已存在但 _own_shard 未登记」的窗口里,本进程自己的
|
|
2700
3073
|
# 追加会被自家探活当成他进程变化(多线程下白重载一次)。
|
|
2701
3074
|
self._own_shard = self._log.path
|
|
2702
|
-
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
|
|
2707
|
-
|
|
3075
|
+
# issue #80 残留面(C 案):被判定陈旧(重放时已放行盘面)的条目
|
|
3076
|
+
# **不得**落分片日志——落了就成『索引侧旧盖新』且跨重启存活。
|
|
3077
|
+
_recs = [{"id": nid, "e": e} for nid, e in batch if nid not in superseded]
|
|
3078
|
+
# #677 C 根治:**一次 write + 一次 flush**(原实现每条 append 都 flush,
|
|
3079
|
+
# 锁内 IO 次数 = 脏集条数;大库下一批上千条就是上千次 flush——这正是
|
|
3080
|
+
# 「写成功但应答超时」的持锁来源)。原子性不变:整批仍在同一把 FileLock 内。
|
|
3081
|
+
_app = getattr(self._log, "append_many", None)
|
|
3082
|
+
if callable(_app):
|
|
3083
|
+
_app(_recs)
|
|
3084
|
+
else: # 兼容旧 ShardedLog(无 append_many)
|
|
3085
|
+
for _r in _recs:
|
|
3086
|
+
self._log.append(_r)
|
|
2708
3087
|
# 写完立即关分片句柄:Windows 上「被本进程打开的文件」无法删除,
|
|
2709
3088
|
# 若持有句柄,rebuild_index 的 ShardedLog.clear 会静默失败,已并进
|
|
2710
3089
|
# 快照的旧记录被永久重放(旧条目反而覆盖新快照)。append 内部已
|
|
@@ -2957,6 +3336,9 @@ class MdCG:
|
|
|
2957
3336
|
atomic_write(self.index_path, json.dumps(idx, ensure_ascii=False))
|
|
2958
3337
|
ShardedLog.clear(self.index_log_dir)
|
|
2959
3338
|
self.index = idx
|
|
3339
|
+
# issue #766:rebuild 同 compact——重写快照 + 清空分片日志 ⇒ 旧基线作废,
|
|
3340
|
+
# 用刚落盘的 idx 立即重建(理由见 compact_index 同名注释)。
|
|
3341
|
+
self._reset_baseline(idx)
|
|
2960
3342
|
# 第 3 层结构索引随全量重建失效(新快照 = 新盘面语义):下次 stg 访问
|
|
2961
3343
|
# 重建——重建后的划分不变量由守卫钉住(写/删/rebuild/compact 后三表与
|
|
2962
3344
|
# 快照一致)。
|
|
@@ -3020,9 +3402,31 @@ class MdCG:
|
|
|
3020
3402
|
# ---------- 写 ----------
|
|
3021
3403
|
|
|
3022
3404
|
# 生效条件: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:三条出口都可追溯)。
|
|
3405
|
+
# 生效条件:prev_entry 为索引条目、content 为本次写入正文;返回 True 表示「正文变了,验证态须降级」。
|
|
3406
|
+
# issue #757:优先用**索引条目的 content_hash**(与盘面同源,见 #741/#756),省一次读盘;
|
|
3407
|
+
# 缺 hash 时才回退读盘、并用**同一个** nodefile.content_hash 归一(不引入第二口径)。
|
|
3408
|
+
# 失败面:索引陈旧只会多判「变了」→ 降 doubted(安全方向);反向不可能(陈旧值来自更早正文)。
|
|
3409
|
+
@staticmethod
|
|
3410
|
+
def _vstate_body_changed(cg, node_id: str, prev_entry, content) -> bool:
|
|
3411
|
+
if not prev_entry:
|
|
3412
|
+
return False
|
|
3413
|
+
prev_hash = prev_entry.get("content_hash")
|
|
3414
|
+
if not prev_hash:
|
|
3415
|
+
try:
|
|
3416
|
+
prev_hash = nodefile.content_hash(
|
|
3417
|
+
(cg.get(node_id) or {}).get("content") or "")
|
|
3418
|
+
except Exception: # noqa: BLE001 —— 读面失败按未变处置
|
|
3419
|
+
return False
|
|
3420
|
+
try:
|
|
3421
|
+
new_hash = nodefile.content_hash(content or "")
|
|
3422
|
+
except Exception: # noqa: BLE001 —— 非 str 正文按未变处置(不打断写入)
|
|
3423
|
+
return False
|
|
3424
|
+
return bool(prev_hash) and prev_hash != new_hash
|
|
3425
|
+
|
|
3426
|
+
|
|
3023
3427
|
def add(self, node_id: str, content: str, layer: str = "knowledge",
|
|
3024
|
-
tags=None, condition_space=None, importance
|
|
3025
|
-
confidence: float =
|
|
3428
|
+
tags=None, condition_space=None, importance=None,
|
|
3429
|
+
confidence: float = None, edges=None, verification_basis: str = None,
|
|
3026
3430
|
non_applicable_conditions=None, override: bool = False,
|
|
3027
3431
|
consistency: bool = False, on_conflict: str = "reject",
|
|
3028
3432
|
consistency_out: dict = None,
|
|
@@ -3165,8 +3569,28 @@ class MdCG:
|
|
|
3165
3569
|
# 故 MdCGOS 的既有语义(非法值回落文档缺省)一字不变。
|
|
3166
3570
|
# 判据单点在模块级 `_require_unit_number`(同仓单点判据纪律:判据只写
|
|
3167
3571
|
# 一份,写侧读侧共用;守卫可对其做定点变异自证)。
|
|
3572
|
+
# importance 缺省 None = 「调用方没声明」⇒ 覆写时继承旧值,新节点回落 0.5。
|
|
3573
|
+
# 必须在**写侧数值闸(#151②)之前**解析:那道闸对 None 是 fail-closed,
|
|
3574
|
+
# 解析晚一步就变成「合法调用被判非法落盘」。与同函数里 check_strength 的
|
|
3575
|
+
# 「传入优先;否则取旧值」同一口径——不能拿 0.5 当缺省,否则一次普通覆写
|
|
3576
|
+
# 就把 0.8 的节点打回 0.5(#732 的另一面)。
|
|
3577
|
+
_prev_fm = {}
|
|
3578
|
+
_prev_body = None
|
|
3579
|
+
if (self.index.get("nodes") or {}).get(node_id) is not None:
|
|
3580
|
+
try:
|
|
3581
|
+
_pn = self.get(node_id) or {}
|
|
3582
|
+
_prev_fm = dict(_pn.get("frontmatter") or {})
|
|
3583
|
+
_prev_body = _pn.get("content")
|
|
3584
|
+
except Exception:
|
|
3585
|
+
_prev_fm, _prev_body = {}, None
|
|
3586
|
+
if importance is None:
|
|
3587
|
+
# 旧库可能有「键存在但值为 None」的节点:dict.get(k, default) 此时返回
|
|
3588
|
+
# None(不是 default)⇒ 下游 _require_unit_number fail-closed 抛错。
|
|
3589
|
+
_pi = _prev_fm.get("importance")
|
|
3590
|
+
importance = _pi if _pi is not None else 0.5
|
|
3168
3591
|
_require_unit_number("importance", importance)
|
|
3169
|
-
|
|
3592
|
+
if confidence is not None:
|
|
3593
|
+
_require_unit_number("confidence", confidence)
|
|
3170
3594
|
if verification_basis is not None and verification_basis not in VERIFICATION_BASIS:
|
|
3171
3595
|
raise ValueError(f"未知验证基底:{verification_basis}(允许:{VERIFICATION_BASIS})")
|
|
3172
3596
|
if check_strength is not None and check_strength not in CHECK_STRENGTHS:
|
|
@@ -3336,13 +3760,49 @@ class MdCG:
|
|
|
3336
3760
|
# (`MdCGSecure.add` 的 `sensitivity or DEFAULT_SENSITIVITY` 把两者
|
|
3337
3761
|
# 归一成同一个值,闸便看不见差异)。本键只是判据载体,**不落 fm**。
|
|
3338
3762
|
_declared_sens = extra.pop("declared_sensitivity", None)
|
|
3339
|
-
|
|
3763
|
+
# issue #795 方案 A(单一时间源):兜底 created_at 与观测窗锚点必须用**同一个** now。
|
|
3764
|
+
# 旧实现两处各调一次 time.time() ⇒ 正常路径下 tw[0] 与 created_at 差几微秒,
|
|
3765
|
+
# test_p2「time_window 锚定写入时刻」用的是 1e-6 严格相等 ⇒ 必红。
|
|
3766
|
+
_now = time.time()
|
|
3767
|
+
_created_given = "created_at" in extra
|
|
3768
|
+
created_at = extra.pop("created_at", _now)
|
|
3769
|
+
if not _created_given and _prev_fm.get("created_at"):
|
|
3770
|
+
created_at = _prev_fm["created_at"] # 出生时间只写一次
|
|
3340
3771
|
# 条件论「观测时间」栏:写入时必须记录观测时间窗。
|
|
3341
|
-
#
|
|
3772
|
+
# 默认窗口长度 OBSERVATION_WINDOW_SEC;**锚点分两种**(#768 返工裁定,见下):
|
|
3773
|
+
# #768:created_at 在**同 id 覆写**时继承自旧节点(出生时间只写一次,#766/#732),
|
|
3774
|
+
# 拿它当锚会把观测窗写成 [旧出生时刻, 旧出生时刻+1h],**落在过去**,且此后每次覆写
|
|
3775
|
+
# 都再写一遍;配合下方 S2 时间门(_cond_prefilter_pass:双方都有且区间不相交 ⇒ 剔除),
|
|
3776
|
+
# 被覆写过的旧节点会在带时间窗的查询里**永久消失**。故覆写继承时锚到写入时刻。
|
|
3777
|
+
# 但**调用方显式回填 created_at**(历史导入/回放)是另一条路径,其语义是「这条是那时
|
|
3778
|
+
# 观测的」,改动它会破坏既有约定(md_cg/test_p2.py 的 ts3 断言),因此保持旧口径。
|
|
3779
|
+
# 两者各管一头:created_at = 出生时刻(只写一次),time_window = 这次观测发生的时刻;
|
|
3780
|
+
# 前者仅在「显式给出」时同时充当锚。
|
|
3342
3781
|
cs = dict(condition_space or {})
|
|
3343
3782
|
tw = cs.get("time_window")
|
|
3344
3783
|
if not (isinstance(tw, (list, tuple)) and len(tw) == 2):
|
|
3345
|
-
|
|
3784
|
+
_anchor = created_at if _created_given else _now
|
|
3785
|
+
cs["time_window"] = [_anchor, _anchor + OBSERVATION_WINDOW_SEC]
|
|
3786
|
+
# BODY_SAME 继承不得覆盖**显式给出**的键(#742 复核):形参缺省无法区分
|
|
3787
|
+
# 「没给」与「给了缺省值」,故以 None 为哨兵;confidence 的 0.6 在继承
|
|
3788
|
+
# 之后才补(显式传入 0.6 也会进 _explicit)。modality 走 extra.pop,
|
|
3789
|
+
# 必须在 pop 之前取「是否显式给了」。
|
|
3790
|
+
_modality_given = "modality" in extra
|
|
3791
|
+
_explicit = set(extra)
|
|
3792
|
+
if _modality_given:
|
|
3793
|
+
_explicit.add("modality")
|
|
3794
|
+
if confidence is None:
|
|
3795
|
+
confidence = 0.6
|
|
3796
|
+
else:
|
|
3797
|
+
_explicit.add("confidence")
|
|
3798
|
+
for _pk, _pv in (('verification_basis', verification_basis),
|
|
3799
|
+
('non_applicable_conditions', non_applicable_conditions),
|
|
3800
|
+
('importance_source', importance_source)):
|
|
3801
|
+
if _pv is not None:
|
|
3802
|
+
_explicit.add(_pk)
|
|
3803
|
+
if edges is not None:
|
|
3804
|
+
_explicit.add("edges") # edges 是形参:显式给了就不能被旧值覆盖
|
|
3805
|
+
|
|
3346
3806
|
fm = {
|
|
3347
3807
|
"id": node_id, "layer": layer,
|
|
3348
3808
|
"modality": extra.pop("modality", "text"),
|
|
@@ -3356,6 +3816,29 @@ class MdCG:
|
|
|
3356
3816
|
"evidence_count": 0, "positive_evidence": 0, "negative_evidence": 0,
|
|
3357
3817
|
}
|
|
3358
3818
|
fm.update(extra)
|
|
3819
|
+
# 覆写继承(issue #732):调用方显式给出的键才覆盖,否则沿用旧值。
|
|
3820
|
+
# 位置在 update(extra) 之后、各闸之前——既有闸(保护/密级/生命周期)
|
|
3821
|
+
# 读的就是这份 fm,故继承值必须在此之前就位。
|
|
3822
|
+
for _k in INHERIT_ON_OVERWRITE:
|
|
3823
|
+
if _k not in extra and _k in _prev_fm:
|
|
3824
|
+
fm[_k] = _prev_fm[_k]
|
|
3825
|
+
# 正文逐字未变(retag / 纯元数据改写)⇒ 自动血缘不必重算。
|
|
3826
|
+
# **只在调用方没给 edges 时继承**:`edges` 是形参不是 extra,若无条件继承
|
|
3827
|
+
# 会把调用方刚算好的新边覆盖回旧值(实测 p17_predict 的「命中 → 因果边
|
|
3828
|
+
# 置信度 +0.05」正是这样被吃掉的)。同理 importance 已改为「传 None 才继承」
|
|
3829
|
+
# 的缺省口径(见上方 S1),不再走本白名单。
|
|
3830
|
+
if _prev_body is not None and _prev_fm:
|
|
3831
|
+
# 判据与 #756 的 content_hash 同源(normalize_body 是它的输入规范化单点):
|
|
3832
|
+
# 单尾换行差异视为「未变」,多尾换行差异视为「变了」。此前用 rstrip("\n")
|
|
3833
|
+
# 是第二份文本等价判据(与 #756 不同源,≥2 尾换行会误判「未变」)。
|
|
3834
|
+
_same_body = (nodefile.normalize_body(_prev_body)
|
|
3835
|
+
== nodefile.normalize_body(content))
|
|
3836
|
+
if _same_body:
|
|
3837
|
+
for _k in INHERIT_ON_OVERWRITE_BODY_SAME:
|
|
3838
|
+
if _k not in _explicit and _k in _prev_fm:
|
|
3839
|
+
fm[_k] = _prev_fm[_k]
|
|
3840
|
+
if edges is None and _prev_fm.get("edges"):
|
|
3841
|
+
fm["edges"] = _prev_fm["edges"]
|
|
3359
3842
|
# 写入面信任标记(使用者裁定 2026-10-21:「未验证、未信任的信息本来就不应该执行」):
|
|
3360
3843
|
# 文本里出现伪装系统消息/指令式短语 ⇒ 落 untrusted 标记 + 命中词,供检索面与
|
|
3361
3844
|
# 上层(注入前)据此把它当**数据**而不是指令;不改正文(数据无损)。
|
|
@@ -3506,24 +3989,20 @@ class MdCG:
|
|
|
3506
3989
|
# 「已验证」。证据针对的是**旧正文**,故只在正文真的变了时才降
|
|
3507
3990
|
# (verified→doubted 是 TRANSITIONS 里的合法迁移,不需 override)。
|
|
3508
3991
|
# 边界:无 principal 的裸库 / ops 未声明(`Principal()` 缺省)⇒
|
|
3509
|
-
# `allows_op`
|
|
3510
|
-
#
|
|
3511
|
-
#
|
|
3992
|
+
# `allows_op` 为真,逐位继承,既有语义零变化。
|
|
3993
|
+
# issue #757:正文比对改用**索引条目的 content_hash**(不再读盘回正文)。
|
|
3994
|
+
# 前提已由 #741/#756 建立:content_hash 内部 normalize_body 是唯一真源,
|
|
3995
|
+
# 直调 add / 重建扫描 / 两级提交写入的条目都同源;两级提交保证「同 id 的
|
|
3996
|
+
# 上一次成功写入」此时已在内存索引里(不依赖是否 flush)。
|
|
3997
|
+
# 失败面是**保守的**:索引若陈旧只会多判「正文变过」→ 降 doubted(安全方向)。
|
|
3512
3998
|
_inherit = prev_vstate
|
|
3513
3999
|
if prev_vstate == "verified" and prev_entry is not None:
|
|
3514
4000
|
_principal = getattr(self, "principal", None)
|
|
3515
4001
|
_may_verify = (not callable(getattr(_principal, "allows_op", None))
|
|
3516
4002
|
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"
|
|
4003
|
+
if not _may_verify and MdCG._vstate_body_changed(
|
|
4004
|
+
self, node_id, prev_entry, content):
|
|
4005
|
+
_inherit = "doubted"
|
|
3527
4006
|
fm[trust.STATE_FIELD] = _inherit
|
|
3528
4007
|
else:
|
|
3529
4008
|
_pe_v = prev_entry or {}
|
|
@@ -3692,7 +4171,7 @@ class MdCG:
|
|
|
3692
4171
|
rejection_index_terms(fm, sealed),
|
|
3693
4172
|
"access_count": fm.get("access_count", 0),
|
|
3694
4173
|
"last_access": fm.get("last_access", 0),
|
|
3695
|
-
"content_hash":
|
|
4174
|
+
"content_hash": nodefile.content_hash(sealed),
|
|
3696
4175
|
"temporal": fm.get("temporal"),
|
|
3697
4176
|
"spatial": fm.get("spatial"),
|
|
3698
4177
|
"time_window": cs.get("time_window"),
|
|
@@ -4363,6 +4842,83 @@ class MdCG:
|
|
|
4363
4842
|
# 生效条件:dry_run 为真时只统计不改盘;否则遍历 index["nodes"],get(nid) 取不到(无密钥/文件缺失)计入 unreadable,
|
|
4364
4843
|
# fm 已有 big_domain 计入 already,content 为 None 计入 unreadable,routing.classify_text(content) 为 None 计入 no_signal,
|
|
4365
4844
|
# 其余写 fm["big_domain"] → _write_node → 同步索引 entry["big_domain"];limit 为真值时 written 达 limit 即停;写完 flush();返回统计 dict。
|
|
4845
|
+
def retag(self, node_id: str, tags_add=None, tags_remove=None,
|
|
4846
|
+
condition_space_patch=None, depends_on=None,
|
|
4847
|
+
dry_run: bool = True) -> dict: # 库层缺省 True:直接调库也安全
|
|
4848
|
+
"""**只改元数据**(tags / condition_space / depends_on),正文与证据链原样。
|
|
4849
|
+
|
|
4850
|
+
为何需要它:给存量节点补 `domain:` 标签以迁出 `knowledge/orphan/`
|
|
4851
|
+
(`routing.route_key` 只认 tags 的 `domain:` 前缀,其次
|
|
4852
|
+
`condition_space.observation_position`),此前唯一通道是同 id 覆写
|
|
4853
|
+
`add()`——而 `add()` 是全量重建 fm,会重置 created_at / session 并丢
|
|
4854
|
+
evidence_log / edges(见 issue #732 与 INHERIT_ON_OVERWRITE)。
|
|
4855
|
+
|
|
4856
|
+
本函数不改判据、不新造写盘点:它**复用 add() 的既有写链**(换桶清理、
|
|
4857
|
+
索引 _stage、密级与保护闸全部照旧),只是把「正文逐字不变」这件事显式
|
|
4858
|
+
保证下来,从而命中 `INHERIT_ON_OVERWRITE_BODY_SAME` 的继承分支——
|
|
4859
|
+
edges 与 importance 也一并保住。
|
|
4860
|
+
|
|
4861
|
+
dry_run=True 只算不写,返回将要落到的桶与路径,供调用方先确认。
|
|
4862
|
+
**库层缺省 True**(#742 复核:直接调库默认落盘与「预演优先」相反);
|
|
4863
|
+
工具面 maintain(action=retag, apply=True) 才落盘,且 apply=False 时
|
|
4864
|
+
即便显式 dry_run=False 也不写(见 mdcos.maintain 的双开关收敛)。
|
|
4865
|
+
"""
|
|
4866
|
+
node = self.get(node_id)
|
|
4867
|
+
if not node:
|
|
4868
|
+
return {"ok": False, "error": "node_not_found", "node_id": node_id}
|
|
4869
|
+
fm = dict(node.get("frontmatter") or {})
|
|
4870
|
+
content = node.get("content") or ""
|
|
4871
|
+
layer = str(fm.get("layer") or "knowledge")
|
|
4872
|
+
old_rel = node.get("path") or ""
|
|
4873
|
+
tags = [str(t) for t in (fm.get("tags") or []) if str(t).strip()]
|
|
4874
|
+
rem = {str(t).strip() for t in _ensure_list(tags_remove)
|
|
4875
|
+
if str(t).strip()}
|
|
4876
|
+
new_tags = [t for t in tags if t not in rem]
|
|
4877
|
+
for t in _ensure_list(tags_add):
|
|
4878
|
+
t = str(t).strip()
|
|
4879
|
+
if t and t not in new_tags:
|
|
4880
|
+
new_tags.append(t)
|
|
4881
|
+
cs = dict(fm.get("condition_space") or {})
|
|
4882
|
+
if isinstance(condition_space_patch, dict):
|
|
4883
|
+
cs.update(condition_space_patch)
|
|
4884
|
+
deps = trust.as_deps(depends_on) if depends_on is not None else None
|
|
4885
|
+
bucket = None
|
|
4886
|
+
if layer in BUCKETED_LAYERS:
|
|
4887
|
+
bucket = routing.bucket_dir(routing.route_key(cs, new_tags))
|
|
4888
|
+
ahead = os.path.join(self.root, layer, bucket)
|
|
4889
|
+
else:
|
|
4890
|
+
ahead = os.path.dirname(os.path.join(self.root, old_rel))
|
|
4891
|
+
new_rel = os.path.relpath(os.path.join(ahead, "%s.md" % node_id),
|
|
4892
|
+
self.root).replace("\\", "/")
|
|
4893
|
+
plan = {
|
|
4894
|
+
"ok": True, "dry_run": bool(dry_run), "node_id": node_id,
|
|
4895
|
+
"layer": layer, "tags": new_tags, "condition_space": cs,
|
|
4896
|
+
"depends_on": deps, "bucket": bucket,
|
|
4897
|
+
"from_path": old_rel, "to_path": new_rel,
|
|
4898
|
+
"moved": os.path.abspath(os.path.join(self.root, new_rel))
|
|
4899
|
+
!= os.path.abspath(os.path.join(self.root, old_rel)),
|
|
4900
|
+
"tags_changed": new_tags != tags,
|
|
4901
|
+
"cs_changed": cs != dict(fm.get("condition_space") or {}),
|
|
4902
|
+
}
|
|
4903
|
+
if dry_run:
|
|
4904
|
+
return plan
|
|
4905
|
+
# 走**同一条写链**(与 cg(op=write) 的元数据补丁路径同一实现):置
|
|
4906
|
+
# `_meta_patch` 后,正文闸/冲突闸/档位闸按「正文没变」放行,而层闸、
|
|
4907
|
+
# 写保护闸、换桶清理、索引 _stage 仍由既有单点负责。这样 admin 面的
|
|
4908
|
+
# maintain retag 与 token 面的 write 补丁行为一致,不会两条路两种结果。
|
|
4909
|
+
from .writepipe import default_pipeline
|
|
4910
|
+
_a = {"op": "write", "node_id": node_id, "layer": layer,
|
|
4911
|
+
"content": content, "tags": new_tags, "condition_space": cs,
|
|
4912
|
+
"_meta_patch": True}
|
|
4913
|
+
if deps is not None:
|
|
4914
|
+
_a["depends_on"] = deps
|
|
4915
|
+
_out = default_pipeline().execute(self, _a)
|
|
4916
|
+
plan["committed"] = bool((_out or {}).get("committed"))
|
|
4917
|
+
if not plan["committed"]:
|
|
4918
|
+
plan["ok"] = False
|
|
4919
|
+
plan["write_out"] = _out
|
|
4920
|
+
return plan
|
|
4921
|
+
|
|
4366
4922
|
def backfill_big_domain(self, dry_run: bool = False, limit: int = None) -> dict:
|
|
4367
4923
|
"""为缺 `big_domain` 的节点补域标签(S1 大域收敛的前置元数据;幂等)。
|
|
4368
4924
|
|
|
@@ -4660,36 +5216,246 @@ class MdCG:
|
|
|
4660
5216
|
parts = [str(v)]
|
|
4661
5217
|
return ";".join(parts)
|
|
4662
5218
|
|
|
5219
|
+
# 条件空间的槽标签 / 首尾标点**不在这里另立名字**:真源只有 nodefile 一处,
|
|
5220
|
+
# 本类通过 `nodefile.COND_SLOT_LABELS` / `nodefile.COND_EDGE_PUNCT` 直接引用。
|
|
5221
|
+
#
|
|
5222
|
+
# 为什么不保留 `MdCG._SLOT_LABELS` / `MdCG._EDGE_PUNCT` 这两个别名
|
|
5223
|
+
# (2026-11-02 review 后收敛):它们是**零读点**——委托化之后
|
|
5224
|
+
# `_cond_terms` / `_cond_terms_diag` 都直接调 nodefile,生产路径一次也不读;
|
|
5225
|
+
# `_EDGE_PUNCT` 连测试都没有。留着等于多出两个可漂移的入口名,
|
|
5226
|
+
# 与「单点收口」的主张自相矛盾。测试 L2 只验 `is` 同一性,
|
|
5227
|
+
# 那验的是「别名没被抄一份」,删掉别名后该断言自然失去对象,一并移除。
|
|
5228
|
+
#
|
|
5229
|
+
# 真源漂移守卫也不用类体 `assert`:`tuple(l for _k, l in CONDITION_SLOTS)`
|
|
5230
|
+
# 与 `COND_SLOT_LABELS` 两边都由 CONDITION_SLOTS 派生(见 nodefile 的
|
|
5231
|
+
# `COND_SLOT_LABELS = tuple(label for _key, label in CONDITION_SLOTS)`),
|
|
5232
|
+
# 恒真;且 `python -O` 会把它整个剥离,防护力为 0。真正有守卫价值的是
|
|
5233
|
+
# 「不是另抄一份」这件事,它已由 `COND_SLOT_LABELS` 的单一定义天然保证。
|
|
5234
|
+
|
|
5235
|
+
@staticmethod
|
|
5236
|
+
# 生效条件:cond_text 为假值时 terms 为空列表且各计数为 0;否则返回 nodefile.condition_terms_diag 的完整诊断字典(切分单点在 nodefile,本方法只是包内别名)。
|
|
5237
|
+
def _cond_terms_diag(cond_text: str):
|
|
5238
|
+
"""条件文本 → {terms, n_empty, n_digit, n_short,
|
|
5239
|
+
n_time_sentinel, n_decl_sentinel}。
|
|
5240
|
+
|
|
5241
|
+
**切分单点在 `nodefile.condition_terms_diag`**,本方法只是别名 ——
|
|
5242
|
+
早先 `nodefile.cond_terms` 是第二份实现、补丁后两份行为分叉,
|
|
5243
|
+
属潜伏风险(零调用点,未成当下缺陷)。改为单点后不可能再分叉。
|
|
5244
|
+
"""
|
|
5245
|
+
return nodefile.condition_terms_diag(cond_text)
|
|
5246
|
+
|
|
4663
5247
|
@staticmethod
|
|
4664
|
-
# 生效条件:cond_text
|
|
5248
|
+
# 生效条件:cond_text 为假值时按空串返回空列表;否则返回 nodefile.cond_terms 的短语列表(规则同 condition_terms_diag)。
|
|
4665
5249
|
def _cond_terms(cond_text: str):
|
|
4666
|
-
"""生效条件声明 → 匹配短语列表(确定性切分,无语义猜测)。
|
|
5250
|
+
"""生效条件声明 → 匹配短语列表(确定性切分,无语义猜测)。"""
|
|
5251
|
+
return nodefile.cond_terms(cond_text)
|
|
5252
|
+
|
|
5253
|
+
@staticmethod
|
|
5254
|
+
# 生效条件:term 为任意值、scene 为字符串;当 term 是「纯 ASCII 字母词」(api/app/core/UTC 这类)时按词边界匹配(左右不得紧邻其他 ASCII 字母),其余形态保持子串匹配;任一路径命中即返回 True。
|
|
5255
|
+
def _term_in_scene(term, scene: str) -> bool:
|
|
5256
|
+
"""条件短语是否在情境串里成立 —— ASCII 词按词边界,中文按子串。
|
|
5257
|
+
|
|
5258
|
+
为什么纯 ASCII 字母词必须走词边界(PR #735 head 实测):
|
|
5259
|
+
|
|
5260
|
+
"capital".find("api") == 1 ⇒ 子串命中,但问句讲的是「capital 结构」
|
|
5261
|
+
"mapping".find("app") == 1 ⇒ 子串命中,但问句讲的是「mapping 对不对」
|
|
5262
|
+
"score".find("core") == 4 ⇒ 子串命中,但问句讲的是「计算 score 的方式」
|
|
4667
5263
|
|
|
4668
|
-
|
|
4669
|
-
|
|
4670
|
-
|
|
4671
|
-
|
|
5264
|
+
条件文本里 `app`/`api`/`core` 来自 `backend/app/core/...`、
|
|
5265
|
+
`/api/uzi/...` 这类路径切开后的碎片;用子串匹配时,任何含这几个
|
|
5266
|
+
字母的词都会误命中,于是「条件未确认」被误判成「已确认」,节点被
|
|
5267
|
+
错误放行(PR #735 已把切分修好,这一类碎片因此才真正暴露出来)。
|
|
5268
|
+
|
|
5269
|
+
只对**纯 ASCII 字母词**收紧,中文仍走子串:中文没有词边界概念,
|
|
5270
|
+
且短语本身已是切分结果,再收紧会大面积漏命中;非字母 ASCII
|
|
5271
|
+
(`9:00` / `3:1` / `dsh-memory` 的连字符)也不收紧 —— 那不是
|
|
5272
|
+
「短词误咬」的形态。
|
|
5273
|
+
|
|
5274
|
+
归一与 `_term_in_scene_norm` 共用 `fold_for_match_keep`(#753/#755 复核);
|
|
5275
|
+
**循环内请改用 `_term_in_scene_norm` + 预归一场**,否则每个词项都会重算场景归一。
|
|
4672
5276
|
"""
|
|
4673
|
-
|
|
4674
|
-
|
|
4675
|
-
|
|
4676
|
-
|
|
4677
|
-
|
|
4678
|
-
|
|
4679
|
-
|
|
4680
|
-
|
|
4681
|
-
|
|
4682
|
-
|
|
4683
|
-
|
|
4684
|
-
|
|
4685
|
-
|
|
4686
|
-
|
|
4687
|
-
|
|
4688
|
-
|
|
5277
|
+
# 入口闸(fail-closed):归一化后场景会被 `str(text)` repr 化——
|
|
5278
|
+
# `["pe"]` → `"['pe']"`、`{"k":"pe"}` → `"{'k': 'pe'}"`。短词项恰好是
|
|
5279
|
+
# repr 的子串,判据就从「不命中」变成**静默 fail-open**(节点被错误判成
|
|
5280
|
+
# 「条件已确认」而 ACCEPT)。故显式只接受 str(None 按空串)。
|
|
5281
|
+
#
|
|
5282
|
+
# **不写成「base 一律 fail-loud」**(我曾这么写,是错的,2026-11-04 三树
|
|
5283
|
+
# 实测):base 只在词边界支抛 TypeError;子串支对容器**会径真**——
|
|
5284
|
+
# `_term_in_scene("估值", ["估值"])` 在 base 与 main 上都是 `True`
|
|
5285
|
+
# (`t in scene` 是 list 成员判断)。所以本闸相对 base 是**收紧**而非
|
|
5286
|
+
# 「保持原样」。生产路径不可达(`judge_qualification` 恒传 `json.dumps`
|
|
5287
|
+
# 的 str,真实库 886 节点 0 落点),取 fail-closed 是有意的代价,
|
|
5288
|
+
# 不是「与 base 等价」。
|
|
5289
|
+
if scene is not None and not isinstance(scene, str):
|
|
5290
|
+
return False
|
|
5291
|
+
return MdCG._term_in_scene_norm(term, MdCG._cond_scene_norm(scene))
|
|
5292
|
+
|
|
5293
|
+
@staticmethod
|
|
5294
|
+
# 生效条件:scene 为任意值(None 按空串)时返回三元组 _SceneNorm(compact, keep, raw)——紧凑归一串/保空白归一串/原文串;归一口径=fold_for_match_keep(fold_accents → routing.fold_variants)+ compact_exact_text 去空白,与 fold_for_match 同一份单点。
|
|
5295
|
+
def _cond_scene_norm(scene):
|
|
5296
|
+
"""场景串 → `_SceneNorm(compact, keep, raw)`(紧凑归一串 / 保空白归一串 / 原文串)。**一次归一,多处复用**。
|
|
5297
|
+
|
|
5298
|
+
`raw` 保留**未归一的原文**:base 的原文判定必须在原文上做(`_term_in_scene_norm`
|
|
5299
|
+
第一段按分支逐字复刻 base),不能拿归一串冒充。
|
|
5300
|
+
|
|
5301
|
+
为什么要拆出来:判据在一个节点的 5~6 个词项上**共用同一个场景串**,不拆就是
|
|
5302
|
+
同一份归一连算 6 遍(O(词项数) 倍;具体微秒数随机器与库规模而变,本条不做数字承诺)。
|
|
5303
|
+
不做 memo —— `routing.set_trad_to_simp()` 运行时可改繁简表,缓存会返回改表前的旧值。
|
|
5304
|
+
|
|
5305
|
+
归一链复用 `fold_for_match_keep`(#753/#755):顺序与 fold_for_match 逐字一致,
|
|
5306
|
+
不另拼第三份实现。
|
|
5307
|
+
"""
|
|
5308
|
+
keep = fold_for_match_keep(scene or "")
|
|
5309
|
+
return _SceneNorm(compact_exact_text(keep), keep, (scene or ""))
|
|
5310
|
+
|
|
5311
|
+
@staticmethod
|
|
5312
|
+
# 生效条件:term 为任意值、norm_scene 为 _cond_scene_norm 的返回值时,纯 ASCII 字母词按词边界(判在保空白串上)匹配、其余按紧凑串子串匹配;任一路径命中即 True。
|
|
5313
|
+
def _term_in_scene_norm(term, norm_scene) -> bool:
|
|
5314
|
+
"""条件短语是否在**已归一**的场景里成立(口径见 `_term_in_scene`)。
|
|
5315
|
+
|
|
5316
|
+
判据顺序(三步,**顺序本身是判据**):
|
|
5317
|
+
|
|
5318
|
+
① 先算 main 的判定(折叠路径)——main 说不命中,就保持不命中。
|
|
5319
|
+
#753 的 D9–D12 那类「子串→词边界」收紧是**有意**的
|
|
5320
|
+
(`data flow` 不该咬 `metadata flow`),本补丁不得撤销。
|
|
5321
|
+
② main 说命中时,再看 **base(#753 之前)在原文上**是否也命中。
|
|
5322
|
+
命中的是 base 本来就有的 → 原样放行(不新造召回损失)。
|
|
5323
|
+
③ 只有 base 不命中、main 命中 ⇒ 这次命中是**折叠新造**的,
|
|
5324
|
+
须过否定作用域闸(否则否定句被判成「条件已确认」)。
|
|
5325
|
+
|
|
5326
|
+
第 ③ 步是本补丁的全部内容。它只在「折叠改变了判定」时才生效,
|
|
5327
|
+
所以对 base 的存量判定与 main 的有意收紧都**零位移**。
|
|
5328
|
+
"""
|
|
5329
|
+
t = "" if term is None else str(term)
|
|
5330
|
+
if not t:
|
|
5331
|
+
return False
|
|
5332
|
+
t_keep = fold_for_match_keep(t)
|
|
5333
|
+
t_fold = compact_exact_text(t_keep)
|
|
5334
|
+
if not t_fold:
|
|
5335
|
+
return False
|
|
5336
|
+
|
|
5337
|
+
# ---- ① main 的判定(与 #753 合入后的实现逐字等价)-------------------
|
|
5338
|
+
if t_fold.isascii() and t_fold.isalpha():
|
|
5339
|
+
# 词边界必须判在**保空白**的归一串上:紧凑串把
|
|
5340
|
+
# `"fdata financials"` 拼成 `"fdatafinancials"`,再判「左右不得紧邻
|
|
5341
|
+
# ASCII 字母」就会把合法的 `fdata` 误杀。
|
|
5342
|
+
pat = (r"(?<![A-Za-z])"
|
|
5343
|
+
+ r"\s*".join(re.escape(p) for p in t_keep.split())
|
|
5344
|
+
+ r"(?![A-Za-z])")
|
|
5345
|
+
main_hit = re.search(pat, norm_scene.keep) is not None
|
|
5346
|
+
else:
|
|
5347
|
+
main_hit = t_fold in norm_scene.compact
|
|
5348
|
+
if not main_hit:
|
|
5349
|
+
# main 说不命中。但可能是**剥重音造出的假阴性**:`apiá` 归一成
|
|
5350
|
+
# `apia`,`api` 右侧凭空紧邻 ASCII 字母 ⇒ 折叠词边界崩掉;而原文里
|
|
5351
|
+
# `á` 不是 ASCII 字母,词边界成立(base 靠这一点命中)。
|
|
5352
|
+
#
|
|
5353
|
+
# 回填的**准入条件**:`t` 只由 ASCII 字母与空白组成。
|
|
5354
|
+
#
|
|
5355
|
+
# 为什么这一条就够:若 `t` 全是 ASCII 字母/空白,则 `t_keep` 相对 `t`
|
|
5356
|
+
# 只可能差在**大小写**,而词边界判的是 `[A-Za-z]` —— 大小写不改变
|
|
5357
|
+
# 边界结论。于是「原文判成立、折叠判不成立」只可能是**场景侧**折叠
|
|
5358
|
+
# (剥重音把 `á`→`a`)凭空造出了一个相邻字母 —— 正是要回填的那一类。
|
|
5359
|
+
#
|
|
5360
|
+
# 各类反例因此被自然排除:
|
|
5361
|
+
# · PE(D11)/Café(D12):**词项自己**被折叠改动,不是 ASCII
|
|
5362
|
+
# → 那条收紧是 #753 有意的,不回填。
|
|
5363
|
+
# · か / が(H5/H6,#659 不折叠假名):非 ASCII → 不回填。
|
|
5364
|
+
# · data flow vs metadata flow(D9):虽是 ASCII,但原文词边界
|
|
5365
|
+
# 本身不成立 → 下面的 `pat_raw` 拦掉。
|
|
5366
|
+
# · 大写 API / PE:ASCII 字母 → 照常回填(不能被大小写误伤)。
|
|
5367
|
+
#
|
|
5368
|
+
# **`pat_raw` 必须逐字连续,不许用 `\s*` 连接各词**:base 只对
|
|
5369
|
+
# `t.isalpha()`(无空白的纯字母)走词边界支,**含空格的 ASCII 短语
|
|
5370
|
+
# 走的是子串支 `t in scene`** —— 那要求逐字连续(单空格)。若这里用
|
|
5371
|
+
# `t.split()` + `\s*` 拼,就允许零个/多个/NBSP 空白,等于给多词词项
|
|
5372
|
+
# 换了一套**比 base 更宽**的判据。真实库 5 个多词纯 ASCII 词项上实测:
|
|
5373
|
+
# 'Connectionabortedé 说明' / 'Connection abortedé 说明' /
|
|
5374
|
+
# 'Connection\u00a0abortedé 说明' —— base=DEFER main=DEFER,
|
|
5375
|
+
# 用 `\s*` 时 v6=ACCEPT(凭空新造),逐字连续时回到 DEFER。
|
|
5376
|
+
# 单词项下 `re.escape(t)` 与原来的 `\s*` 拼法逐字等价。
|
|
5377
|
+
if t.isascii() and all(c.isalpha() or c.isspace() for c in t):
|
|
5378
|
+
pat_raw = (r"(?<![A-Za-z])" + re.escape(t) + r"(?![A-Za-z])")
|
|
5379
|
+
if re.search(pat_raw, norm_scene.raw) is not None:
|
|
5380
|
+
# 回填**不是放行证**:它恢复的只是「base 在原文上也认这一次」,
|
|
5381
|
+
# 而 base 的原文判定**没有**否定作用域这一层(那是负条件面独有)。
|
|
5382
|
+
# 故回填出的命中同样须过 ③,否则 `api` vs `不是 apiá 日志` 会出现
|
|
5383
|
+
# 「正说已确认、负说不成立」—— 相对 main **新造**两面分裂,方向还
|
|
5384
|
+
# 是放宽(ACCEPT)。实测:真实库纯 ASCII 词项 × 8 重音符 × 4 否定
|
|
5385
|
+
# 前缀 = 2528 格,不过闸时分裂率 100%;过闸后分裂 0,且肯定模板上
|
|
5386
|
+
# 召回损失 0(那些格 `_occ` 不在否定窗口内)。
|
|
5387
|
+
return MdCG._fold_hit_unnagated(norm_scene.compact, t_fold)
|
|
5388
|
+
return False
|
|
5389
|
+
|
|
5390
|
+
# ---- ② base(#753 之前)在**原文**上的判定 -------------------------
|
|
5391
|
+
# 这里用**子串**判,而不是复刻 base 的词边界分支 —— 两者在这一点上等价:
|
|
5392
|
+
# 走到这里说明 main_hit 已成立(对纯 ASCII 字母词是「判在 keep 上的词边界」
|
|
5393
|
+
# 成立)。若 `t` 在原文里只出现在词内部(`api` 之于 `capital`),那么归一串
|
|
5394
|
+
# 里同样在词内部(fold_accents 只会把字母并得更紧,不会拆开),main_hit
|
|
5395
|
+
# 就会是 False —— 走不到这里。故子串判与词边界判在此处不可区分。
|
|
5396
|
+
if t in norm_scene.raw:
|
|
5397
|
+
# issue #790(方案 C):原文命中不再**无条件**放行——只拦「否定词 + 虚化动词 + 宾语」
|
|
5398
|
+
# 这一支(未使用X / 未采用X / 没有使用X)。判据见 `_verb_negated_at`:它要求否定词与
|
|
5399
|
+
# 命中之间**含虚化动词字**,故 base 原有的「不是 PE」「不是 api」判定一字不动
|
|
5400
|
+
# (族枚举 recall_loss 2340 仍在保护之下;与折叠路径的 `_negated_at` 分开,不合并)。
|
|
5401
|
+
_occ_raw = _occurrences(norm_scene.compact, t_fold)
|
|
5402
|
+
if _occ_raw and all(_verb_negated_at(norm_scene.compact, i)
|
|
5403
|
+
for i in _occ_raw):
|
|
5404
|
+
return False
|
|
5405
|
+
return True
|
|
5406
|
+
|
|
5407
|
+
# ---- ③ 折叠新造出的命中:须过否定作用域闸 --------------------------
|
|
5408
|
+
return MdCG._fold_hit_unnagated(norm_scene.compact, t_fold)
|
|
5409
|
+
|
|
5410
|
+
@staticmethod
|
|
5411
|
+
# 生效条件:norm_compact 为紧凑归一串、t_fold 为词项紧凑归一串时,返回「该词面在串中无出现」或「存在至少一次出现未被否定词作用域覆盖」(与 neg_condition_hits 的 _negated_at 同源同判)。
|
|
5412
|
+
def _fold_hit_unnagated(norm_compact, t_fold) -> bool:
|
|
5413
|
+
"""**折叠**新认出的命中,须存在一次出现未被否定词覆盖。
|
|
5414
|
+
|
|
5415
|
+
为什么需要这一层:#753 统一的是**最外层**(字符归一),而
|
|
5416
|
+
`neg_condition_hits` 比正条件面还多三道闸 —— `NEG_MIN_TERM`、
|
|
5417
|
+
自主题豁免、**否定作用域 `_negated_at`**。于是折叠让正条件面认出 `pe`,
|
|
5418
|
+
而负条件面那一次命中正被「不是/不属于/没有」挡着:
|
|
5419
|
+
|
|
5420
|
+
base : (False, False) 一致,条件未确认 → DEFER
|
|
5421
|
+
修前 : (True , False) 正说「已确认」、负说「不适用不成立」⇒ 新造分裂
|
|
5422
|
+
|
|
5423
|
+
方向是**放宽**(把否定句判成「条件已确认」而 ACCEPT),与「修分裂」相反。
|
|
5424
|
+
真实库 24010 格(`reach_three.py`)实测:本闸挡回 1368 格
|
|
5425
|
+
`ACCEPT→DEFER`,且这 1368 格**全部**是 `pre753 != main`(#753 新造的)
|
|
5426
|
+
——`pre753 == main 且 main != patched` 的格数 = **0**,即本闸对存量
|
|
5427
|
+
判定零位移。
|
|
5428
|
+
|
|
5429
|
+
**只闸折叠路径**:base 的原文路径在调用点原样放行、一字不动。若连原文
|
|
5430
|
+
路径也闸,`new_split` 同样归零,但会把 base 本来就命中的 `不是 PE` /
|
|
5431
|
+
`不是 api` 一并收紧(族枚举 recall_loss 2340)——那是改 base 的判定,
|
|
5432
|
+
超出「字符归一」这条的范围。
|
|
5433
|
+
|
|
5434
|
+
已知同型缺口(本补丁不修):负条件面还有 `own_topic_text` 自主题豁免,
|
|
5435
|
+
正条件面没有。构造用例能让 base `DEFER → ACCEPT`,但真实库 886 个
|
|
5436
|
+
节点里「不适用条件条目**整条**落在自主题面」的格数为 0(2026-11-04
|
|
5437
|
+
实测;此前我写成 882,是笔误)。登记为已知同型缺口,**不是「已覆盖」**。
|
|
5438
|
+
|
|
5439
|
+
**`_occ` 恒非空(可证),故此处不再留「空则放行」的分支。**
|
|
5440
|
+
理由:两条到达本函数的路都保证 `t_fold` 是 `norm_compact` 的子串——
|
|
5441
|
+
· 路径 ②③(main_hit 为真):词边界支是「在 `keep` 上用 `\\s*` 连接各词
|
|
5442
|
+
命中」,空洞里只有空白,去掉空白后该词面在 `compact` 里连成一片;
|
|
5443
|
+
子串支本身就是 `t_fold in compact`。
|
|
5444
|
+
· 路径 ①b(main_hit 为假):前提是**原文** `raw` 上词边界成立,故
|
|
5445
|
+
`raw` 里含有 `t`;归一化逐字符进行、去空白不减内容,于是
|
|
5446
|
+
`fold(raw)` 含 `fold(t)`,`compact` 含 `t_fold`。
|
|
5447
|
+
实测 200000 组随机构造,`main_hit ∧ ¬raw ∧ _occ 空` = **0 格**。
|
|
5448
|
+
此前这里写「`_occ` 为空则放行,例如 `pe ratio` → 场景 `pe ratios`」——
|
|
5449
|
+
**理由是错的**:`pe ratio` 与 `pe ratios` 在 main 判定就**不命中**,
|
|
5450
|
+
根本到不了本函数。删代码而不是补断言。
|
|
5451
|
+
"""
|
|
5452
|
+
return any(not _negated_at(norm_compact, k)
|
|
5453
|
+
for k in _occurrences(norm_compact, t_fold))
|
|
4689
5454
|
|
|
4690
5455
|
@staticmethod
|
|
4691
5456
|
# 生效条件: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
|
|
5457
|
+
def judge_qualification(node_dict, query: str, context=None,
|
|
5458
|
+
strict_conditions: bool = True):
|
|
4693
5459
|
"""四态判定(白箱第 1/2 篇)。
|
|
4694
5460
|
|
|
4695
5461
|
输入:节点 + 查询 + 当前情境
|
|
@@ -4738,36 +5504,109 @@ class MdCG:
|
|
|
4738
5504
|
# 情境为空(无 query 且无 context)→ 无可判定依据,跳过本段不降级:
|
|
4739
5505
|
# 「无情境」不能被误判成「不适用」。
|
|
4740
5506
|
cond_hit = None
|
|
5507
|
+
relaxed = False # #722:未确认条件被放宽(state 仍 DEFER)
|
|
4741
5508
|
has_scene = bool((query or "").strip()) or bool(context)
|
|
5509
|
+
# 正条件段「跳过比对」的原因(review 5b 可观测性):不记录的话,
|
|
5510
|
+
# 「没写条件」「写了空值声明」「写了全时窗哨兵」三者在日志上完全同形。
|
|
5511
|
+
# 取值:None(没跳过)/ "no_condition"(没写)/ "sentinel_decl"(空值声明)/
|
|
5512
|
+
# "sentinel_time"(时间维全时窗)。
|
|
5513
|
+
exempt = None
|
|
4742
5514
|
if has_scene:
|
|
4743
5515
|
cond_text = MdCG._ccg_line(content, "生效条件")
|
|
4744
5516
|
if not cond_text and fm.get("condition_space"):
|
|
4745
5517
|
cond_text = nodefile.condition_space_text(fm["condition_space"])
|
|
4746
|
-
if cond_text
|
|
4747
|
-
|
|
4748
|
-
|
|
4749
|
-
|
|
4750
|
-
|
|
4751
|
-
|
|
4752
|
-
|
|
4753
|
-
|
|
5518
|
+
if not cond_text or cond_text.strip() == "无条件":
|
|
5519
|
+
exempt = "no_condition"
|
|
5520
|
+
else:
|
|
5521
|
+
diag = MdCG._cond_terms_diag(cond_text)
|
|
5522
|
+
terms_ = diag["terms"]
|
|
5523
|
+
if not terms_:
|
|
5524
|
+
# 「写了条件却切不出可用短语」≠「本来就没写条件」:
|
|
5525
|
+
# 后者跳过比对是对的,前者是条件不可用,不能静默放行。
|
|
5526
|
+
#
|
|
5527
|
+
# 但两类残段是**合法空值声明**,不是「切不出」:
|
|
5528
|
+
# · 时间维哨兵(全时窗/任意时刻)—— 文档口径「不因其未命中而降级」
|
|
5529
|
+
# · 空值语义哨兵(无/不适用)—— 「约束:无」声明的是「无约束」,
|
|
5530
|
+
# 是完整声明,不是坏条件(旧实现靠 len<2 把它静默滤掉,
|
|
5531
|
+
# 恰好得到 ACCEPT;本补丁若只用 len 判定会把它误判成 DEFER)
|
|
5532
|
+
# 判据是**析取式**:残段全部落在合法声明桶 → 豁免;
|
|
5533
|
+
# 只要有一段落在硬不可用桶(纯标点/纯数字/单字碎片)→ 不豁免。
|
|
5534
|
+
unusable = diag["n_empty"] + diag["n_digit"] + diag["n_short"]
|
|
5535
|
+
if not unusable:
|
|
5536
|
+
# 残段全部落在合法声明桶 -> 豁免。再按桶分因:
|
|
5537
|
+
# 时间维哨兵与空值语义哨兵是不同口径的声明,日志里必须分开。
|
|
5538
|
+
if diag["n_time_sentinel"] and not diag["n_decl_sentinel"]:
|
|
5539
|
+
exempt = "sentinel_time"
|
|
5540
|
+
else:
|
|
5541
|
+
exempt = "sentinel_decl"
|
|
5542
|
+
if unusable:
|
|
5543
|
+
bits = []
|
|
5544
|
+
if diag["n_empty"]:
|
|
5545
|
+
bits.append(f"纯标点 {diag['n_empty']}")
|
|
5546
|
+
if diag["n_digit"]:
|
|
5547
|
+
bits.append(f"纯数字 {diag['n_digit']}")
|
|
5548
|
+
if diag["n_short"]:
|
|
5549
|
+
bits.append(f"单字碎片 {diag['n_short']}")
|
|
5550
|
+
return {"state": STATE_DEFER,
|
|
5551
|
+
"reason": ("生效条件切不出可用短语("
|
|
5552
|
+
+ "、".join(bits)
|
|
5553
|
+
+ "):" + cond_text.strip()[:40]
|
|
5554
|
+
+ ";请改写为 2 字以上的实词短语")}
|
|
5555
|
+
else:
|
|
5556
|
+
# 命中判据统一走 _term_in_scene:纯 ASCII 字母词按词边界,
|
|
5557
|
+
# 其余按子串。直接 `t in scene_str` 会让 `api` 咬住
|
|
5558
|
+
# `capital`、`app` 咬住 `mapping`、`core` 咬住 `score`。
|
|
5559
|
+
# 场景归一**只算一次**(同一节点的所有词项共用一个场景串)
|
|
5560
|
+
_norm_scene = MdCG._cond_scene_norm(scene_str)
|
|
5561
|
+
cond_hit = next((t for t in terms_
|
|
5562
|
+
if MdCG._term_in_scene_norm(t, _norm_scene)), None)
|
|
5563
|
+
if cond_hit is None:
|
|
5564
|
+
if strict_conditions:
|
|
5565
|
+
return {"state": STATE_DEFER,
|
|
5566
|
+
"reason": ("生效条件未在情境确认(未命中任何声明条件:"
|
|
5567
|
+
+ "、".join(terms_[:3])
|
|
5568
|
+
+ ");可补充情境或条件词面后重判")}
|
|
5569
|
+
# issue #722(Q2=A):放宽**只到 usable**——state 仍是 DEFER,
|
|
5570
|
+
# 不稀释 ACCEPT=已确认 的语义;切不出可用短语不放宽(坏条件)。
|
|
5571
|
+
relaxed = True
|
|
4754
5572
|
|
|
4755
5573
|
# 4) DEFER:节点无 verification_basis → 信任根基不足
|
|
4756
5574
|
if not fm.get("verification_basis"):
|
|
4757
5575
|
return {"state": STATE_DEFER,
|
|
4758
5576
|
"reason": "未声明验证基底,需补充才能继续判定"}
|
|
4759
5577
|
|
|
5578
|
+
# 5) 放宽出口(#722 Q2=A):state 仍 DEFER,usable=True + code/relaxed 供下游分流。
|
|
5579
|
+
if relaxed:
|
|
5580
|
+
return {"state": STATE_DEFER,
|
|
5581
|
+
"code": "relaxed_condition",
|
|
5582
|
+
"condition_status": "unconfirmed",
|
|
5583
|
+
"relaxed": True,
|
|
5584
|
+
"usable": True,
|
|
5585
|
+
"reason": ("生效条件未在情境确认;strict_conditions=false 放宽:"
|
|
5586
|
+
"可参考使用,但未冒充已确认(原判 DEFER)")}
|
|
4760
5587
|
# 5) ACCEPT:默认——reason 诚实标注正条件是否经情境确认
|
|
4761
5588
|
acc = "5 要素齐全 + 不适用条件未命中 + 验证基底已声明"
|
|
4762
5589
|
if cond_hit:
|
|
4763
5590
|
acc = f"生效条件已确认(命中「{cond_hit}」)+ " + acc
|
|
4764
5591
|
elif not has_scene:
|
|
4765
5592
|
acc = "无情境可比(未做正条件确认)+ " + acc
|
|
5593
|
+
else:
|
|
5594
|
+
# 走到这里说明「有情境、但没命中任何短语」而仍然 ACCEPT。
|
|
5595
|
+
# 以前这条与「根本没写条件」共用同一句 reason,日志上无法区分
|
|
5596
|
+
# (2026-11-02 review 5b:本 PR 最该抓的可观测性缺口)。
|
|
5597
|
+
# 按 `exempt` 记录的**跳过原因**逐一分因——三种语义不能合并成一句。
|
|
5598
|
+
_EXEMPT_TEXT = {
|
|
5599
|
+
"no_condition": "未声明生效条件(跳过正条件比对)",
|
|
5600
|
+
"sentinel_decl": "生效条件为空值声明(已豁免)",
|
|
5601
|
+
"sentinel_time": "生效条件为时间维全时窗(已豁免)",
|
|
5602
|
+
}
|
|
5603
|
+
acc = _EXEMPT_TEXT.get(exempt, "生效条件未做正条件确认") + " + " + acc
|
|
4766
5604
|
return {"state": STATE_ACCEPT, "reason": acc}
|
|
4767
5605
|
|
|
4768
5606
|
# 生效条件: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
5607
|
@staticmethod
|
|
4770
|
-
def judge_with_boundary(node_dict, query: str, context=None
|
|
5608
|
+
def judge_with_boundary(node_dict, query: str, context=None,
|
|
5609
|
+
strict_conditions: bool = True) -> dict:
|
|
4771
5610
|
"""资格判定 + 拒绝域命中——**分开计数、分开呈现**(§5.2 / P0-4)。
|
|
4772
5611
|
|
|
4773
5612
|
返回形状(P2 的检索面直接消费)::
|
|
@@ -4816,10 +5655,12 @@ class MdCG:
|
|
|
4816
5655
|
qual = dict(MdCG.judge_qualification(
|
|
4817
5656
|
node_dict,
|
|
4818
5657
|
strip_boundary_terms(query, bh["terms"]) if suppressed else query,
|
|
4819
|
-
context
|
|
5658
|
+
context,
|
|
5659
|
+
strict_conditions=strict_conditions))
|
|
4820
5660
|
qual["boundary_suppressed"] = suppressed
|
|
4821
5661
|
# #362d 案②(零破坏子形态):另算一次**未摘词面**的判定作证据,见下方 reason 段。
|
|
4822
|
-
raw = (dict(MdCG.judge_qualification(node_dict, query, context
|
|
5662
|
+
raw = (dict(MdCG.judge_qualification(node_dict, query, context,
|
|
5663
|
+
strict_conditions=strict_conditions))
|
|
4823
5664
|
if suppressed else qual)
|
|
4824
5665
|
# 非边界问句下 raw 即 qual 本身,**不产生第二次判定**(默认口径零位移);
|
|
4825
5666
|
# 该证据只并入顶层 reason——键集与 state 一字不动,§5.2 的不变量保持成立;
|
|
@@ -4842,9 +5683,14 @@ class MdCG:
|
|
|
4842
5683
|
why += (";**摘词面前原判 %s**(查询逐字含本节点的拒绝域条目,该 REJECT "
|
|
4843
5684
|
"被边界问句的摘词面抑制;边界命中使其可召回可展示)"
|
|
4844
5685
|
% STATE_REJECT)
|
|
4845
|
-
|
|
4846
|
-
|
|
4847
|
-
|
|
5686
|
+
_q = {"state": qual.get("state"),
|
|
5687
|
+
"reason": qual.get("reason"),
|
|
5688
|
+
"boundary_suppressed": qual["boundary_suppressed"]}
|
|
5689
|
+
# issue #722:放宽标记必须随 qualification 透出(否则调用方只能看 reason 文案)。
|
|
5690
|
+
for _k in ("usable", "relaxed", "code", "condition_status"):
|
|
5691
|
+
if _k in qual:
|
|
5692
|
+
_q[_k] = qual[_k]
|
|
5693
|
+
return {"qualification": _q,
|
|
4848
5694
|
"boundary": {"hit": bh["hit"], "terms": bh["terms"],
|
|
4849
5695
|
"marker": bh["marker"], "reason": bh["reason"]},
|
|
4850
5696
|
"counts": counts, "recallable": recallable,
|
|
@@ -4858,7 +5704,8 @@ class MdCG:
|
|
|
4858
5704
|
include_neg: bool = True, judge: bool = True, pools=None,
|
|
4859
5705
|
session=None, branch=None, validity=None,
|
|
4860
5706
|
start_time=None, end_time=None, start_operator=None,
|
|
4861
|
-
end_operator=None, time_axis=None, view=None
|
|
5707
|
+
end_operator=None, time_axis=None, view=None,
|
|
5708
|
+
strict_conditions: bool = True):
|
|
4862
5709
|
"""返回 (results, meta)。results = [(node_dict, score, qualification)]。
|
|
4863
5710
|
|
|
4864
5711
|
validity:**只排除「已过期」(expired),不排除「未生效」(not_yet)**。
|
|
@@ -5100,7 +5947,8 @@ class MdCG:
|
|
|
5100
5947
|
if valid >= min_results:
|
|
5101
5948
|
return self._emit(scored, k, tier, stat, route_bucket, record,
|
|
5102
5949
|
len(docs), judge, context, neg_coverage,
|
|
5103
|
-
big_domain, big_scores, pool_cfg
|
|
5950
|
+
big_domain, big_scores, pool_cfg,
|
|
5951
|
+
strict_conditions=strict_conditions)
|
|
5104
5952
|
return None
|
|
5105
5953
|
|
|
5106
5954
|
# T0/T1:路由桶内
|
|
@@ -5295,7 +6143,8 @@ class MdCG:
|
|
|
5295
6143
|
self.record_access([r[0]["id"] for r in _merged[:k]], TIER_SPREAD)
|
|
5296
6144
|
return self._emit(_merged, k, TIER_SPREAD, stat, route_bucket,
|
|
5297
6145
|
record, len(_merged), judge, context,
|
|
5298
|
-
neg_coverage, big_domain, big_scores, pool_cfg
|
|
6146
|
+
neg_coverage, big_domain, big_scores, pool_cfg,
|
|
6147
|
+
strict_conditions=strict_conditions)
|
|
5299
6148
|
else:
|
|
5300
6149
|
gates["s3"] = {"seeds": len(_seeds), "expanded": 0,
|
|
5301
6150
|
"hops": _s3_hops, "reason": "no_edges"}
|
|
@@ -5333,7 +6182,8 @@ class MdCG:
|
|
|
5333
6182
|
scored = self._score(picked, q, qb, pool_cfg)
|
|
5334
6183
|
return self._emit(scored, k, TIER_GLOBAL_SCAN, stat, route_bucket,
|
|
5335
6184
|
record, len(picked), judge,
|
|
5336
|
-
context, neg_coverage, big_domain, big_scores, pool_cfg
|
|
6185
|
+
context, neg_coverage, big_domain, big_scores, pool_cfg,
|
|
6186
|
+
strict_conditions=strict_conditions)
|
|
5337
6187
|
|
|
5338
6188
|
# 生效条件:无条件按 hits 的 path 与 allowed 集合做双向邻接扩散(只读 index["nodes"] 的 edges/target,不读节点文件),
|
|
5339
6189
|
# hops<=0 或无命中/无 allowed 时返回 ({}, seeds);否则返回 ({被扩散节点 path: decay**跳数}, seeds),不含种子自身;
|
|
@@ -5655,7 +6505,7 @@ class MdCG:
|
|
|
5655
6505
|
# 生效条件: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
6506
|
def _emit(self, scored, k, tier, stat, bucket, record, candidates,
|
|
5657
6507
|
judge, context, neg_coverage, big_domain=None, big_scores=None,
|
|
5658
|
-
pools=None):
|
|
6508
|
+
pools=None, strict_conditions: bool = True):
|
|
5659
6509
|
# ---- S5 负记忆抑制(契约 §3 S5;flag 控、默认关)----
|
|
5660
6510
|
# 现状:rejected/unresolved 命中只会被「附加」到结果里(sensing),对正候选毫无影响。
|
|
5661
6511
|
# 这里把它变成**抑制信号**:与负记忆「边相邻」或「词面高度重叠」的正候选按
|
|
@@ -5829,7 +6679,8 @@ class MdCG:
|
|
|
5829
6679
|
for r in results:
|
|
5830
6680
|
if judge:
|
|
5831
6681
|
_jw = MdCG.judge_with_boundary(r[0], stat.get("query") or "",
|
|
5832
|
-
context
|
|
6682
|
+
context,
|
|
6683
|
+
strict_conditions=strict_conditions)
|
|
5833
6684
|
qual = dict(_jw["qualification"])
|
|
5834
6685
|
_b = boundary_mark(r[0], stat.get("query") or "", context)
|
|
5835
6686
|
if _b.get("hit"):
|
|
@@ -6109,22 +6960,110 @@ class MdCG:
|
|
|
6109
6960
|
"path": rel, "reason": reason}
|
|
6110
6961
|
|
|
6111
6962
|
# 生效条件: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;
|
|
6963
|
+
def _verify_superseded(self, node_id: str, node: dict, evidence: str,
|
|
6964
|
+
superseded_by: str = None,
|
|
6965
|
+
override: bool = False) -> dict:
|
|
6966
|
+
"""把节点标记为「已被新版本取代」(`lifecycle.superseded`)。
|
|
6967
|
+
|
|
6968
|
+
与 `falsified` 的关键区别:**不删除、不进 trash、不动 verification_state**。
|
|
6969
|
+
「它现在成不成立」与「它是否还是当前版本」是正交的两件事——前者归
|
|
6970
|
+
`trust.verification_state`,后者归 `lifecycle.lifecycle_state`。`superseded`
|
|
6971
|
+
早在 2026-10-18 就进了 lifecycle 状态机(`active/converged/demoted →
|
|
6972
|
+
superseded`,且 `superseded → active` 可回滚),并经 `is_retired()`
|
|
6973
|
+
退出默认检索面。缺的只是**工具面入口**,本函数补的就是这一环——不新增
|
|
6974
|
+
状态、不改判据、不复制第二份迁移表。
|
|
6975
|
+
|
|
6976
|
+
为何 superseded_by 必填而非用 override:护栏的目的不是「多按一次确认」,
|
|
6977
|
+
而是「取代关系要能指名替代者」。裸 override 允许随手退役;指名替代者
|
|
6978
|
+
则同时产出血缘与可追溯依据。
|
|
6979
|
+
"""
|
|
6980
|
+
by = str(superseded_by or "").strip()
|
|
6981
|
+
if not by:
|
|
6982
|
+
raise ValueError(
|
|
6983
|
+
"superseded 必须给 superseded_by=<取代它的节点 id>:"
|
|
6984
|
+
"取代关系要能指名替代者,空值等于「随手退役」")
|
|
6985
|
+
if by == node_id:
|
|
6986
|
+
raise ValueError("superseded_by 不能是节点自身")
|
|
6987
|
+
if not self.get(by):
|
|
6988
|
+
raise ValueError(
|
|
6989
|
+
"superseded_by 指向的节点不存在:%r(取代关系必须可追溯)" % by)
|
|
6990
|
+
fm = dict(node.get("frontmatter") or {})
|
|
6991
|
+
_orig_fm = dict(fm) # 回滚点(set_state 失败时还原)
|
|
6992
|
+
fm["superseded_by"] = by
|
|
6993
|
+
fm["superseded_at"] = time.time()
|
|
6994
|
+
# 先把「被谁取代」写进 fm,再走 lifecycle 的唯一推进入口(它会重读盘面
|
|
6995
|
+
# 再写一次,故顺序不能倒——先 set_state 后写 fm 会被覆盖回去)。
|
|
6996
|
+
self._write_node(node_id, os.path.join(self.root, node["path"]), fm,
|
|
6997
|
+
node.get("content") or "")
|
|
6998
|
+
# 保护位同样会拦「降级出去」(active→superseded 在 lifecycle._RANK 上加 3 档,
|
|
6999
|
+
# 被 is_downgrade 判为降级)。这里**自动带 override**,理由与 superseded_by
|
|
7000
|
+
# 必填是同一件事:护栏要防的是「随手丢弃」,不是「有序退役」——本操作不删
|
|
7001
|
+
# 数据、不改验证态、且 superseded→active 可回滚,同时必须指名替代者。
|
|
7002
|
+
# 强制情况回填进返回体(forced_protected),审计面看得见这一次是按保护位破的。
|
|
7003
|
+
# **两类更硬的保护不吃自动 override**(#742 复核):
|
|
7004
|
+
# · `immutable`:语义比 protected 更硬,退役必须显式声明;
|
|
7005
|
+
# · self/anchor 层:is_retired() 会让它退出默认检索面,等价于「软删出
|
|
7006
|
+
# 模型视野」——正是保护闸要防的效果,故必须显式 override。
|
|
7007
|
+
_immutable = bool(fm.get("immutable"))
|
|
7008
|
+
_layer = str(fm.get("layer") or node.get("layer") or "")
|
|
7009
|
+
if _immutable and not override:
|
|
7010
|
+
return {"action": "superseded", "ok": False, "error": "immutable",
|
|
7011
|
+
"superseded_by": by,
|
|
7012
|
+
"hint": "节点标记 immutable:退役必须显式 override=True"}
|
|
7013
|
+
if _layer in ("self", "anchor") and not override:
|
|
7014
|
+
return {"action": "superseded", "ok": False, "error": "protected_layer",
|
|
7015
|
+
"superseded_by": by,
|
|
7016
|
+
"hint": "self/anchor 层退役必须显式 override=True"
|
|
7017
|
+
"(自动 override 只覆盖 protected / importance 档)"}
|
|
7018
|
+
_prot = bool(fm.get("protected") or _immutable)
|
|
7019
|
+
_audit = (" [override:immutable]" if _immutable else
|
|
7020
|
+
(" [override:protected]" if _prot else ""))
|
|
7021
|
+
lc = lifecycle.set_state(
|
|
7022
|
+
self, node_id, "superseded",
|
|
7023
|
+
reason=f"被 {by} 取代:{str(evidence)[:80]}{_audit}",
|
|
7024
|
+
actor=getattr(self, "actor", None) or "verify:superseded",
|
|
7025
|
+
override=_prot)
|
|
7026
|
+
if not (lc or {}).get("ok"):
|
|
7027
|
+
# 原子性(#742 复核):set_state 失败 ⇒ 回滚已写进 fm 的两个键,
|
|
7028
|
+
# 不让盘面留下「有 superseded_by 但 lifecycle 仍是 active」的不自洽态。
|
|
7029
|
+
try:
|
|
7030
|
+
self._write_node(node_id, os.path.join(self.root, node["path"]),
|
|
7031
|
+
_orig_fm, node.get("content") or "")
|
|
7032
|
+
except Exception: # noqa: BLE001 —— 回滚失败不掩盖原始失败
|
|
7033
|
+
pass
|
|
7034
|
+
return {"action": "superseded", "ok": False,
|
|
7035
|
+
"superseded_by": by, "lifecycle": lc}
|
|
7036
|
+
try:
|
|
7037
|
+
propagation = trust.mark_dependents(
|
|
7038
|
+
self, node_id,
|
|
7039
|
+
reason=f"上游 {node_id} 已被 {by} 取代——引用方需复核是否仍以旧版为准",
|
|
7040
|
+
actor="verify:superseded", trigger="verify_superseded")
|
|
7041
|
+
except Exception: # noqa: BLE001 —— 传播失败不推翻已完成的退役
|
|
7042
|
+
propagation = {"ok": False, "changed": 0,
|
|
7043
|
+
"reason": "propagation_failed"}
|
|
7044
|
+
return {"action": "superseded", "ok": True, "superseded_by": by,
|
|
7045
|
+
"forced_protected": _prot, "lifecycle": lc,
|
|
7046
|
+
"propagation": propagation, "demoted": None}
|
|
7047
|
+
|
|
6112
7048
|
def verify(self, node_id: str, evidence: str, verdict: str,
|
|
6113
|
-
override: bool = False):
|
|
7049
|
+
override: bool = False, superseded_by: str = None):
|
|
6114
7050
|
"""验证单元(白箱第 3 篇第 13 章):对节点做一次外部验证裁决。
|
|
6115
7051
|
|
|
6116
|
-
verdict ∈ {"confirmed", "weakened", "falsified"}
|
|
7052
|
+
verdict ∈ {"confirmed", "weakened", "falsified", "superseded"}
|
|
6117
7053
|
- confirmed:positive_evidence+1,confidence 上调 +0.05
|
|
6118
7054
|
- weakened:negative_evidence+1,confidence 下调 -0.15(反例权重更大)
|
|
6119
7055
|
- falsified:节点移入 rejected/(幂等:相同 hypothesis 不重复);
|
|
6120
7056
|
受保护节点(self/anchor 层、protected 标记、importance≥0.7)
|
|
6121
7057
|
不可一键证伪删除——需显式 override=True(先快照+留痕)
|
|
7058
|
+
- superseded:**被新版本取代**(需 superseded_by=<替代者 id>)。与
|
|
7059
|
+
falsified 的区别是「不删除、不进 trash、不动 verification_state」:
|
|
7060
|
+
「还成不成立」归 trust,「是否还是当前版本」归 lifecycle,两者正交。
|
|
6122
7061
|
|
|
6123
7062
|
每次裁决累加 evidence_count(白箱第 5 篇第 4 章)。
|
|
6124
7063
|
weakened 后 confidence 跌破 DEMOTE_CONFIDENCE 且原属 knowledge 层 →
|
|
6125
7064
|
降级为 contextual(假设层),返回 demoted 审计记录。
|
|
6126
7065
|
"""
|
|
6127
|
-
if verdict not in ("confirmed", "weakened", "falsified"):
|
|
7066
|
+
if verdict not in ("confirmed", "weakened", "falsified", "superseded"):
|
|
6128
7067
|
raise ValueError(f"未知裁决:{verdict}")
|
|
6129
7068
|
node = self.get(node_id)
|
|
6130
7069
|
if not node:
|
|
@@ -6184,6 +7123,9 @@ class MdCG:
|
|
|
6184
7123
|
return {"action": "falsified", "new_id": None,
|
|
6185
7124
|
"evidence_count": None, "demoted": None,
|
|
6186
7125
|
"propagation": propagation}
|
|
7126
|
+
if verdict == "superseded":
|
|
7127
|
+
return self._verify_superseded(node_id, node, evidence,
|
|
7128
|
+
superseded_by, override=override)
|
|
6187
7129
|
# confirmed/weakened:调整 confidence(白箱第 5 篇:
|
|
6188
7130
|
# 反例的权重应该比正例大——这里用非对称步长实现)
|
|
6189
7131
|
fm = node["frontmatter"]
|
|
@@ -6228,7 +7170,7 @@ class MdCG:
|
|
|
6228
7170
|
# 搬过去的内容与回执同源(顺序依据见交付汇报)。
|
|
6229
7171
|
_land_fm()
|
|
6230
7172
|
demoted = self._move_layer(
|
|
6231
|
-
node_id, "contextual",
|
|
7173
|
+
node_id, "contextual", override=override,
|
|
6232
7174
|
reason=f"confidence {fm['confidence']} < {DEMOTE_CONFIDENCE}")
|
|
6233
7175
|
# 层降级 = 生命周期降级(②):knowledge→contextual 即 state→demoted。
|
|
6234
7176
|
# 受保护节点已被 `guard_move` 拦在上一层(走不到这里);此处仍按负路由
|
|
@@ -6243,17 +7185,30 @@ class MdCG:
|
|
|
6243
7185
|
# weakened → doubted(证据被削弱 ⇒ 存疑,待复核)
|
|
6244
7186
|
# 受保护节点不接受降级——负路由 ok=False 只说明「不可降」,不回滚已完成的
|
|
6245
7187
|
# 证据计数(与上方 lifecycle 降级同风格:不假装成功,也不推翻既成事实)。
|
|
7188
|
+
#
|
|
7189
|
+
# issue #733:`override` 必须透传到验证态推进。此前它只透传给了
|
|
7190
|
+
# falsified 分支的 `protect.guard_forget`,两条正常裁决分支整段没带。
|
|
7191
|
+
# 而它们落到的 `trust.set_state` → `stamp` 对**受保护节点**的降级迁移
|
|
7192
|
+
# 会直接拒绝(`ok=False, error="protected"`),提示语正是
|
|
7193
|
+
# 「确需降级请显式 override=True」——调用方照做却仍被拒 ⇒ 受保护节点的
|
|
7194
|
+
# weakened 裁决**永远无法生效**:回执 ok=False、verification_state 停在
|
|
7195
|
+
# 原值,而 confidence / evidence_count / evidence_log 已按 weakened 扣减
|
|
7196
|
+
# 并落盘,形成「证据记了、结论没落地」的盘面不自洽态。
|
|
7197
|
+
# 该面与 falsified 分支同属「verify 覆盖受保护节点」的唯一合法通路,
|
|
7198
|
+
# 故 override 在两条分支同源透传(缺省 False,既有调用方行为逐位不变)。
|
|
6246
7199
|
if verdict == "confirmed":
|
|
6247
7200
|
ver = self.set_verification(
|
|
6248
7201
|
node_id, "verified",
|
|
6249
7202
|
reason=f"外部裁决 confirmed:{str(evidence)[:80]}",
|
|
6250
7203
|
actor="verify:confirmed", evidence=evidence,
|
|
6251
|
-
method=fm.get("verification_basis"), trigger="verify"
|
|
7204
|
+
method=fm.get("verification_basis"), trigger="verify",
|
|
7205
|
+
override=override)
|
|
6252
7206
|
else:
|
|
6253
7207
|
ver = self.set_verification(
|
|
6254
7208
|
node_id, "doubted",
|
|
6255
7209
|
reason=f"外部裁决 weakened:{str(evidence)[:80]}",
|
|
6256
|
-
actor="verify:weakened", evidence=evidence, trigger="verify"
|
|
7210
|
+
actor="verify:weakened", evidence=evidence, trigger="verify",
|
|
7211
|
+
override=override)
|
|
6257
7212
|
# 结论已变 ⇒ 下游的「地基动了」:同步一跳传播(永不抛,降级不阻断)
|
|
6258
7213
|
propagation = trust.mark_dependents(
|
|
6259
7214
|
self, node_id, reason=f"上游验证结论变为 {verdict}",
|