@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.
Files changed (179) hide show
  1. package/CHANGELOG.en.md +450 -0
  2. package/CHANGELOG.md +112 -0
  3. package/README.en.md +244 -0
  4. package/README.md +272 -260
  5. package/codebuddy/CODEBUDDY.md +1 -1
  6. package/docs/README.md +2 -0
  7. package/docs/discipline/templates/full.md.tmpl +1 -1
  8. package/docs/discipline/templates/rules.mdc.tmpl +1 -1
  9. package/docs/en/README.md +190 -0
  10. package/docs/en/TRANSLATION.md +78 -0
  11. package/docs/en/TRANSLATION_MANIFEST.json +170 -0
  12. package/docs/en/TRANSLATION_REPORT.md +11 -0
  13. package/docs/en/dev/README.md +10 -0
  14. package/docs/en/dev/coding-testing.md +72 -0
  15. package/docs/en/dev/switch-matrix.md +10 -0
  16. package/docs/en/glossary.md +97 -0
  17. package/docs/en/harnesses/claude.md +100 -0
  18. package/docs/en/harnesses/codebuddy.md +93 -0
  19. package/docs/en/harnesses/codex.md +88 -0
  20. package/docs/en/harnesses/dsh.md +84 -0
  21. package/docs/en/harnesses/zcode.md +42 -0
  22. package/docs/en/mdcg/ccg.md +32 -0
  23. package/docs/en/mdcg/generated-docs.md +20 -0
  24. package/docs/en/mdcg/guardrail-charter.md +170 -0
  25. package/docs/en/mdcg/mcp-tool-names.md +43 -0
  26. package/docs/en/mdcg/multi-harness.md +43 -0
  27. package/docs/en/mdcg/recall-metadata.md +30 -0
  28. package/docs/en/mdcg/world-model-endpoint.md +379 -0
  29. package/docs/en/mdcg/write-aliases.md +130 -0
  30. package/docs/en/ops/README.md +11 -0
  31. package/docs/en/ops/environment-known-issues.md +244 -0
  32. package/docs/en/ops/install.md +72 -0
  33. package/docs/en/ops/operations-troubleshooting.md +86 -0
  34. package/docs/en/ops/permissions-review.md +79 -0
  35. package/docs/en/ops/release-governance.md +49 -0
  36. package/docs/en/ops/tool-name-migration.md +30 -0
  37. package/docs/en/ops/ui-install-troubleshooting.md +53 -0
  38. package/docs/en/standards/ai-coding-standard-checklist.md +71 -0
  39. package/docs/en/standards/ai-coding-standard-lingshu.md +47 -0
  40. package/docs/en/standards/ai-coding-standard.md +185 -0
  41. package/docs/en/ui/minimal.md +62 -0
  42. package/docs/mdcg/cogmap_ops.md +16 -15
  43. package/lib/client.js +29 -3
  44. package/lib/hooks.d.ts +34 -0
  45. package/lib/hooks.js +167 -33
  46. package/lib/index.js +19 -3
  47. package/lib/lib/console_web.mjs +30 -3
  48. package/lib/lib/hook_audit.d.ts +3 -2
  49. package/lib/lib/hook_audit.js +14 -4
  50. package/lib/lib/mdcg_client.d.ts +5 -2
  51. package/lib/lib/mdcg_client.js +8 -4
  52. package/lib/lib/prompt_safety.d.ts +24 -0
  53. package/lib/lib/prompt_safety.js +77 -1
  54. package/lib/lib/token_store.js +5 -2
  55. package/lib/tools.js +5 -3
  56. package/md_cg/bucketindex.py +231 -0
  57. package/md_cg/bucketscope.py +339 -0
  58. package/md_cg/config_registry_bulk.py +19 -10
  59. package/md_cg/config_validate.py +14 -2
  60. package/md_cg/detrerank.py +137 -0
  61. package/md_cg/fsutil.py +215 -25
  62. package/md_cg/govern/__init__.py +23 -0
  63. package/md_cg/iface/__init__.py +46 -0
  64. package/md_cg/iface/_verify.py +609 -0
  65. package/md_cg/iface/contracts.py +337 -0
  66. package/md_cg/judgment_manifest.py +14 -0
  67. package/md_cg/kernel/__init__.py +27 -0
  68. package/md_cg/mcp_server.py +457 -23
  69. package/md_cg/mdcg.py +1034 -79
  70. package/md_cg/mdcos.py +263 -21
  71. package/md_cg/metacognition.py +66 -13
  72. package/md_cg/mutate_extract_shipped.py +126 -0
  73. package/md_cg/mutate_ledger_e2e.py +100 -0
  74. package/md_cg/nodefile.py +147 -23
  75. package/md_cg/op_table.py +22 -4
  76. package/md_cg/probe_c_ledger_integrity.py +258 -0
  77. package/md_cg/probe_d_retirement_discipline.py +263 -0
  78. package/md_cg/reconcile.py +9 -11
  79. package/md_cg/review_cli.py +6 -1
  80. package/md_cg/rollback.py +16 -1
  81. package/md_cg/run_tests.py +30 -1
  82. package/md_cg/scopeselect.py +214 -0
  83. package/md_cg/scrub.py +160 -23
  84. package/md_cg/security.py +4 -2
  85. package/md_cg/state_extract.py +149 -0
  86. package/md_cg/state_slots.py +58 -10
  87. package/md_cg/structboost.py +179 -0
  88. package/md_cg/test_alternatives_historical.py +162 -0
  89. package/md_cg/test_b2_sensitivity_landing.py +226 -223
  90. package/md_cg/test_b3_merge_keeps_content.py +608 -583
  91. package/md_cg/test_bucket_cards.py +85 -0
  92. package/md_cg/test_bucket_day_order.py +74 -0
  93. package/md_cg/test_bucket_quota.py +79 -0
  94. package/md_cg/test_bucket_recency_guards.py +75 -0
  95. package/md_cg/test_bucket_three_causes.py +83 -0
  96. package/md_cg/test_bucketindex.py +130 -0
  97. package/md_cg/test_bucketscope_early.py +71 -0
  98. package/md_cg/test_cond_term_fold.py +183 -0
  99. package/md_cg/test_cond_term_fold_gate.py +1210 -0
  100. package/md_cg/test_cond_term_neg_scope.py +147 -0
  101. package/md_cg/test_cond_terms_colon.py +348 -0
  102. package/md_cg/test_detrerank.py +157 -0
  103. package/md_cg/test_gate_four_kpi.py +136 -0
  104. package/md_cg/test_generation_guard.py +76 -43
  105. package/md_cg/test_issue192_move_layer_indices_guard.py +48 -0
  106. package/md_cg/test_issue362_neg_condition.py +44 -7
  107. package/md_cg/test_issue39_utf8_stdio.py +572 -572
  108. package/md_cg/test_issue413_preimage_failclosed.py +147 -9
  109. package/md_cg/test_issue444_scrub_evidence_plaintext.py +14 -8
  110. package/md_cg/test_issue677_flush_batch_io.py +139 -0
  111. package/md_cg/test_issue677_info_fast.py +82 -0
  112. package/md_cg/test_issue677_remember_dedupe.py +106 -0
  113. package/md_cg/test_issue712_tokens_sessions_read.py +199 -0
  114. package/md_cg/test_issue722_strict_conditions.py +96 -0
  115. package/md_cg/test_issue730_narrowing_audit.py +121 -0
  116. package/md_cg/test_issue733_verify_override.py +193 -0
  117. package/md_cg/test_issue733_verify_override_and_overwrite_inherit.py +315 -0
  118. package/md_cg/test_issue740_filelock_fd_leak.py +218 -0
  119. package/md_cg/test_issue741_content_hash_same_source.py +158 -0
  120. package/md_cg/test_issue747_slot_contradiction.py +125 -0
  121. package/md_cg/test_issue754_nested_root_guard.py +197 -0
  122. package/md_cg/test_issue757_index_hash_compare.py +85 -0
  123. package/md_cg/test_issue758_disk_hash_single.py +67 -0
  124. package/md_cg/test_issue759_twophase_hash.py +67 -0
  125. package/md_cg/test_issue768_overwrite_time_window_anchor.py +135 -0
  126. package/md_cg/test_issue789_log_plaintext_probe.py +100 -0
  127. package/md_cg/test_issue790_verb_negation.py +77 -0
  128. package/md_cg/test_issue810_root_guard.py +71 -0
  129. package/md_cg/test_issue812_info_index_stale.py +78 -0
  130. package/md_cg/test_issue827_weaken_dedup.py +361 -0
  131. package/md_cg/test_issue829_calibration_positive_gate.py +473 -0
  132. package/md_cg/test_kernel_iface_contracts.py +18 -0
  133. package/md_cg/test_md_cg_no_hive_dep.py +238 -17
  134. package/md_cg/test_n204_n205_n226_n227_n228_n229_exit_gates.py +545 -542
  135. package/md_cg/test_n209_verify_write_face_gates.py +5 -2
  136. package/md_cg/test_neg_condition_hits.py +336 -333
  137. package/md_cg/test_probe_cd_shipped.py +385 -0
  138. package/md_cg/test_recent_tail.py +93 -0
  139. package/md_cg/test_run_tests_entry_gates.py +110 -0
  140. package/md_cg/test_scopeselect.py +70 -0
  141. package/md_cg/test_scopeselect_clock.py +70 -0
  142. package/md_cg/test_scrub_source_line_false_positive.py +64 -0
  143. package/md_cg/test_session_attribution_consistency.py +835 -813
  144. package/md_cg/test_state_extract_shipped.py +162 -0
  145. package/md_cg/test_state_ledger_chain.py +207 -0
  146. package/md_cg/test_state_ledger_e2e.py +145 -0
  147. package/md_cg/test_structboost.py +102 -0
  148. package/md_cg/test_timeboost.py +83 -0
  149. package/md_cg/test_timeboost_relativedate.py +71 -0
  150. package/md_cg/test_topicagg.py +129 -0
  151. package/md_cg/test_twophase.py +286 -286
  152. package/md_cg/timeboost.py +223 -0
  153. package/md_cg/tokens.py +55 -7
  154. package/md_cg/topicagg.py +142 -0
  155. package/md_cg/twophase.py +15 -6
  156. package/md_cg/whitebox_kb/wisdom/code_compose.py +33 -5
  157. package/md_cg/whitebox_kb/wisdom/compose_engine.py +5 -1
  158. package/md_cg/whitebox_kb/wisdom/role_compose.py +271 -268
  159. package/md_cg/writepipe.py +35 -3
  160. package/package.json +4 -1
  161. package/scripts/workspace_index.py +2 -0
  162. package/src/hooks.ts +182 -34
  163. package/src/index.ts +19 -3
  164. package/src/lib/console_web.mjs +30 -3
  165. package/src/lib/hook_audit.ts +15 -5
  166. package/src/lib/mdcg_client.ts +8 -4
  167. package/src/lib/prompt_safety.ts +73 -1
  168. package/src/lib/token_store.ts +5 -2
  169. package/src/tools.ts +5 -3
  170. package/ui/minimal/integrity.json +2 -2
  171. package/ui/minimal/payload/build-ui.mjs +41 -2
  172. package/ui/minimal/payload/lib/client.js +29 -3
  173. package/ui/minimal/payload/lib/lib/console_web.mjs +30 -3
  174. package/ui/minimal/payload/src/lib/console_web.mjs +30 -3
  175. package/ui/minimal/payload/web/app.js +3 -1
  176. package/ui/minimal/payload/web/client.js +30 -3
  177. package/web/app.js +3 -1
  178. package/web/client.js +30 -3
  179. package/zcode/AGENTS.md +1 -1
@@ -175,6 +175,102 @@ def _note_doc_filter(meta, dropped, enabled):
175
175
  return meta
176
176
 
177
177
 
178
+ def norm_tags(value):
179
+ """#721:把调用方给的标签入参规范化成 tuple。
180
+
181
+ 判据(与 op_table.read.params 的注释同一真源,改一处须改两处):
182
+ · None / 缺省 / 空容器 => () —— 调用方「没提这个维度」,不是「要空集」
183
+ · 单个 str => (str,) —— 允许省略列表,避免调用方为一个标签写数组
184
+ · list/tuple/set => 逐项转 str 后去重保序
185
+ · 其他(int/dict/…) => TypeError —— 显式报错,不静默当没传
186
+ """
187
+ if value is None:
188
+ return ()
189
+ if isinstance(value, str):
190
+ v = value.strip()
191
+ return (v,) if v else ()
192
+ if isinstance(value, (list, tuple, set, frozenset)):
193
+ out = []
194
+ for it in value:
195
+ if not isinstance(it, str):
196
+ raise TypeError("标签必须是字符串,收到 %s" % type(it).__name__)
197
+ s = it.strip()
198
+ if s and s not in out:
199
+ out.append(s)
200
+ return tuple(out)
201
+ raise TypeError("标签入参必须是字符串或字符串列表,收到 %s" % type(value).__name__)
202
+
203
+
204
+ def filter_by_tags(items, tags_of, include_tags=(), exclude_tags=()):
205
+ """#721:按标签过滤检索结果(域隔离)。
206
+
207
+ 语义(三条判据,显式声明,与 issue #721 的建议一致):
208
+ · 多标签 = **OR**:命中所给任一标签即命中(include 保留 / exclude 剔除);
209
+ · 匹配 = **全等**:不做前缀、不做大小写折叠以外的归一(见 _fold);
210
+ · 无匹配 = **返回空集,不报错**:空集是合法检索答案,不是异常。
211
+ 优先级:**exclude 先于 include** —— 同一节点两边都命中时被剔除。
212
+ 缺省(两个都为空)=> 原样返回且 dropped=0,调用方行为逐位不变。
213
+ """
214
+ inc = tuple(include_tags or ())
215
+ exc = tuple(exclude_tags or ())
216
+ if not inc and not exc:
217
+ return items, 0
218
+ kept = []
219
+ dropped = 0
220
+ for it in items or []:
221
+ tags = set(tags_of(it) or ())
222
+ if exc and tags & set(exc):
223
+ dropped += 1
224
+ continue
225
+ if inc and not (tags & set(inc)):
226
+ dropped += 1
227
+ continue
228
+ kept.append(it)
229
+ return kept, dropped
230
+
231
+
232
+ def _note_tag_filter(meta, dropped, include_tags, exclude_tags):
233
+ """#721:把标签过滤读数体现在 meta 上(不静默吞掉筛掉的条数)。"""
234
+ if not isinstance(meta, dict):
235
+ meta = {}
236
+ else:
237
+ meta = dict(meta)
238
+ meta["include_tags"] = list(include_tags or ())
239
+ meta["exclude_tags"] = list(exclude_tags or ())
240
+ meta["tag_filtered"] = dropped
241
+ return meta
242
+
243
+
244
+ def tags_of_item(cg, item):
245
+ """#721:取一条结果所属节点的标签集合。
246
+
247
+ 先看结果自带的(search 面的 node dict / recall 面的 pack 条目),缺了才回库取一次。
248
+ 回库失败按「无标签」处理而**不抛**:读面不该因为一次 tags 查询炸掉整次检索
249
+ ——失败读数会体现在 meta.tag_filtered 上,而不是静默。
250
+ """
251
+ if isinstance(item, (list, tuple)): # search 面: (node, score, qual)
252
+ item = item[0] if item else None
253
+ if not isinstance(item, dict):
254
+ return ()
255
+ fm = item.get("frontmatter")
256
+ if isinstance(fm, dict) and fm.get("tags") is not None:
257
+ return fm.get("tags") or ()
258
+ if item.get("tags") is not None:
259
+ return item.get("tags") or ()
260
+ nid = item.get("id") or item.get("node_id")
261
+ if nid and cg is not None:
262
+ try:
263
+ node = cg.get(nid)
264
+ except Exception: # noqa: BLE001 —— 见 docstring
265
+ node = None
266
+ if isinstance(node, dict):
267
+ nfm = node.get("frontmatter")
268
+ if isinstance(nfm, dict):
269
+ return nfm.get("tags") or ()
270
+ return node.get("tags") or ()
271
+ return ()
272
+
273
+
178
274
  def _p(t, desc, req=False, **extra):
179
275
  d = {"type": t, "description": desc}
180
276
  if req:
@@ -239,6 +335,9 @@ TOOLS = [
239
335
  tags=_p("array", "标签"), importance=_p("number", "重要性 0-1"),
240
336
  importance_hint=_p("number", "闸门的重要性提示(≥0.7 保护优先直接 ACCEPT)"),
241
337
  gated=_p("boolean", "启用主动遗忘闸门(默认否;写情景层建议开)"),
338
+ dedupe=_p("boolean", "写入幂等(issue #677,缺省 false):同层已存在内容指纹"
339
+ "相同的节点时不新增,直接返回既有 id 且 deduped=true。"
340
+ "用于「调用超时但可能已落盘」的重试(自动记忆面同样适用)"),
242
341
  override=_p("boolean", "覆盖受保护节点需显式 true"),
243
342
  consistency=_p("boolean", "写入前节点间自动冲突检测(三级决策,默认 true)"),
244
343
  on_conflict=_p("string", "冲突处置:reject(默认,抛错)|defer(不写)|record(记录放行)"),
@@ -275,6 +374,11 @@ TOOLS = [
275
374
  exclude_doc=_p("boolean", "检索面排除 doc_ 索引节点(会话日志切片;"
276
375
  "默认 false = 保持既有契约——test_p27_docindex ⑤ 断言"
277
376
  "文档节点必须可被检索到;需要「只看真记忆卡」的调用方显式传 true)"),
377
+ # issue #721(#802):op_table 的 read 面登记了这两个参数,但 cg 的
378
+ # schema 里没有 ⇒ check_op_table_parity 判「幻影参数」,并连带让
379
+ # test_issue153b / test_issue71 的跨面对账红。此处补齐。
380
+ include_tags=_p("array", "issue #721:检索期按标签过滤——只保留含任一标签的节点"),
381
+ exclude_tags=_p("array", "issue #721:检索期按标签过滤——剔除含任一标签的节点"),
278
382
  expand=_p("array", "LLM 查询侧扩展词:[{term,weight}] 或 [\"词\"];"
279
383
  "仅在查询时刻生效,索引侧仍白箱"),
280
384
  session=_p("string", "会话归属过滤(frontmatter.session;"
@@ -798,15 +902,31 @@ KERNEL_TOOLS = [
798
902
  "receipt(回执审计:命令与预期输出);"
799
903
  "非法值库层报错(fail-closed)"),
800
904
  budget_tokens=_p("integer", "read 的 token 预算"),
801
- exclude_doc=_p("boolean", "检索面排除 doc_ 索引节点(会话日志切片;"
905
+ # issue #722:工具面缺省 false=放宽(库面默认严格)。
906
+ strict_conditions=_p("boolean", "条件闸门严格度(**缺省 false=放宽**:"
907
+ "生效条件未在情境确认时仍标 usable,但 state 保持"
908
+ "DEFER、不冒充已确认;传 true 回严格闸门)"), exclude_doc=_p("boolean", "检索面排除 doc_ 索引节点(会话日志切片;"
802
909
  "默认 false = 保持既有契约——test_p27_docindex 断言"
803
910
  "文档节点必须可被检索到;需要只看真记忆卡时显式传 true)"),
911
+ # issue #721(#802):op_table 的 read 面登记了 include_tags/exclude_tags,
912
+ # 但 cg 的 schema 里没有 ⇒ check_op_table_parity 判「幻影参数」,
913
+ # 并连带 test_issue153b / test_issue71 的跨面对账红。此处补齐。
914
+ include_tags=_p("array", "issue #721:检索期按标签过滤——只保留含任一标签的节点"),
915
+ exclude_tags=_p("array", "issue #721:检索期按标签过滤——剔除含任一标签的节点"),
804
916
  excerpt_strategy=_p("string", "read 超预算条目摘录方式:prefix(默认)或 query(查询相关原文片段)"),
805
917
  bm25=_p("boolean", "read:显式使用 BM25 倒排评分(默认否)"),
806
918
  evidence=_p("string", "verify 的证据;state_event:出处(五元之一,"
807
919
  "回指原文/轮次)"),
808
- verdict=_p("string", "verify 裁决:confirmed|weakened|falsified;"
920
+ verdict=_p("string", "verify 裁决:confirmed|weakened|falsified"
921
+ "|superseded(superseded=被新版本取代:不删除、"
922
+ "不动验证态,需同时给 superseded_by);"
809
923
  "insight verify:verified|falsified"),
924
+ superseded_by=_p("string", "verify verdict=superseded 时必填:"
925
+ "取代它的节点 id"),
926
+ tags_add=_p("array", "maintain retag:要新增的标签(含 domain:<域>)"),
927
+ tags_remove=_p("array", "maintain retag:要移除的标签"),
928
+ condition_space_patch=_p("object", "maintain retag:条件空间补丁"
929
+ "(浅合并,如 observation_position)"),
810
930
  question=_p("string", "whitebox:ask/verify 的问题"),
811
931
  message=_p("string", "whitebox ask:问题(question 的别名)"),
812
932
  session_id=_p("string", "whitebox:会话 id(默认 md_cg-whitebox-verify)"),
@@ -865,6 +985,8 @@ KERNEL_TOOLS = [
865
985
  reason=_p("string", "原因;consolidate contextualize 的归位理由(写台账)"),
866
986
  force=_p("boolean", "restore 强制(忽略前置条件:墓碑等)"),
867
987
  overwrite_live=_p("boolean", "restore 覆写同 id 在位节点需显式确认(#426-E,默认 False)"),
988
+ full=_p("boolean", "info:全量诊断(健康/理论/链接/代校验/策略自描述)。缺省 false = 只回内存态快照"
989
+ "(issue #677:大库上慢诊断面会让 info 本身超时)"),
868
990
  path=_p("string", "index_code/index_doc 的目录(大域);link import 的证据包文件"),
869
991
  patterns=_p("array", "index_code/index_doc 的文件后缀,默认取各自注册表"
870
992
  "(代码 .py/.ts/.tsx/.js/.mjs/.cjs;文档 .md/.markdown)"),
@@ -884,6 +1006,7 @@ KERNEL_TOOLS = [
884
1006
  incremental=_p("boolean", "index_code/index_doc:按 _refindex.json 水位跳过"
885
1007
  "未变文件(默认否=全量重切,保证不漏召回);"
886
1008
  "传 sensitivity 覆盖时自动退回全量"),
1009
+ allow_nested=_p("boolean", "index_code/index_doc:显式允许与已索引根互相嵌套(issue #754);默认拒绝——同一物理文件会因「相对 root 的 path」不同而生成两套节点"),
887
1010
  max_nodes=_p("integer", "ref action=check:最多巡检节点数(默认 2000,"
888
1011
  "越限返回 truncated=true)"),
889
1012
  sensitivity=_p("string", "密级声明:index_doc 的节点密级(默认 internal 并显式"
@@ -915,7 +1038,8 @@ KERNEL_TOOLS = [
915
1038
  "(仅重要性重算;固化需 LLM 仍交人工。默认否)"),
916
1039
  allow_evolve=_p("boolean", "sustain heal:放行演化类修复"
917
1040
  "(确定性动作才执行;默认否)"),
918
- dry_run=_p("boolean", "sustain heal / scrub:只列动作不落盘"),
1041
+ dry_run=_p("boolean", "sustain heal / scrub:只列动作不落盘;"
1042
+ "maintain retag:只算不写(缺省沿用 apply 口径)"),
919
1043
  ids=_p("array", "scrub:节点 id 列表(缺省全库)"),
920
1044
  kinds=_p("string", "scrub:限定污染类型,逗号分隔"),
921
1045
  strategy=_p("string", "scrub sample:stratified|risk|random"),
@@ -2012,6 +2136,11 @@ def _action_sig(a, op):
2012
2136
 
2013
2137
 
2014
2138
  # 生效条件:op0=(a.get("op") or "").strip().lower(),op0 为空时按 a.get("content")→"write"、a.get("query") 或 a.get("node_id")→"read"、a.get("intent")→"route"、都无→"read" 推导 op;act0=(args.get("action") or "").strip().lower(),act0 为空时用 _action_sig(args, op) 推导且推导出时写回 args["action"];另恒定计算 act_source(explicit|sig|default|none);args["op"]=op 后调 _cg_dispatch,返回 dict 且 op0 为空时补 out["op"]、out["op_derived"]=True 与 hint,**无条件** setdefault out["action_source"]=act_source,act0 为空且 (act_derived 或 op in _ACTION_DEFAULT) 时 setdefault("action", eff)、out["action_derived"]=True 并按是否有 act_derived 写 hint_action。
2139
+ #: issue #810:允许 `root` 参数的 op —— 它们的 `root` 语义是「覆盖索引里记录的根」(跨机器搬迁),
2140
+ #: **不是**数据根选择。数据面(write/read/recall/...)出现 `root` 一律显式拒绝。
2141
+ _ROOT_SCOPED_OPS = frozenset({"ref", "index_code", "index_doc"})
2142
+
2143
+
2015
2144
  def _cg_call(cg, a):
2016
2145
  """认知图唯一入口(外层:op/action 缺省推导兜底 + 推导透出;主体见 `_cg_dispatch`)。
2017
2146
 
@@ -2055,6 +2184,16 @@ def _cg_call(cg, a):
2055
2184
  op = "route"
2056
2185
  else:
2057
2186
  op = "read" # 无任何签名可依:维持旧缺省 read
2187
+ # issue #810(2026-11-07 真实污染事故):`root` **不参与数据根选择**——数据根的真源是
2188
+ # 插件 datapath.ts 的四层链(env MDCG_DATA_ROOT/MDCG_ROOT → paths.json → 插件 config.mdcg.root → 默认)。
2189
+ # 历史上 `root` 被静默忽略,调用方「以为分库了、实际全写进主库」(Ornn8 事件:主库 33805→35884)。
2190
+ # 现在在数据面上**显式拒绝**,只在「覆盖索引里记录的 root」那几个面保留(ref / index_code / index_doc)。
2191
+ # 空串视为「未传」(复核 0097:`root=""` 会让数据面全线报错,那是误伤)。
2192
+ if a.get("root") and op not in _ROOT_SCOPED_OPS:
2193
+ raise ValueError(
2194
+ "root 不用于选择数据根(issue #810):请用环境变量 MDCG_ROOT 启动独立进程;"
2195
+ "root 参数仅在 ref / index_code / index_doc 上有效(覆盖索引里记录的 root)。"
2196
+ )
2058
2197
  args = dict(a)
2059
2198
  act0 = (args.get("action") or "").strip().lower()
2060
2199
  act_sig = act_derived = None
@@ -2376,7 +2515,14 @@ def _require_verify_for_vstate(p, a):
2376
2515
 
2377
2516
 
2378
2517
  def _cg_dispatch(cg, a):
2518
+ # issue #722(Q1=A):**工具面 read/route 缺省放宽**——在派发入口补默认,
2519
+ # 而不是在每个调用点编造参数:读面「不编造默认」约束的是**参数推导/回显**,
2520
+ # 这里是 op 级默认策略(不改 action_source,不伪造调用方意图)。
2521
+ if a.get("op") in ("read", "route") and "strict_conditions" not in a:
2522
+ a["strict_conditions"] = False
2379
2523
  """认知图唯一入口的 op 分发主体。"""
2524
+ # 防御性再剥一次(`_dispatch` 已剥;内部调用方若直接调本函数,同样不许传内部标志)。
2525
+ a = {k: v for k, v in (a or {}).items() if not str(k).startswith("_")}
2380
2526
  op = (a.get("op") or "read").strip().lower()
2381
2527
  if op == "help":
2382
2528
  return _help_call(cg, a)
@@ -2556,16 +2702,94 @@ def _cg_dispatch(cg, a):
2556
2702
  raise ValueError(f"link 未知 action:{act}")
2557
2703
 
2558
2704
  if op == "info":
2705
+ # 桶索引的**每日收尾自动重建**(2026-11-09 使用者裁定):
2706
+ # info 是低温、天然被面板/诊断周期性调用的点,适合做「陈旧才重建 + 后台线程」。
2707
+ # 重建 3–5 秒,绝不阻塞本请求:maybe_auto_rebuild 缺省 background=True。
2708
+ # 开关:MDCG_BUCKET_AUTO=0 关;间隔:MDCG_BUCKET_INTERVAL_H(缺省 20 小时)。
2709
+ _bucket_auto = None
2710
+ try:
2711
+ from . import bucketindex as _bki # noqa: PLC0415
2712
+ _bucket_auto = _bki.maybe_auto_rebuild(cg)
2713
+ except Exception: # noqa: BLE001 —— 自动重建失败不影响 info
2714
+ _bucket_auto = {"rebuilt": False, "reason": "error"}
2559
2715
  from . import audit
2560
2716
  from . import nodefile
2561
2717
  from . import theory as _th
2562
2718
  from . import links as _lk
2563
- h = cg.health_os()
2564
- h.update({"surface": SURFACE,
2565
- "tools": [t["name"] for t in tools_for_surface()],
2566
- "audit_kinds": audit.kinds(), "whoami": cg.whoami(),
2567
- # 裁定 B:CCG 六要素的契约角色(术语真源在 nodefile,此处只透出)
2568
- "ccg_contract": dict(nodefile.CCG_CONTRACT_ROLES)})
2719
+ # issue #677(B,2026-11-04):info 的**慢面**(`health_os()`:分桶健康 + 审计规模,
2720
+ # 全库扫描类,大库上数十秒)改为 **full=true 才跑**;其余诊断键(策略/代校验/
2721
+ # 理论/链接/审计种类)留在缺省返回 —— 既有消费者不受影响。
2722
+ # 为什么必须拆:MCP stdio **串行**,一个慢 info 会把后续请求(含写入应答)挡在队列里,
2723
+ # 客户端 60s 超时(#677 现场:write 与 info 同时超时)。
2724
+ _full = _as_flag(a.get("full"))
2725
+ _nodes_info = ((getattr(cg, "index", None) or {}).get("nodes") or {})
2726
+ # issue #812:`node_count` 是**进程内存索引**的条目数;外部进程(如直接调 MdCGOS 批量 forget)
2727
+ # 改库后,这里不会变——2026-11-07 实测:批量软删 1987 条后 node_count 35884→35886,
2728
+ # 而落盘 `_index.json` 实际只有 33900 条(被删节点已不在盘上索引里)。
2729
+ # 修法:默认只透出 `index_mtime`(os.stat,零成本);`full=true` 时再解析落盘索引,
2730
+ # 给出 `index_node_count` 与 `index_stale`,让「内存 vs 落盘」的偏差可判定而不是靠猜。
2731
+ # issue #812:`MdCG` 有 `index_path`,`MdCGOS` 没有 ⇒ 退回按 `root` 拼(同一文件名,见 mdcg.py)。
2732
+ _idx_path = getattr(cg, "index_path", None)
2733
+ if not _idx_path:
2734
+ _root = getattr(cg, "root", None)
2735
+ if _root:
2736
+ _idx_path = os.path.join(str(_root), "_index.json")
2737
+ _idx_mtime = None
2738
+ if _idx_path:
2739
+ try:
2740
+ _idx_mtime = os.stat(str(_idx_path)).st_mtime
2741
+ except OSError:
2742
+ _idx_mtime = None
2743
+ h = {"surface": SURFACE,
2744
+ "tools": [t["name"] for t in tools_for_surface()],
2745
+ # 纯 MdCG 没有 whoami(Secure 才有)——诊断面不得因它崩(#677 B)。
2746
+ "whoami": (cg.whoami() if callable(getattr(cg, "whoami", None)) else None),
2747
+ "node_count": len(_nodes_info),
2748
+ # issue #812:口径写明——它是**内存索引条目数**,不是「磁盘上活节点数」
2749
+ "node_count_scope": "memory_index",
2750
+ "bucket_auto": _bucket_auto,
2751
+ # issue #812:落盘索引的 mtime(零成本)。若它晚于本进程启动,说明索引被外部改过。
2752
+ "index_mtime": _idx_mtime,
2753
+ "audit_kinds": audit.kinds(),
2754
+ # 裁定 B:CCG 六要素的契约角色(术语真源在 nodefile,此处只透出)
2755
+ "ccg_contract": dict(nodefile.CCG_CONTRACT_ROLES),
2756
+ "full": _full}
2757
+ _fs = getattr(cg, "flush_state", None)
2758
+ h["flush_state"] = None # 键**恒在**(守卫按必需键登记;值可 None)
2759
+ if callable(_fs):
2760
+ try:
2761
+ h["flush_state"] = _fs()
2762
+ except Exception: # noqa: BLE001 —— 诊断面不得拖崩
2763
+ h["flush_state"] = None
2764
+ # issue #812:落盘索引 vs 内存索引的偏差(只在 full=true 时解析——58MB JSON,快照面不能付这个成本)。
2765
+ if _full and _idx_path:
2766
+ try:
2767
+ import json as _json
2768
+ with open(str(_idx_path), encoding="utf-8") as _fh:
2769
+ _disk_nodes = len(((_json.load(_fh) or {}).get("nodes")) or {})
2770
+ h["index_node_count"] = _disk_nodes
2771
+ h["index_stale"] = _disk_nodes != len(_nodes_info)
2772
+ h["index_stale_hint"] = ("index_stale=true 表示内存索引与落盘索引不一致。两种成因:"
2773
+ "① 外部进程改过库(如直接调 MdCGOS 批量 forget);"
2774
+ "② 本进程有尚未 flush 的写入。前者需重载/重启,"
2775
+ "后者等待 flush 即可——不要一律当成外部改动") if h["index_stale"] else None
2776
+ except Exception as _ie: # noqa: BLE001 —— 诊断面不拖崩
2777
+ h["index_node_count"] = None
2778
+ h["index_stale"] = None
2779
+ h["index_stale_error"] = "%s: %s" % (type(_ie).__name__, _ie)
2780
+ if _full:
2781
+ # 慢面:只有显式 full=true 才跑。**慢面不得覆盖快照已有键**(#677 复核:
2782
+ # 旧序 h.update(health_os()) 会让同名键覆盖快照值,两条腿对同一键不同值)。
2783
+ # 异常收口,诊断面不拖崩。
2784
+ try:
2785
+ _hh = cg.health_os() or {}
2786
+ except Exception as _he: # noqa: BLE001
2787
+ _hh = {"health_os_error": "%s: %s" % (type(_he).__name__, _he)}
2788
+ for _k, _v in _hh.items():
2789
+ h.setdefault(_k, _v)
2790
+ else:
2791
+ h["hint"] = ("快照模式(issue #677):未包含 health_os 慢面(分桶健康/审计规模);"
2792
+ "要它请加 full=true")
2569
2793
  # 能力外置可观测:本进程实际注入了哪些外部验证器(含失败原因)
2570
2794
  h["external_verifiers"] = audit.load_external_verifiers()
2571
2795
  # 写入策略来源(issue #43 契约④):与启动 stderr / --show-config 同一
@@ -2609,7 +2833,9 @@ def _cg_dispatch(cg, a):
2609
2833
  intent = a.get("intent") or a.get("query") or ""
2610
2834
  res, meta = cg.search(intent, k=_int_arg(a, "k", 10),
2611
2835
  context=a.get("context"), record=False,
2612
- view=a.get("view"))
2836
+ view=a.get("view"),
2837
+ **({"strict_conditions": _as_flag(a["strict_conditions"])}
2838
+ if "strict_conditions" in a else {}))
2613
2839
  knowledge, caps = [], []
2614
2840
  for n, s, q in res:
2615
2841
  fm = n.get("frontmatter") or {}
@@ -2700,6 +2926,20 @@ def _cg_dispatch(cg, a):
2700
2926
  q = a.get("query") or a.get("intent") or ""
2701
2927
  # issue #303 O4:k 越界的信号单点(保留夹紧/切片行为,只在返回体加 warning)
2702
2928
  _kwarn = _k_warning(_int_arg(a, "k", 20))
2929
+ # issue #721:检索期按标签过滤(域隔离)。
2930
+ # 入参规范化放在**两条路径分叉之前**——recall(budget_tokens) 与 search 必须同口径,
2931
+ # 否则同一个参数在两条路径上语义不同,正是本 issue 要消灭的那类「软约束」。
2932
+ # 类型非法 -> 结构化 error(fail-closed),不静默当没传:静默会把调用方的
2933
+ # 「域隔离」请求变成「全部域」返回,比报错危险得多。
2934
+ try:
2935
+ _inc_tags = norm_tags(a.get("include_tags"))
2936
+ _exc_tags = norm_tags(a.get("exclude_tags"))
2937
+ except TypeError as _e:
2938
+ return {"ok": False, "error": "invalid_tags",
2939
+ "include_tags": a.get("include_tags"),
2940
+ "exclude_tags": a.get("exclude_tags"),
2941
+ "hint": "%s;标签须为字符串或字符串列表" % _e}
2942
+ _tag_on = bool(_inc_tags or _exc_tags)
2703
2943
  # 显式 0 也是「显式」(2026-09-24 修复):旧写法 `if a.get("budget_tokens")`
2704
2944
  # 把 0 当没传,静默换成 1200 —— 调用方以为「零预算」拿到的是满预算结果。
2705
2945
  if a.get("budget_tokens") is not None:
@@ -2724,6 +2964,15 @@ def _cg_dispatch(cg, a):
2724
2964
  _out["pack"] = _pack2
2725
2965
  _out["meta"] = _note_doc_filter(_out.get("meta"), _drop2,
2726
2966
  a.get("exclude_doc", False))
2967
+ # issue #721:标签过滤(recall 路径)。与 search 路径同一判据函数。
2968
+ if _tag_on:
2969
+ _pack3, _drop3 = filter_by_tags(
2970
+ _out.get("pack") or [], lambda it: tags_of_item(cg, it),
2971
+ include_tags=_inc_tags, exclude_tags=_exc_tags)
2972
+ _out = dict(_out)
2973
+ _out["pack"] = _pack3
2974
+ _out["meta"] = _note_tag_filter(_out.get("meta"), _drop3,
2975
+ _inc_tags, _exc_tags)
2727
2976
  if _kwarn and isinstance(_out, dict):
2728
2977
  _out = dict(_out)
2729
2978
  _out["warning"] = _kwarn
@@ -2734,10 +2983,16 @@ def _cg_dispatch(cg, a):
2734
2983
  _doc_filter_on = _as_flag(a.get("exclude_doc", False))
2735
2984
  search_args = dict(layer=a.get("layer"), k=_int_arg(a, "k", 20),
2736
2985
  context=a.get("context"), session=a.get("session"),
2737
- validity=a.get("validity"), **_tkw)
2986
+ validity=a.get("validity"),
2987
+ # issue #722:**只在显式传参时透传**(读面纪律:不编造默认)。
2988
+ **({"strict_conditions": _as_flag(a["strict_conditions"])}
2989
+ if "strict_conditions" in a else {}),
2990
+ **_tkw)
2738
2991
  _k_want = search_args["k"]
2739
- if _doc_filter_on:
2740
- # 只在过滤开启时超取(过滤后再截回 _k_want,对外语义不变)
2992
+ if _doc_filter_on or _tag_on:
2993
+ # 只在过滤开启时超取(过滤后再截回 _k_want,对外语义不变)。
2994
+ # issue #721:标签过滤与 doc 过滤同理会吃配额——top-k 被反面域占满时
2995
+ # 结果会假性空掉,故两者共用同一条超取规则。
2741
2996
  search_args["k"] = min(max(_k_want * 4, _k_want + 32), 400)
2742
2997
  if a.get("bm25", True) and hasattr(cg, "search_rrf"):
2743
2998
  ranked, meta = cg.search_rrf(q, paths=("bm25",), **search_args)
@@ -2749,13 +3004,27 @@ def _cg_dispatch(cg, a):
2749
3004
  # issue #653:判据收敛到 drop_doc_nodes(单一真源),不再就地手写第二条。
2750
3005
  res, _excluded_doc = drop_doc_nodes(
2751
3006
  res, lambda x: (x[0] or {}).get("id"), _doc_filter_on)
2752
- # 截回调用方要的 k(超取只为让 doc_ 不占配额,不改变对外语义)
2753
- if _doc_filter_on and len(res) > _k_want:
3007
+ # issue #721:标签过滤(search 路径)。与 recall 路径同一判据函数 filter_by_tags,
3008
+ # 语义见其 docstring:多标签 OR / 全等 / 无匹配返回空集 / exclude 优先于 include。
3009
+ _tag_dropped = 0
3010
+ if _tag_on:
3011
+ res, _tag_dropped = filter_by_tags(
3012
+ res, lambda x: tags_of_item(cg, x), include_tags=_inc_tags,
3013
+ exclude_tags=_exc_tags)
3014
+ # 截回调用方要的 k(超取只为让被过滤项不占配额,不改变对外语义)
3015
+ if (_doc_filter_on or _tag_on) and len(res) > _k_want:
2754
3016
  res = res[:_k_want]
2755
3017
  meta = _note_doc_filter(meta, _excluded_doc, _doc_filter_on)
3018
+ if _tag_on:
3019
+ meta = _note_tag_filter(meta, _tag_dropped, _inc_tags, _exc_tags)
2756
3020
  _out = {"meta": meta, "results": [
2757
3021
  {"node": _node_view(n), "score": s, "state": q2.get("state"),
2758
- "reason": q2.get("reason"), **refindex.ref_fields(n)}
3022
+ "reason": q2.get("reason"),
3023
+ **({"usable": q2["usable"],
3024
+ "relaxed": q2["relaxed"],
3025
+ "code": q2["code"]}
3026
+ if "usable" in q2 else {}),
3027
+ **refindex.ref_fields(n)}
2759
3028
  for n, s, q2 in res]}
2760
3029
  if _kwarn:
2761
3030
  _out["warning"] = _kwarn
@@ -2800,6 +3069,36 @@ def _cg_dispatch(cg, a):
2800
3069
  # 本文件;新增闸门 = register_before 一行,即插即拔。
2801
3070
  # 角色/层权限校验在 MdCGSecure.add 库层,结构上不可被拦截器绕过。
2802
3071
  from .writepipe import default_pipeline
3072
+ # **元数据补丁**(issue #732 的实用形态):只给 node_id + tags /
3073
+ # condition_space / depends_on 而不给 content ⇒ 视为「改元数据、不动
3074
+ # 正文」,正文按原样从盘面取回再走同一条写链。这样「给存量节点补
3075
+ # domain: 标签以迁出 orphan 桶」不必再用同 id 覆写——覆写是全量重建
3076
+ # fm,历史上会重置 created_at/session 并丢 evidence_log/edges。
3077
+ # 为何挂在 write 下而不是新造 op:它本质是**单节点写**(与 verify 同类),
3078
+ # 不是批量维护;也不给令牌 face 引入新 op 词(派生收窄面零改动)。
3079
+ if not str(a.get("content") or "").strip() and a.get("node_id"):
3080
+ _cur = cg.get(a.get("node_id"))
3081
+ if not _cur:
3082
+ return {"ok": False, "error": "node_not_found",
3083
+ "node_id": a.get("node_id"),
3084
+ "hint": "content 为空时按「元数据补丁」处理,此时 node_id "
3085
+ "必须指向既有节点(新建节点必须给 content)"}
3086
+ a = dict(a)
3087
+ a["content"] = _cur.get("content") or ""
3088
+ # 内容类型必须补齐:写入闸按 content_kind 选规则,缺省会判
3089
+ # 「未知内容类型 ''」→ BLINDSPOT → 入审核队列(实测)。补丁的
3090
+ # 正文是原来那条,故类型也沿用原节点的(modality 是既有落盘列)。
3091
+ _pfm = _cur.get("frontmatter") or {}
3092
+ if not a.get("content_kind"):
3093
+ a["content_kind"] = (_pfm.get("content_kind")
3094
+ or _pfm.get("modality") or "text")
3095
+ # 显式标记:写链据此放行内容闸与档位闸(见 writepipe.execute 的注释)。
3096
+ # 只有**这条**路径会置位——普通 write 即便正文一样也走全套闸。
3097
+ a["_meta_patch"] = True
3098
+ # importance 继承:写链 direct 出口对未声明值回落 0.5(那是两出口的
3099
+ # 既有不变量,不动),故补丁要保原值必须在这里把旧值显式填进去。
3100
+ if a.get("importance") is None and _pfm.get("importance") is not None:
3101
+ a["importance"] = _pfm["importance"]
2803
3102
  return default_pipeline().execute(cg, a)
2804
3103
 
2805
3104
  if op == "goal":
@@ -2857,10 +3156,37 @@ def _cg_dispatch(cg, a):
2857
3156
  if op == "recent":
2858
3157
  act = (a.get("action") or "list").strip().lower()
2859
3158
  if act in ("add", "append", "remember"):
2860
- return cg.remember_event(a.get("role") or "user",
2861
- a.get("text") or a.get("content") or "",
2862
- tags=a.get("tags"), meta=a.get("meta"),
3159
+ _role = a.get("role") or "user"
3160
+ _text = a.get("text") or a.get("content") or ""
3161
+ _meta = a.get("meta") or {}
3162
+ _res = cg.remember_event(_role, _text, tags=a.get("tags"),
3163
+ meta=a.get("meta"),
2863
3164
  window=int(a.get("window") or 200))
3165
+ # L2 状态台账的**双端共用触发点**(2026-11-02 接线)。
3166
+ # 放在这里而不是各端钩子里的理由:DSH 端(src/hooks.ts 的
3167
+ # recentAdd)与 zcode 端(sync_zcode_session)**都**经过本分支,
3168
+ # 一处接线即覆盖两端;且 op 面零扩张——本 op 的 require 是
3169
+ # `recent`,而「能写 _recent」本就已隐含「能写运行态面」,
3170
+ # 不把任何角色抬到 `write`(实测:output/guest 两个角色有 recent
3171
+ # 无 write,但它们 can_write=False,remember_event 已在上一行拒掉,
3172
+ # 到不了这里)。
3173
+ #
3174
+ # 三个前置条件(缺一不抽):
3175
+ # ① role == "user"——抽取器只认真人发言(助手自述不复盖真值);
3176
+ # ② meta 带 session——无会话归属的事件无法做去重与审计;
3177
+ # ③ 开关 MDCG_STATE_EXTRACT 开(缺省开)。
3178
+ # 逐轮 fail-soft:抽取/记账任何失败都**不得**影响窗口写入的返回值
3179
+ # (窗口是运行态面,状态台账是派生面)。
3180
+ if _role == "user" and _text and _meta.get("session"):
3181
+ try:
3182
+ from . import state_extract as _sx
3183
+ if _sx.enabled():
3184
+ _sx.extract_and_record(
3185
+ cg, _meta.get("session"),
3186
+ _meta.get("turn"), "user", _text)
3187
+ except Exception: # noqa: BLE001
3188
+ pass
3189
+ return _res
2864
3190
  if act == "clear":
2865
3191
  return {"cleared": cg.clear_recent()}
2866
3192
  return {"events": cg.recent_events(limit=int(a.get("limit") or 20),
@@ -2889,7 +3215,8 @@ def _cg_dispatch(cg, a):
2889
3215
  if op == "verify":
2890
3216
  return cg.verify(a.get("node_id", ""), a.get("evidence", ""),
2891
3217
  a.get("verdict", ""),
2892
- override=bool(a.get("override")))
3218
+ override=bool(a.get("override")),
3219
+ superseded_by=a.get("superseded_by"))
2893
3220
 
2894
3221
  if op == "review":
2895
3222
  act = (a.get("action") or "list").strip().lower()
@@ -2979,6 +3306,18 @@ def _cg_dispatch(cg, a):
2979
3306
  check_path_root(a.get("path"), "MDCG_INGEST_ROOT", "index_code")
2980
3307
  if not os.path.isdir(root):
2981
3308
  return {"ok": False, "error": f"目录不存在:{root}"}
3309
+ # issue #754:父/子根互相包含 ⇒ 同一物理文件生成两套节点(id 键是相对 path)。
3310
+ # 默认 root(未显式给 path)是部署侧「全库刷一遍」语义,不做嵌套拦截;
3311
+ # allow_nested=true 强制时回执留痕(nested_override),便于日后清理区分。
3312
+ _nest, _nest_ok = ((None, True) if not a.get("path")
3313
+ else _nested_root_guard(cg, root, "code_ref"))
3314
+ _nest_allowed = _nest if (_nest and a.get("allow_nested")) else None
3315
+ if _nest and not a.get("allow_nested"):
3316
+ return {"ok": False, "error": "nested_root", "path": root,
3317
+ "conflicts_with": _nest,
3318
+ "hint": ("该目录与已索引根互相嵌套(%s)——同一文件会生成两套"
3319
+ "节点(issue #754)。请改为索引最外层根;确需同时"
3320
+ "索引请显式 allow_nested=true。" % _nest)}
2982
3321
  # 写序(commit=False → add_items 成功后再 save):水位是**派生物的水位**,
2983
3322
  # 必须落在「节点已写成功」之后。否则进程在两步之间被杀,会留下
2984
3323
  # 「水位新 + 节点旧」——下次巡检按水位判「未变、可跳过」,漂移静默漏报。
@@ -3009,6 +3348,11 @@ def _cg_dispatch(cg, a):
3009
3348
  "skipped_unchanged": stats.get("skipped_unchanged", 0),
3010
3349
  "skipped_suffixes": stats["skipped_suffixes"], "note": note}
3011
3350
  out.update(_skip_dirs_report(stats))
3351
+ if _nest_allowed: # issue #754:强制放行留痕(不静默)
3352
+ out["nested_override"] = True
3353
+ out["conflicts_with"] = _nest_allowed
3354
+ if not _nest_ok: # 守卫读不到水位 ⇒ 显式降级,不扮成「无嵌套」
3355
+ out["nested_guard"] = "unavailable"
3012
3356
  if stats["truncated"]:
3013
3357
  # 截断必须显式说出来:以前静默 return,调用方以为索引是完整的。
3014
3358
  out["truncated_reason"] = stats["truncated_reason"]
@@ -3034,6 +3378,16 @@ def _cg_dispatch(cg, a):
3034
3378
  check_path_root(a.get("path"), "MDCG_INGEST_ROOT", "index_doc")
3035
3379
  if not os.path.isdir(root):
3036
3380
  return {"ok": False, "error": f"目录不存在:{root}"}
3381
+ # issue #754:同 index_code——父/子根嵌套会双写(按 doc_ref kind 判)。
3382
+ _nest, _nest_ok = ((None, True) if not a.get("path")
3383
+ else _nested_root_guard(cg, root, "doc_ref"))
3384
+ _nest_allowed = _nest if (_nest and a.get("allow_nested")) else None
3385
+ if _nest and not a.get("allow_nested"):
3386
+ return {"ok": False, "error": "nested_root", "path": root,
3387
+ "conflicts_with": _nest,
3388
+ "hint": ("该目录与已索引根互相嵌套(%s)——同一文件会生成两套"
3389
+ "节点(issue #754)。请改为索引最外层根;确需同时"
3390
+ "索引请显式 allow_nested=true。" % _nest)}
3037
3391
  layer = a.get("layer") or "knowledge"
3038
3392
  # 显式改密级时必须全量重切(增量会跳过未变文件、覆盖不生效)。
3039
3393
  incremental = bool(a.get("incremental")) and not a.get("sensitivity")
@@ -3063,6 +3417,11 @@ def _cg_dispatch(cg, a):
3063
3417
  "skipped_suffixes": stats["skipped_suffixes"],
3064
3418
  "layer": layer, "sensitivity": sens_counts, "note": note}
3065
3419
  out.update(_skip_dirs_report(stats))
3420
+ if _nest_allowed: # issue #754:强制放行留痕(不静默)
3421
+ out["nested_override"] = True
3422
+ out["conflicts_with"] = _nest_allowed
3423
+ if not _nest_ok: # 守卫读不到水位 ⇒ 显式降级,不扮成「无嵌套」
3424
+ out["nested_guard"] = "unavailable"
3066
3425
  if stats["truncated"]:
3067
3426
  out["truncated_reason"] = stats["truncated_reason"]
3068
3427
  out["note"] = (f"⚠ 索引被截断,结果不完整({stats['truncated_reason']}),"
@@ -3326,7 +3685,6 @@ def _session_call(cg, a):
3326
3685
  raise ValueError(f"session 未知 action:{act}(允许 note/recall/compact)")
3327
3686
 
3328
3687
 
3329
- # 生效条件:flag=a.get("prune", True),flag 为字符串时重算为 flag.strip().lower() not in ("false","0","no","off","");若 not flag 或 stats.get("truncated") 为真则返回 None;否则返回 refindex.prune_orphans(cg, kind=kind, root=root, items=items, dry_run=bool(a.get("prune_dry_run"))).
3330
3688
  def _prune_after_index(cg, a, *, kind, root, items, stats):
3331
3689
  """索引后的**节点级对账**:清退「同 root + 同 path 的过期代」。
3332
3690
 
@@ -3350,6 +3708,66 @@ def _prune_after_index(cg, a, *, kind, root, items, stats):
3350
3708
 
3351
3709
 
3352
3710
  # 生效条件:sd=list(stats.get("skipped_dirs") or []),返回 {"skipped_dirs": sd[:limit], "skipped_dirs_count": len(sd), "skip_dirs": list(stats.get("skip_dirs") or [])},且仅当 len(sd)>limit 时追加 skipped_dirs_note。
3711
+ # 生效条件:cg 为认知图实例、root 为待索引源根、kind 为 code_ref/doc_ref 时,读
3712
+ # <cg.root>/_refindex.json 的 files 记录(逐条带 root/kind),若新 root 与**同 kind** 的
3713
+ # 某个已索引根 realpath 互相包含(且不是同一个根)则返回 (该根, True);无嵌套返回
3714
+ # (None, True);水位缺失/损坏/schema 不符 ⇒ (None, False)(不拦,但回执显式降级)。
3715
+ def _nested_root_guard(cg, root, kind):
3716
+ '''issue #754:同一物理文件从父/子根各索引一次会写两套 doc/code 节点。
3717
+
3718
+ node_id 的键是「相对传入 root 的 path」⇒ 换 root 就换 id;#352-E 的冲突检测只在
3719
+ **同 id 被另一源根占用**时触发,本例 id 不同 ⇒ 静默双写。故在入口按 realpath 判
3720
+ 「新根与已索引根互相包含」,命中即拒(调用方可显式 allow_nested=true 强制)。
3721
+
3722
+ **按 kind 过滤(#754 复核)**:code_ref 与 doc_ref 的后缀面不相交,repo 的代码索引
3723
+ 与 repo/docs 的文档索引是**两种域**,不能因目录嵌套就互拦。
3724
+
3725
+ 为什么读水位而不是扫节点:水位文件的 files 记录逐文件带 root(绝对路径键),是
3726
+ 全库已索引根的可靠单点;扫节点需逐个 get() 读 fm,大库不可承受。
3727
+ '''
3728
+ import os as _os
3729
+ from . import refindex
3730
+ try:
3731
+ _fp = _os.path.join(cg.root, refindex.LEDGER_FILE)
3732
+ if _os.path.exists(_fp):
3733
+ import json as _json
3734
+ with open(_fp, "r", encoding="utf-8") as _f:
3735
+ _raw = _json.load(_f)
3736
+ if not (isinstance(_raw, dict)
3737
+ and _raw.get("schema") == refindex.SCHEMA
3738
+ and isinstance(_raw.get("files"), dict)):
3739
+ return None, False # 水位在但 schema/形状不符 ⇒ 显式降级,不静默放行
3740
+ files = _raw["files"]
3741
+ else:
3742
+ files = {} # 尚无水位=全新库,不是降级
3743
+ except Exception: # noqa: BLE001 —— 读失败不改既有行为,但须显式降级
3744
+ return None, False
3745
+ try:
3746
+ new = _os.path.normcase(_os.path.realpath(str(root)))
3747
+ seen = []
3748
+ for rec in files.values():
3749
+ if not isinstance(rec, dict) or rec.get("kind") != kind:
3750
+ continue
3751
+ r = rec.get("root")
3752
+ if not r:
3753
+ continue # root 兜底值(dirname)不自洽 ⇒ 不当根用
3754
+ seen.append(str(r))
3755
+ for r_raw in seen:
3756
+ r = _os.path.normcase(_os.path.realpath(r_raw))
3757
+ if r == new:
3758
+ continue
3759
+ # commonpath 而非 startswith(r+sep):后者对盘符根与尾分隔符失效
3760
+ try:
3761
+ common = _os.path.commonpath([new, r])
3762
+ except ValueError: # 不同盘符 ⇒ 必不包含
3763
+ continue
3764
+ if common == r or common == new:
3765
+ return r_raw, True
3766
+ except Exception: # noqa: BLE001 —— 守卫自身不得成为新失败源
3767
+ return None, False
3768
+ return None, True
3769
+
3770
+
3353
3771
  def _skip_dirs_report(stats, limit=20):
3354
3772
  """把「本次被 skip_dirs 排掉的目录」压成可审计字段。
3355
3773
 
@@ -3517,7 +3935,11 @@ def _maintain_call(cg, a):
3517
3935
  min_conf=a.get("min_conf"), basis_text=a.get("basis_text"),
3518
3936
  prefixes=a.get("prefixes"), aeis_root=a.get("aeis_root"),
3519
3937
  sample_n=a.get("sample_n"), prefix=a.get("prefix"),
3520
- verdicts=a.get("verdicts"), reason=a.get("reason"))
3938
+ verdicts=a.get("verdicts"), reason=a.get("reason"),
3939
+ # action=retag 的形参(只改元数据,正文与证据链原样):
3940
+ tags_add=a.get("tags_add"), tags_remove=a.get("tags_remove"),
3941
+ condition_space_patch=a.get("condition_space_patch"),
3942
+ depends_on=a.get("depends_on"), dry_run=a.get("dry_run"))
3521
3943
 
3522
3944
 
3523
3945
  # 生效条件:act=(a.get("action") or "promote").strip().lower();principal 非 None 时一律先 require_admin(f"consolidate_{act}");imp=a.get("min_importance"),为 None 时回落为 a.get("importance"),随后以 imp 等参数调 cg.consolidate_run 并返回。
@@ -4068,7 +4490,10 @@ def _oversize_r2(nid, a):
4068
4490
 
4069
4491
 
4070
4492
  def _dispatch(cg, name, args):
4071
- a = args or {}
4493
+ # issue #742 复核(提权面):`_meta_patch` 等**下划线前缀键是内部标志**,只能由
4494
+ # 内部路径置位(见 `_cg_dispatch` 的元数据补丁分支)。外部调用方若能在 args 里
4495
+ # 自己带上它们,就能绕过内容闸/档位闸直接落盘——故在唯一外部入口统一剥离。
4496
+ a = {k: v for k, v in (args or {}).items() if not str(k).startswith("_")}
4072
4497
  # issue #86(2026-10-09 DSH 端):**令牌运行期复检**(见 _runtime_token_recheck)
4073
4498
  _re86 = _runtime_token_recheck(getattr(cg, "principal", None))
4074
4499
  if _re86:
@@ -4115,6 +4540,15 @@ def _dispatch(cg, name, args):
4115
4540
  _ov212 = _oversize212(nid, a)
4116
4541
  if _ov212 is not None:
4117
4542
  return _ov212
4543
+ # issue #677(A,2026-11-04):**自动记忆面也支持幂等**。超时重试是既有病灶
4544
+ # (节点已落盘但应答没回 ⇒ 重试新增一条,实测三条同内容)。`dedupe` 走与
4545
+ # cg(op=write) **同一个闸**(writepipe._gate_dedupe:同层 + 内容指纹 ⇒ 复用既有 id),
4546
+ # 位置也在链首(未落盘、未建边、不过闸审计)。
4547
+ # layer 缺省按本通路口径(contextual)代入——否则闸会去 knowledge 层找而永不命中。
4548
+ from .writepipe import _gate_dedupe as _dedupe677
4549
+ _dup677 = _dedupe677({"a": {**a, "layer": a.get("layer") or "contextual"}, "cg": cg})
4550
+ if _dup677 is not None:
4551
+ return _dup677
4118
4552
  # issue #93(2026-10-09 DSH 端):**这条通路此前不过 policy 的 forbidden 规则**。
4119
4553
  # 同样内容走 writepipe(cg(op=write))会被判 REJECT 或打码,而 mdcg_remember
4120
4554
  # ——hooks 自动记忆走的正是它——直接落盘 ⇒ AKIA / ghp_ / URL 内嵌凭据 /