@furongjun1999/dsh-memory 0.9.23 → 0.10.3

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 (118) hide show
  1. package/CHANGELOG.en.md +515 -404
  2. package/CHANGELOG.md +642 -449
  3. package/README.en.md +244 -240
  4. package/README.md +272 -262
  5. package/codebuddy/CODEBUDDY.md +1 -1
  6. package/docs/discipline/templates/full.md.tmpl +1 -1
  7. package/docs/discipline/templates/rules.mdc.tmpl +1 -1
  8. package/docs/en/mdcg/world-model-endpoint.md +1 -1
  9. package/docs/mdcg/cogmap_ops.md +19 -16
  10. package/lib/client.js +29 -3
  11. package/lib/hooks.d.ts +12 -0
  12. package/lib/hooks.js +43 -1
  13. package/lib/tools.d.ts +2 -2
  14. package/md_cg/bucketindex.py +231 -0
  15. package/md_cg/bucketscope.py +357 -0
  16. package/md_cg/cohesion.py +337 -0
  17. package/md_cg/config_registry_bulk.py +24 -10
  18. package/md_cg/config_validate.py +14 -2
  19. package/md_cg/constraint_audit.py +231 -0
  20. package/md_cg/constraint_watch.py +206 -0
  21. package/md_cg/context_audit.py +240 -0
  22. package/md_cg/context_plan.py +142 -0
  23. package/md_cg/detrerank.py +137 -0
  24. package/md_cg/distill.py +247 -0
  25. package/md_cg/dossier.py +151 -0
  26. package/md_cg/entities.py +133 -0
  27. package/md_cg/fsutil.py +135 -0
  28. package/md_cg/govern/__init__.py +23 -0
  29. package/md_cg/iface/__init__.py +46 -0
  30. package/md_cg/iface/_verify.py +609 -0
  31. package/md_cg/iface/contracts.py +337 -0
  32. package/md_cg/judgment_manifest.py +14 -0
  33. package/md_cg/kernel/__init__.py +27 -0
  34. package/md_cg/mcp_server.py +6044 -5761
  35. package/md_cg/mdcg.py +501 -16
  36. package/md_cg/mdcos.py +546 -12
  37. package/md_cg/metacognition.py +66 -13
  38. package/md_cg/mutate_extract_shipped.py +126 -0
  39. package/md_cg/mutate_ledger_e2e.py +100 -0
  40. package/md_cg/op_table.py +22 -0
  41. package/md_cg/probe_c_ledger_integrity.py +258 -0
  42. package/md_cg/probe_d_retirement_discipline.py +263 -0
  43. package/md_cg/profiles.py +298 -0
  44. package/md_cg/protocol.py +7 -1
  45. package/md_cg/reldate.py +142 -0
  46. package/md_cg/review_cli.py +6 -1
  47. package/md_cg/run_tests.py +30 -1
  48. package/md_cg/scopeselect.py +214 -0
  49. package/md_cg/scrub.py +66 -9
  50. package/md_cg/selfstmt.py +139 -0
  51. package/md_cg/state_extract.py +149 -0
  52. package/md_cg/state_slots.py +62 -10
  53. package/md_cg/state_view.py +181 -0
  54. package/md_cg/structboost.py +179 -0
  55. package/md_cg/sustain.py +28 -2
  56. package/md_cg/test_alternatives_historical.py +165 -0
  57. package/md_cg/test_b2_sensitivity_landing.py +226 -223
  58. package/md_cg/test_b3_merge_keeps_content.py +608 -583
  59. package/md_cg/test_bucket_cards.py +85 -0
  60. package/md_cg/test_bucket_day_order.py +74 -0
  61. package/md_cg/test_bucket_quota.py +79 -0
  62. package/md_cg/test_bucket_recency_guards.py +75 -0
  63. package/md_cg/test_bucket_three_causes.py +83 -0
  64. package/md_cg/test_bucket_time_rounds.py +87 -0
  65. package/md_cg/test_bucketindex.py +130 -0
  66. package/md_cg/test_bucketscope_early.py +71 -0
  67. package/md_cg/test_cohesion.py +107 -0
  68. package/md_cg/test_cond_term_fold_gate.py +1210 -0
  69. package/md_cg/test_cond_term_neg_scope.py +147 -0
  70. package/md_cg/test_constraint_audit.py +87 -0
  71. package/md_cg/test_constraint_watch.py +108 -0
  72. package/md_cg/test_context_audit.py +110 -0
  73. package/md_cg/test_context_plan.py +81 -0
  74. package/md_cg/test_detrerank.py +157 -0
  75. package/md_cg/test_gate_four_kpi.py +136 -0
  76. package/md_cg/test_generation_guard.py +14 -2
  77. package/md_cg/test_issue192_move_layer_indices_guard.py +48 -0
  78. package/md_cg/test_issue39_utf8_stdio.py +572 -572
  79. package/md_cg/test_issue413_preimage_failclosed.py +147 -9
  80. package/md_cg/test_issue768_overwrite_time_window_anchor.py +135 -0
  81. package/md_cg/test_issue789_log_plaintext_probe.py +100 -0
  82. package/md_cg/test_issue790_verb_negation.py +77 -0
  83. package/md_cg/test_issue810_root_guard.py +71 -0
  84. package/md_cg/test_issue812_info_index_stale.py +78 -0
  85. package/md_cg/test_issue827_weaken_dedup.py +361 -0
  86. package/md_cg/test_issue829_calibration_positive_gate.py +473 -0
  87. package/md_cg/test_kernel_iface_contracts.py +18 -0
  88. package/md_cg/test_md_cg_no_hive_dep.py +238 -17
  89. package/md_cg/test_probe_cd_shipped.py +385 -0
  90. package/md_cg/test_recent_tail.py +93 -0
  91. package/md_cg/test_run_tests_entry_gates.py +110 -0
  92. package/md_cg/test_scopeselect.py +70 -0
  93. package/md_cg/test_scopeselect_clock.py +70 -0
  94. package/md_cg/test_session_attribution_consistency.py +835 -813
  95. package/md_cg/test_state_extract_shipped.py +162 -0
  96. package/md_cg/test_state_ledger_chain.py +207 -0
  97. package/md_cg/test_state_ledger_e2e.py +145 -0
  98. package/md_cg/test_structboost.py +102 -0
  99. package/md_cg/test_timeboost.py +83 -0
  100. package/md_cg/test_timeboost_relativedate.py +71 -0
  101. package/md_cg/test_topicagg.py +129 -0
  102. package/md_cg/timeboost.py +223 -0
  103. package/md_cg/tokens.py +1 -1
  104. package/md_cg/topicagg.py +142 -0
  105. package/md_cg/version_anchor.py +84 -1
  106. package/md_cg/whitebox_kb/wisdom/code_compose.py +33 -5
  107. package/md_cg/whitebox_kb/wisdom/code_solidified.json +6195 -6195
  108. package/md_cg/whitebox_kb/wisdom/compose_engine.py +5 -1
  109. package/md_cg/whitebox_kb/wisdom/role_compose.py +271 -268
  110. package/package.json +1 -1
  111. package/src/hooks.ts +43 -1
  112. package/ui/minimal/payload/build-ui.mjs +41 -2
  113. package/ui/minimal/payload/lib/client.js +29 -3
  114. package/ui/minimal/payload/web/app.js +3 -1
  115. package/ui/minimal/payload/web/client.js +30 -3
  116. package/web/app.js +3 -1
  117. package/web/client.js +30 -3
  118. package/zcode/AGENTS.md +1 -1
package/md_cg/mdcos.py CHANGED
@@ -45,7 +45,7 @@ from . import (nodefile, routing, chain, subgraph, forgetting, protect,
45
45
  identity, consistency, metacognition, crypto, sustain,
46
46
  self_state, predict, evolution, weights, pooling,
47
47
  writelimit, reach, trust, roleviews, autonomy_modes, lifecycle,
48
- rrf_candidates)
48
+ rrf_candidates, reldate)
49
49
  from .fsutil import (FileLock, atomic_write, append_jsonl, read_jsonl,
50
50
  read_jsonl_tail, count_jsonl, publish,
51
51
  merge_rmw_lock, node_write_lock)
@@ -846,8 +846,12 @@ class MdCGOS(MdCG):
846
846
  TRASH = "trash"
847
847
 
848
848
  # 生效条件:传入 root 时以 super().__init__(root, autoflush=autoflush) 初始化父类,把 actor 存入 self.actor,并按 root(及类常量 AUDIT_ARCHIVE/HIPPOCAMPUS/TRASH)拼出 audit_log/audit_archive/hippocampus/inbox_log/decisions_log/trash_dir 等路径,同时 makedirs(hippocampus/trash_dir, exist_ok=True);读缓存装配走 readcache.install_default(#370:自动装配的唯一入口,基类已装则为幂等空操作,MDCG_READ_CACHE=0 时不装配)。
849
- def __init__(self, root: str, autoflush: int = 64, actor: str = "system"):
850
- super().__init__(root, autoflush=autoflush)
849
+ def __init__(self, root: str, autoflush: int = 64, actor: str = "system",
850
+ async_flush=None):
851
+ # async_flush 必须**显式转发**:本层用 **kw 之外的位置接参会让父类的
852
+ # 同名握手断链(实测 TypeError: MdCGOS.__init__() got an unexpected
853
+ # keyword argument 'async_flush')。None = 随 env(含本层自有缺省)。
854
+ super().__init__(root, autoflush=autoflush, async_flush=async_flush)
851
855
  self.actor = actor
852
856
  self.audit_log = os.path.join(self.root, "_audit.jsonl")
853
857
  self.audit_archive = os.path.join(self.root, self.AUDIT_ARCHIVE)
@@ -1155,6 +1159,16 @@ class MdCGOS(MdCG):
1155
1159
  continue
1156
1160
  _ov = _ofm.get(_ik)
1157
1161
  if _ov is not None:
1162
+ # #768:`condition_space.time_window` 是「**这次观测**发生在什么时候」,
1163
+ # 不是节点的静态属性——#550 的「未传字段继承旧值」把它一起继承过来后
1164
+ # 观测窗就被冻结在**首写时刻**(覆写旧节点 ⇒ 窗口落在过去),而
1165
+ # mdcg.add 的默认窗口构造因为「cs 已带 time_window」整段跳过、
1166
+ # 再也不刷新。故继承 cs 时剔除该键,让写面按本次写入重新定锚
1167
+ # (显式回填 created_at 仍锚在给出的时刻,见 mdcg.add)。
1168
+ if _ik == "condition_space" and isinstance(_ov, dict):
1169
+ _ov = {k: v for k, v in _ov.items() if k != "time_window"}
1170
+ if not _ov:
1171
+ continue
1158
1172
  kw[_ik] = _ov
1159
1173
  nid = super().add(node_id, content, layer=layer, **kw)
1160
1174
  e = self.index["nodes"].get(nid)
@@ -1182,6 +1196,14 @@ class MdCGOS(MdCG):
1182
1196
  self._audit("add", nid, layer=layer, role=role,
1183
1197
  payload_hash=_sig(content), sens=kw.get("sensitivity"),
1184
1198
  session=kw.get("session"))
1199
+ # 【自述轮次登记】写时判一次(与查询无关),供 recall 读时注入;
1200
+ # 登记只是加速索引,失败不得影响写入成败(故整段吞异常)。
1201
+ try:
1202
+ from . import selfstmt as _ss
1203
+ if _ss.matches(content):
1204
+ _ss.record(getattr(self, "root", ""), nid)
1205
+ except Exception:
1206
+ pass
1185
1207
  return nid
1186
1208
 
1187
1209
  # 生效条件:在已用 root 构造的实例上遍历 index["nodes"],恒剔除 layer 为 rejected/unresolved/goals 的节点,恒剔除 lifecycle.is_retired(e) 为真(archived ∪ superseded,#562)的节点(退役不参与默认检索;缺 lifecycle 键=active 照常,converged/demoted 仍参与),session 为真值而 e["session"] 不等于它时剔除,e["branch_id"] 不在 (None, branch) 时剔除(branch=None 时只留 branch_id 为 None 者),validity 为真值而 trust.is_expired(e) 为真时剔除(**只排已过期,not_yet 保留**),layer 为真值而 layer 不等时剔除,roles 不为 None 时仅留 role 落在 roles 内的节点;view 为真值时 role 维度裁决权移交 roleviews.matches(receipt=工作角色白名单须绕过默认剔除才可达,非法 view ValueError),view 为假值且 include_work 为假时剔除 WORK_ROLES 角色,时间算子启用时按 time_axis 轴过滤(效力轴不可判定 fail-open、观察轴不可判定 fail-closed 并入 self._time_filter_stat),其余收集进 out 返回。
@@ -2168,7 +2190,7 @@ class MdCGOS(MdCG):
2168
2190
  early_stop_threshold=None,
2169
2191
  start_time=None, end_time=None, start_operator=None,
2170
2192
  end_operator=None, time_axis=None, view=None,
2171
- strict_conditions: bool = True):
2193
+ strict_conditions: bool = True, now=None):
2172
2194
  """并行多路召回 + RRF 融合。返回 (results, meta)。
2173
2195
 
2174
2196
  validity:**只排除「已过期」(expired),不排除「未生效」(not_yet)**。
@@ -2492,6 +2514,18 @@ class MdCGOS(MdCG):
2492
2514
  # 温路径早停判据(2026-09-19 热温冷分层):
2493
2515
  # top-1 RRF 分 >= threshold 且 top-k 全部来自 >=2 路共识 → 提前返回
2494
2516
  # 不改 RRF 核心算法,只在融合后判断
2517
+ # 结构重排需要**先超取再截断**:实测(476 题)在 k=10 的池子里重排,gold@3 不动;
2518
+ # 在 2×k 池子里重排再截到 k,gold@3 71.9%→85.5%。池子宽窄决定这条信号有没有用。
2519
+ _struct_on = (int(os.environ.get("MDCG_STRUCT_BOOST", "0")) > 0)
2520
+ # 注意:**不要**复用 `_time_on`——那是上面「时间算子启用」的既有变量,
2521
+ # 覆盖它会让「时间算子查询绕开热缓存」失效(实测:默认查询被污染成 11 条)。
2522
+ _timeboost_on = (int(os.environ.get("MDCG_TIME_BOOST", "0")) > 0)
2523
+ # 时间重排的时钟:**复用**本函数内既有的唯一 time 调用点(#111 契约:打分层时钟恰 1 处),
2524
+ # 新增 time.time() 会直接让契约守卫转红(实测:新增后「时钟调用 2 次」)。
2525
+ # 故这里只派生,不取时钟:`_validity_clock` 未启用时由 _candidates 侧时钟兜底(见下)。
2526
+ # `now` 由调用方显式给(缺省回落既有唯一时钟点);None ⇒ 时间重排不启用(不猜「今天」)。
2527
+ _rerank_now = now if now is not None else _validity_clock
2528
+ _k_fetch = min(k * 2, 200) if ((_struct_on or _timeboost_on) and k) else k
2495
2529
  early_stopped = False
2496
2530
  if early_stop_threshold is not None and len(fused_all) >= k:
2497
2531
  top1_score = fused_all[0][1]
@@ -2509,7 +2543,7 @@ class MdCGOS(MdCG):
2509
2543
  filtered = 0
2510
2544
  if early_stopped:
2511
2545
  # 早停:直接取 top-k,不做 judge_ranking
2512
- fused = fused_all[:k]
2546
+ fused = fused_all[:_k_fetch]
2513
2547
  judge = False # 早停时跳过资格判定
2514
2548
  judge_ranking = False
2515
2549
  elif judge and judge_ranking:
@@ -2521,7 +2555,7 @@ class MdCGOS(MdCG):
2521
2555
  # qualified result (including the deterministic id tie).
2522
2556
  # A fixed oversampling window can run out of safe candidates.
2523
2557
  upper = max(fs, fs * 0.5)
2524
- if (k > 0 and len(kept) == k
2558
+ if (_k_fetch > 0 and len(kept) == _k_fetch
2525
2559
  and (-upper, nid) >= (-kept[-1][1], kept[-1][0])):
2526
2560
  break
2527
2561
  node, s = node_by_id[nid]
@@ -2534,14 +2568,14 @@ class MdCGOS(MdCG):
2534
2568
  continue
2535
2569
  kept.append((nid, fs if st == STATE_ACCEPT else fs * 0.5))
2536
2570
  kept.sort(key=lambda x: (-x[1], x[0]))
2537
- if k > 0:
2538
- kept = kept[:k]
2571
+ if _k_fetch > 0:
2572
+ kept = kept[:_k_fetch]
2539
2573
  kept.sort(key=lambda x: (-x[1], x[0]))
2540
2574
  if _ta_tier:
2541
2575
  kept.sort(key=lambda x: _ta_tier.get(x[0], 2)) # 稳定排序:交集者前置
2542
- fused = kept[:k]
2576
+ fused = kept[:_k_fetch]
2543
2577
  else:
2544
- fused = fused_all[:k]
2578
+ fused = fused_all[:_k_fetch]
2545
2579
 
2546
2580
  results = []
2547
2581
  # P2-2(§5.2):默认召回路径上的**拒绝域双语义**——与 `MdCG._emit` 同款
@@ -2679,6 +2713,83 @@ class MdCGOS(MdCG):
2679
2713
  view=view, extra=_cache_extra, clock_window=_query_window)
2680
2714
  if _rrf_dropped:
2681
2715
  stat["min_score"] = _rrf_min
2716
+ # ===== 结构信号重排(章节路由 + 元素覆盖):bench 读数驱动,缺省关 =====
2717
+ # 读数(六元素判断题 476,gold=evidence 行号):gold@1 49.6→52.5 / @3 71.9→85.7 / @10 92.0→96.2。
2718
+ # 只在**已召回候选集内**重排(不改候选集、不过滤)⇒ 无召回损失风险;
2719
+ # 与 recent_tail 的顺序无关(tail 是 0 分补尾,重排在补尾之前更干净)。
2720
+ _struct_boosted = False
2721
+ try:
2722
+ if (int(os.environ.get("MDCG_STRUCT_BOOST", "0")) > 0
2723
+ and results and q):
2724
+ from . import structboost as _sb # noqa: PLC0415
2725
+ results = _sb.rerank(results, q)
2726
+ _struct_boosted = True
2727
+ except Exception: # noqa: BLE001 —— 重排失败回退原序,绝不拖崩检索
2728
+ _struct_boosted = False
2729
+ # ===== 时间桶重排(主库「章节=写入日期」):缺省关,超取路径与 struct 共用 =====
2730
+ # 读数(主库 k=20 池):同日期在 top-5 的占比 10% → 37.5%;池内含该日期时有候选的日期到 100%。
2731
+ # 边界(实测):候选里**没有**那天的节点时重排无效——那需要「按日期二次召回」,
2732
+ # 当前实现(timeboost.scoped_recall)在主库实测 2–17 秒且只有 0–4/6 命中,**未接线**。
2733
+ _time_boosted = False
2734
+ try:
2735
+ if _timeboost_on and results and q and _rerank_now:
2736
+ from . import timeboost as _tb # noqa: PLC0415
2737
+ results = _tb.rerank(results, q, _rerank_now, k=k)
2738
+ _time_boosted = True
2739
+ except Exception: # noqa: BLE001
2740
+ _time_boosted = False
2741
+ if (_struct_boosted or _time_boosted) and k:
2742
+ results = results[:k] # 超取 → 重排 → 截回 k(对外语义不变)
2743
+ # issue #814 后续 / Ornn8 测评建议②(读取策略立项单 A 之外的最小项):
2744
+ # **cutoff 邻近保障**——检索完成后,把「最近 N 条用户轮次」中与 query
2745
+ # 有词法交集、且尚未出现在结果里的事件,按 0 分追加到结果**尾部**。
2746
+ # 动机(测评 turn16/75/25 漏检):相关但「不相似」的最近事实会被多路排序挤掉;
2747
+ # 它们是用户刚刚说过的话,即使 RRF 排不进 k,也必须可见。
2748
+ # 设计约束:**不进热路径缓存**(每轮 recent 不同,缓存键无法表达);
2749
+ # **不参与打分**(score=0.0,打乱正排等于换算法);meta 记 recent_tail 计数。
2750
+ _recent_tail_n = 0
2751
+ try:
2752
+ _rt_n = int(os.environ.get("MDCG_RECENT_TAIL", "6"))
2753
+ if _rt_n > 0 and results:
2754
+ _have_ids = {r[0].get("id") for r in results}
2755
+ _q_terms = [t.lower() for t in re.split(r"[\s,,、;;]+", q or "")
2756
+ if len(t) >= 2]
2757
+ _tail = []
2758
+ _have_texts = [str(r[0].get("content") or "") for r in results]
2759
+ for _ev in self.recent_events(limit=max(20, _rt_n * 4),
2760
+ roles=["user"]):
2761
+ if len(_tail) >= _rt_n:
2762
+ break
2763
+ _txt = str(_ev.get("text") or "")
2764
+ if not _txt or _ev.get("id") in _have_ids:
2765
+ continue
2766
+ # 判重边界(B10 修订裁定):补尾**只按事件 id 查重**,不做内容级判重。
2767
+ # 理由:「(轮20)灯箱已经报价」与正排命中的「灯箱已报价」是同一事实的
2768
+ # 不同措辞,词面判重(子串/分词覆盖)都会**漏判或误判**——语义判重
2769
+ # 属于跨层职责(将来可由 memory 层的 dup 信号提供),不进检索面。
2770
+ # 代价接受:同一事实可能正排一次 + 补尾一次(≤2 次出现,有 recent_event
2771
+ # 标记可识别)。宁可重复可见,不可静默丢失——与 #802/#811 的「不过滤
2772
+ # 就显式」是同一条哲学。
2773
+ _low = _txt.lower()
2774
+ if _q_terms and not any(t in _low for t in _q_terms):
2775
+ continue
2776
+ _tail.append({
2777
+ "id": _ev.get("id"),
2778
+ "frontmatter": {"tags": _ev.get("tags") or [],
2779
+ "recent_event": True},
2780
+ "content": _txt,
2781
+ "path": "_recent.jsonl#" + str(_ev.get("id")),
2782
+ "recent_event": True,
2783
+ })
2784
+ for _node in _tail:
2785
+ # issue #111 契约:打分层内 "state" 键字面量恰 1 处(取值=judge 结果)——
2786
+ # recent_tail 不自造 state(由 judge 面给),只给 reason。
2787
+ results.append((_node, 0.0,
2788
+ {"reason": "recent_tail"},
2789
+ []))
2790
+ _recent_tail_n += 1
2791
+ except Exception: # noqa: BLE001 —— 保障面不拖崩主检索
2792
+ _recent_tail_n = 0
2682
2793
  # issue #672:把生效的时效口径如实透出——调用方看名字容易以为「只给有效的」,
2683
2794
  # 读 meta 一眼可辨(只排过期 / 未启用)。
2684
2795
  _validity_meta = ({"validity_scope": "expired_only"} if validity
@@ -2688,6 +2799,9 @@ class MdCGOS(MdCG):
2688
2799
  if _rrf_min > 0 else {}),
2689
2800
  **(_rrf_note or {}),
2690
2801
  "paths": per_path, "fused": len(results),
2802
+ "recent_tail": _recent_tail_n,
2803
+ "struct_boost": _struct_boosted,
2804
+ "time_boost": _time_boosted,
2691
2805
  "judge_ranking": bool(judge and judge_ranking),
2692
2806
  "judge_filtered": filtered,
2693
2807
  "early_stopped": early_stopped,
@@ -2702,6 +2816,22 @@ class MdCGOS(MdCG):
2702
2816
  # ================= 7. budget-driven pack =================
2703
2817
 
2704
2818
  # 生效条件:query(配合 use_rrf 取 items)逐条按 budget_tokens 与 max_item_tokens 装包:若 used+t > budget_tokens,则 max_item_tokens 为真且 room=budget_tokens-used 不小于 min_excerpt(max_item_tokens 为真时取 max(1, min(50, max_item_tokens // 5)),否则为 0)时按 keep=min(max_item_tokens, room) 摘录,摘录后 est_tokens<=0 则该条以 excerpt_empty 进 skipped 并 continue;否则以 oversize_or_over_budget 进 skipped 并 continue;未超预算则计入 used 并 append,include_recent 为真时再按 left=budget_tokens-used 追加 recent_limit 条近期事件(逐条 est_tokens 不超过 left 才计入),最终返回含 pack/tokens_used/budget/skipped/recent/meta 的 dict;validity 真值时向候选层透传时效过滤(只排已过期)。
2819
+ def _topic_aggregates(self, pack, query, min_members: int = 2,
2820
+ max_groups: int = 5) -> list:
2821
+ """跨轮状态聚合(读取策略 A 项):把同话题的命中条目排成状态时间线。
2822
+
2823
+ 动机(Ornn8 终局报告):答案状态常**散在多轮**里(轮9 报价 + 轮20 未安排制作),
2824
+ search 只按单轮相关性交付,调用方拼不出完整状态。本方法**不改排序**,
2825
+ 只在装包后给一个「同话题 → 时间线」的聚合视图。
2826
+
2827
+ 聚合键:优先用 tags 与 query 的亲和(`_tag_affinity`,与 entity 路同源),
2828
+ 无命中的条目归到 `__untagged__` 组(不输出,避免噪声)。
2829
+ `state` 只读**既有字段**(qual 结果 / verification 状态),不自造——
2830
+ 遵守 issue #111「打分层不自造 state」的同一条纪律。
2831
+ """
2832
+ from .topicagg import aggregate as _agg # noqa: PLC0415 —— 聚合实现单点
2833
+ return _agg(pack, query, min_members=min_members, max_groups=max_groups)
2834
+
2705
2835
  def recall(self, query: str, budget_tokens: int = DEFAULT_BUDGET, k: int = 20,
2706
2836
  layer: str = None, context=None, roles=None,
2707
2837
  include_work: bool = False, judge: bool = True, use_rrf: bool = True,
@@ -2711,7 +2841,7 @@ class MdCGOS(MdCG):
2711
2841
  validity=None, max_item_tokens: int = DEFAULT_MAX_ITEM_TOKENS,
2712
2842
  start_time=None, end_time=None, start_operator=None,
2713
2843
  end_operator=None, time_axis=None, view=None,
2714
- excerpt_strategy: str = "prefix"):
2844
+ excerpt_strategy: str = "prefix", now=None):
2715
2845
  """按 token 预算装包:装到预算花完为止。
2716
2846
 
2717
2847
  装包策略(2026-09-14 调整):
@@ -2766,6 +2896,26 @@ class MdCGOS(MdCG):
2766
2896
  if _v is not None: # 时间算子透传(None = 未启用,不入参)
2767
2897
  kw[_k] = _v
2768
2898
  results, meta = self.search_rrf(query, **kw)
2899
+ # 【外测诊断 2026-11-12】实测「同一 query:search 把资料卡排第 1(0.564),
2900
+ # recall 的候选集里却 0 条(paths.lexical=1)」——断点在**候选生成**,不在过滤。
2901
+ # 故按**实体标签直取**资料卡并入候选:确定性、与词法切词无关,卡不再依赖 lexical 命中。
2902
+ try:
2903
+ _extra = self._profile_candidates(query)
2904
+ # 【外测 2026-11-12】34/39 个值「原轮次没进 pack」;而资料卡每条事实带「来源 <id>」
2905
+ # ⇒ 把**被注入卡的源轮次**一并拉进候选:卡给属性、源轮次给原句。
2906
+ _extra += self._profile_source_nodes(_extra, limit=4)
2907
+ # 【外测 2026-11-12 实验】自述轮次通例召回:值覆盖 12.8%→35.9%、题级全命中 1/19→6/19。
2908
+ # 零模型、与题目无关;读时只 load 小索引(写时登记),不扫全库。
2909
+ _extra += self._selfstmt_nodes(limit=6)
2910
+ if _extra:
2911
+ _seen = {r[0].get("id") for r in results if r and r[0]}
2912
+ for _n, _sc, _q, _p in _extra:
2913
+ if _n.get("id") not in _seen:
2914
+ results.append((_n, _sc, _q, _p))
2915
+ if isinstance(meta, dict):
2916
+ meta["profile_injected"] = len(results) - len(_seen)
2917
+ except Exception: # noqa: BLE001 —— 注入面不拖崩召回
2918
+ pass
2769
2919
  items = [(r[0], r[1], r[2], r[3]) for r in results]
2770
2920
  else:
2771
2921
  res, meta = self.search(query, layer=layer, k=k, context=context,
@@ -2853,8 +3003,363 @@ class MdCGOS(MdCG):
2853
3003
  recent.append({"role": ev.get("role"), "t": ev.get("t"),
2854
3004
  "text": ev.get("text"), "tokens": t,
2855
3005
  "tags": ev.get("tags") or []})
3006
+ # ===== 桶作用域召回(日期 + 会话是默认坐标;会话优先,日桶按日期倒排)=====
3007
+ # 使用者口径(2026-11-09):这两类是**默认开启**的通用设置,不是可选优化;
3008
+ # 「条件才是筛选方式」,故桶召回只按查询词面筛选 + 时间降序,**不改正排名次**(score=0)。
3009
+ # 关闭:MDCG_BUCKET_SCOPE=0。预算从同一包预算里扣(诚实口径:附了就是占了)。
3010
+ _bucket_scope_n = 0
3011
+ try:
3012
+ if (os.environ.get("MDCG_BUCKET_SCOPE", "1") != "0"
3013
+ and pack is not None):
3014
+ from . import bucketscope as _bs # noqa: PLC0415
3015
+ # 【#843】validity 必须透传:桶补召回在候选检索**之后**追加,
3016
+ # 不传就会把调用方显式排除的过期记忆重新装回 pack(issue #843 复现)。
3017
+ # 【外测 2026-11-11 卡点 2】时钟必须从**最外层 API** 透传:
3018
+ # 早先这里只认内部 _rerank_clock / time.time(),宿主或外部复测走 recall 时
3019
+ # 逻辑时间被真实时钟覆盖(resolved_dates 返回真实今天)。与 #111 同纪律。
3020
+ _scope_now = (now if now is not None else
3021
+ (_rerank_clock if '_rerank_clock' in dir() else time.time()))
3022
+ _extra = _bs.scope_recall(self, query, session, _scope_now,
3023
+ validity=bool(validity))
3024
+ _have = {e.get("id") for e in pack}
3025
+ for _node, _score, _qual, _prov in _extra:
3026
+ if _node.get("id") in _have:
3027
+ continue
3028
+ _txt = str(_node.get("content") or "")
3029
+ _t = est_tokens(_txt)
3030
+ if used + _t > budget_tokens:
3031
+ continue
3032
+ fm = _node.get("frontmatter") or {}
3033
+ # 【外测 v2.1】metadata 必须带上 resolved_dates:早先只复制 state/reason/bucket,
3034
+ # 调用方在 pack 里取不到解析出的绝对日期,第 3 条建议等于没生效。
3035
+ _bm = {"state": (_qual or {}).get("state"),
3036
+ "reason": "bucket_scope",
3037
+ "bucket": (_qual or {}).get("bucket")}
3038
+ if (_qual or {}).get("resolved_dates"):
3039
+ _bm["resolved_dates"] = _qual["resolved_dates"]
3040
+ if (_qual or {}).get("fallback"):
3041
+ _bm["fallback"] = _qual["fallback"]
3042
+ pack.append({"id": _node.get("id"), "score": 0.0,
3043
+ "state": (_qual or {}).get("state"),
3044
+ "tokens": _t, "content": _txt,
3045
+ "frontmatter": fm, "provenance": _prov or [],
3046
+ "metadata": _bm})
3047
+ used += _t
3048
+ _bucket_scope_n += 1
3049
+ if _bucket_scope_n >= _bs.DEFAULT_CAP:
3050
+ break
3051
+ except Exception: # noqa: BLE001 —— 桶召回失败不拖崩装包
3052
+ _bucket_scope_n = 0
3053
+ # ===== 检索裁定:结论必须由确定性规则裁决(structural: mem_ruling_vector_ref_deterministic)=====
3054
+ # 向量/语义相似度只提供候选参考;**最终名次由词法·时间·空间·交互四类可数信号重排**,
3055
+ # 且必须确定性可回放。纯后处理:不改 pack 内容、不改 fused 分数,只调整交付顺序。
3056
+ # 缺省关(MDCG_DET_RERANK=0);开启后 meta 透出 det_reranked 与时钟来源。
3057
+ det_reranked = False
3058
+ _rerank_clock = (meta.get('clock') if isinstance(meta, dict) else None) or time.time()
3059
+ _clock_source = ('search_meta' if (isinstance(meta, dict) and meta.get('clock'))
3060
+ else 'recall_local')
3061
+ try:
3062
+ if int(os.environ.get('MDCG_DET_RERANK', '0')) > 0 and len(pack) >= 2:
3063
+ from . import detrerank as _dr # noqa: PLC0415
3064
+ _items = [({'id': e.get('id'),
3065
+ 'content': e.get('content'),
3066
+ 'frontmatter': e.get('frontmatter')},
3067
+ float(e.get('score') or 0.0), {}, []) for e in pack]
3068
+ # 模式可配(bench 用):tiebreak(缺省,零风险)/ window(有界上浮)/ replace(v1,已被读数否决)
3069
+ _mode = (os.environ.get('MDCG_DET_MODE') or 'tiebreak').strip().lower()
3070
+ _ranked = _dr.rerank_v2(_items, query, _rerank_clock,
3071
+ mode=_mode, session=session)
3072
+ _order = {it[0][0]['id']: i for i, it in enumerate(_ranked)}
3073
+ pack.sort(key=lambda e: _order.get(e.get('id'), len(pack)))
3074
+ # 四信号读数随包透出(可审计:谁因为什么排在前面)
3075
+ _sig_by_id = {it[0][0]['id']: it[2] for it in _ranked}
3076
+ for e in pack:
3077
+ sig = _sig_by_id.get(e.get('id'))
3078
+ if sig is not None:
3079
+ e['det'] = {'signals': sig, 'score': _dr.score(sig)}
3080
+ det_reranked = True
3081
+ except Exception: # noqa: BLE001 —— 重排失败回退原序,绝不拖崩装包
3082
+ det_reranked = False
3083
+ # ===== 读取策略改造 · A 项:跨轮状态聚合(Ornn8 测评建议①,+2~4 点最大头)=====
3084
+ # 病灶(report 原文):「答案状态散在轮9 和轮20 两条里,检索给了直接相关的一条,
3085
+ # 拼不出完整状态」——这是**记忆组织**问题:search 只按单轮相关性给材料。
3086
+ # 本段不改排序、不改打分,只在**装包之后**追加一个聚合视图:同一话题的命中条目
3087
+ # 按时间排在一起,附「该话题的状态时间线」,让调用方能拼出完整状态。
3088
+ # 关闭:MDCG_TOPIC_AGG=0。
3089
+ aggregates = []
3090
+ try:
3091
+ if int(os.environ.get("MDCG_TOPIC_AGG", "1")) > 0 and len(pack) >= 2:
3092
+ aggregates = self._topic_aggregates(pack, query)
3093
+ except Exception: # noqa: BLE001 —— 聚合面不拖崩装包
3094
+ aggregates = []
3095
+ if isinstance(meta, dict):
3096
+ meta["det_reranked"] = det_reranked
3097
+ if det_reranked:
3098
+ meta["det_clock_source"] = _clock_source
3099
+ meta["det_mode"] = _mode
3100
+ # 【2026-11-11 外测】状态序列必须作为**一等公民**进材料:
3101
+ # 实测(Ornn8 B 类 19 题)——模型面对 20–30 条按检索分排的片段,
3102
+ # **没有确定性的时序依据**去选「最早那次」:同一题两次跑给出不同锚点,
3103
+ # 提示词让它「按日期排序再取最早」,它排的是自己回忆的顺序而不是材料里的日期序。
3104
+ # 这里按 created_at 升序给出 (date, id, head) 三列——模型读表即得时序,不必归纳。
3105
+ # 注意:这是**节点级**时间线(不含实体/槽位抽取),是「状态追踪」的便宜中间态。
3106
+ # 【2026-11-12 外测】pack 条目自带**格式化日期**:`frontmatter.created_at` 是 epoch 浮点,
3107
+ # 下游任何 `str(v)[:10]` 都会截出 `1784043360` 这种假日期(外测脚手架真实踩过:
3108
+ # 材料前缀变成 `[1784043360]`,模型被喂了机器值;连带把『模型编造时间戳』这条归因带偏)。
3109
+ # 结构性根治:在这里给出 `created_at_date`(YYYY-MM-DD),下游不该再自己截字符串。
3110
+ # 取不到合法时间戳时不编造:置 None(下游按缺失处理,不得当今天)。
3111
+ for _e in pack or []:
3112
+ _fm = _e.get("frontmatter") or {}
3113
+ _ts = _fm.get("created_at") or _fm.get("valid_from")
3114
+ _d = None
3115
+ if _ts is not None:
3116
+ try:
3117
+ _d = time.strftime("%Y-%m-%d", time.localtime(float(_ts)))
3118
+ except (TypeError, ValueError, OSError):
3119
+ _d = None
3120
+ _e["created_at_date"] = _d
3121
+ # 【2026-11-12 使用者裁定】相对日期**确定性地**补绝对日期,且内联在正文里:
3122
+ # 外测判官原文:视图节给了绝对日期,模型仍照抄「周一/昨天」⇒ 平行章节被忽略,
3123
+ # 只有正文内联标注才会被读到。锚点取本条的陈述时刻(created_at),不是今天。
3124
+ try:
3125
+ _e["content_dated"] = reldate.annotate(_e.get("content") or "", _ts)
3126
+ except Exception: # noqa: BLE001 —— 标注失败不拖崩装包,退化为原文
3127
+ _e["content_dated"] = _e.get("content")
3128
+ # 【情景层 v0.1 / 档1 验收主因】资料卡配额:外测实测每题 pack 里挤进 16–30 张 profile 卡,
3129
+ # 把 30 条名额吃光,**正确的那张反而被挤掉**(这是档 1 未涨分的第一机制,比错名更普遍)。
3130
+ # 故对 profile-* 单独设上限(缺省 3,`MDCG_PROFILE_CARDS` 可调),按已有 score 取前 N。
3131
+ _prof_cap = 3
3132
+ try:
3133
+ _prof_cap = int(os.environ.get("MDCG_PROFILE_CARDS", "3"))
3134
+ except ValueError:
3135
+ _prof_cap = 3
3136
+ _profs = [(i, e) for i, e in enumerate(pack or [])
3137
+ if str(e.get("id") or "").startswith("profile-")]
3138
+ if _prof_cap >= 0 and len(_profs) > _prof_cap:
3139
+ # 配额内**优先保留非 event 卡**:event 卡一天一张、数量最多,按纯 score 排会把
3140
+ # role/person 卡挤掉(外测实证 ②=0 的直接成因)。
3141
+ def _rank(it):
3142
+ _nid = str(it[1].get("id") or "")
3143
+ _is_ev = 1 if _nid.startswith("profile-event-") else 0
3144
+ return (_is_ev, -(float(it[1].get("score") or 0.0)))
3145
+ _keep = set()
3146
+ # 【外测 ③ 回退 4→2】配额不能把「score 最高的那张」也按类型筛掉:
3147
+ # 给 1 个豁免位,其余再按类型优先补足。
3148
+ _by_score = sorted(_profs, key=lambda x: -(float(x[1].get("score") or 0.0)))
3149
+ if _by_score:
3150
+ _keep.add(_by_score[0][0])
3151
+ for _i, _e in sorted(_profs, key=_rank):
3152
+ if len(_keep) >= _prof_cap:
3153
+ break
3154
+ _keep.add(_i)
3155
+ pack = [e for i, e in enumerate(pack)
3156
+ if i in _keep or not str(e.get("id") or "").startswith("profile-")]
3157
+ timeline = self._pack_timeline(pack)
3158
+ # 【2026-11-11 外测第二阶段】实测「原文+timeline」B 类 19 题稳定通过 2→15;
3159
+ # 「只给 timeline」仍达 14 ⇒ 信息大半在序列里。剩下的 4 题属「改期终态 / 多要素合成」,
3160
+ # 需要**按主题归并**的序列(不是全表一张)。这里用已有字段做廉价归并:
3161
+ # 优先 frontmatter.bucket(条件桶 cond_<topic>_<hash> 天然是主题轴),其次首个 tag。
3162
+ timeline_groups = self._pack_timeline_groups(pack)
2856
3163
  return {"pack": pack, "tokens_used": used, "budget": budget_tokens,
2857
- "skipped": skipped, "recent": recent, "meta": meta}
3164
+ "skipped": skipped, "recent": recent, "meta": meta,
3165
+ "aggregates": aggregates, "timeline": timeline,
3166
+ "timeline_groups": timeline_groups}
3167
+
3168
+
3169
+
3170
+
3171
+
3172
+ # 生效条件:pack 为装好的条目;返回按「主题轴」归并的序列 [{"topic","items":[{date,id,head}]}]
3173
+ def _pack_timeline_groups(self, pack):
3174
+ """把时间线按**主题轴**归并(廉价版「七维图」的归并层,不用抽取器)。
3175
+
3176
+ 为什么需要:外测实测「原文+timeline」已把 B 类 19 题从 2 救到 15,
3177
+ 但剩 4 题是「改期终态 / 多要素合成」——它们要的是**同一主题下的序列**
3178
+ (最终值是什么、哪几个要素同时在场),而不是所有主题混在一张表里。
3179
+
3180
+ 主题轴取已有字段,按优先级:
3181
+ ① `frontmatter.bucket`(条件桶 `cond_<topic>_<hash>`,本身就是主题分组);
3182
+ ② 首个 `tag`(如 `domain:*` / 项目名);
3183
+ ③ 都缺 ⇒ "未分组"。
3184
+ 这是**启发式**:同一条件桶未必同主题,覆盖不全时仍有 timeline 兜底。
3185
+ """
3186
+ groups: dict = {}
3187
+ for e in pack or []:
3188
+ fm = e.get("frontmatter") or {}
3189
+ ts = fm.get("created_at") or fm.get("valid_from")
3190
+ date = ""
3191
+ if ts is not None:
3192
+ try:
3193
+ date = time.strftime("%Y-%m-%d", time.localtime(float(ts)))
3194
+ except (TypeError, ValueError, OSError):
3195
+ date = ""
3196
+ head = ""
3197
+ for line in str(e.get("content") or "").splitlines():
3198
+ s0 = line.strip()
3199
+ if not s0 or s0.startswith("#"):
3200
+ continue
3201
+ head = s0[:80]
3202
+ break
3203
+ topic = fm.get("bucket")
3204
+ if not topic:
3205
+ tags = fm.get("tags") or []
3206
+ topic = tags[0] if isinstance(tags, (list, tuple)) and tags else "未分组"
3207
+ groups.setdefault(str(topic), []).append(
3208
+ {"date": date, "id": e.get("id"), "head": head})
3209
+ out = []
3210
+ for topic, items in groups.items():
3211
+ items.sort(key=lambda x: (x["date"] or "9999-99-99", str(x.get("id") or "")))
3212
+ out.append({"topic": topic, "items": items})
3213
+ out.sort(key=lambda g: (-len(g["items"]), g["topic"]))
3214
+ return out
3215
+
3216
+
3217
+ #: 注入分类型配额(外测实证:event 卡一天一张、天数多、分高,会把 role/person 卡挤光,
3218
+ #: 而 event 卡对「姓名/年龄/职业」这类属性题没有帮助)。
3219
+ _PROFILE_INJECT_QUOTA = (('role', 2), ('person', 2), ('place', 1))
3220
+
3221
+ # 生效条件:无参;返回自述轮次节点(写时登记的小索引,limit 控制注入量)
3222
+ def _selfstmt_nodes(self, limit=None):
3223
+ """自述轮次注入:零模型、与题目无关(外测实证 12.8%→35.9% 的那条规则)。
3224
+
3225
+ 写时登记、读时 load 小索引 —— 不做每查询全库扫(2k 节点 ≈ 2s 不可接受)。
3226
+ 只注入**已存在**的节点;去重;受 limit 约束防淹没。
3227
+ """
3228
+ if limit is None:
3229
+ try:
3230
+ limit = int(os.environ.get("MDCG_SELFSTMT_LIMIT", "20"))
3231
+ except ValueError:
3232
+ limit = 20
3233
+ try:
3234
+ from . import selfstmt as _ss
3235
+ ids = _ss.load(getattr(self, "root", ""))
3236
+ except Exception:
3237
+ return []
3238
+ # 【外测 2026-11-12】原实现 `reversed(ids)` + limit=6(最新优先)把**早期自述轮次**全滤掉:
3239
+ # P16 的「我最早在江北…学徒」、P17 的「我叫谈书宁…」都排不进最近 6 ⇒ 收益被吃掉
3240
+ # (实验全量注入 35.9%,实现 12.8%)。改为:**按信息密度降序**,限量放宽到 20(登记总量 3–16/库)。
3241
+ scored = []
3242
+ for _pos, nid in enumerate(ids):
3243
+ node = self.get(nid)
3244
+ if not node:
3245
+ continue
3246
+ scored.append((-_ss.density(node.get("content") or ""), -_pos, node))
3247
+ scored.sort(key=lambda x: (x[0], x[1]))
3248
+ out, seen = [], set()
3249
+ for _d, _p, node in scored:
3250
+ nid = str(node.get("id") or "")
3251
+ if len(out) >= limit:
3252
+ break
3253
+ if nid in seen:
3254
+ continue
3255
+ seen.add(nid)
3256
+ out.append((node, 0.85, {"path": "self_stmt", "density": -_d}, "self_stmt"))
3257
+ return out
3258
+
3259
+ # 生效条件:cards 为已注入的资料卡候选;返回其事实行里「来源 <id>」指向的源节点
3260
+ def _profile_source_nodes(self, cards, limit=4):
3261
+ """资料卡的**源轮次**注入:卡给属性、源轮次给原句(外测:34/39 值缺的是原句轮次)。
3262
+
3263
+ 卡正文事实行形如 `- 2026-05-12 | 文本(来源 n1)`;抽出 n1 即源节点 id。
3264
+ 只注入已存在的节点;去重;受 limit 约束(防淹没)。
3265
+ """
3266
+ if not cards:
3267
+ return []
3268
+ import re as _re
3269
+ out, seen = [], set()
3270
+ for node, *_rest in cards:
3271
+ body = (node or {}).get("content") or ""
3272
+ for nid in _re.findall(r"(来源\s*([^)\s]+)\s*)", body):
3273
+ if nid in seen or len(out) >= limit:
3274
+ continue
3275
+ seen.add(nid)
3276
+ src = self.get(nid)
3277
+ if src:
3278
+ out.append((src, 0.9, {"path": "profile_source"}, "profile_source"))
3279
+ return out
3280
+
3281
+ # 生效条件:query 非空;返回按实体标签命中的资料卡候选 [(node, score, qual, prov)]
3282
+ def _profile_candidates(self, query, limit=6):
3283
+ """按**实体标签**直取资料卡(外测实证:search 能排第 1,recall 候选集却没有)。
3284
+
3285
+ 判据:卡的 tags 含 `person:` / `role:` / `place:` 前缀,且该实体名出现在 query 里。
3286
+ 不走词法切词——长句在 lexical 里可能只剩 1 个词,卡就进不来。
3287
+ """
3288
+ q = str(query or "")
3289
+ if not q:
3290
+ return []
3291
+ out = []
3292
+ # 【外测 2026-11-12】16/19 题是**第一人称提问**(「我全名咋写 / 多大来着 / 我住哪个城市」),
3293
+ # query 里没有实体名 ⇒ 按字面匹配永远命中不了。语言上「我」就指向 speaker,
3294
+ # 故:query 含自指且配置了 MDCG_ROLE_USER 时,优先注入该角色卡(确定性,不猜)。
3295
+ import os as _os
3296
+ _me = (_os.environ.get("MDCG_ROLE_USER") or "").strip()
3297
+ if _me and any(w in q for w in ("我", "咱", "本人")):
3298
+ _self_node = self.get("profile-role-" + _me)
3299
+ if _self_node:
3300
+ out.append((_self_node, 1.0, {"path": "profile_self"}, "profile_self"))
3301
+ _quota = dict(self._PROFILE_INJECT_QUOTA)
3302
+ _taken = {k: 0 for k in _quota}
3303
+ # G1a:从 cg.index 取回的 nodes 必须**先取快照**(并发写会 dictionary changed size)。
3304
+ for nid, rec in list(((self.index or {}).get("nodes") or {}).items()):
3305
+ if not str(nid).startswith("profile-"):
3306
+ continue
3307
+ _parts = str(nid).split("-", 2)
3308
+ _kind = _parts[1] if len(_parts) >= 3 else ""
3309
+ if _kind not in _taken:
3310
+ continue # 非 role/person/place(含 event)**不参与注入**
3311
+ if _taken[_kind] >= _quota[_kind]:
3312
+ continue
3313
+ tags = (rec or {}).get("tags") or []
3314
+ hit = False
3315
+ for t in tags:
3316
+ for pre in ("person:", "role:", "place:"):
3317
+ if str(t).startswith(pre) and str(t)[len(pre):] in q:
3318
+ hit = True
3319
+ break
3320
+ if hit:
3321
+ break
3322
+ if not hit:
3323
+ continue
3324
+ node = self.get(nid)
3325
+ if node:
3326
+ out.append((node, 1.0, {"path": "profile_entity"}, "profile_entity"))
3327
+ _taken[_kind] += 1
3328
+ if len(out) >= limit:
3329
+ break
3330
+ return out
3331
+
3332
+ # 生效条件:pack 为 recall 装好的条目列表;返回按 created_at **升序**的时间线 [{"date","id","head"}]
3333
+ def _pack_timeline(self, pack):
3334
+ """把装好的条目压成「日期 | 事件首句」时间线(issue:模型无法从片段做时序归纳)。
3335
+
3336
+ 为什么必须由算法给:实测同一道「最早那次」题两次跑给出不同锚点 —— 说明模型没有
3337
+ 确定性依据在多个同主题候选里挑最早的。日期与事件首句都是**已有字段**,
3338
+ 压成表零成本;模型只需读表,不必排序。
3339
+
3340
+ 只取首句(≤80 字)并跳过 CCG 头(`# 功能名:` 等六要素行),避免把元数据当事件。
3341
+ """
3342
+ out = []
3343
+ for e in pack or []:
3344
+ fm = e.get("frontmatter") or {}
3345
+ ts = fm.get("created_at") or fm.get("valid_from")
3346
+ date = None
3347
+ if ts is not None:
3348
+ try:
3349
+ date = time.strftime("%Y-%m-%d", time.localtime(float(ts)))
3350
+ except (TypeError, ValueError, OSError):
3351
+ date = None
3352
+ body = ""
3353
+ for line in str(e.get("content") or "").splitlines():
3354
+ s0 = line.strip()
3355
+ if not s0 or s0.startswith("#"):
3356
+ continue
3357
+ body = s0[:80]
3358
+ break
3359
+ out.append({"date": date or "", "id": e.get("id"), "head": body})
3360
+ out.sort(key=lambda x: (x["date"] or "9999-99-99", str(x.get("id") or "")))
3361
+ return out
3362
+
2858
3363
 
2859
3364
  # ================= 1. Fix pairs 自动挖掘 =================
2860
3365
 
@@ -4948,6 +5453,27 @@ class MdCGOS(MdCG):
4948
5453
  node_id or "", tags_add=tags_add, tags_remove=tags_remove,
4949
5454
  condition_space_patch=condition_space_patch,
4950
5455
  depends_on=depends_on, dry_run=_dry)
5456
+ if act == "profiles":
5457
+ # 【资料树档 1,2026-11-12 使用者裁定】人物/地点/事件 = 核心状态;物品/情绪 = 辅助(只进 facet)。
5458
+ # 把散落节点聚合成**可召回的一等节点**(profile-<kind>-<slug>):外测归因证明弱项 19 题
5459
+ # 「要素不在 pack」(2/19),单点事实需要稠密容器才召得回。
5460
+ # 幂等:渲染结果逐字比对,变了才写;增量:事实按 (日期, 节点 id) 稳定排序,新节点只追加。
5461
+ # 缺省 dry_run:沿用 maintain 的「预演优先」口径,apply=True 才落盘。
5462
+ from . import profiles as _prof
5463
+ _dry_p = (not apply) if dry_run is None else (bool(dry_run) or not apply)
5464
+ _st = _prof.build(self, dry_run=_dry_p, limit=limit)
5465
+ _st.update({"ok": True, "op": "maintain", "action": "profiles"})
5466
+ return _st
5467
+ if act == "selfstmt":
5468
+ # 【自述轮次登记,2026-11-12 外测实证】存量库补登入口。
5469
+ # 写时钩子已在 add() 里自动登记;此处用于「已有图、未重写节点」的库。
5470
+ # dry_run 口径同 maintain 其余动作:apply=True 才落盘。
5471
+ from . import selfstmt as _ss
5472
+ _dry_s = (not apply) if dry_run is None else (bool(dry_run) or not apply)
5473
+ _st = _ss.rebuild(self, dry_run=_dry_s, limit=limit or 100000)
5474
+ _st.update({"ok": True, "op": "maintain", "action": "selfstmt",
5475
+ "ids_sample": _ss.load(self)[:5]})
5476
+ return _st
4951
5477
  if act == "importance":
4952
5478
  return weights.recalc(self, layer=layer, limit=limit, apply=apply,
4953
5479
  min_delta=(weights.APPLY_DELTA if min_delta is None
@@ -6902,6 +7428,14 @@ class MdCGSecure(MdCGOS):
6902
7428
  nid = super().add(node_id, content, layer=layer, sensitivity=sens,
6903
7429
  declared_sensitivity=sensitivity, **kw)
6904
7430
  self._index_sensitivity(nid, sens)
7431
+ # 【自述轮次登记】写时判一次(与查询无关),供 recall 读时注入。
7432
+ # 失败一律吞掉:登记只是加速索引,不能影响写入成败。
7433
+ try:
7434
+ from . import selfstmt as _ss
7435
+ if _ss.matches(content):
7436
+ _ss.record(self.root, nid)
7437
+ except Exception:
7438
+ pass
6905
7439
  return nid
6906
7440
 
6907
7441
  # 生效条件:sens 经 _write_sensitivity(id 走基类单点 _rejected_nid)解析——#439:未声明且有既有节点 ⇒ 继承其密级、显式声明原样优先、既有密级判不了则 fail-closed 抛 AccessDenied;先 principal.require_layer_write("rejected", sens) 与 _attribution(kw, sens)(会话归因走三态解析)后转 super().add_rejected,最后按下发的 nid 调 _index_sensitivity 并返回 nid。