@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.
- package/CHANGELOG.en.md +515 -404
- package/CHANGELOG.md +642 -449
- package/README.en.md +244 -240
- package/README.md +272 -262
- package/codebuddy/CODEBUDDY.md +1 -1
- package/docs/discipline/templates/full.md.tmpl +1 -1
- package/docs/discipline/templates/rules.mdc.tmpl +1 -1
- package/docs/en/mdcg/world-model-endpoint.md +1 -1
- package/docs/mdcg/cogmap_ops.md +19 -16
- package/lib/client.js +29 -3
- package/lib/hooks.d.ts +12 -0
- package/lib/hooks.js +43 -1
- package/lib/tools.d.ts +2 -2
- package/md_cg/bucketindex.py +231 -0
- package/md_cg/bucketscope.py +357 -0
- package/md_cg/cohesion.py +337 -0
- package/md_cg/config_registry_bulk.py +24 -10
- package/md_cg/config_validate.py +14 -2
- package/md_cg/constraint_audit.py +231 -0
- package/md_cg/constraint_watch.py +206 -0
- package/md_cg/context_audit.py +240 -0
- package/md_cg/context_plan.py +142 -0
- package/md_cg/detrerank.py +137 -0
- package/md_cg/distill.py +247 -0
- package/md_cg/dossier.py +151 -0
- package/md_cg/entities.py +133 -0
- package/md_cg/fsutil.py +135 -0
- 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 +6044 -5761
- package/md_cg/mdcg.py +501 -16
- package/md_cg/mdcos.py +546 -12
- 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/op_table.py +22 -0
- package/md_cg/probe_c_ledger_integrity.py +258 -0
- package/md_cg/probe_d_retirement_discipline.py +263 -0
- package/md_cg/profiles.py +298 -0
- package/md_cg/protocol.py +7 -1
- package/md_cg/reldate.py +142 -0
- package/md_cg/review_cli.py +6 -1
- package/md_cg/run_tests.py +30 -1
- package/md_cg/scopeselect.py +214 -0
- package/md_cg/scrub.py +66 -9
- package/md_cg/selfstmt.py +139 -0
- package/md_cg/state_extract.py +149 -0
- package/md_cg/state_slots.py +62 -10
- package/md_cg/state_view.py +181 -0
- package/md_cg/structboost.py +179 -0
- package/md_cg/sustain.py +28 -2
- package/md_cg/test_alternatives_historical.py +165 -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_bucket_time_rounds.py +87 -0
- package/md_cg/test_bucketindex.py +130 -0
- package/md_cg/test_bucketscope_early.py +71 -0
- package/md_cg/test_cohesion.py +107 -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_constraint_audit.py +87 -0
- package/md_cg/test_constraint_watch.py +108 -0
- package/md_cg/test_context_audit.py +110 -0
- package/md_cg/test_context_plan.py +81 -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 +14 -2
- package/md_cg/test_issue192_move_layer_indices_guard.py +48 -0
- package/md_cg/test_issue39_utf8_stdio.py +572 -572
- package/md_cg/test_issue413_preimage_failclosed.py +147 -9
- 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_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_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/timeboost.py +223 -0
- package/md_cg/tokens.py +1 -1
- package/md_cg/topicagg.py +142 -0
- package/md_cg/version_anchor.py +84 -1
- package/md_cg/whitebox_kb/wisdom/code_compose.py +33 -5
- package/md_cg/whitebox_kb/wisdom/code_solidified.json +6195 -6195
- package/md_cg/whitebox_kb/wisdom/compose_engine.py +5 -1
- package/md_cg/whitebox_kb/wisdom/role_compose.py +271 -268
- package/package.json +1 -1
- package/src/hooks.ts +43 -1
- package/ui/minimal/payload/build-ui.mjs +41 -2
- package/ui/minimal/payload/lib/client.js +29 -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/state_slots.py
CHANGED
|
@@ -26,8 +26,21 @@
|
|
|
26
26
|
· `tier` =最后有值事件的顶层 `tier` 透传(`append(extra=…)` 会把 extra 并入行
|
|
27
27
|
顶层,故「extra.tier」与「行顶层 tier」是同一处);缺失(键不在或为 None)→
|
|
28
28
|
`TIER_UNSPECIFIED`——**不编造**。
|
|
29
|
-
· `alternatives`
|
|
30
|
-
|
|
29
|
+
· `alternatives`(**本批已落地**,判据见下);`blindspots` 仍**结构在场、恒为空列表**
|
|
30
|
+
——「声明缺口」的判定口径**后置**(P1 事件行尚无该信号),**不得臆造填充**。
|
|
31
|
+
|
|
32
|
+
`alternatives` 判据(本批,2026-11-02)——**只读面,写侧一字未动**:
|
|
33
|
+
定义为「该槽位**曾被断言过、且不等于当前值**的去重值集合」(保持首次出现序)。
|
|
34
|
+
· 明确**不用**「同一时间窗」判「同期」:台账 `t` 是 `time.time()` **记账时刻**,
|
|
35
|
+
不是事件发生时刻;`seq` 是调用方给的轮/序号且**可缺省为 None**。
|
|
36
|
+
拿它们做时间窗判据会把「相隔很久的两次记账」误判成同期 ⇒ 违背「不臆造」。
|
|
37
|
+
· 因此本字段的语义是**历史遗留候选**,比设计稿「同期未决值」弱——已在
|
|
38
|
+
`docs/eval/` 读数文档中标注定级,不冒充强语义。
|
|
39
|
+
· retired 态(值已撤回)下,被撤回的值**仍进 alternatives**(可回溯);
|
|
40
|
+
复位后当前值不入 alternatives,更旧的遗留值仍在。
|
|
41
|
+
· `history=False` 的快速路径(`_project_current_page`)**不保留历史**,
|
|
42
|
+
算不出本字段 ⇒ 恒返回空列表,并在返回值上如实标注 `alternatives_partial=True`
|
|
43
|
+
(**不静默给一个看起来完整的空**)。
|
|
31
44
|
· `history` =该槽位全部事件原样(每条=事件行的 `t/seq/old/new/kind/evidence/
|
|
32
45
|
actor` 七字段,值不改写;缺键取 None);`history=False` 时**不带该键**。
|
|
33
46
|
|
|
@@ -47,8 +60,9 @@ CLI(纯只读人工入口,**恒可用、无开关**):
|
|
|
47
60
|
CLI 是人工排查入口(只读、不改任何状态)。
|
|
48
61
|
|
|
49
62
|
不适用条件:本模块**不判语义**——「不是事实」的言语(玩笑/元层/回忆转述)之消歧
|
|
50
|
-
标记(`not_fact` 等)不在本批(P1 事件行无该信号);`
|
|
51
|
-
|
|
63
|
+
标记(`not_fact` 等)不在本批(P1 事件行无该信号);`blindspots` 的真值判定亦
|
|
64
|
+
未落地(见上,恒空列表)。`alternatives` **已落地**(历史遗留候选,见上判据段)。
|
|
65
|
+
跨库/多租户合并不在此(单库=单台账)。
|
|
52
66
|
"""
|
|
53
67
|
from __future__ import annotations
|
|
54
68
|
|
|
@@ -82,7 +96,30 @@ def _hist_item(rec) -> dict:
|
|
|
82
96
|
return {k: rec.get(k) for k in _HIST_FIELDS}
|
|
83
97
|
|
|
84
98
|
|
|
85
|
-
# 生效条件:
|
|
99
|
+
# 生效条件:recs 为同组台账记录(落盘序)、value 为当前值——返回该槽位**曾被断言过、且不等于当前值**的去重值列表(保持首次出现序);撤回事件(`_is_void`)不计,当前值不计;去重按相等比较线性进行(**不用 set**:`new` 可以是不可哈希的 dict/list)。
|
|
100
|
+
def _alternatives_of(recs, value) -> list:
|
|
101
|
+
"""该槽位**曾被断言过、且不等于当前值**的去重值(保持首次出现序)。
|
|
102
|
+
|
|
103
|
+
判据见模块头:只读历史 `new` 的非空值,剔除当前值;**不用时间窗/seq 判「同期」**
|
|
104
|
+
(台账 `t` 是记账时刻、`seq` 可缺省),故语义是「历史遗留候选」而非强「同期未决」。
|
|
105
|
+
|
|
106
|
+
去重**不用 `set`**:台账是外部可写面,`new` 可以是任意 JSON 值(dict/list),
|
|
107
|
+
不可哈希 ⇒ `set` 会抛 `TypeError`(本批实测踩到,见
|
|
108
|
+
`test_state_projection_streaming` 的 dict 值用例)。改用线性「已见列表 + 相等比较」:
|
|
109
|
+
槽位值个数极小,O(n²) 无实际代价,且对 dict/list/None/数字一律成立。
|
|
110
|
+
"""
|
|
111
|
+
out = []
|
|
112
|
+
for rec in recs:
|
|
113
|
+
if _is_void(rec):
|
|
114
|
+
continue
|
|
115
|
+
v = rec.get("new")
|
|
116
|
+
if v == value:
|
|
117
|
+
continue
|
|
118
|
+
if v not in out:
|
|
119
|
+
out.append(v)
|
|
120
|
+
return out
|
|
121
|
+
|
|
122
|
+
|
|
86
123
|
def _replay(subject, slot, recs, *, history=True) -> dict:
|
|
87
124
|
"""单组回放:现值 / 档位 / 区间 / 变迁史(规则逐条见模块头)。"""
|
|
88
125
|
value = None
|
|
@@ -99,12 +136,14 @@ def _replay(subject, slot, recs, *, history=True) -> dict:
|
|
|
99
136
|
# 全程无有值事件(孤立撤回):起端无可溯源 ⇒ None(不编造)。
|
|
100
137
|
t_from, seq_from = None, None
|
|
101
138
|
tier = TIER_UNSPECIFIED
|
|
139
|
+
kind, ttl = None, None
|
|
102
140
|
else:
|
|
103
141
|
lv = recs[last_valued]
|
|
104
142
|
t_from, seq_from = lv.get("t"), lv.get("seq")
|
|
105
143
|
tier = lv.get("tier")
|
|
106
144
|
if tier is None:
|
|
107
145
|
tier = TIER_UNSPECIFIED
|
|
146
|
+
kind, ttl = lv.get("kind"), lv.get("ttl")
|
|
108
147
|
# 覆盖者:retired 态=撤回事件(最后一条,闭合点=值作废时刻);否则=有值事件的
|
|
109
148
|
# **下一条**事件(存在则闭合,不存在=None=未闭合);两者共用同一取舍。
|
|
110
149
|
nxt = (len(recs) - 1) if retired else (
|
|
@@ -118,17 +157,27 @@ def _replay(subject, slot, recs, *, history=True) -> dict:
|
|
|
118
157
|
"t_from": t_from, "t_to": t_to,
|
|
119
158
|
"seq_from": seq_from, "seq_to": seq_to,
|
|
120
159
|
"tier": tier,
|
|
121
|
-
|
|
122
|
-
"
|
|
160
|
+
"kind": kind,
|
|
161
|
+
"ttl": ttl,
|
|
162
|
+
# alternatives 本批已落地(判据见模块头);blindspots 仍后置、恒空。
|
|
163
|
+
"alternatives": _alternatives_of(recs, value),
|
|
164
|
+
"blindspots": [],
|
|
123
165
|
"event_count": len(recs)}
|
|
124
166
|
if history:
|
|
125
167
|
unit["history"] = [_hist_item(r) for r in recs]
|
|
126
168
|
return unit
|
|
127
169
|
|
|
128
170
|
|
|
129
|
-
# 生效条件:recs
|
|
171
|
+
# 生效条件:recs 为落盘序记录(可迭代、可空)时——history=True 经共享分页回放单点返回全量单元;history=False 与 `project_page` 走**同一归约器**(`_project_current_page`),保证两条入口同口径(否则 alternatives 在两条路上一真一空);include_retired 为假时剔除退役单元;不改写入参记录。
|
|
130
172
|
def _project(recs, *, include_retired=False, history=True) -> list:
|
|
131
|
-
"""落盘序记录 → 全量投影;流式分组后逐组释放原始记录。
|
|
173
|
+
"""落盘序记录 → 全量投影;流式分组后逐组释放原始记录。
|
|
174
|
+
|
|
175
|
+
history=False 必须与 `project_page(history=False)` 同源:两处若各走一条路,
|
|
176
|
+
`alternatives` 会出现「一条路径有真值、另一条恒空」的口径分叉
|
|
177
|
+
(`test_state_projection_streaming` 的 L46/L49 就是钉这条的)。
|
|
178
|
+
"""
|
|
179
|
+
if not history:
|
|
180
|
+
return _project_current_page(recs, include_retired=include_retired)[1]
|
|
132
181
|
return _project_history_page(recs, include_retired=include_retired,
|
|
133
182
|
history=history)[1]
|
|
134
183
|
|
|
@@ -205,7 +254,10 @@ def _project_current_page(recs, *, include_retired=False, limit=None) -> tuple:
|
|
|
205
254
|
"t_from": t_from, "t_to": t_to,
|
|
206
255
|
"seq_from": seq_from, "seq_to": seq_to,
|
|
207
256
|
"tier": TIER_UNSPECIFIED if tier is None else tier,
|
|
208
|
-
|
|
257
|
+
# 单遍路径**不保留历史** ⇒ 算不出 alternatives。
|
|
258
|
+
# 不静默给一个看起来完整的空:如实标注该字段不可得。
|
|
259
|
+
"alternatives": [], "alternatives_partial": True,
|
|
260
|
+
"blindspots": [], "event_count": count})
|
|
209
261
|
return total, out
|
|
210
262
|
|
|
211
263
|
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""状态视图(state_view)——L2 槽位寄存器的**stable 语义 + 多槽位联合投影**。
|
|
3
|
+
|
|
4
|
+
设计依据:`docs/设计_状态账本与终态投影_v0.1.md` §3.2/§3.3,理论依据《智能论 v3.4》
|
|
5
|
+
3.2.2(stable 租约)+ 5.2(混杂系统:连续衰减 dc/dt=-γ(c-c0)、dTTL/dt=-1;
|
|
6
|
+
离散跳变 guard(V_hit, t>TTL, conflict) → transition)。
|
|
7
|
+
|
|
8
|
+
与既有模块的分工(**不新增真源、不复制回放规则**):
|
|
9
|
+
· `state_events` = 账本(append-only 唯一真源,五元结构);
|
|
10
|
+
· `state_slots` = 纯回放投影(value/state/t_from/t_to/alternatives/history),**不判语义**;
|
|
11
|
+
· **本模块** = 在 `state_slots` 之上加一层**租约语义**:
|
|
12
|
+
stable ⟺ (now − t_from) < TTL 且 值非撤回
|
|
13
|
+
超时 ⇒ weak=True(**降级不删除**,值仍返回;3.2.2 P1-003)
|
|
14
|
+
并把同一 subject 的**全部槽位联合给出**(§3.3:多要素题需要一次看到全部当前值)。
|
|
15
|
+
|
|
16
|
+
为什么 TTL 放在这一层而不进 `state_slots`:后者是"回放"语义(同一账本必得同一投影),
|
|
17
|
+
TTL 是"此刻是否仍可信"的**时间相关**判断——混进回放会让历史查询随 wall clock 变化。
|
|
18
|
+
|
|
19
|
+
TTL 取值(**无理论依据,见设计稿 §7 盲区**):
|
|
20
|
+
· 理论只说「由验证单元按条件空间校准」,未给数 ⇒ 本模块用**槽位名启发式**给缺省,
|
|
21
|
+
并允许 `MDCG_STATE_TTL_DAYS` 全局覆盖(单一标量,便于校准实验);
|
|
22
|
+
· 日期/时间类 30d · 地点类 365d · 状态类 7d · 其余 180d。
|
|
23
|
+
这不是"事实",是**可调缺省**;任何读数都要带 TTL 配置一起报。
|
|
24
|
+
|
|
25
|
+
不适用条件:`pending`(未决值)**未实现**——账本行当前不带置信度字段,
|
|
26
|
+
"最后一条断言是否足以改终态"无法从 payload 判出(设计稿 §7 已列此盲区);
|
|
27
|
+
本模块只做「TTL 是否过期」这一条 guard,不臆造冲突判定。
|
|
28
|
+
"""
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import os
|
|
32
|
+
import time
|
|
33
|
+
|
|
34
|
+
from . import state_slots
|
|
35
|
+
|
|
36
|
+
#: 槽位名启发式 → TTL 天数的缺省表(顺序敏感:先命中先返回)。
|
|
37
|
+
_TTL_RULES = (
|
|
38
|
+
(("时间", "日期", "time", "date", "deadline", "截止"), 30),
|
|
39
|
+
(("地点", "地址", "place", "location", "住所", "住址"), 365),
|
|
40
|
+
(("状态", "state", "status", "进度", "progress"), 7),
|
|
41
|
+
)
|
|
42
|
+
#: 兜底 TTL(天)。
|
|
43
|
+
TTL_DEFAULT_DAYS = 180
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# 生效条件:环境变量 MDCG_STATE_TTL_DAYS 为可解析的正数时返回该值(全局覆盖),否则返回 None
|
|
47
|
+
def _env_ttl():
|
|
48
|
+
raw = (os.environ.get("MDCG_STATE_TTL_DAYS") or "").strip()
|
|
49
|
+
if not raw:
|
|
50
|
+
return None
|
|
51
|
+
try:
|
|
52
|
+
v = float(raw)
|
|
53
|
+
except ValueError:
|
|
54
|
+
return None
|
|
55
|
+
return v if v > 0 else None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
#: `extra.ttl` 表示「永不过期」的取值(已发生事实:事件时点/交稿日期/获得日)。
|
|
59
|
+
IMMUTABLE_WORDS = ("immutable", "never", "none", "-", "0")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
# 生效条件:slot 为字符串(可为 None);返回 TTL 天数,**None 表示不可变(永不 weak)**
|
|
63
|
+
def ttl_days_of(slot, kind=None, ttl=None):
|
|
64
|
+
"""槽位租约天数。**判据:这个值会不会被改写**(2026-11 定)。
|
|
65
|
+
|
|
66
|
+
优先级(前者胜):
|
|
67
|
+
① 调用方显式声明 `extra.ttl`:`"immutable"` ⇒ None(永不 weak);数字 ⇒ 该天数;
|
|
68
|
+
② env `MDCG_STATE_TTL_DAYS` 全局覆盖;
|
|
69
|
+
③ `kind == "migration"`(改期/变更)⇒ 30d:承诺类**会**被改写,必须复核;
|
|
70
|
+
④ 槽位名启发式(时间30/地点365/状态7/其余180)。
|
|
71
|
+
|
|
72
|
+
为什么①优先且要支持 immutable:外测实证——「7 月 20 日交的稿」是不可变历史,
|
|
73
|
+
按槽位名(含『日期』)判 30d 会在 9 月查询时被标 weak,判官看到「需核实」反而降分;
|
|
74
|
+
而「尚未寄出」是状态量,45 天后确实可能已变 ⇒ 该标 weak。**槽位名分不出这两类**,
|
|
75
|
+
只有写入方知道,故以显式声明为准,推断只做保守缺省。
|
|
76
|
+
"""
|
|
77
|
+
raw = ttl
|
|
78
|
+
if raw is not None:
|
|
79
|
+
if isinstance(raw, str) and raw.strip().lower() in IMMUTABLE_WORDS:
|
|
80
|
+
return None
|
|
81
|
+
try:
|
|
82
|
+
v = float(str(raw).strip())
|
|
83
|
+
except (TypeError, ValueError):
|
|
84
|
+
v = None
|
|
85
|
+
if v is not None and v > 0:
|
|
86
|
+
return v
|
|
87
|
+
env = _env_ttl()
|
|
88
|
+
if env is not None:
|
|
89
|
+
return env
|
|
90
|
+
if str(kind or "").strip().lower() == "migration":
|
|
91
|
+
return 30.0
|
|
92
|
+
s = str(slot or "").lower()
|
|
93
|
+
for keys, days in _TTL_RULES:
|
|
94
|
+
for k in keys:
|
|
95
|
+
if k in s:
|
|
96
|
+
return float(days)
|
|
97
|
+
return float(TTL_DEFAULT_DAYS)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
# 生效条件:unit 为 state_slots 投影单元(含 value/state/t_from);返回 {weak, age_days, ttl_days, weak_reason}
|
|
101
|
+
def lease_of(unit, now=None):
|
|
102
|
+
"""算一条槽位单元的租约状态(3.2.2 stable 租约)。"""
|
|
103
|
+
now = time.time() if now is None else float(now)
|
|
104
|
+
u = unit or {}
|
|
105
|
+
ttl = ttl_days_of(u.get("slot"), kind=u.get("kind"), ttl=u.get("ttl"))
|
|
106
|
+
t_from = (unit or {}).get("t_from")
|
|
107
|
+
age = None
|
|
108
|
+
if t_from is not None:
|
|
109
|
+
try:
|
|
110
|
+
age = max(0.0, (now - float(t_from)) / 86400.0)
|
|
111
|
+
except (TypeError, ValueError):
|
|
112
|
+
age = None
|
|
113
|
+
weak = False
|
|
114
|
+
reason = None
|
|
115
|
+
if u.get("state") == "retired":
|
|
116
|
+
reason = "retired" # 值已撤回:不是 weak,是"没有当前值"
|
|
117
|
+
elif ttl is None:
|
|
118
|
+
reason = "immutable" # 显式声明不可变:已发生事实,永不 weak
|
|
119
|
+
elif age is None:
|
|
120
|
+
weak, reason = True, "no_timestamp" # 不知道什么时候确认的 ⇒ 不敢当稳定值
|
|
121
|
+
elif age >= ttl:
|
|
122
|
+
weak, reason = True, "ttl_exceeded"
|
|
123
|
+
return {"weak": weak, "weak_reason": reason, "age_days": None if age is None else round(age, 1),
|
|
124
|
+
"ttl_days": ttl}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
# 生效条件:units 为 state_slots 投影单元列表;返回按 subject 归并的视图(同主体全部槽位联合)
|
|
128
|
+
def build_view(units, now=None):
|
|
129
|
+
"""把槽位单元按 subject 归并成「一个主体一张卡」(设计稿 §3.3)。
|
|
130
|
+
|
|
131
|
+
为什么必须联合给:多要素题(如"周五下午谁收、放哪")要求同一主体
|
|
132
|
+
的时间/参与人/地点**同时在场**;逐槽位分开给等于让模型自己做合成。
|
|
133
|
+
"""
|
|
134
|
+
by_subject = {}
|
|
135
|
+
for u in units or []:
|
|
136
|
+
subj = u.get("subject")
|
|
137
|
+
slot = u.get("slot")
|
|
138
|
+
lease = lease_of(u, now=now)
|
|
139
|
+
card = {
|
|
140
|
+
"value": u.get("value"),
|
|
141
|
+
"state": u.get("state"),
|
|
142
|
+
"t_from": u.get("t_from"),
|
|
143
|
+
"t_to": u.get("t_to"),
|
|
144
|
+
"tier": u.get("tier"),
|
|
145
|
+
"alternatives": u.get("alternatives") or [],
|
|
146
|
+
"event_count": u.get("event_count"),
|
|
147
|
+
"kind": u.get("kind"),
|
|
148
|
+
"ttl_declared": u.get("ttl"),
|
|
149
|
+
**lease,
|
|
150
|
+
}
|
|
151
|
+
by_subject.setdefault(subj, {"subject": subj, "slots": {}, "weak_slots": []})
|
|
152
|
+
by_subject[subj]["slots"][slot] = card
|
|
153
|
+
if lease["weak"]:
|
|
154
|
+
by_subject[subj]["weak_slots"].append(slot)
|
|
155
|
+
out = list(by_subject.values())
|
|
156
|
+
# 稳定排序 + 弱值多的排前面(越需要复核的主体越先看到)
|
|
157
|
+
out.sort(key=lambda c: (-len(c["weak_slots"]), str(c["subject"])))
|
|
158
|
+
return out
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
# 生效条件:cg 提供 root;返回 {view, units_count, weak_count, ttl_env, now}
|
|
162
|
+
def state_view(cg, subject=None, slot=None, include_retired=False,
|
|
163
|
+
now=None, history=True, limit=None):
|
|
164
|
+
"""读账本 → 回放投影(state_slots)→ 加租约 → 按主体联合。
|
|
165
|
+
|
|
166
|
+
纯只读:不写盘、不建缓存;同一账本 + 同一 now 必得同一结果(可复算)。
|
|
167
|
+
"""
|
|
168
|
+
units = state_slots.project(cg, subject=subject, slot=slot,
|
|
169
|
+
include_retired=include_retired, history=history)
|
|
170
|
+
if limit:
|
|
171
|
+
units = units[:int(limit)]
|
|
172
|
+
view = build_view(units, now=now)
|
|
173
|
+
weak = sum(1 for c in view for s in c["weak_slots"])
|
|
174
|
+
return {
|
|
175
|
+
"view": view,
|
|
176
|
+
"units_count": len(units),
|
|
177
|
+
"weak_count": weak,
|
|
178
|
+
"ttl_days_default": TTL_DEFAULT_DAYS,
|
|
179
|
+
"ttl_env": _env_ttl(),
|
|
180
|
+
"now": time.time() if now is None else float(now),
|
|
181
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""结构信号重排(structboost)——**章节路由 + 元素覆盖**的确定性提升。
|
|
3
|
+
|
|
4
|
+
bench 读数(hive-memory-bench · 六元素判断题 476 · 行窗切块 · gold=evidence 行号):
|
|
5
|
+
|
|
6
|
+
| 配置 | gold@1 | gold@3 | gold@10 |
|
|
7
|
+
|---|---:|---:|---:|
|
|
8
|
+
| baseline | 49.6% | 71.9% | 92.0% |
|
|
9
|
+
| 章节 ×2 | 49.0% | 85.7% | 95.8% |
|
|
10
|
+
| **章节 ×2 + 元素 ×1.0** | **52.5%** | **85.7%** | **96.2%** |
|
|
11
|
+
|
|
12
|
+
两条信号都是**确定性可数**的(与 detrerank 同一纪律):
|
|
13
|
+
· 章节:题面「第N章」→ 候选正文里的「## 第N章」标题 / tags 里的章号;
|
|
14
|
+
· 元素:题面按 `·`(六元素分隔符)切出的元素,在候选正文中出现的比例。
|
|
15
|
+
|
|
16
|
+
不做硬过滤:题面可能故意写错章节(负例题),硬滤会把正确证据筛掉 ⇒ 只用**乘性提升**。
|
|
17
|
+
"""
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import re
|
|
21
|
+
|
|
22
|
+
#: 章节命中提升倍数(bench 扫描 1.5/2.0/3.0 结果相同,取中位 2.0)。
|
|
23
|
+
CHAPTER_BOOST = 2.0
|
|
24
|
+
#: 元素覆盖率提升系数(bench 扫描 0.5/1.0/2.0,1.0 最优:@3 不掉、@1/@10 最高)。
|
|
25
|
+
ELEMENT_BOOST = 1.0
|
|
26
|
+
|
|
27
|
+
_CN = {"一": 1, "二": 2, "三": 3, "四": 4, "五": 5,
|
|
28
|
+
"六": 6, "七": 7, "八": 8, "九": 9, "十": 10}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def cn2int(s):
|
|
32
|
+
"""中文数字/阿拉伯数字 → int(1..99 够用);解析不出返回 None。"""
|
|
33
|
+
s = (s or "").strip()
|
|
34
|
+
if not s:
|
|
35
|
+
return None
|
|
36
|
+
if s.isdigit():
|
|
37
|
+
return int(s)
|
|
38
|
+
if s in _CN:
|
|
39
|
+
return _CN[s]
|
|
40
|
+
if len(s) == 2 and s[1] == "十":
|
|
41
|
+
return _CN.get(s[0], 0) * 10
|
|
42
|
+
if len(s) == 2 and s[0] == "十":
|
|
43
|
+
return 10 + _CN.get(s[1], 0)
|
|
44
|
+
if len(s) == 3 and s[1] == "十":
|
|
45
|
+
return _CN.get(s[0], 0) * 10 + _CN.get(s[2], 0)
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def query_chapter(query):
|
|
50
|
+
"""从查询里取章号(「第N章」/「第N章「标题」」);没有返回 None。"""
|
|
51
|
+
m = re.search(r"第\s*([一二三四五六七八九十\d]+)\s*章", str(query or ""))
|
|
52
|
+
return cn2int(m.group(1)) if m else None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def node_chapter(node):
|
|
56
|
+
"""候选节点的章号:**正文标题优先**,其次 tags。
|
|
57
|
+
|
|
58
|
+
为什么正文优先:实测(476 题)tags 里常有与正文不一致的章号(人工打标/批次标签),
|
|
59
|
+
按 tags 优先会让提升打到错的章上——@1 从 0.50 掉到 0.30。
|
|
60
|
+
正文的 `## 第N章` 标题是语料自带的结构,才可信。
|
|
61
|
+
"""
|
|
62
|
+
text = str(node.get("content") or "")
|
|
63
|
+
m = re.search(r"^#{1,4}\s*第\s*([一二三四五六七八九十\d]+)\s*章", text, re.M)
|
|
64
|
+
if m:
|
|
65
|
+
return cn2int(m.group(1))
|
|
66
|
+
fm = node.get("frontmatter") or {}
|
|
67
|
+
for tag in (fm.get("tags") or []):
|
|
68
|
+
t = str(tag)
|
|
69
|
+
if t.startswith(CHAPTER_TAG_PREFIX): # 入库期盖章约定:ch:3
|
|
70
|
+
try:
|
|
71
|
+
return int(t[len(CHAPTER_TAG_PREFIX):])
|
|
72
|
+
except ValueError:
|
|
73
|
+
continue
|
|
74
|
+
got = query_chapter(t)
|
|
75
|
+
if got:
|
|
76
|
+
return got
|
|
77
|
+
return None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def elements(query):
|
|
81
|
+
"""六元素:按 `·` 切分,去掉章节标签与过短片段。"""
|
|
82
|
+
parts = [p.strip() for p in str(query or "").split("·") if p.strip()]
|
|
83
|
+
out = []
|
|
84
|
+
for p in parts:
|
|
85
|
+
if query_chapter(p):
|
|
86
|
+
continue
|
|
87
|
+
p = re.sub(r"^[《「【((]|[》」】))]$", "", p).strip()
|
|
88
|
+
if len(p) >= 2:
|
|
89
|
+
out.append(p)
|
|
90
|
+
return out
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def boost(node, query, chap=0, elems=None):
|
|
94
|
+
"""单个候选的提升倍数(确定性;无信号返回 1.0)。
|
|
95
|
+
|
|
96
|
+
`chap`:**显式章号**(0 表示「本条不启用章节信号」)。
|
|
97
|
+
这里刻意**不**在函数内重新解析 query——否则调用方用 `chap=None` 关闸时,
|
|
98
|
+
函数又把章号解析回来,闸门形同虚设(实测:gold@1 仍然从 0.50 掉到 0.15)。
|
|
99
|
+
"""
|
|
100
|
+
q_chap = chap or None
|
|
101
|
+
es = elements(query) if elems is None else elems
|
|
102
|
+
factor = 1.0
|
|
103
|
+
if q_chap is not None and node_chapter(node) == q_chap:
|
|
104
|
+
factor *= CHAPTER_BOOST
|
|
105
|
+
if es:
|
|
106
|
+
text = str(node.get("content") or "")
|
|
107
|
+
hits = sum(1 for e in es if e in text)
|
|
108
|
+
factor *= 1.0 + ELEMENT_BOOST * (hits / float(len(es)))
|
|
109
|
+
return factor
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
#: 章节提升的启用前提:候选集中**已知章号**的比例达到此值。
|
|
113
|
+
#: 实测(476 题):仅 23/153 块自带章节标题时启用章节提升,gold@1 从 0.50 掉到 0.16——
|
|
114
|
+
#: 因为提升只打在「少数知道章号的块」上,把它们错误地顶到前面。
|
|
115
|
+
#: 故候选集里章号信息不足时,**整条章节信号弃用**(而不是半用)。
|
|
116
|
+
CHAPTER_MIN_KNOWN = 0.5
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def rerank(results, query, k=None):
|
|
120
|
+
"""对 [(node, score, ...), ...] 做稳定重排:score × boost,同分按原序(确定性)。
|
|
121
|
+
|
|
122
|
+
只在**已召回的候选集内**重排,不改候选集、不做过滤 ⇒ 无召回损失风险。
|
|
123
|
+
章节信号按 `CHAPTER_MIN_KNOWN` 闸门决定是否启用(信息不足则整条弃用)。
|
|
124
|
+
"""
|
|
125
|
+
q_chap = query_chapter(query)
|
|
126
|
+
es = elements(query)
|
|
127
|
+
if q_chap is not None and results:
|
|
128
|
+
known = sum(1 for item in results if node_chapter(item[0]) is not None)
|
|
129
|
+
if known / float(len(results)) < CHAPTER_MIN_KNOWN:
|
|
130
|
+
q_chap = 0 # 章号信息不足 ⇒ 弃用章节信号(0 = 关,只留元素信号)
|
|
131
|
+
order = []
|
|
132
|
+
for idx, item in enumerate(results or ()):
|
|
133
|
+
node = item[0]
|
|
134
|
+
try:
|
|
135
|
+
score = float(item[1])
|
|
136
|
+
except (TypeError, ValueError, IndexError):
|
|
137
|
+
score = 0.0
|
|
138
|
+
order.append((score * boost(node, query, q_chap, es), idx, item))
|
|
139
|
+
order.sort(key=lambda t: (-t[0], t[1]))
|
|
140
|
+
out = [t[2] for t in order]
|
|
141
|
+
return out[:k] if k else out
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
#: 盖章用的 tag 前缀(`ch:3`)。与内容标题同源,避免与人工 tag 混用。
|
|
145
|
+
CHAPTER_TAG_PREFIX = "ch:"
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def stamp_chapters(nodes):
|
|
149
|
+
"""入库期章号盖章:按给定顺序遍历节点,把「最近一次出现的章节标题」写成 tag。
|
|
150
|
+
|
|
151
|
+
为什么需要(bench 实测):行窗切块后 **153 块里只有 23 块自带 `## 第N章` 标题**,
|
|
152
|
+
其余块在查询期无法判知自己属于哪一章 ⇒ 章节提升会打到「章节首块」上,
|
|
153
|
+
gold@1 从 0.50 掉到 0.16。章号必须在**入库期**按文档顺序继承,查询期才有得用。
|
|
154
|
+
|
|
155
|
+
nodes: [{"id":..., "content":...}, ...](有序);返回 {id: chapter},并原地把
|
|
156
|
+
`ch:N` 写进 `frontmatter["tags"]`(若给定的是可变 dict)。
|
|
157
|
+
"""
|
|
158
|
+
out = {}
|
|
159
|
+
last = None
|
|
160
|
+
for node in nodes or ():
|
|
161
|
+
text = str(node.get("content") or "")
|
|
162
|
+
m = re.search(r"^#{1,4}\s*第\s*([一二三四五六七八九十\d]+)\s*章", text, re.M)
|
|
163
|
+
if m:
|
|
164
|
+
got = cn2int(m.group(1))
|
|
165
|
+
if got:
|
|
166
|
+
last = got
|
|
167
|
+
if last is None:
|
|
168
|
+
continue
|
|
169
|
+
nid = node.get("id")
|
|
170
|
+
out[nid] = last
|
|
171
|
+
fm = node.get("frontmatter")
|
|
172
|
+
if isinstance(fm, dict):
|
|
173
|
+
tags = fm.get("tags")
|
|
174
|
+
if not isinstance(tags, list):
|
|
175
|
+
tags = fm["tags"] = []
|
|
176
|
+
key = "%s%d" % (CHAPTER_TAG_PREFIX, last)
|
|
177
|
+
if key not in tags:
|
|
178
|
+
tags.append(key)
|
|
179
|
+
return out
|
package/md_cg/sustain.py
CHANGED
|
@@ -476,6 +476,30 @@ def _hb_prune_shards(root: str):
|
|
|
476
476
|
|
|
477
477
|
|
|
478
478
|
# 生效条件:开关关(heartbeat_ledger_enabled() 为假)时返回 None 且不写盘;否则先经 _hb_rotate_if_needed(root) 有界闸门,再向 root/HEARTBEAT_LOG 追加一行 {"t","name","pid","kind":"beat","ok"(,"error")},返回该行;任何写入异常被吞掉并返回 None(心跳不可因台账而中断)。
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
# 生效条件:e 为 tick 内捕获的异常;返回「类名: 消息 @ 文件:行(末3帧摘要)」单行字符串(≤600 字)
|
|
482
|
+
def _tick_error_summary(e: BaseException) -> str:
|
|
483
|
+
"""tick 失败的**可定位**摘要(issue #804)。
|
|
484
|
+
|
|
485
|
+
早先只记 `类名: 消息` —— `RuntimeError: dictionary changed size during iteration`
|
|
486
|
+
这种没有栈的报错等于零定位信息(实测 5 次、5 个不同 pid 全无 traceback)。
|
|
487
|
+
现在追加末 3 帧 `文件:行 函数` 与最终错误行;仍压成**一行**,不破坏 `_heartbeat.jsonl` 的逐行 JSON 契约。
|
|
488
|
+
"""
|
|
489
|
+
import traceback
|
|
490
|
+
head = "%s: %s" % (type(e).__name__, str(e)[:200])
|
|
491
|
+
try:
|
|
492
|
+
tb = traceback.extract_tb(e.__traceback__)
|
|
493
|
+
except Exception: # noqa: BLE001 —— 取栈失败也不影响主流程
|
|
494
|
+
return head
|
|
495
|
+
if not tb:
|
|
496
|
+
return head
|
|
497
|
+
frames = tb[-3:]
|
|
498
|
+
where = " <- ".join("%s:%d %s" % (os.path.basename(f.filename), f.lineno, f.name)
|
|
499
|
+
for f in frames)
|
|
500
|
+
return ("%s @ %s" % (head, where))[:600]
|
|
501
|
+
|
|
502
|
+
|
|
479
503
|
def record_heartbeat(root: str, name: str, *, ok: bool = True, error=None,
|
|
480
504
|
t=None, pid=None, extra=None,
|
|
481
505
|
kind: str = HB_KIND_BEAT) -> dict:
|
|
@@ -1583,9 +1607,11 @@ class SustainLoop:
|
|
|
1583
1607
|
if name != "beat":
|
|
1584
1608
|
# D2:失败档**必须在台账可见**——非 beat 业务档每轮失败追加
|
|
1585
1609
|
# 一条 kind="tick" 行(beat 自身失败已由 beat() 记 ok=False)。
|
|
1610
|
+
# 【issue #804】早先只记「类名: 消息」⇒ 5 次 RuntimeError 全无定位信息
|
|
1611
|
+
# (连抛在哪一行都不知道)。现追加 traceback 尾部(最后 3 帧 + 错误行),
|
|
1612
|
+
# 台账仍是一条 JSON 行(不破坏既有解析)。
|
|
1586
1613
|
record_heartbeat(self.cg.root, name, ok=False,
|
|
1587
|
-
error=
|
|
1588
|
-
str(e)[:200]),
|
|
1614
|
+
error=_tick_error_summary(e),
|
|
1589
1615
|
kind=HB_KIND_TICK)
|
|
1590
1616
|
self.last_tick_error = {"name": name, "t": time.time(),
|
|
1591
1617
|
"error": "%s: %s" % (type(e).__name__,
|