@furongjun1999/dsh-memory 0.9.6 → 0.9.8
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/README.md +150 -662
- package/codebuddy/CODEBUDDY.md +333 -204
- package/data/policy.json +38 -38
- package/docs/README.md +18 -0
- package/docs/discipline/harnesses.yaml +11 -3
- package/docs/discipline/templates/compact.txt.tmpl +20 -18
- package/docs/discipline/templates/full.md.tmpl +63 -61
- package/docs/discipline/templates/rules.mdc.tmpl +5 -3
- package/docs/discipline/templates/skill.md.tmpl +25 -23
- package/docs/discipline/templates/spec.txt.tmpl +2 -2
- package/docs/discipline/templates/zcode-user.md.tmpl +1 -1
- package/dsh/cordis.yml.example +139 -139
- package/lib/hooks.d.ts +19 -0
- package/lib/hooks.js +30 -7
- package/lib/index.js +18 -3
- package/lib/init.js +19 -4
- package/lib/lib/hook_audit.js +64 -2
- package/lib/lib/prompt_safety.js +14 -3
- package/lib/tools.d.ts +7 -0
- package/lib/tools.js +22 -1
- package/md_cg/_guard_kit.py +121 -121
- package/md_cg/anchor.py +114 -114
- package/md_cg/audit.py +15 -2
- package/md_cg/chain.py +3 -2
- package/md_cg/config_registry_guard.py +487 -487
- package/md_cg/conformance.py +747 -747
- package/md_cg/consolidate.py +1793 -1793
- package/md_cg/crypto.py +794 -794
- package/md_cg/hyperedge.py +262 -262
- package/md_cg/interface_schema.py +146 -146
- package/md_cg/lifecycle.py +426 -426
- package/md_cg/mdcos.py +12 -8
- package/md_cg/predict.py +1103 -1103
- package/md_cg/protect.py +654 -654
- package/md_cg/provenance.py +606 -606
- package/md_cg/queue_health.py +130 -130
- package/md_cg/refine.py +613 -613
- package/md_cg/retrieve.py +128 -128
- package/md_cg/revise.py +140 -140
- package/md_cg/rollback.py +657 -657
- package/md_cg/rollback_cli.py +124 -124
- package/md_cg/rotate.py +346 -346
- package/md_cg/routing.py +490 -490
- package/md_cg/self_surface.py +50 -50
- package/md_cg/semantic/canonical.py +144 -144
- package/md_cg/semantic/zh_en_atoms.py +141 -141
- package/md_cg/sources.py +1091 -1091
- package/md_cg/stg.py +3 -2
- package/md_cg/sustain.py +10 -1
- package/md_cg/test_audit_rotate_parity.py +279 -279
- package/md_cg/test_autonomy_modes.py +2013 -2013
- package/md_cg/test_cn_recall_grams.py +206 -206
- package/md_cg/test_code_kind_forbidden.py +101 -0
- package/md_cg/test_condaccept.py +156 -156
- package/md_cg/test_condgate.py +141 -141
- package/md_cg/test_heartbeat_ledger.py +9 -3
- package/md_cg/test_i50e_readside_protection.py +658 -658
- package/md_cg/test_issue111_gate_order.py +76 -76
- package/md_cg/test_issue111_scoring_contract.py +86 -86
- package/md_cg/test_issue121_calibration_bounds.py +293 -293
- package/md_cg/test_issue145_sleep_no_silent_rollback.py +167 -167
- package/md_cg/test_issue147_pack_id_escape.py +378 -378
- package/md_cg/test_issue148_merge_downgrade_leak.py +192 -192
- package/md_cg/test_issue149_accel_default_face.py +248 -248
- package/md_cg/test_issue150_empty_query_terms.py +328 -328
- package/md_cg/test_issue151_153_157_write_cache_index.py +151 -151
- package/md_cg/test_issue152_sealed_postings.py +309 -309
- package/md_cg/test_issue153b_index_generation_invalidation.py +142 -142
- package/md_cg/test_issue157b_index_remainder.py +344 -344
- package/md_cg/test_issue189_conclusion_bidirectional.py +223 -223
- package/md_cg/test_issue191_import_trust.py +382 -382
- package/md_cg/test_issue193_write_scope.py +378 -378
- package/md_cg/test_issue212_writeface_gaps.py +349 -349
- package/md_cg/test_issue214_reject_sensitivity.py +266 -266
- package/md_cg/test_issue215_condition_source_gap.py +272 -272
- package/md_cg/test_issue216_clash_routes.py +214 -214
- package/md_cg/test_issue217_slot_routes.py +248 -248
- package/md_cg/test_issue218_postcondition_value_blind.py +222 -222
- package/md_cg/test_issue258_pack_sensitivity.py +468 -468
- package/md_cg/test_issue265_coldverify_multiproc.py +438 -438
- package/md_cg/test_issue274_read_node_id_none.py +341 -341
- package/md_cg/test_issue275_layer_param.py +250 -250
- package/md_cg/test_issue277_node_id_traversal.py +384 -384
- package/md_cg/test_issue278_neg_separated_tension.py +271 -271
- package/md_cg/test_issue278_neg_window.py +294 -294
- package/md_cg/test_issue278_negative_layering.py +83 -83
- package/md_cg/test_issue284_skip_not_pass.py +291 -291
- package/md_cg/test_issue294_flywheel_sensitivity.py +573 -573
- package/md_cg/test_issue301_baseline_corpus_gate.py +245 -245
- package/md_cg/test_issue303_design_boundaries.py +262 -262
- package/md_cg/test_issue315_merge_branch_sensitivity.py +383 -383
- package/md_cg/test_issue319_tenant_unregistered_bypass.py +256 -256
- package/md_cg/test_issue321_mcp_deep_json.py +304 -304
- package/md_cg/test_issue322_node_write_lock.py +727 -727
- package/md_cg/test_issue324_write_size_fields.py +214 -214
- package/md_cg/test_issue325_audit_poison.py +229 -229
- package/md_cg/test_issue326_ingest_auto_whitelist.py +331 -331
- package/md_cg/test_issue326_key_perms.py +355 -355
- package/md_cg/test_issue326_twin_parser_parity.py +323 -323
- package/md_cg/test_issue326_vm_call_frame.py +569 -569
- package/md_cg/test_issue345_writelimit_effective_sens.py +233 -233
- package/md_cg/test_issue346_overwrite_sensitivity_gate.py +424 -424
- package/md_cg/test_issue348_insight_verify_op.py +199 -199
- package/md_cg/test_issue348_merge_rmw_lock.py +345 -345
- package/md_cg/test_issue350_casefold_collision.py +235 -235
- package/md_cg/test_issue351_ingest_root_fallback.py +201 -201
- package/md_cg/test_issue352_imgaudit.py +418 -418
- package/md_cg/test_issue352_pathsjson.py +537 -537
- package/md_cg/test_issue352_refindex.py +412 -412
- package/md_cg/test_issue352_rollback.py +604 -604
- package/md_cg/test_issue354_p2_writelimit_toctou.py +327 -327
- package/md_cg/test_issue354_rust_index_containment.py +571 -571
- package/md_cg/test_issue354_rust_wal_containment.py +606 -606
- package/md_cg/test_issue358_truncation_observable.py +247 -247
- package/md_cg/test_issue360_tidy_private_excerpt.py +195 -195
- package/md_cg/test_issue361_blindspot_not_silent_drop.py +494 -494
- package/md_cg/test_issue362_neg_condition.py +468 -468
- package/md_cg/test_issue363_lexical_idf.py +275 -275
- package/md_cg/test_issue370_readcache_assembly.py +488 -488
- package/md_cg/test_issue376_heartbeat_failed.py +293 -293
- package/md_cg/test_issue377_layer_protect_stamp.py +324 -324
- package/md_cg/test_issue378_protected_floor.py +310 -310
- package/md_cg/test_issue383_state_event_write_gate.py +462 -462
- package/md_cg/test_issue397_sens_eff_wiring.py +435 -435
- package/md_cg/test_issue398_toolface_op_parity.py +511 -511
- package/md_cg/test_issue399_hive_json_shape.py +317 -317
- package/md_cg/test_issue401_wisdom_codegen.py +295 -295
- package/md_cg/test_issue404_heal_receipt.py +389 -389
- package/md_cg/test_issue409_compact_index_completeness.py +509 -509
- package/md_cg/test_issue410_verify_demote_write.py +366 -366
- package/md_cg/test_issue411_scrub_idempotence.py +575 -575
- package/md_cg/test_issue412_discipline_producer_parity.py +311 -311
- package/md_cg/test_issue413_preimage_failclosed.py +239 -239
- package/md_cg/test_issue413_preimage_twin.py +339 -339
- package/md_cg/test_issue415_deps_gate_probe.py +357 -357
- package/md_cg/test_issue416_entry_key_subset.py +525 -525
- package/md_cg/test_issue417_twophase_merge_landed.py +423 -423
- package/md_cg/test_issue425_ingest_library_path.py +331 -331
- package/md_cg/test_issue426c_enqueue_not_silent.py +346 -346
- package/md_cg/test_issue426e_restore_overwrite_live.py +310 -310
- package/md_cg/test_issue426f_paths_gbk_failclosed.py +301 -301
- package/md_cg/test_issue427_serve_status_shape.py +191 -191
- package/md_cg/test_issue431_432_468_protect_single_point.py +322 -322
- package/md_cg/test_issue433_outlook_threshold_single_point.py +278 -278
- package/md_cg/test_issue434_435_float_gate.py +90 -90
- package/md_cg/test_issue439_sibling_sensitivity_inherit.py +448 -448
- package/md_cg/test_issue43_default_policy.py +874 -874
- package/md_cg/test_issue444_scrub_evidence_plaintext.py +281 -281
- package/md_cg/test_issue445_metacognition_ledger_gate.py +454 -454
- package/md_cg/test_issue446_453_403_verified_evidence.py +382 -382
- package/md_cg/test_issue450_sensitivity_fallback_reason.py +51 -51
- package/md_cg/test_issue450_writegate_unknown_sens.py +203 -203
- package/md_cg/test_issue451_audit_actor.py +313 -313
- package/md_cg/test_issue452_ingest_root_sensitivity.py +299 -299
- package/md_cg/test_issue463_ghost_prune_guard.py +259 -259
- package/md_cg/test_issue466_basis_registry.py +469 -469
- package/md_cg/test_issue467_identity_sensitivity_parity.py +360 -360
- package/md_cg/test_issue469_scrub_override_passthrough.py +126 -126
- package/md_cg/test_issue470_wal_event_durable.py +427 -427
- package/md_cg/test_issue471_identity_readable.py +136 -136
- package/md_cg/test_issue472_audit_chain.py +90 -90
- package/md_cg/test_issue472_prune_ledger.py +105 -105
- package/md_cg/test_issue472_rollback_degraded.py +81 -81
- package/md_cg/test_issue491_compose_sandbox.py +460 -460
- package/md_cg/test_issue498_merge_trace_stale_index.py +280 -280
- package/md_cg/test_issue511_scoreboard_bad_files.py +256 -256
- package/md_cg/test_issue521_rotate_lock_suffix.py +110 -110
- package/md_cg/test_issue524_orphan_noise_no_demote.py +88 -88
- package/md_cg/test_issue525_read_null_semantics.py +52 -52
- package/md_cg/test_issue547_append_jsonl_whitelist.py +114 -114
- package/md_cg/test_issue547_audit_durable.py +96 -96
- package/md_cg/test_issue557_r2_write_entries_size_gate.py +83 -83
- package/md_cg/test_issue559_refine_prefix.py +69 -69
- package/md_cg/test_issue562_retired_faces.py +150 -0
- package/md_cg/test_issue71_queue_backlog.py +376 -376
- package/md_cg/test_issue72_coldverify_controlled_drain.py +420 -420
- package/md_cg/test_issue82_credential_rules.py +271 -271
- package/md_cg/test_issue91_verifier_sandbox.py +314 -314
- package/md_cg/test_issue93_remember_redaction.py +282 -282
- package/md_cg/test_logref.py +1141 -1141
- package/md_cg/test_md_access_parity.py +330 -330
- package/md_cg/test_md_cg_no_hive_dep.py +139 -139
- package/md_cg/test_mutation_residue.py +119 -119
- package/md_cg/test_mutation_rollback.py +835 -835
- package/md_cg/test_n123_derive_expiry_chain.py +210 -210
- package/md_cg/test_n184_keys_concurrent_provision.py +1 -1
- package/md_cg/test_n209_verify_write_face_gates.py +466 -466
- package/md_cg/test_n62_tenant_bind_failclosed.py +200 -200
- package/md_cg/test_neg_tail_honesty.py +733 -733
- package/md_cg/test_p21_tokens.py +294 -294
- package/md_cg/test_p27_docindex.py +792 -792
- package/md_cg/test_p28_refcheck.py +1053 -1053
- package/md_cg/test_p2_six_elements.py +476 -476
- package/md_cg/test_p33_ccg_wiring.py +300 -300
- package/md_cg/test_p3_legacy_closure.py +438 -438
- package/md_cg/test_p40_refine_worklist.py +244 -244
- package/md_cg/test_p4_freshness.py +781 -781
- package/md_cg/test_p9c_dedup_hints.py +288 -288
- package/md_cg/test_policy_required_ccg.py +444 -444
- package/md_cg/test_read_scope_b27.py +2 -2
- package/md_cg/test_retr_s5.py +312 -312
- package/md_cg/test_s1_ast_judge.py +109 -109
- package/md_cg/test_security_audit_v21.py +249 -249
- package/md_cg/test_state_event_op.py +521 -521
- package/md_cg/test_stgidx_index_parity.py +1024 -1024
- package/md_cg/test_sustain_bad_stamp.py +178 -0
- package/md_cg/test_sustain_bounded.py +652 -652
- package/md_cg/test_trust_edge_reachability.py +405 -405
- package/md_cg/test_w7_redlines.py +659 -659
- package/md_cg/test_write_return_shape.py +919 -919
- package/md_cg/test_writepipe.py +228 -228
- package/md_cg/trust.py +1114 -1114
- package/md_cg/twophase.py +303 -303
- package/md_cg/whitebox.py +536 -536
- package/md_cg/whitebox_kb/wisdom/compose_engine.py +1634 -1634
- package/md_cg/whitebox_kb/wisdom/core/condition_vm.py +318 -318
- package/md_cg/whitebox_kb/wisdom/core/parser.py +1082 -1082
- package/md_cg/whitebox_kb/wisdom/md_access.py +490 -490
- package/md_cg/whitebox_kb/wisdom/migrate_wisdom.py +497 -497
- package/md_cg/whitebox_kb/wisdom/mini_python.py +995 -995
- package/md_cg/whitebox_kb/wisdom/net_units.py +2900 -2900
- package/md_cg/whitebox_kb/wisdom/semantic_translate.py +4060 -4060
- package/md_cg/writepipe.py +1337 -1337
- package/package.json +3 -2
- package/scripts/workspace_index.py +328 -0
- package/src/hooks.ts +932 -908
- package/src/index.ts +21 -6
- package/src/init.ts +16 -4
- package/src/lib/hook_audit.ts +48 -2
- package/src/lib/mdcg_client.ts +469 -469
- package/src/lib/prompt_safety.ts +17 -3
- package/src/tools.ts +23 -1
- package/zcode/AGENTS.md +333 -204
package/md_cg/twophase.py
CHANGED
|
@@ -1,304 +1,304 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""写入两段式提交(Pi 可学习优点 ③):先记意图,再记结果,崩溃后可对账。
|
|
3
|
-
|
|
4
|
-
**问题(交接文档 §3③)**:写入只有**一条事后记录**——`_audit.jsonl` 只在
|
|
5
|
-
`op=add` **成功之后**追加一行。进程在「闸门通过之后、落盘前后」被杀,日志里
|
|
6
|
-
没有任何痕迹:
|
|
7
|
-
· 落盘成功但簿记没写 → 记忆存在、历史里查不到(静默的记忆);
|
|
8
|
-
· 落盘只做了一半(原子写保证文件不半截,但索引增量可能没落)→ 对账无从下手,
|
|
9
|
-
只能人工翻目录。
|
|
10
|
-
两段式把一次写入拆成两条记录:
|
|
11
|
-
1. **intent**(意图,**先行**持久化):写下「我准备写 node_id,正文指纹 = h」;
|
|
12
|
-
2. **outcome**(结果):写下「这笔以 committed / interrupted / error 结束」。
|
|
13
|
-
崩溃后 `reconcile()` 扫日志配对,对**有 intent 无 outcome** 的逐条判定:
|
|
14
|
-
· 节点在库且正文指纹 == intent 的 h → **补账** outcome{committed, reconciled};
|
|
15
|
-
· 节点不在、或指纹不符 → outcome{interrupted},如实标记(**不假装成功**)。
|
|
16
|
-
对账**幂等**:补出来的 outcome 与正常 outcome 同为 outcome 记录,第二次扫描
|
|
17
|
-
不再有未配对 intent。
|
|
18
|
-
|
|
19
|
-
**为何用独立文件 `_write_2pc.jsonl` 而非写进 `_audit.jsonl`**(对交接文档
|
|
20
|
-
「落 `_audit.jsonl`」建议的偏离,取证理由):
|
|
21
|
-
· `_audit.jsonl` 已被当作**单一语义流**消费——`test_p45_session_identity` 的 F
|
|
22
|
-
段断言 `rows[-1]` 必须带 harness / unit / session 归因,coggraph 会话串链按
|
|
23
|
-
`op` 值串链。混入两段式事件,同一文件的读者要多分辨三种事件语义,且既有
|
|
24
|
-
断言口径被无谓扰动(一次写入 = 三行日志)。
|
|
25
|
-
· 本仓已有「独立审计文件」惯例:`protect.py` 的 `_protected_audit.jsonl`。
|
|
26
|
-
· 两段式是**写路径的崩溃一致性账本**,不是访问审计——语义本就不同源。
|
|
27
|
-
|
|
28
|
-
**诚实边界**:
|
|
29
|
-
· `append_jsonl` 在 Windows 上非原子(O_APPEND 是 lseek+write 两步),多进程
|
|
30
|
-
高并发下可能丢 intent——对账是**增益**,不是「保证不丢」;单进程/低并发足够,
|
|
31
|
-
且 kill -9 不会丢已 write 的数据(只有断电才丢,见 `fsutil` 注释)。
|
|
32
|
-
· 对账只做「补账 / 标记」,**不重放写入**——是否重做是使用者的决定。
|
|
33
|
-
· 账本是 append-only:对账不重写历史,只追加 outcome。
|
|
34
|
-
"""
|
|
35
|
-
|
|
36
|
-
import os
|
|
37
|
-
import time
|
|
38
|
-
import uuid
|
|
39
|
-
|
|
40
|
-
from . import nodefile
|
|
41
|
-
from .fsutil import append_jsonl
|
|
42
|
-
|
|
43
|
-
#: 账本文件名(独立于 `_audit.jsonl`,理由见模块 docstring)
|
|
44
|
-
LOG_FILE = "_write_2pc.jsonl"
|
|
45
|
-
|
|
46
|
-
#: outcome 状态集
|
|
47
|
-
STATUS_COMMITTED = "committed" # 落盘完成(正常路径或对账补账)
|
|
48
|
-
STATUS_INTERRUPTED = "interrupted" # 有意图、未落盘(或指纹不符)——如实标记
|
|
49
|
-
STATUS_ERROR = "error" # 执行抛异常
|
|
50
|
-
STATUS_ABORTED = "aborted" # 闸门判定不落盘(reject/defer/丢弃)
|
|
51
|
-
|
|
52
|
-
#: 对账判定码
|
|
53
|
-
R_NODE_OK = "node_present_hash_match" # 落盘已完成 → 补 committed
|
|
54
|
-
R_NODE_MISSING = "node_missing" # 未落盘 → interrupted
|
|
55
|
-
#: #417:源 id 本就不会落盘(MERGE 把内容并入**目标节点**),而盘面留下了
|
|
56
|
-
#: 「本节点合并过此来源 id」的痕迹 ⇒ 该笔**已合并落盘** → 补 committed(带去向)。
|
|
57
|
-
R_MERGED_INTO = "merged_into_present"
|
|
58
|
-
R_MISMATCH = "content_mismatch" # 落了别的正文 → interrupted(不覆盖)
|
|
59
|
-
R_UNREADABLE = "node_unreadable" # 读节点失败 → interrupted(不猜测)
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
# 生效条件:给定 cg 且其 root 属性可参与 os.path.join 时,恒返回 os.path.join(cg.root, LOG_FILE),无分支与早退。
|
|
63
|
-
def log_path(cg) -> str:
|
|
64
|
-
return os.path.join(cg.root, LOG_FILE)
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
# 生效条件:text 为假值(None/"")时按空串处理,否则用 text 本身,返回去尾换行后的字符串(仅剥 "\n")。
|
|
68
|
-
def _norm(text: str) -> str:
|
|
69
|
-
"""正文口径归一(**对账正确性的前提**):`nodefile.dumps` 写盘时会给正文补尾
|
|
70
|
-
换行,`loads` 读回即带它。若 intent 按入参原文、对账按读回内容各算一次指纹,
|
|
71
|
-
两者**永远不会相等** → 每一笔都误报 interrupted——比不做对账更坏(假阳性会
|
|
72
|
-
淹没真问题,且诱人去"修"不存在的问题)。故两侧统一按「去尾换行」归一。
|
|
73
|
-
"""
|
|
74
|
-
return (text or "").rstrip("\n")
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
# 生效条件:给定 cg 与 rec 时,把 rec 以 JSONL 追加写入 log_path(cg),无返回值、无分支。
|
|
78
|
-
def _append(cg, rec: dict) -> None:
|
|
79
|
-
append_jsonl(log_path(cg), rec)
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
# 生效条件:pr 取自 cg.principal 或(假值时)回落 cg.session——pr 为真字符串时 meta["session"]=pr;否则 pr 非 None 时把 pr.session 记入 session、把 pr.writer 或(假值时)pr.unit 记入 writer;actor 为真时 meta["actor"]=actor,最后返回 meta。
|
|
83
|
-
def _ident(cg, actor=None) -> dict:
|
|
84
|
-
"""归因字段(尽力而为):principal 缺省时留空,不编造。"""
|
|
85
|
-
pr = getattr(cg, "principal", None) or getattr(cg, "session", None)
|
|
86
|
-
meta = {}
|
|
87
|
-
if isinstance(pr, str) and pr:
|
|
88
|
-
meta["session"] = pr
|
|
89
|
-
elif pr is not None:
|
|
90
|
-
sid = getattr(pr, "session", None)
|
|
91
|
-
if sid:
|
|
92
|
-
meta["session"] = sid
|
|
93
|
-
wid = getattr(pr, "writer", None) or getattr(pr, "unit", None)
|
|
94
|
-
if wid:
|
|
95
|
-
meta["writer"] = wid
|
|
96
|
-
if actor:
|
|
97
|
-
meta["actor"] = actor
|
|
98
|
-
return meta
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
# 生效条件:给定 cg、node_id、content 时生成 iid 与 content_hash(对 _norm(content) 计算),先写 phase="intent" 记录再返回 tok;layer 为真才写入 rec["layer"],actor 与 **meta 分别经 _ident、rec.update 合入。
|
|
102
|
-
def begin(cg, node_id: str, content: str, layer: str = None,
|
|
103
|
-
actor: str = None, **meta) -> dict:
|
|
104
|
-
"""记录写入**意图**(先行持久化)→ 返回令牌 tok(供 `commit` 配对)。
|
|
105
|
-
|
|
106
|
-
先于落盘调用;崩溃后据 tok 里的指纹判定该笔是否落盘完成。
|
|
107
|
-
"""
|
|
108
|
-
tok = {
|
|
109
|
-
"iid": uuid.uuid4().hex[:16],
|
|
110
|
-
"node_id": node_id,
|
|
111
|
-
"content_hash": nodefile.content_hash(_norm(content)),
|
|
112
|
-
}
|
|
113
|
-
rec = {"t": time.time(), "phase": "intent", "iid": tok["iid"],
|
|
114
|
-
"id": node_id, "content_hash": tok["content_hash"]}
|
|
115
|
-
if layer:
|
|
116
|
-
rec["layer"] = layer
|
|
117
|
-
rec.update(_ident(cg, actor))
|
|
118
|
-
rec.update(meta)
|
|
119
|
-
_append(cg, rec)
|
|
120
|
-
return tok
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
# 生效条件:nid 取 node_id,node_id 为假值(None/"")时回落 (tok or {}).get("node_id"),iid 取 (tok or {}).get("iid")(tok 为假值时两项均为 None);status 用实参或默认 STATUS_COMMITTED;tok 为真且 tok.get("content_hash") 为真才写入 content_hash;reason 为真才写入 rec["reason"];追加记录后返回 rec。
|
|
124
|
-
def commit(cg, tok: dict, status: str = STATUS_COMMITTED, node_id: str = None,
|
|
125
|
-
reason: str = None, **meta) -> dict:
|
|
126
|
-
"""记录写入**结果**(与 intent 按 iid 配对)。返回结果记录。"""
|
|
127
|
-
nid = node_id or (tok or {}).get("node_id")
|
|
128
|
-
rec = {"t": time.time(), "phase": "outcome", "iid": (tok or {}).get("iid"),
|
|
129
|
-
"id": nid, "status": status}
|
|
130
|
-
if tok and tok.get("content_hash"):
|
|
131
|
-
rec["content_hash"] = tok["content_hash"]
|
|
132
|
-
if reason:
|
|
133
|
-
rec["reason"] = reason
|
|
134
|
-
rec.update(_ident(cg))
|
|
135
|
-
rec.update(meta)
|
|
136
|
-
_append(cg, rec)
|
|
137
|
-
return rec
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
# ----------------------------------------------------------------------
|
|
141
|
-
# 读侧:盘点 / 对账
|
|
142
|
-
|
|
143
|
-
# 生效条件:log_path(cg) 不是文件时直接返回空列表;否则逐行读取,空行跳过,json.loads 抛异常的行跳过,返回成功解析的记录列表。
|
|
144
|
-
def records(cg) -> list:
|
|
145
|
-
"""读全部账本记录(append-only,坏行跳过不炸)。"""
|
|
146
|
-
out = []
|
|
147
|
-
p = log_path(cg)
|
|
148
|
-
if not os.path.isfile(p):
|
|
149
|
-
return out
|
|
150
|
-
import json
|
|
151
|
-
with open(p, encoding="utf-8", errors="replace") as f:
|
|
152
|
-
for line in f:
|
|
153
|
-
if not line.strip():
|
|
154
|
-
continue
|
|
155
|
-
try:
|
|
156
|
-
out.append(json.loads(line))
|
|
157
|
-
except Exception:
|
|
158
|
-
continue
|
|
159
|
-
return out
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
# 生效条件:遍历 records(cg),记录 r.get("iid") 为假值(缺键或空串)时跳过;否则按 iid 建槽,仅当槽内 intent/outcome 仍为 None 时分别填入首个 phase=="intent" / phase=="outcome" 的记录,返回 pairs。
|
|
163
|
-
def _pair(cg) -> dict:
|
|
164
|
-
"""把账本配成 {iid: {"intent":…, "outcome":…}}(同时计入无 iid 的脏行)。"""
|
|
165
|
-
pairs = {}
|
|
166
|
-
for r in records(cg):
|
|
167
|
-
iid = r.get("iid")
|
|
168
|
-
if not iid:
|
|
169
|
-
continue
|
|
170
|
-
slot = pairs.setdefault(iid, {"intent": None, "outcome": None})
|
|
171
|
-
if r.get("phase") == "intent" and slot["intent"] is None:
|
|
172
|
-
slot["intent"] = r
|
|
173
|
-
elif r.get("phase") == "outcome" and slot["outcome"] is None:
|
|
174
|
-
slot["outcome"] = r
|
|
175
|
-
return pairs
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
# 生效条件:遍历 _pair(cg) 取有 intent 且 outcome 为 None 的槽(展开 intent 字段)组成 out,按 r.get("t") or 0 升序排序后返回 out[:max(0, int(limit))]——limit 为 0 或负数时切片为空列表,默认值 200 仅在未传参时生效。
|
|
179
|
-
def pending(cg, limit: int = 200) -> list:
|
|
180
|
-
"""未结清的写入意图(有 intent 无 outcome)——只读,不改盘。
|
|
181
|
-
|
|
182
|
-
供 `cg(op=recent)` / 巡检看「有没有半途而废的写入」。
|
|
183
|
-
"""
|
|
184
|
-
out = []
|
|
185
|
-
for iid, slot in _pair(cg).items():
|
|
186
|
-
if slot["intent"] is not None and slot["outcome"] is None:
|
|
187
|
-
out.append({"iid": iid, **slot["intent"]})
|
|
188
|
-
out.sort(key=lambda r: r.get("t") or 0)
|
|
189
|
-
return out[:max(0, int(limit))]
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
# 生效条件:cg 的 index["nodes"] 为映射时——先按该映射查(_merge_target_in);未命中且 cg 有 _scan_nodes 时**回退盘面扫描**再查同一条复合判据(扫描抛异常按未命中);无索引/无命中/字段形态不符一律返回 None;恒不写盘、不抛。
|
|
193
|
-
def _merge_target(cg, nid):
|
|
194
|
-
"""源 id 是否已被**合并**进某个目标节点(#417/#498)——事实来源=**盘面**。
|
|
195
|
-
|
|
196
|
-
为什么需要它:MERGE 的落盘对象是**目标节点**(`forgetting.reinforce`),
|
|
197
|
-
源 id 本就不会成文;而崩溃窗口落在「内容已并入目标、`commit` 还没落账」
|
|
198
|
-
之间 ⇒ 只看源 id 的判据必然误报 `interrupted/node_missing`(与事实相反,
|
|
199
|
-
且会诱导重做**不可逆**的 MERGE)。
|
|
200
|
-
|
|
201
|
-
为什么要读 `merge_source_ids` 而不是 `merge_sources`:后者记的是
|
|
202
|
-
**写入方归属**(`{session, actor, t}`,`forgetting.note_source`),
|
|
203
|
-
**不含来源节点 id** —— 拿它反查来源永远查不到("判据与事实不符"换个地方复发)。
|
|
204
|
-
故 `forgetting.reinforce` 另立一列把来源 id 落盘(并有界保留),本函数据此反查;
|
|
205
|
-
索引命中后**仍回盘复核**(索引是派生物,盘面才是事实来源)。
|
|
206
|
-
|
|
207
|
-
#498(P1):**索引是派生物,且可能陈旧**——崩溃窗口内 `_index.json` 未持久化、
|
|
208
|
-
或本进程是长活实例(签名未变 ⇒ 不重载)时,索引里没有 `merge_source_ids`
|
|
209
|
-
这个键,于是判据看不到盘面明明已经存在的合并痕迹,结论与盘面相反。故索引
|
|
210
|
-
**落空后回退盘面扫描**(复用库层唯一扫描实现 `_scan_nodes`,不新写第二套
|
|
211
|
-
遍历),扫出的条目交给**同一条**复合判据(仍 `cg.get(tid)` 回盘复核)。
|
|
212
|
-
语义不放宽:盘面确无痕迹时照旧返回 None ⇒ `_judge` 仍判 `interrupted`。
|
|
213
|
-
代价只落在 miss 冷路径(恢复期),命中路径仍只读索引。
|
|
214
|
-
"""
|
|
215
|
-
nodes = (getattr(cg, "index", None) or {}).get("nodes") or {}
|
|
216
|
-
tgt = _merge_target_in(cg, nid, nodes)
|
|
217
|
-
if tgt is not None:
|
|
218
|
-
return tgt
|
|
219
|
-
scan = getattr(cg, "_scan_nodes", None)
|
|
220
|
-
if scan is None:
|
|
221
|
-
return None
|
|
222
|
-
try:
|
|
223
|
-
disk_nodes = scan() # 盘面全量扫描(只读、不写盘)
|
|
224
|
-
except Exception: # noqa: BLE001 —— 扫不动不猜测
|
|
225
|
-
return None
|
|
226
|
-
if not isinstance(disk_nodes, dict):
|
|
227
|
-
return None
|
|
228
|
-
return _merge_target_in(cg, nid, disk_nodes)
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
# 生效条件:nodes 为映射时遍历(先 tuple() 取快照)找出「merge_source_ids 含 nid」的条目并取其 id;命中后用 cg.get(该 id) 在**盘面**复核(读不到或 fm 未记 nid 则返回 None);字段形态不符/无命中一律返回 None;恒不写盘、不抛。索引面与盘面扫描面**共用**这一条复合判据(单点,不各写一份)。
|
|
232
|
-
def _merge_target_in(cg, nid, nodes):
|
|
233
|
-
"""在给定条目映射(索引或盘面扫描结果)上反查合并痕迹——复合判据的**单点**。"""
|
|
234
|
-
for tid, e in tuple(nodes.items()): # H-4(a):迭代前取快照
|
|
235
|
-
if not isinstance(e, dict):
|
|
236
|
-
continue
|
|
237
|
-
ids = e.get("merge_source_ids")
|
|
238
|
-
if not isinstance(ids, (list, tuple)) or nid not in ids:
|
|
239
|
-
continue
|
|
240
|
-
try:
|
|
241
|
-
tgt = cg.get(tid)
|
|
242
|
-
except Exception: # noqa: BLE001 —— 读失败不猜测
|
|
243
|
-
return None
|
|
244
|
-
if not tgt:
|
|
245
|
-
return None
|
|
246
|
-
fm = tgt.get("frontmatter") or {}
|
|
247
|
-
if nid in (fm.get("merge_source_ids") or []):
|
|
248
|
-
return tid
|
|
249
|
-
return None
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
# 生效条件:intent 的 id 为假值或 cg.get(nid) 抛异常时返回 (STATUS_INTERRUPTED, R_UNREADABLE);取回 node 为假值时——先经 _merge_target(cg, nid) 查盘面合并痕迹,命中则返回 (STATUS_COMMITTED, R_MERGED_INTO + ":" + 目标 id),未命中仍返回 (STATUS_INTERRUPTED, R_NODE_MISSING)(**不放宽**);intent 的 content_hash 为真且与 _norm(node.get("content") or "") 的指纹不等时返回 (STATUS_INTERRUPTED, R_MISMATCH);否则返回 (STATUS_COMMITTED, R_NODE_OK)。
|
|
253
|
-
def _judge(cg, intent: dict):
|
|
254
|
-
"""判定一笔未结清意图的真实结局 → `(status, code)`。**不猜测**:读不到就如实说。
|
|
255
|
-
|
|
256
|
-
#417(2026-10-16):源 id 查不到**不再直接等于未落盘**——MERGE 类写入的
|
|
257
|
-
落盘对象是**目标节点**(事实来源=盘面合并痕迹,见 `_merge_target`)。
|
|
258
|
-
命中合并痕迹 ⇒ `committed` + 去向;**未命中 ⇒ 仍判 `interrupted`**
|
|
259
|
-
(新判据只补「已合并」这一种真实情形,不把未命中放宽成「可能已落盘」)。
|
|
260
|
-
"""
|
|
261
|
-
nid = intent.get("id")
|
|
262
|
-
want = intent.get("content_hash")
|
|
263
|
-
if not nid:
|
|
264
|
-
return STATUS_INTERRUPTED, R_UNREADABLE
|
|
265
|
-
try:
|
|
266
|
-
node = cg.get(nid)
|
|
267
|
-
except Exception:
|
|
268
|
-
return STATUS_INTERRUPTED, R_UNREADABLE
|
|
269
|
-
if not node:
|
|
270
|
-
tgt = _merge_target(cg, nid)
|
|
271
|
-
if tgt:
|
|
272
|
-
return STATUS_COMMITTED, "%s:%s" % (R_MERGED_INTO, tgt)
|
|
273
|
-
return STATUS_INTERRUPTED, R_NODE_MISSING
|
|
274
|
-
got = nodefile.content_hash(_norm(node.get("content") or ""))
|
|
275
|
-
if want and got != want:
|
|
276
|
-
return STATUS_INTERRUPTED, R_MISMATCH
|
|
277
|
-
return STATUS_COMMITTED, R_NODE_OK
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
# 生效条件:以 limit 调 pending(cg, limit=limit) 得到未结清意图并统计 unpaired/committed/interrupted;apply 为真时对每笔 intent 调 commit 补写 outcome(reconciled=True、actor="twophase:reconcile"),apply 为假值时只报告不写账本,rep["applied"]=bool(apply);limit 为 0 或负数时 pending 返回空、details 为空列表。
|
|
281
|
-
def reconcile(cg, apply: bool = True, limit: int = 2000) -> dict:
|
|
282
|
-
"""启动/巡检对账:把半途写入**补账或如实标记**。
|
|
283
|
-
|
|
284
|
-
`apply=False` 为 dry-run(只报告,不写账本)。返回汇总:
|
|
285
|
-
`{"unpaired", "committed", "interrupted", "applied", "details"}`。
|
|
286
|
-
幂等——补出的 outcome 与正常 outcome 同形,二次扫描不再有未配对项。
|
|
287
|
-
"""
|
|
288
|
-
pend = pending(cg, limit=limit)
|
|
289
|
-
rep = {"unpaired": len(pend), "committed": 0, "interrupted": 0,
|
|
290
|
-
"applied": bool(apply), "details": []}
|
|
291
|
-
for intent in pend:
|
|
292
|
-
status, code = _judge(cg, intent)
|
|
293
|
-
if status == STATUS_COMMITTED:
|
|
294
|
-
rep["committed"] += 1
|
|
295
|
-
else:
|
|
296
|
-
rep["interrupted"] += 1
|
|
297
|
-
rep["details"].append({"iid": intent.get("iid"), "id": intent.get("id"),
|
|
298
|
-
"status": status, "reason": code})
|
|
299
|
-
if apply:
|
|
300
|
-
commit(cg, {"iid": intent.get("iid"), "node_id": intent.get("id"),
|
|
301
|
-
"content_hash": intent.get("content_hash")},
|
|
302
|
-
status=status, reason=code, reconciled=True,
|
|
303
|
-
actor="twophase:reconcile")
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""写入两段式提交(Pi 可学习优点 ③):先记意图,再记结果,崩溃后可对账。
|
|
3
|
+
|
|
4
|
+
**问题(交接文档 §3③)**:写入只有**一条事后记录**——`_audit.jsonl` 只在
|
|
5
|
+
`op=add` **成功之后**追加一行。进程在「闸门通过之后、落盘前后」被杀,日志里
|
|
6
|
+
没有任何痕迹:
|
|
7
|
+
· 落盘成功但簿记没写 → 记忆存在、历史里查不到(静默的记忆);
|
|
8
|
+
· 落盘只做了一半(原子写保证文件不半截,但索引增量可能没落)→ 对账无从下手,
|
|
9
|
+
只能人工翻目录。
|
|
10
|
+
两段式把一次写入拆成两条记录:
|
|
11
|
+
1. **intent**(意图,**先行**持久化):写下「我准备写 node_id,正文指纹 = h」;
|
|
12
|
+
2. **outcome**(结果):写下「这笔以 committed / interrupted / error 结束」。
|
|
13
|
+
崩溃后 `reconcile()` 扫日志配对,对**有 intent 无 outcome** 的逐条判定:
|
|
14
|
+
· 节点在库且正文指纹 == intent 的 h → **补账** outcome{committed, reconciled};
|
|
15
|
+
· 节点不在、或指纹不符 → outcome{interrupted},如实标记(**不假装成功**)。
|
|
16
|
+
对账**幂等**:补出来的 outcome 与正常 outcome 同为 outcome 记录,第二次扫描
|
|
17
|
+
不再有未配对 intent。
|
|
18
|
+
|
|
19
|
+
**为何用独立文件 `_write_2pc.jsonl` 而非写进 `_audit.jsonl`**(对交接文档
|
|
20
|
+
「落 `_audit.jsonl`」建议的偏离,取证理由):
|
|
21
|
+
· `_audit.jsonl` 已被当作**单一语义流**消费——`test_p45_session_identity` 的 F
|
|
22
|
+
段断言 `rows[-1]` 必须带 harness / unit / session 归因,coggraph 会话串链按
|
|
23
|
+
`op` 值串链。混入两段式事件,同一文件的读者要多分辨三种事件语义,且既有
|
|
24
|
+
断言口径被无谓扰动(一次写入 = 三行日志)。
|
|
25
|
+
· 本仓已有「独立审计文件」惯例:`protect.py` 的 `_protected_audit.jsonl`。
|
|
26
|
+
· 两段式是**写路径的崩溃一致性账本**,不是访问审计——语义本就不同源。
|
|
27
|
+
|
|
28
|
+
**诚实边界**:
|
|
29
|
+
· `append_jsonl` 在 Windows 上非原子(O_APPEND 是 lseek+write 两步),多进程
|
|
30
|
+
高并发下可能丢 intent——对账是**增益**,不是「保证不丢」;单进程/低并发足够,
|
|
31
|
+
且 kill -9 不会丢已 write 的数据(只有断电才丢,见 `fsutil` 注释)。
|
|
32
|
+
· 对账只做「补账 / 标记」,**不重放写入**——是否重做是使用者的决定。
|
|
33
|
+
· 账本是 append-only:对账不重写历史,只追加 outcome。
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
import os
|
|
37
|
+
import time
|
|
38
|
+
import uuid
|
|
39
|
+
|
|
40
|
+
from . import nodefile
|
|
41
|
+
from .fsutil import append_jsonl
|
|
42
|
+
|
|
43
|
+
#: 账本文件名(独立于 `_audit.jsonl`,理由见模块 docstring)
|
|
44
|
+
LOG_FILE = "_write_2pc.jsonl"
|
|
45
|
+
|
|
46
|
+
#: outcome 状态集
|
|
47
|
+
STATUS_COMMITTED = "committed" # 落盘完成(正常路径或对账补账)
|
|
48
|
+
STATUS_INTERRUPTED = "interrupted" # 有意图、未落盘(或指纹不符)——如实标记
|
|
49
|
+
STATUS_ERROR = "error" # 执行抛异常
|
|
50
|
+
STATUS_ABORTED = "aborted" # 闸门判定不落盘(reject/defer/丢弃)
|
|
51
|
+
|
|
52
|
+
#: 对账判定码
|
|
53
|
+
R_NODE_OK = "node_present_hash_match" # 落盘已完成 → 补 committed
|
|
54
|
+
R_NODE_MISSING = "node_missing" # 未落盘 → interrupted
|
|
55
|
+
#: #417:源 id 本就不会落盘(MERGE 把内容并入**目标节点**),而盘面留下了
|
|
56
|
+
#: 「本节点合并过此来源 id」的痕迹 ⇒ 该笔**已合并落盘** → 补 committed(带去向)。
|
|
57
|
+
R_MERGED_INTO = "merged_into_present"
|
|
58
|
+
R_MISMATCH = "content_mismatch" # 落了别的正文 → interrupted(不覆盖)
|
|
59
|
+
R_UNREADABLE = "node_unreadable" # 读节点失败 → interrupted(不猜测)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
# 生效条件:给定 cg 且其 root 属性可参与 os.path.join 时,恒返回 os.path.join(cg.root, LOG_FILE),无分支与早退。
|
|
63
|
+
def log_path(cg) -> str:
|
|
64
|
+
return os.path.join(cg.root, LOG_FILE)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# 生效条件:text 为假值(None/"")时按空串处理,否则用 text 本身,返回去尾换行后的字符串(仅剥 "\n")。
|
|
68
|
+
def _norm(text: str) -> str:
|
|
69
|
+
"""正文口径归一(**对账正确性的前提**):`nodefile.dumps` 写盘时会给正文补尾
|
|
70
|
+
换行,`loads` 读回即带它。若 intent 按入参原文、对账按读回内容各算一次指纹,
|
|
71
|
+
两者**永远不会相等** → 每一笔都误报 interrupted——比不做对账更坏(假阳性会
|
|
72
|
+
淹没真问题,且诱人去"修"不存在的问题)。故两侧统一按「去尾换行」归一。
|
|
73
|
+
"""
|
|
74
|
+
return (text or "").rstrip("\n")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# 生效条件:给定 cg 与 rec 时,把 rec 以 JSONL 追加写入 log_path(cg),无返回值、无分支。
|
|
78
|
+
def _append(cg, rec: dict) -> None:
|
|
79
|
+
append_jsonl(log_path(cg), rec)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# 生效条件:pr 取自 cg.principal 或(假值时)回落 cg.session——pr 为真字符串时 meta["session"]=pr;否则 pr 非 None 时把 pr.session 记入 session、把 pr.writer 或(假值时)pr.unit 记入 writer;actor 为真时 meta["actor"]=actor,最后返回 meta。
|
|
83
|
+
def _ident(cg, actor=None) -> dict:
|
|
84
|
+
"""归因字段(尽力而为):principal 缺省时留空,不编造。"""
|
|
85
|
+
pr = getattr(cg, "principal", None) or getattr(cg, "session", None)
|
|
86
|
+
meta = {}
|
|
87
|
+
if isinstance(pr, str) and pr:
|
|
88
|
+
meta["session"] = pr
|
|
89
|
+
elif pr is not None:
|
|
90
|
+
sid = getattr(pr, "session", None)
|
|
91
|
+
if sid:
|
|
92
|
+
meta["session"] = sid
|
|
93
|
+
wid = getattr(pr, "writer", None) or getattr(pr, "unit", None)
|
|
94
|
+
if wid:
|
|
95
|
+
meta["writer"] = wid
|
|
96
|
+
if actor:
|
|
97
|
+
meta["actor"] = actor
|
|
98
|
+
return meta
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# 生效条件:给定 cg、node_id、content 时生成 iid 与 content_hash(对 _norm(content) 计算),先写 phase="intent" 记录再返回 tok;layer 为真才写入 rec["layer"],actor 与 **meta 分别经 _ident、rec.update 合入。
|
|
102
|
+
def begin(cg, node_id: str, content: str, layer: str = None,
|
|
103
|
+
actor: str = None, **meta) -> dict:
|
|
104
|
+
"""记录写入**意图**(先行持久化)→ 返回令牌 tok(供 `commit` 配对)。
|
|
105
|
+
|
|
106
|
+
先于落盘调用;崩溃后据 tok 里的指纹判定该笔是否落盘完成。
|
|
107
|
+
"""
|
|
108
|
+
tok = {
|
|
109
|
+
"iid": uuid.uuid4().hex[:16],
|
|
110
|
+
"node_id": node_id,
|
|
111
|
+
"content_hash": nodefile.content_hash(_norm(content)),
|
|
112
|
+
}
|
|
113
|
+
rec = {"t": time.time(), "phase": "intent", "iid": tok["iid"],
|
|
114
|
+
"id": node_id, "content_hash": tok["content_hash"]}
|
|
115
|
+
if layer:
|
|
116
|
+
rec["layer"] = layer
|
|
117
|
+
rec.update(_ident(cg, actor))
|
|
118
|
+
rec.update(meta)
|
|
119
|
+
_append(cg, rec)
|
|
120
|
+
return tok
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# 生效条件:nid 取 node_id,node_id 为假值(None/"")时回落 (tok or {}).get("node_id"),iid 取 (tok or {}).get("iid")(tok 为假值时两项均为 None);status 用实参或默认 STATUS_COMMITTED;tok 为真且 tok.get("content_hash") 为真才写入 content_hash;reason 为真才写入 rec["reason"];追加记录后返回 rec。
|
|
124
|
+
def commit(cg, tok: dict, status: str = STATUS_COMMITTED, node_id: str = None,
|
|
125
|
+
reason: str = None, **meta) -> dict:
|
|
126
|
+
"""记录写入**结果**(与 intent 按 iid 配对)。返回结果记录。"""
|
|
127
|
+
nid = node_id or (tok or {}).get("node_id")
|
|
128
|
+
rec = {"t": time.time(), "phase": "outcome", "iid": (tok or {}).get("iid"),
|
|
129
|
+
"id": nid, "status": status}
|
|
130
|
+
if tok and tok.get("content_hash"):
|
|
131
|
+
rec["content_hash"] = tok["content_hash"]
|
|
132
|
+
if reason:
|
|
133
|
+
rec["reason"] = reason
|
|
134
|
+
rec.update(_ident(cg))
|
|
135
|
+
rec.update(meta)
|
|
136
|
+
_append(cg, rec)
|
|
137
|
+
return rec
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# ----------------------------------------------------------------------
|
|
141
|
+
# 读侧:盘点 / 对账
|
|
142
|
+
|
|
143
|
+
# 生效条件:log_path(cg) 不是文件时直接返回空列表;否则逐行读取,空行跳过,json.loads 抛异常的行跳过,返回成功解析的记录列表。
|
|
144
|
+
def records(cg) -> list:
|
|
145
|
+
"""读全部账本记录(append-only,坏行跳过不炸)。"""
|
|
146
|
+
out = []
|
|
147
|
+
p = log_path(cg)
|
|
148
|
+
if not os.path.isfile(p):
|
|
149
|
+
return out
|
|
150
|
+
import json
|
|
151
|
+
with open(p, encoding="utf-8", errors="replace") as f:
|
|
152
|
+
for line in f:
|
|
153
|
+
if not line.strip():
|
|
154
|
+
continue
|
|
155
|
+
try:
|
|
156
|
+
out.append(json.loads(line))
|
|
157
|
+
except Exception:
|
|
158
|
+
continue
|
|
159
|
+
return out
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
# 生效条件:遍历 records(cg),记录 r.get("iid") 为假值(缺键或空串)时跳过;否则按 iid 建槽,仅当槽内 intent/outcome 仍为 None 时分别填入首个 phase=="intent" / phase=="outcome" 的记录,返回 pairs。
|
|
163
|
+
def _pair(cg) -> dict:
|
|
164
|
+
"""把账本配成 {iid: {"intent":…, "outcome":…}}(同时计入无 iid 的脏行)。"""
|
|
165
|
+
pairs = {}
|
|
166
|
+
for r in records(cg):
|
|
167
|
+
iid = r.get("iid")
|
|
168
|
+
if not iid:
|
|
169
|
+
continue
|
|
170
|
+
slot = pairs.setdefault(iid, {"intent": None, "outcome": None})
|
|
171
|
+
if r.get("phase") == "intent" and slot["intent"] is None:
|
|
172
|
+
slot["intent"] = r
|
|
173
|
+
elif r.get("phase") == "outcome" and slot["outcome"] is None:
|
|
174
|
+
slot["outcome"] = r
|
|
175
|
+
return pairs
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
# 生效条件:遍历 _pair(cg) 取有 intent 且 outcome 为 None 的槽(展开 intent 字段)组成 out,按 r.get("t") or 0 升序排序后返回 out[:max(0, int(limit))]——limit 为 0 或负数时切片为空列表,默认值 200 仅在未传参时生效。
|
|
179
|
+
def pending(cg, limit: int = 200) -> list:
|
|
180
|
+
"""未结清的写入意图(有 intent 无 outcome)——只读,不改盘。
|
|
181
|
+
|
|
182
|
+
供 `cg(op=recent)` / 巡检看「有没有半途而废的写入」。
|
|
183
|
+
"""
|
|
184
|
+
out = []
|
|
185
|
+
for iid, slot in _pair(cg).items():
|
|
186
|
+
if slot["intent"] is not None and slot["outcome"] is None:
|
|
187
|
+
out.append({"iid": iid, **slot["intent"]})
|
|
188
|
+
out.sort(key=lambda r: r.get("t") or 0)
|
|
189
|
+
return out[:max(0, int(limit))]
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
# 生效条件:cg 的 index["nodes"] 为映射时——先按该映射查(_merge_target_in);未命中且 cg 有 _scan_nodes 时**回退盘面扫描**再查同一条复合判据(扫描抛异常按未命中);无索引/无命中/字段形态不符一律返回 None;恒不写盘、不抛。
|
|
193
|
+
def _merge_target(cg, nid):
|
|
194
|
+
"""源 id 是否已被**合并**进某个目标节点(#417/#498)——事实来源=**盘面**。
|
|
195
|
+
|
|
196
|
+
为什么需要它:MERGE 的落盘对象是**目标节点**(`forgetting.reinforce`),
|
|
197
|
+
源 id 本就不会成文;而崩溃窗口落在「内容已并入目标、`commit` 还没落账」
|
|
198
|
+
之间 ⇒ 只看源 id 的判据必然误报 `interrupted/node_missing`(与事实相反,
|
|
199
|
+
且会诱导重做**不可逆**的 MERGE)。
|
|
200
|
+
|
|
201
|
+
为什么要读 `merge_source_ids` 而不是 `merge_sources`:后者记的是
|
|
202
|
+
**写入方归属**(`{session, actor, t}`,`forgetting.note_source`),
|
|
203
|
+
**不含来源节点 id** —— 拿它反查来源永远查不到("判据与事实不符"换个地方复发)。
|
|
204
|
+
故 `forgetting.reinforce` 另立一列把来源 id 落盘(并有界保留),本函数据此反查;
|
|
205
|
+
索引命中后**仍回盘复核**(索引是派生物,盘面才是事实来源)。
|
|
206
|
+
|
|
207
|
+
#498(P1):**索引是派生物,且可能陈旧**——崩溃窗口内 `_index.json` 未持久化、
|
|
208
|
+
或本进程是长活实例(签名未变 ⇒ 不重载)时,索引里没有 `merge_source_ids`
|
|
209
|
+
这个键,于是判据看不到盘面明明已经存在的合并痕迹,结论与盘面相反。故索引
|
|
210
|
+
**落空后回退盘面扫描**(复用库层唯一扫描实现 `_scan_nodes`,不新写第二套
|
|
211
|
+
遍历),扫出的条目交给**同一条**复合判据(仍 `cg.get(tid)` 回盘复核)。
|
|
212
|
+
语义不放宽:盘面确无痕迹时照旧返回 None ⇒ `_judge` 仍判 `interrupted`。
|
|
213
|
+
代价只落在 miss 冷路径(恢复期),命中路径仍只读索引。
|
|
214
|
+
"""
|
|
215
|
+
nodes = (getattr(cg, "index", None) or {}).get("nodes") or {}
|
|
216
|
+
tgt = _merge_target_in(cg, nid, nodes)
|
|
217
|
+
if tgt is not None:
|
|
218
|
+
return tgt
|
|
219
|
+
scan = getattr(cg, "_scan_nodes", None)
|
|
220
|
+
if scan is None:
|
|
221
|
+
return None
|
|
222
|
+
try:
|
|
223
|
+
disk_nodes = scan() # 盘面全量扫描(只读、不写盘)
|
|
224
|
+
except Exception: # noqa: BLE001 —— 扫不动不猜测
|
|
225
|
+
return None
|
|
226
|
+
if not isinstance(disk_nodes, dict):
|
|
227
|
+
return None
|
|
228
|
+
return _merge_target_in(cg, nid, disk_nodes)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
# 生效条件:nodes 为映射时遍历(先 tuple() 取快照)找出「merge_source_ids 含 nid」的条目并取其 id;命中后用 cg.get(该 id) 在**盘面**复核(读不到或 fm 未记 nid 则返回 None);字段形态不符/无命中一律返回 None;恒不写盘、不抛。索引面与盘面扫描面**共用**这一条复合判据(单点,不各写一份)。
|
|
232
|
+
def _merge_target_in(cg, nid, nodes):
|
|
233
|
+
"""在给定条目映射(索引或盘面扫描结果)上反查合并痕迹——复合判据的**单点**。"""
|
|
234
|
+
for tid, e in tuple(nodes.items()): # H-4(a):迭代前取快照
|
|
235
|
+
if not isinstance(e, dict):
|
|
236
|
+
continue
|
|
237
|
+
ids = e.get("merge_source_ids")
|
|
238
|
+
if not isinstance(ids, (list, tuple)) or nid not in ids:
|
|
239
|
+
continue
|
|
240
|
+
try:
|
|
241
|
+
tgt = cg.get(tid)
|
|
242
|
+
except Exception: # noqa: BLE001 —— 读失败不猜测
|
|
243
|
+
return None
|
|
244
|
+
if not tgt:
|
|
245
|
+
return None
|
|
246
|
+
fm = tgt.get("frontmatter") or {}
|
|
247
|
+
if nid in (fm.get("merge_source_ids") or []):
|
|
248
|
+
return tid
|
|
249
|
+
return None
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
# 生效条件:intent 的 id 为假值或 cg.get(nid) 抛异常时返回 (STATUS_INTERRUPTED, R_UNREADABLE);取回 node 为假值时——先经 _merge_target(cg, nid) 查盘面合并痕迹,命中则返回 (STATUS_COMMITTED, R_MERGED_INTO + ":" + 目标 id),未命中仍返回 (STATUS_INTERRUPTED, R_NODE_MISSING)(**不放宽**);intent 的 content_hash 为真且与 _norm(node.get("content") or "") 的指纹不等时返回 (STATUS_INTERRUPTED, R_MISMATCH);否则返回 (STATUS_COMMITTED, R_NODE_OK)。
|
|
253
|
+
def _judge(cg, intent: dict):
|
|
254
|
+
"""判定一笔未结清意图的真实结局 → `(status, code)`。**不猜测**:读不到就如实说。
|
|
255
|
+
|
|
256
|
+
#417(2026-10-16):源 id 查不到**不再直接等于未落盘**——MERGE 类写入的
|
|
257
|
+
落盘对象是**目标节点**(事实来源=盘面合并痕迹,见 `_merge_target`)。
|
|
258
|
+
命中合并痕迹 ⇒ `committed` + 去向;**未命中 ⇒ 仍判 `interrupted`**
|
|
259
|
+
(新判据只补「已合并」这一种真实情形,不把未命中放宽成「可能已落盘」)。
|
|
260
|
+
"""
|
|
261
|
+
nid = intent.get("id")
|
|
262
|
+
want = intent.get("content_hash")
|
|
263
|
+
if not nid:
|
|
264
|
+
return STATUS_INTERRUPTED, R_UNREADABLE
|
|
265
|
+
try:
|
|
266
|
+
node = cg.get(nid)
|
|
267
|
+
except Exception:
|
|
268
|
+
return STATUS_INTERRUPTED, R_UNREADABLE
|
|
269
|
+
if not node:
|
|
270
|
+
tgt = _merge_target(cg, nid)
|
|
271
|
+
if tgt:
|
|
272
|
+
return STATUS_COMMITTED, "%s:%s" % (R_MERGED_INTO, tgt)
|
|
273
|
+
return STATUS_INTERRUPTED, R_NODE_MISSING
|
|
274
|
+
got = nodefile.content_hash(_norm(node.get("content") or ""))
|
|
275
|
+
if want and got != want:
|
|
276
|
+
return STATUS_INTERRUPTED, R_MISMATCH
|
|
277
|
+
return STATUS_COMMITTED, R_NODE_OK
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
# 生效条件:以 limit 调 pending(cg, limit=limit) 得到未结清意图并统计 unpaired/committed/interrupted;apply 为真时对每笔 intent 调 commit 补写 outcome(reconciled=True、actor="twophase:reconcile"),apply 为假值时只报告不写账本,rep["applied"]=bool(apply);limit 为 0 或负数时 pending 返回空、details 为空列表。
|
|
281
|
+
def reconcile(cg, apply: bool = True, limit: int = 2000) -> dict:
|
|
282
|
+
"""启动/巡检对账:把半途写入**补账或如实标记**。
|
|
283
|
+
|
|
284
|
+
`apply=False` 为 dry-run(只报告,不写账本)。返回汇总:
|
|
285
|
+
`{"unpaired", "committed", "interrupted", "applied", "details"}`。
|
|
286
|
+
幂等——补出的 outcome 与正常 outcome 同形,二次扫描不再有未配对项。
|
|
287
|
+
"""
|
|
288
|
+
pend = pending(cg, limit=limit)
|
|
289
|
+
rep = {"unpaired": len(pend), "committed": 0, "interrupted": 0,
|
|
290
|
+
"applied": bool(apply), "details": []}
|
|
291
|
+
for intent in pend:
|
|
292
|
+
status, code = _judge(cg, intent)
|
|
293
|
+
if status == STATUS_COMMITTED:
|
|
294
|
+
rep["committed"] += 1
|
|
295
|
+
else:
|
|
296
|
+
rep["interrupted"] += 1
|
|
297
|
+
rep["details"].append({"iid": intent.get("iid"), "id": intent.get("id"),
|
|
298
|
+
"status": status, "reason": code})
|
|
299
|
+
if apply:
|
|
300
|
+
commit(cg, {"iid": intent.get("iid"), "node_id": intent.get("id"),
|
|
301
|
+
"content_hash": intent.get("content_hash")},
|
|
302
|
+
status=status, reason=code, reconciled=True,
|
|
303
|
+
actor="twophase:reconcile")
|
|
304
304
|
return rep
|