@furongjun1999/dsh-memory 0.8.1 → 0.9.6

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 (714) hide show
  1. package/README.md +662 -659
  2. package/codebuddy/README.md +1 -1
  3. package/data/policy.json +17 -6
  4. package/docs/README.md +18 -2
  5. package/docs/discipline/harnesses.yaml +1 -1
  6. package/docs/discipline/templates/spec.txt.tmpl +23 -0
  7. package/docs//350/247/204/350/214/203/AI/347/274/226/347/250/213/351/200/232/347/224/250/350/247/204/350/214/203.md +179 -0
  8. package/docs//350/247/204/350/214/203/AI/347/274/226/347/250/213/351/200/232/347/224/250/350/247/204/350/214/203_/347/201/265/346/236/242/351/200/202/351/205/215.md +45 -0
  9. package/docs//350/247/204/350/214/203/AI/347/274/226/347/250/213/351/200/232/347/224/250/350/247/204/350/214/203_/350/207/252/346/243/200/346/270/205/345/215/225.md +69 -0
  10. package/dsh/README.md +1 -1
  11. package/dsh/cordis.yml.example +1 -1
  12. package/hive/README.md +705 -0
  13. package/hive/id_charset_blocks.txt +147 -0
  14. package/lib/bridge.d.ts +3 -0
  15. package/lib/bridge.js +32 -11
  16. package/lib/cli.js +14 -17
  17. package/lib/hooks.d.ts +18 -3
  18. package/lib/hooks.js +147 -18
  19. package/lib/index.d.ts +2 -2
  20. package/lib/index.js +18 -4
  21. package/lib/init.js +21 -21
  22. package/lib/lib/datapath.d.ts +56 -0
  23. package/lib/lib/datapath.js +102 -9
  24. package/lib/lib/hook_audit.d.ts +0 -1
  25. package/lib/lib/hook_audit.js +13 -1
  26. package/lib/lib/mdcg_client.d.ts +4 -1
  27. package/lib/lib/mdcg_client.js +10 -2
  28. package/lib/lib/mutual.js +61 -15
  29. package/lib/lib/prompt_safety.js +16 -1
  30. package/lib/lib/roleplay_web.js +30 -2
  31. package/lib/lib/token_store.d.ts +25 -6
  32. package/lib/lib/token_store.js +224 -33
  33. package/lib/tools.d.ts +8 -2
  34. package/lib/tools.js +22 -3
  35. package/md_cg/_guard_kit.py +121 -0
  36. package/md_cg/admission.py +718 -718
  37. package/md_cg/anchor.py +114 -0
  38. package/md_cg/audit.py +22 -5
  39. package/md_cg/autonomy.py +433 -288
  40. package/md_cg/autonomy_modes.py +781 -642
  41. package/md_cg/bench_beir_bm25.py +154 -0
  42. package/md_cg/bench_beir_scifact.py +170 -0
  43. package/md_cg/bench_bm25_blockmax.py +134 -0
  44. package/md_cg/bench_bm25_incremental.py +246 -0
  45. package/md_cg/bench_ccg_heading.py +118 -0
  46. package/md_cg/bench_csre_correctness.py +145 -0
  47. package/md_cg/bench_excerpt_budget.py +94 -0
  48. package/md_cg/bench_fuzzy_substrings.py +299 -0
  49. package/md_cg/bench_memory_rsi.py +358 -0
  50. package/md_cg/bench_memory_rsi_latency.py +82 -0
  51. package/md_cg/bench_memory_rsi_public.py +116 -0
  52. package/md_cg/bench_memory_rsi_tools.py +229 -0
  53. package/md_cg/bench_rrf_candidates.py +212 -0
  54. package/md_cg/bench_rrf_public.py +100 -0
  55. package/md_cg/bench_text_projections.py +221 -0
  56. package/md_cg/bench_timeanchor.py +357 -0
  57. package/md_cg/bm25.py +601 -0
  58. package/md_cg/branches.py +404 -327
  59. package/md_cg/build_postings.py +74 -73
  60. package/md_cg/ccgc.py +4 -2
  61. package/md_cg/chain.py +572 -379
  62. package/md_cg/coldverify.py +531 -292
  63. package/md_cg/condaccept.py +263 -0
  64. package/md_cg/condgate.py +308 -0
  65. package/md_cg/config_registry.py +329 -0
  66. package/md_cg/config_registry_bulk.py +482 -0
  67. package/md_cg/config_registry_guard.py +487 -0
  68. package/md_cg/config_render.py +354 -0
  69. package/md_cg/config_validate.py +455 -0
  70. package/md_cg/conformance.py +21 -0
  71. package/md_cg/conformance_core.py +753 -0
  72. package/md_cg/consistency.py +1278 -955
  73. package/md_cg/consolidate.py +180 -20
  74. package/md_cg/crypto.py +794 -472
  75. package/md_cg/datapath.py +137 -12
  76. package/md_cg/eval_common.py +522 -575
  77. package/md_cg/evidence.py +946 -585
  78. package/md_cg/evidence_delivery.py +101 -0
  79. package/md_cg/experience_consolidation.py +317 -0
  80. package/md_cg/export.py +329 -222
  81. package/md_cg/forgetting.py +1050 -922
  82. package/md_cg/freshness.py +601 -548
  83. package/md_cg/fsutil.py +1120 -824
  84. package/md_cg/goal_gen.py +458 -0
  85. package/md_cg/hotcache.py +107 -9
  86. package/md_cg/hyperedge.py +14 -3
  87. package/md_cg/identity.py +573 -391
  88. package/md_cg/imgskill.py +1712 -0
  89. package/md_cg/insight.py +540 -521
  90. package/md_cg/interface_schema.py +146 -0
  91. package/md_cg/interop.py +20 -0
  92. package/md_cg/judgment_manifest.py +24 -1
  93. package/md_cg/lifecycle.py +86 -5
  94. package/md_cg/links.py +27 -6
  95. package/md_cg/logref.py +332 -327
  96. package/md_cg/mcp_server.py +5227 -4449
  97. package/md_cg/mdcg.py +1301 -203
  98. package/md_cg/mdcos.py +7104 -5440
  99. package/md_cg/memory_rsi.py +308 -0
  100. package/md_cg/metacognition.py +726 -591
  101. package/md_cg/nodefile.py +151 -3
  102. package/md_cg/op_table.py +1128 -0
  103. package/md_cg/postings.py +524 -300
  104. package/md_cg/predict.py +4 -1
  105. package/md_cg/probe_memory_rsi.py +95 -0
  106. package/md_cg/probe_memory_rsi_mcp.py +66 -0
  107. package/md_cg/protect.py +188 -28
  108. package/md_cg/protocol.py +492 -411
  109. package/md_cg/provenance.py +7 -1
  110. package/md_cg/qmd.py +477 -0
  111. package/md_cg/qmd_llm.py +334 -0
  112. package/md_cg/query_excerpt.py +171 -0
  113. package/md_cg/queue_health.py +130 -0
  114. package/md_cg/reach.py +470 -453
  115. package/md_cg/readcache.py +115 -3
  116. package/md_cg/reconcile.py +239 -228
  117. package/md_cg/refindex.py +1191 -1042
  118. package/md_cg/refine.py +12 -3
  119. package/md_cg/retrieve.py +128 -0
  120. package/md_cg/review_cli.py +204 -26
  121. package/md_cg/revise.py +140 -0
  122. package/md_cg/rollback.py +256 -19
  123. package/md_cg/rollback_cli.py +21 -1
  124. package/md_cg/rotate.py +347 -0
  125. package/md_cg/routing.py +62 -1
  126. package/md_cg/rrf_candidates.py +204 -0
  127. package/md_cg/run_tests.py +19 -1
  128. package/md_cg/scrub.py +177 -23
  129. package/md_cg/security.py +269 -17
  130. package/md_cg/self_state.py +1053 -1029
  131. package/md_cg/self_surface.py +50 -0
  132. package/md_cg/semantic/canonical.py +1 -1
  133. package/md_cg/semantic/export_en_zh_map.py +2 -2
  134. package/md_cg/semantic/zh_en_atoms.py +2 -0
  135. package/md_cg/session5.py +106 -0
  136. package/md_cg/signer.py +76 -2
  137. package/md_cg/sleep.py +1779 -1583
  138. package/md_cg/sources.py +273 -15
  139. package/md_cg/state_events.py +75 -10
  140. package/md_cg/state_slots.py +312 -221
  141. package/md_cg/stg.py +82 -16
  142. package/md_cg/stgidx.py +537 -281
  143. package/md_cg/subgraph.py +851 -729
  144. package/md_cg/sustain.py +458 -19
  145. package/md_cg/task_memory.py +367 -0
  146. package/md_cg/test_action_derive.py +210 -203
  147. package/md_cg/test_audit_heartbeat_20261015.py +417 -0
  148. package/md_cg/test_audit_protection_20261015.py +483 -0
  149. package/md_cg/test_audit_rotate_parity.py +280 -0
  150. package/md_cg/test_audit_state_20261015.py +253 -0
  151. package/md_cg/test_audit_write_20261015.py +161 -0
  152. package/md_cg/test_auto_defaults.py +43 -4
  153. package/md_cg/test_autonomy_emotion.py +328 -0
  154. package/md_cg/test_autonomy_modes.py +43 -3
  155. package/md_cg/test_b1_foreign_read.py +245 -0
  156. package/md_cg/test_bm25.py +438 -0
  157. package/md_cg/test_bm25_hydration_refill.py +265 -0
  158. package/md_cg/test_bm25_incremental.py +241 -0
  159. package/md_cg/test_bm25_incremental_mutations.py +160 -0
  160. package/md_cg/test_bm25_mutations.py +205 -0
  161. package/md_cg/test_bm25_pool_view.py +196 -0
  162. package/md_cg/test_boot_openblas_guard.py +218 -197
  163. package/md_cg/test_boundary_hit.py +1 -1
  164. package/md_cg/test_branches_sensitivity.py +375 -0
  165. package/md_cg/test_c8_search_rrf_gates.py +1 -1
  166. package/md_cg/test_canonical_timezones.py +211 -0
  167. package/md_cg/test_ccg_heading_parser.py +73 -0
  168. package/md_cg/test_chain_best_first.py +403 -0
  169. package/md_cg/test_chain_candidate_scope.py +227 -0
  170. package/md_cg/test_cn_recall_grams.py +206 -0
  171. package/md_cg/test_coldverify_drain.py +127 -0
  172. package/md_cg/test_condaccept.py +156 -0
  173. package/md_cg/test_condgate.py +141 -0
  174. package/md_cg/test_config_registry.py +55 -0
  175. package/md_cg/test_crypto_rotate.py +257 -0
  176. package/md_cg/test_csre_correctness.py +297 -0
  177. package/md_cg/test_csre_index_import_guard.py +161 -0
  178. package/md_cg/test_csre_mutations.py +34 -0
  179. package/md_cg/test_csre_session.py +69 -0
  180. package/md_cg/test_curiosity_budget.py +468 -0
  181. package/md_cg/test_d17_autostart_toolface.py +453 -0
  182. package/md_cg/test_datapath_tilde_home.py +271 -0
  183. package/md_cg/test_derived_cache_generations.py +256 -0
  184. package/md_cg/test_evidence_delivery_compact.py +54 -0
  185. package/md_cg/test_exact_text_cache.py +191 -0
  186. package/md_cg/test_excerpt_budget.py +188 -0
  187. package/md_cg/test_experience_consolidation.py +112 -0
  188. package/md_cg/test_export_default_collision.py +138 -0
  189. package/md_cg/test_export_snapshots.py +322 -0
  190. package/md_cg/test_fuzzy_substring_equivalence.py +127 -0
  191. package/md_cg/test_gain_gate.py +16 -5
  192. package/md_cg/test_goal_gen.py +355 -0
  193. package/md_cg/test_h2_session_view_norm.py +251 -233
  194. package/md_cg/test_h4_sustain_snapshot.py +1490 -1387
  195. package/md_cg/test_heartbeat_ledger.py +557 -0
  196. package/md_cg/test_hierarchy_audit_graph.py +237 -0
  197. package/md_cg/test_i50c_meta_passthrough.py +628 -608
  198. package/md_cg/test_i50e_readside_protection.py +6 -4
  199. package/md_cg/test_identity_attribution.py +96 -2
  200. package/md_cg/test_identity_contract.py +329 -0
  201. package/md_cg/test_imgskill.py +1444 -0
  202. package/md_cg/test_index_snapshot_shape.py +240 -0
  203. package/md_cg/test_interop_judgment.py +258 -228
  204. package/md_cg/test_issue111_gate_order.py +77 -0
  205. package/md_cg/test_issue111_scoring_contract.py +87 -0
  206. package/md_cg/test_issue121_calibration_bounds.py +293 -0
  207. package/md_cg/test_issue128_session_env_authority.py +246 -0
  208. package/md_cg/test_issue130_rrf_rank_credibility.py +217 -0
  209. package/md_cg/test_issue131_postings_content_staleness.py +424 -0
  210. package/md_cg/test_issue145_sleep_no_silent_rollback.py +168 -0
  211. package/md_cg/test_issue146_frontmatter_quarantine.py +428 -0
  212. package/md_cg/test_issue147_pack_id_escape.py +378 -0
  213. package/md_cg/test_issue148_merge_downgrade_leak.py +192 -0
  214. package/md_cg/test_issue149_accel_default_face.py +249 -0
  215. package/md_cg/test_issue150_empty_query_terms.py +328 -0
  216. package/md_cg/test_issue151_153_157_write_cache_index.py +152 -0
  217. package/md_cg/test_issue151b_base_add_importance_guard.py +166 -0
  218. package/md_cg/test_issue152_sealed_postings.py +309 -0
  219. package/md_cg/test_issue152b_decrypt_cache.py +218 -0
  220. package/md_cg/test_issue153b_cache_alias_and_canon.py +236 -0
  221. package/md_cg/test_issue153b_index_generation_invalidation.py +143 -0
  222. package/md_cg/test_issue157b_index_remainder.py +344 -0
  223. package/md_cg/test_issue189_conclusion_bidirectional.py +223 -0
  224. package/md_cg/test_issue190_tidy_idempotent.py +806 -0
  225. package/md_cg/test_issue191_import_trust.py +382 -0
  226. package/md_cg/test_issue192_move_layer_indices_guard.py +258 -0
  227. package/md_cg/test_issue193_consistency_knowledge_guard.py +524 -0
  228. package/md_cg/test_issue193_write_scope.py +378 -0
  229. package/md_cg/test_issue197_rank_credibility_property.py +201 -0
  230. package/md_cg/test_issue211_export_target.py +325 -0
  231. package/md_cg/test_issue212_writeface_gaps.py +349 -0
  232. package/md_cg/test_issue214_reject_sensitivity.py +267 -0
  233. package/md_cg/test_issue215_condition_source_gap.py +272 -0
  234. package/md_cg/test_issue216_clash_routes.py +214 -0
  235. package/md_cg/test_issue217_slot_routes.py +248 -0
  236. package/md_cg/test_issue218_postcondition_value_blind.py +222 -0
  237. package/md_cg/test_issue225_consistency_torn_log.py +433 -0
  238. package/md_cg/test_issue245_swarm_traversal.py +366 -0
  239. package/md_cg/test_issue258_pack_sensitivity.py +468 -0
  240. package/md_cg/test_issue265_coldverify_multiproc.py +438 -0
  241. package/md_cg/test_issue274_read_node_id_none.py +341 -0
  242. package/md_cg/test_issue275_layer_param.py +250 -0
  243. package/md_cg/test_issue277_node_id_traversal.py +384 -0
  244. package/md_cg/test_issue278_neg_separated_tension.py +271 -0
  245. package/md_cg/test_issue278_neg_window.py +294 -0
  246. package/md_cg/test_issue278_negative_layering.py +83 -0
  247. package/md_cg/test_issue279_signers_path_guard.py +652 -0
  248. package/md_cg/test_issue284_skip_not_pass.py +291 -0
  249. package/md_cg/test_issue294_flywheel_sensitivity.py +573 -0
  250. package/md_cg/test_issue295_sleep_root_binding.py +589 -0
  251. package/md_cg/test_issue297_rewrite_sensitivity.py +454 -0
  252. package/md_cg/test_issue298_consistency_ledger_sensitivity.py +421 -0
  253. package/md_cg/test_issue301_baseline_corpus_gate.py +245 -0
  254. package/md_cg/test_issue303_design_boundaries.py +262 -0
  255. package/md_cg/test_issue313_writelimit_sensitivity.py +404 -0
  256. package/md_cg/test_issue315_merge_branch_sensitivity.py +384 -0
  257. package/md_cg/test_issue315_sensitivity_passthrough_guard.py +514 -0
  258. package/md_cg/test_issue319_tenant_unregistered_bypass.py +257 -0
  259. package/md_cg/test_issue320_vstate_requires_verify.py +279 -0
  260. package/md_cg/test_issue321_mcp_deep_json.py +305 -0
  261. package/md_cg/test_issue322_node_write_lock.py +727 -0
  262. package/md_cg/test_issue323_aggregate_segment_boundary.py +365 -0
  263. package/md_cg/test_issue324_write_size_fields.py +215 -0
  264. package/md_cg/test_issue325_audit_poison.py +230 -0
  265. package/md_cg/test_issue326_append_jsonl_oserror.py +464 -0
  266. package/md_cg/test_issue326_ingest_auto_whitelist.py +331 -0
  267. package/md_cg/test_issue326_key_perms.py +355 -0
  268. package/md_cg/test_issue326_twin_parser_parity.py +323 -0
  269. package/md_cg/test_issue326_vm_call_frame.py +569 -0
  270. package/md_cg/test_issue345_writelimit_effective_sens.py +234 -0
  271. package/md_cg/test_issue346_overwrite_sensitivity_gate.py +424 -0
  272. package/md_cg/test_issue346_review_overwrite_guard.py +509 -0
  273. package/md_cg/test_issue348_insight_verify_op.py +200 -0
  274. package/md_cg/test_issue348_merge_rmw_lock.py +345 -0
  275. package/md_cg/test_issue350_casefold_collision.py +236 -0
  276. package/md_cg/test_issue351_ingest_root_fallback.py +202 -0
  277. package/md_cg/test_issue352_imgaudit.py +418 -0
  278. package/md_cg/test_issue352_pathsjson.py +537 -0
  279. package/md_cg/test_issue352_refindex.py +412 -0
  280. package/md_cg/test_issue352_rollback.py +604 -0
  281. package/md_cg/test_issue352_vstateinherit.py +196 -0
  282. package/md_cg/test_issue354_p1_writelimit_type.py +522 -0
  283. package/md_cg/test_issue354_p2_datapath_clock.py +381 -0
  284. package/md_cg/test_issue354_p2_writelimit_toctou.py +327 -0
  285. package/md_cg/test_issue354_rust_index_containment.py +571 -0
  286. package/md_cg/test_issue354_rust_wal_containment.py +606 -0
  287. package/md_cg/test_issue358_truncation_observable.py +247 -0
  288. package/md_cg/test_issue360_tidy_private_excerpt.py +196 -0
  289. package/md_cg/test_issue361_blindspot_not_silent_drop.py +494 -0
  290. package/md_cg/test_issue362_neg_condition.py +468 -0
  291. package/md_cg/test_issue363_lexical_idf.py +275 -0
  292. package/md_cg/test_issue370_readcache_assembly.py +488 -0
  293. package/md_cg/test_issue375_state_slot_retire.py +325 -0
  294. package/md_cg/test_issue376_heartbeat_failed.py +293 -0
  295. package/md_cg/test_issue377_layer_protect_stamp.py +324 -0
  296. package/md_cg/test_issue378_protected_floor.py +310 -0
  297. package/md_cg/test_issue383_state_event_write_gate.py +462 -0
  298. package/md_cg/test_issue397_sens_eff_wiring.py +435 -0
  299. package/md_cg/test_issue398_toolface_op_parity.py +511 -0
  300. package/md_cg/test_issue399_hive_json_shape.py +317 -0
  301. package/md_cg/test_issue400_hive_dirty_args.py +450 -0
  302. package/md_cg/test_issue401_wisdom_codegen.py +295 -0
  303. package/md_cg/test_issue404_heal_receipt.py +390 -0
  304. package/md_cg/test_issue405_git_pathspec.py +333 -0
  305. package/md_cg/test_issue408_eface_registry.py +291 -0
  306. package/md_cg/test_issue409_compact_index_completeness.py +509 -0
  307. package/md_cg/test_issue410_verify_demote_write.py +366 -0
  308. package/md_cg/test_issue411_scrub_idempotence.py +575 -0
  309. package/md_cg/test_issue412_discipline_producer_parity.py +312 -0
  310. package/md_cg/test_issue413_preimage_failclosed.py +239 -0
  311. package/md_cg/test_issue413_preimage_twin.py +340 -0
  312. package/md_cg/test_issue414_write_args_parity.py +613 -0
  313. package/md_cg/test_issue415_deps_gate_probe.py +358 -0
  314. package/md_cg/test_issue416_entry_key_subset.py +525 -0
  315. package/md_cg/test_issue417_twophase_merge_landed.py +423 -0
  316. package/md_cg/test_issue418_identity_role_type_gate.py +188 -0
  317. package/md_cg/test_issue418_role_type_gate.py +265 -0
  318. package/md_cg/test_issue419_pii_redaction.py +642 -0
  319. package/md_cg/test_issue424_merge_confirm_sensitivity.py +381 -0
  320. package/md_cg/test_issue425_ingest_library_path.py +331 -0
  321. package/md_cg/test_issue426a_dedup_receipt.py +242 -0
  322. package/md_cg/test_issue426b_root_clash_invisible.py +270 -0
  323. package/md_cg/test_issue426c_enqueue_not_silent.py +346 -0
  324. package/md_cg/test_issue426e_restore_overwrite_live.py +310 -0
  325. package/md_cg/test_issue426f_paths_gbk_failclosed.py +301 -0
  326. package/md_cg/test_issue427_serve_status_shape.py +191 -0
  327. package/md_cg/test_issue431_432_468_protect_single_point.py +322 -0
  328. package/md_cg/test_issue433_outlook_threshold_single_point.py +278 -0
  329. package/md_cg/test_issue434_435_float_gate.py +90 -0
  330. package/md_cg/test_issue439_sibling_sensitivity_inherit.py +448 -0
  331. package/md_cg/test_issue43_default_policy.py +13 -4
  332. package/md_cg/test_issue443a_state_event_length_gate.py +94 -0
  333. package/md_cg/test_issue443b_audit_record_length_gate.py +83 -0
  334. package/md_cg/test_issue443c_self_state_imgskill_length_gate.py +77 -0
  335. package/md_cg/test_issue444_scrub_evidence_plaintext.py +281 -0
  336. package/md_cg/test_issue445_metacognition_ledger_gate.py +454 -0
  337. package/md_cg/test_issue446_453_403_verified_evidence.py +382 -0
  338. package/md_cg/test_issue446_is_encrypted_envelope.py +166 -0
  339. package/md_cg/test_issue447_recent_sens_failclosed.py +270 -0
  340. package/md_cg/test_issue450_sensitivity_fallback_reason.py +51 -0
  341. package/md_cg/test_issue450_writegate_unknown_sens.py +203 -0
  342. package/md_cg/test_issue451_audit_actor.py +313 -0
  343. package/md_cg/test_issue452_ingest_root_hint.py +238 -0
  344. package/md_cg/test_issue452_ingest_root_sensitivity.py +299 -0
  345. package/md_cg/test_issue463_ghost_prune_guard.py +259 -0
  346. package/md_cg/test_issue466_basis_registry.py +469 -0
  347. package/md_cg/test_issue467_identity_sensitivity.py +204 -0
  348. package/md_cg/test_issue467_identity_sensitivity_parity.py +361 -0
  349. package/md_cg/test_issue469_scrub_override_passthrough.py +126 -0
  350. package/md_cg/test_issue470_wal_event_durable.py +427 -0
  351. package/md_cg/test_issue471_identity_readable.py +137 -0
  352. package/md_cg/test_issue472_audit_chain.py +91 -0
  353. package/md_cg/test_issue472_prune_ledger.py +106 -0
  354. package/md_cg/test_issue472_rollback_degraded.py +82 -0
  355. package/md_cg/test_issue491_compose_sandbox.py +460 -0
  356. package/md_cg/test_issue492_dup_readout_opt_in.py +292 -0
  357. package/md_cg/test_issue498_merge_trace_stale_index.py +280 -0
  358. package/md_cg/test_issue511_scoreboard_bad_files.py +256 -0
  359. package/md_cg/test_issue521_rotate_lock_suffix.py +110 -0
  360. package/md_cg/test_issue522_review_record_sensitivity.py +267 -0
  361. package/md_cg/test_issue524_orphan_noise_no_demote.py +88 -0
  362. package/md_cg/test_issue525_read_null_semantics.py +52 -0
  363. package/md_cg/test_issue538_hook_condition_space.py +97 -0
  364. package/md_cg/test_issue540_path_guard_whitespace.py +126 -0
  365. package/md_cg/test_issue541_tidy_protect_gate.py +141 -0
  366. package/md_cg/test_issue542_tenant_root_same.py +153 -0
  367. package/md_cg/test_issue543_issue_authorization.py +147 -0
  368. package/md_cg/test_issue544_sandbox_reflection_gate.py +175 -0
  369. package/md_cg/test_issue545_charset_vs_size_diagnostic.py +77 -0
  370. package/md_cg/test_issue546_ledger_concurrency.py +81 -0
  371. package/md_cg/test_issue547_append_jsonl_whitelist.py +115 -0
  372. package/md_cg/test_issue547_audit_durable.py +96 -0
  373. package/md_cg/test_issue549_durable_append.py +143 -0
  374. package/md_cg/test_issue557_r1_credential_value_forms.py +76 -0
  375. package/md_cg/test_issue557_r2_write_entries_size_gate.py +84 -0
  376. package/md_cg/test_issue557_r3_pem_block_redaction.py +75 -0
  377. package/md_cg/test_issue559_refine_prefix.py +70 -0
  378. package/md_cg/test_issue561_pending_review.py +109 -0
  379. package/md_cg/test_issue66_scrub_semantics.py +107 -0
  380. package/md_cg/test_issue67_scrub_control_pool.py +233 -0
  381. package/md_cg/test_issue69_audit_boundary.py +129 -0
  382. package/md_cg/test_issue71_queue_backlog.py +377 -0
  383. package/md_cg/test_issue72_coldverify_controlled_drain.py +420 -0
  384. package/md_cg/test_issue73_doc_chapter_refs.py +326 -0
  385. package/md_cg/test_issue75_neural_failure.py +582 -0
  386. package/md_cg/test_issue78_export_concurrency.py +334 -0
  387. package/md_cg/test_issue80_residual_flush.py +169 -0
  388. package/md_cg/test_issue82_credential_rules.py +271 -0
  389. package/md_cg/test_issue82_layer_and_size.py +120 -0
  390. package/md_cg/test_issue84_portability.py +95 -0
  391. package/md_cg/test_issue85_export_overwrite.py +113 -0
  392. package/md_cg/test_issue86_runtime_revoke.py +110 -0
  393. package/md_cg/test_issue87_default_sensitivity_single.py +201 -0
  394. package/md_cg/test_issue88_conclusion_face.py +280 -0
  395. package/md_cg/test_issue88_execution_conflicts.py +87 -0
  396. package/md_cg/test_issue89_zero_score.py +169 -0
  397. package/md_cg/test_issue89a_score_cap_tiebreak.py +279 -0
  398. package/md_cg/test_issue91_verifier_sandbox.py +314 -0
  399. package/md_cg/test_issue91_verifier_timeout.py +528 -0
  400. package/md_cg/test_issue93_remember_redaction.py +282 -0
  401. package/md_cg/test_issue96_key_fallback.py +102 -0
  402. package/md_cg/test_issue98_tenant_root.py +104 -0
  403. package/md_cg/test_jsonl_commit_watermark.py +221 -0
  404. package/md_cg/test_live_validity_cache.py +256 -0
  405. package/md_cg/test_logref.py +32 -0
  406. package/md_cg/test_mcp_call_argument_types.py +99 -0
  407. package/md_cg/test_md_access_parity.py +80 -5
  408. package/md_cg/test_md_cg_no_hive_dep.py +140 -0
  409. package/md_cg/test_memory_rsi.py +215 -0
  410. package/md_cg/test_memory_rsi_adversarial.py +91 -0
  411. package/md_cg/test_mode_parity.py +1413 -1393
  412. package/md_cg/test_mutation_residue.py +120 -0
  413. package/md_cg/test_mutation_rollback.py +62 -32
  414. package/md_cg/test_n123_derive_expiry_chain.py +10 -5
  415. package/md_cg/test_n130_verify_falsified_protect.py +185 -185
  416. package/md_cg/test_n209_verify_write_face_gates.py +7 -2
  417. package/md_cg/test_n230_dirty_replay.py +52 -9
  418. package/md_cg/test_n62_tenant_bind_failclosed.py +3 -3
  419. package/md_cg/test_neg_coverage_budget.py +500 -0
  420. package/md_cg/test_neg_tail_honesty.py +79 -9
  421. package/md_cg/test_p0.py +16 -2
  422. package/md_cg/test_p14_root_fallback.py +373 -0
  423. package/md_cg/test_p1x_ref_root.py +47 -10
  424. package/md_cg/test_p21_tokens.py +2 -1
  425. package/md_cg/test_p24_evidence.py +232 -227
  426. package/md_cg/test_p26_refindex.py +20 -3
  427. package/md_cg/test_p27_docindex.py +16 -1
  428. package/md_cg/test_p28_refcheck.py +45 -24
  429. package/md_cg/test_p29_session_ingest_export.py +6 -0
  430. package/md_cg/test_p2_mcp.py +474 -453
  431. package/md_cg/test_p2_six_elements.py +14 -1
  432. package/md_cg/test_p3.py +370 -261
  433. package/md_cg/test_p33_ccg_wiring.py +9 -2
  434. package/md_cg/test_p3_legacy_closure.py +6 -1
  435. package/md_cg/test_p40_refine_worklist.py +5 -2
  436. package/md_cg/test_p47_session_view.py +25 -9
  437. package/md_cg/test_p4_freshness.py +8 -1
  438. package/md_cg/test_p83_jsonrpc_parse_error.py +124 -0
  439. package/md_cg/test_p9c_dedup_hints.py +7 -2
  440. package/md_cg/test_policy_required_ccg.py +12 -0
  441. package/md_cg/test_postings_digest_memo.py +139 -0
  442. package/md_cg/test_predict_beta.py +138 -135
  443. package/md_cg/test_qmd.py +500 -0
  444. package/md_cg/test_query_excerpt.py +209 -0
  445. package/md_cg/test_reach.py +456 -378
  446. package/md_cg/test_reach_snapshot_admission.py +218 -0
  447. package/md_cg/test_readcache_prodpath.py +4 -0
  448. package/md_cg/test_recall_face_guards.py +854 -812
  449. package/md_cg/test_recall_metadata.py +422 -0
  450. package/md_cg/test_retr_s5.py +104 -5
  451. package/md_cg/test_retr_score_once.py +14 -2
  452. package/md_cg/test_review_cli_attribution.py +11 -7
  453. package/md_cg/test_review_queue_batch.py +123 -0
  454. package/md_cg/test_review_queue_index.py +130 -0
  455. package/md_cg/test_rrf_candidates.py +292 -0
  456. package/md_cg/test_rrf_qualified_topk.py +214 -0
  457. package/md_cg/test_rrf_unique_votes.py +218 -0
  458. package/md_cg/test_s1_ast_judge.py +110 -0
  459. package/md_cg/test_scrub_ledger.py +413 -0
  460. package/md_cg/test_security_audit_b26.py +34 -3
  461. package/md_cg/test_security_audit_v21.py +1 -2
  462. package/md_cg/test_sensitivity_predicate_single_point.py +184 -0
  463. package/md_cg/test_session5_identity.py +93 -0
  464. package/md_cg/test_session_attribution_consistency.py +813 -0
  465. package/md_cg/test_session_identity_tristate.py +486 -0
  466. package/md_cg/test_sleep_p1.py +35 -3
  467. package/md_cg/test_state_event_op.py +8 -1
  468. package/md_cg/test_state_projection_streaming.py +136 -0
  469. package/md_cg/test_stg_interval_candidates.py +280 -0
  470. package/md_cg/test_stg_time_blocks.py +239 -0
  471. package/md_cg/test_stgidx_index_parity.py +16 -12
  472. package/md_cg/test_subgraph_bounded_bfs.py +227 -0
  473. package/md_cg/test_sustain_bounded.py +30 -2
  474. package/md_cg/test_task_memory.py +394 -0
  475. package/md_cg/test_text_projection_mutations.py +101 -0
  476. package/md_cg/test_time_anchor.py +421 -0
  477. package/md_cg/test_time_core_lint.py +1024 -975
  478. package/md_cg/test_tool_face.py +200 -189
  479. package/md_cg/test_trust_bounded_frontier.py +248 -0
  480. package/md_cg/test_trust_edge_reachability.py +405 -0
  481. package/md_cg/test_w5_path_fingerprint.py +381 -0
  482. package/md_cg/test_w7_redlines.py +659 -0
  483. package/md_cg/test_write_return_shape.py +919 -0
  484. package/md_cg/test_writepipe.py +5 -3
  485. package/md_cg/timeanchor.py +534 -0
  486. package/md_cg/tokens.py +68 -5
  487. package/md_cg/tool_face.py +273 -260
  488. package/md_cg/trust.py +110 -26
  489. package/md_cg/twophase.py +74 -2
  490. package/md_cg/weights.py +642 -638
  491. package/md_cg/whitebox.py +9 -0
  492. package/md_cg/whitebox_kb/aeis_core/core.py +5026 -5026
  493. package/md_cg/whitebox_kb/wisdom/chat_engine.py +1504 -1506
  494. package/md_cg/whitebox_kb/wisdom/code_compose.py +876 -837
  495. package/md_cg/whitebox_kb/wisdom/compiler_code_units.py +3040 -3033
  496. package/md_cg/whitebox_kb/wisdom/compose_engine.py +3 -2
  497. package/md_cg/whitebox_kb/wisdom/core/condition_vm.py +22 -2
  498. package/md_cg/whitebox_kb/wisdom/core/parser.py +17 -0
  499. package/md_cg/whitebox_kb/wisdom/csre.py +412 -264
  500. package/md_cg/whitebox_kb/wisdom/csre_session.py +97 -0
  501. package/md_cg/whitebox_kb/wisdom/md_access.py +23 -3
  502. package/md_cg/whitebox_kb/wisdom/migrate_wisdom.py +21 -0
  503. package/md_cg/whitebox_kb/wisdom/mini_python.py +44 -7
  504. package/md_cg/whitebox_kb/wisdom/navigate.py +249 -248
  505. package/md_cg/whitebox_kb/wisdom/net_units.py +12 -7
  506. package/md_cg/whitebox_kb/wisdom/neural_retrieve.py +100 -10
  507. package/md_cg/whitebox_kb/wisdom/semantic_translate.py +13 -7
  508. package/md_cg/whitebox_kb/wisdom/test_ecosystem_assembly.py +158 -158
  509. package/md_cg/whitebox_kb/wisdom/test_safe_module_proxy.py +147 -0
  510. package/md_cg/whitebox_kb/wisdom/verifier.py +1918 -1297
  511. package/md_cg/writelimit.py +584 -390
  512. package/md_cg/writepipe.py +587 -76
  513. package/package.json +13 -9
  514. package/src/bridge.ts +34 -11
  515. package/src/cli.ts +75 -65
  516. package/src/hooks.ts +908 -776
  517. package/src/index.ts +19 -5
  518. package/src/init.ts +362 -361
  519. package/src/lib/datapath.ts +419 -326
  520. package/src/lib/hook_audit.ts +256 -243
  521. package/src/lib/mdcg_client.ts +10 -2
  522. package/src/lib/mutual.ts +481 -432
  523. package/src/lib/prompt_safety.ts +164 -149
  524. package/src/lib/roleplay_web.ts +30 -2
  525. package/src/lib/token_store.ts +274 -52
  526. package/src/tools.ts +249 -223
  527. package/zcode/README.md +1 -1
  528. package/docs/GBrain/345/217/257/345/200/237/351/211/264/347/202/271_/347/201/265/346/236/242/350/220/275/347/202/271/344/272/244/346/216/245_20260919.md +0 -169
  529. package/docs/Pi/345/217/257/345/255/246/344/271/240/344/274/230/347/202/271_/347/201/265/346/236/242/345/244/247/350/204/221/346/224/271/350/277/233/344/272/244/346/216/245_20260915.md +0 -144
  530. package/docs/eval/AGI/344/270/203/347/273/264/350/257/204/345/210/206/346/212/245/345/221/212_md_cg_v1.0.md +0 -299
  531. package/docs/eval/AGI/344/270/203/347/273/264/350/257/204/345/210/206/346/212/245/345/221/212_md_cg_v2.0.md +0 -239
  532. package/docs/eval/AGI/344/270/203/347/273/264/350/257/204/345/210/206/346/212/245/345/221/212_/345/205/255/345/256/266/350/256/260/345/277/206/347/263/273/347/273/237/345/220/214/345/260/272/345/256/236/346/265/213_v3.1.md +0 -340
  533. package/docs/eval/DSH/346/227/245/345/277/227/347/264/242/345/274/225v2_/345/217/202/350/200/203dsh-TUI_v1.0.md +0 -248
  534. package/docs/eval/DSH/346/227/245/345/277/227/347/264/242/345/274/225/346/225/210/346/236/234/351/252/214/350/257/201_v1.0.md +0 -209
  535. package/docs/eval/DSH/347/253/257/347/274/272/351/231/267/344/270/223/351/241/271_v1.0.md +0 -254
  536. package/docs/eval/N225_/347/264/242/345/274/225/346/227/245/345/277/227/351/235/236/345/257/271/350/261/241/350/243/205/350/275/275/351/235/242/347/261/273/345/236/213/351/227/270_v1.0.md +0 -418
  537. package/docs/eval/P1b2_/350/257/273/351/235/242/344/273/243/351/231/205/344/277/256/345/244/215_v1.0.md +0 -124
  538. package/docs/eval/bench_lingshu_self/bench_self.py +0 -140
  539. package/docs/eval/bench_lingshu_self/self_bench_result.json +0 -404
  540. package/docs/eval/bench_lingshu_self//347/201/265/346/236/242/350/207/252/345/272/223/347/253/257/345/210/260/347/253/257/346/243/200/347/264/242/345/256/236/346/265/213_v1.0.md +0 -38
  541. package/docs/eval/cons200_/345/206/262/347/252/201/346/243/200/346/265/213/351/200/211/351/235/242_/345/256/236/346/226/275/350/256/260/345/275/225_v1.0.md +0 -223
  542. package/docs/eval/cons200_/345/206/262/347/252/201/346/243/200/346/265/213/351/200/211/351/235/242_/345/256/236/346/226/275/350/256/260/345/275/225_v1.1.md +0 -340
  543. package/docs/eval/issue43_/351/273/230/350/256/244/347/255/226/347/225/245/344/270/216/351/224/256/347/261/273/345/236/213/351/227/270_v1.1.md +0 -441
  544. package/docs/eval/issue43_/351/273/230/350/256/244/347/255/226/347/225/245/345/212/240/350/275/275/344/270/216/345/207/255/346/215/256/346/230/216/346/226/207/351/230/237/345/210/227_v1.0.md +0 -398
  545. package/docs/eval/issue50_/345/205/203/346/225/260/346/215/256/351/200/217/344/274/240/344/270/216/345/205/234/345/272/225_/344/277/256/345/244/215/350/256/260/345/275/225_v1.0.md +0 -437
  546. package/docs/eval/issue50_/345/215/212/351/207/215/345/244/215/345/276/205/345/256/232/345/244/215/346/240/270_/344/277/256/345/244/215/350/256/260/345/275/225_v1.0.md +0 -488
  547. package/docs/eval/issue50_/345/276/205/345/256/232/345/244/215/346/240/270/345/205/245/351/230/237_/344/277/256/345/244/215/350/256/260/345/275/225_v1.0.md +0 -428
  548. package/docs/eval/issue50_/350/257/273/351/235/242/344/277/235/346/212/244/345/217/252/350/256/244/346/230/276/345/274/217/346/235/245/346/272/220_/344/277/256/345/244/215/350/256/260/345/275/225_v1.0.md +0 -271
  549. package/docs/eval/issue50_/351/207/215/350/246/201/345/272/246/345/220/214/346/272/220/344/270/216/344/277/235/346/212/244/350/257/255/344/271/211_/344/277/256/345/244/215/350/256/260/345/275/225_v1.0.md +0 -306
  550. package/docs/eval/issue51_/344/270/200/351/224/256/345/256/211/350/243/205/345/244/261/350/264/245_/345/275/222/345/261/236/345/210/244/345/256/232_v1.0.md +0 -58
  551. package/docs/eval/issue52_/346/235/241/344/273/266/345/205/210/350/241/214/344/270/216/346/210/252/346/226/255/345/217/257/350/247/202/346/265/213_/344/277/256/345/244/215/350/256/260/345/275/225_v1.0.md +0 -360
  552. package/docs/eval/issue64_replay_check_/346/240/270/351/252/214/344/270/216/344/277/256/345/244/215_v1.0.md +0 -284
  553. package/docs/eval/issue65_session_recall_/344/274/232/350/257/235/351/232/224/347/246/273_/346/240/270/351/252/214/344/270/216/344/277/256/345/244/215_v1.0.md +0 -329
  554. package/docs/eval//344/270/211/346/241/243/350/207/252/346/262/273_/346/255/245/351/252/244/342/221/241/346/241/243/344/275/215/345/215/225/344/270/200/345/205/245/345/217/243_/350/220/275/347/240/201/350/256/260/345/275/225_v1.0.md +0 -651
  555. package/docs/eval//344/270/211/346/241/243/350/207/252/346/262/273_/346/255/245/351/252/244/342/221/242/345/217/230/346/233/264/345/215/225/344/270/216/345/233/236/346/273/232/345/216/237/350/257/255_/350/220/275/347/240/201/350/256/260/345/275/225_v1.0.md +0 -439
  556. package/docs/eval//344/270/211/346/241/243/350/207/252/346/262/273_/346/255/245/351/252/244/342/221/243/345/207/206/345/205/245/350/257/273/346/225/260_/350/220/275/347/240/201/350/256/260/345/275/225_v1.0.md +0 -1337
  557. package/docs/eval//344/270/211/346/241/243/350/207/252/346/262/273_/346/255/245/351/252/244/342/221/244/346/224/266/345/256/230/344/270/216/345/205/250/351/223/276/351/252/214/346/224/266_/350/220/275/347/240/201/350/256/260/345/275/225_v1.0.md +0 -1817
  558. package/docs/eval//344/270/215/345/217/257/351/235/240/346/200/247/350/220/275/345/234/260_P0_v1.0.md +0 -185
  559. package/docs/eval//344/274/230/345/214/226/347/254/254/344/270/200/346/211/271_/346/216/245/347/272/277/344/270/216/347/255/211/344/273/267/345/217/230/346/215/242_v1.0.md +0 -498
  560. package/docs/eval//344/274/230/345/214/226/347/254/254/344/270/211/346/211/271_/351/227/250/347/246/201/350/275/254/346/255/243/344/270/216/350/260/203/345/272/246/346/255/242/350/241/200/344/270/216/351/227/250/346/216/247/346/224/266/345/217/243_v1.0.md +0 -669
  561. package/docs/eval//344/274/230/345/214/226/347/254/254/344/272/214/346/211/271_/344/276/235/350/265/226/351/200/217/344/274/240/344/270/216/345/257/271/346/213/215/345/217/243/345/276/204/344/270/216/350/264/237/347/274/223/345/255/230_v1.0.md +0 -683
  562. package/docs/eval//345/207/272/350/264/247/351/235/242/345/206/222/347/203/237_/350/277/233/350/264/247/351/227/250/347/246/201_v1.0.md +0 -460
  563. package/docs/eval//345/217/221/345/270/20306_/344/270/200/351/224/256/351/205/215/347/275/256/344/270/216DSH0172_v1.0.md +0 -171
  564. package/docs/eval//345/217/221/345/270/20307_/345/244/226/351/203/250/346/212/245/345/221/212/345/233/233/346/211/271/344/277/256/345/244/215/344/270/216/346/217/222/344/273/266/351/235/242/345/212/240/345/233/272_v1.0.md +0 -209
  565. package/docs/eval//345/217/221/345/270/20308_/350/207/252/350/277/255/344/273/243/344/270/216/347/235/241/347/234/240_/345/233/276/346/243/200/347/264/242/350/267/257/344/270/216/346/235/203/351/207/215_v1.0.md +0 -97
  566. package/docs/eval//345/217/221/345/270/20309_/346/243/200/347/264/242/351/235/242/344/270/211/346/211/271/346/224/266/345/217/243_v1.0.md +0 -66
  567. package/docs/eval//345/217/221/345/270/20310_/350/257/273/351/235/242/346/215/237/345/235/217UTF8/345/256/266/346/227/217/346/224/266/345/217/243_v1.0.md +0 -71
  568. package/docs/eval//345/217/221/345/270/20311_/345/244/226/346/212/245/345/205/255/350/277/236/344/277/256/344/270/216/344/270/226/347/225/214/346/250/241/345/236/213/345/272/225/345/272/247_v1.0.md +0 -91
  569. package/docs/eval//345/217/221/345/270/20312_/344/270/226/347/225/214/346/250/241/345/236/213/345/212/237/350/203/275/347/253/257_v1.0.md +0 -108
  570. package/docs/eval//345/217/221/345/270/20313_/344/270/212/344/270/213/346/226/207/350/207/252/347/256/241/347/220/206/346/234/272/345/210/266_v1.0.md +0 -114
  571. package/docs/eval//345/217/221/345/270/20314_/350/272/253/344/275/223/303/227/350/204/221/347/273/204/345/220/210_v1.0.md +0 -160
  572. package/docs/eval//345/217/221/345/270/20315_/344/274/232/350/257/235/351/232/224/347/246/273/344/277/256/345/244/215/344/270/216/350/272/253/344/275/223/345/272/223/345/261/225/347/244/272_v1.0.md +0 -88
  573. package/docs/eval//345/256/236/351/252/214/346/226/271/346/241/210_/345/255/246/344/271/240/351/227/255/347/216/257AB/344/270/216/346/250/252/350/257/204_v1.0.md +0 -174
  574. package/docs/eval//345/275/222/344/270/200/345/261/202/347/274/272/347/234/201/347/277/273/345/205/263_/344/277/256/345/244/215/350/256/260/345/275/225_v1.0.md +0 -458
  575. package/docs/eval//346/200/247/350/203/275/344/270/223/351/241/271_/345/206/267/346/237/245/350/257/242/344/270/216/345/206/205/345/255/230_v1.0.md +0 -218
  576. package/docs/eval//346/225/205/351/232/234/346/263/250/345/205/245/345/256/236/346/265/213_v1.0.md +0 -432
  577. package/docs/eval//346/250/252/350/257/204_/345/205/255/345/256/266100/351/242/230/344/270/255/350/213/261/345/217/214/346/237/245_v1.0.md +0 -223
  578. package/docs/eval//347/224/250/346/210/267/350/243/201/345/206/263/345/244/204/347/275/256_/347/254/254/344/270/200/346/211/271_v1.0.md +0 -195
  579. package/docs/eval//347/224/250/346/210/267/350/243/201/345/206/263/345/244/204/347/275/256_/347/254/254/344/272/214/346/211/271B6_/346/234/254/346/234/272/350/267/257/345/276/204/347/233/270/345/257/271/345/214/226_v1.0.md +0 -78
  580. package/docs/eval//347/253/257/345/210/260/347/253/257LoCoMoQA/345/220/214/345/217/243/345/276/204/345/257/271/347/205/247_v1.0.md +0 -100
  581. package/docs/eval//347/253/257/345/210/260/347/253/257/345/271/262/346/211/260/346/261/240/350/257/204/346/265/213_/347/241/256/345/256/232/346/200/247/350/243/201/345/206/263vsLLM_judge_v1.1.md +0 -197
  582. package/docs/eval//347/254/2543/345/261/202stg/347/273/223/346/236/204/347/264/242/345/274/225_/345/256/236/346/226/275/350/256/260/345/275/225_v1.0.md +0 -250
  583. package/docs/eval//347/254/254/344/270/211/346/226/271/351/252/214/350/257/201/346/212/245/345/221/212_LoCoMo_/347/201/265/346/236/242_.png +0 -0
  584. package/docs/eval//347/254/254/344/270/211/346/226/271/351/252/214/350/257/201/346/212/245/345/221/212_/347/201/265/346/236/242_vs_dejavu_/347/273/237/344/270/200/350/257/204/345/210/206_v7.md +0 -202
  585. package/docs/eval//347/274/226/347/240/201/351/235/242/345/211/215/347/275/256_/345/205/245/345/217/243/350/207/252/344/277/235/350/257/201UTF8/344/270/216/346/226/207/346/234/254open/345/256/210/345/215/253_v1.0.md +0 -646
  586. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v1.md +0 -156
  587. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v10.md +0 -210
  588. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v11.md +0 -227
  589. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v12.md +0 -203
  590. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v13.md +0 -233
  591. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v14.md +0 -191
  592. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v15.md +0 -213
  593. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v16.md +0 -214
  594. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v17.md +0 -199
  595. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v18.md +0 -183
  596. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v19.md +0 -207
  597. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v2.md +0 -156
  598. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v20.md +0 -283
  599. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v21.md +0 -224
  600. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v22.md +0 -223
  601. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v23.md +0 -293
  602. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v24.md +0 -303
  603. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v25.md +0 -230
  604. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v26.md +0 -196
  605. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v27.md +0 -259
  606. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v28.md +0 -217
  607. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v29.md +0 -270
  608. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v3.md +0 -152
  609. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v30.md +0 -231
  610. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v31.md +0 -281
  611. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v4.md +0 -128
  612. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v5.md +0 -114
  613. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v6.md +0 -192
  614. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v7.md +0 -187
  615. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v8.md +0 -207
  616. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v9.md +0 -203
  617. package/docs/eval//350/257/255/344/271/211/346/227/266/347/251/272/345/233/276/350/241/245/345/205/250_P1_/346/212/275/345/217/226/345/231/250v4_/344/270/211/347/216/207/350/257/273/346/225/260_v1.0.md +0 -231
  618. package/docs/eval//351/262/270/345/250/230/344/270/203/347/261/273/347/212/266/346/200/201/350/277/275/350/270/252_v1.0.md +0 -176
  619. package/docs/hive//344/270/273/344/273/243/347/220/206/345/255/220/344/273/243/347/220/206/350/256/260/345/277/206/346/236/266/346/236/204/350/256/276/350/256/241.md +0 -385
  620. package/docs/hive//344/273/244/347/211/214/344/270/216/350/247/222/350/211/262/346/235/203/350/201/214/345/210/206/347/246/273_v0.1.md +0 -165
  621. package/docs/hive//344/273/244/347/211/214/350/257/255/344/271/211/344/277/256/346/255/243_/344/273/262/350/243/201/344/275/215_v0.1.md +0 -76
  622. package/docs/hive//345/244/232/347/253/257harness/351/200/232/344/277/241/345/245/221/347/272/246_v0.1.md +0 -42
  623. package/docs/hive//345/255/220/344/273/243/347/220/206/351/205/215/347/275/256/346/240/207/345/207/206_v0.5.md +0 -236
  624. package/docs/hive//345/256/211/345/205/250/345/256/241/350/256/241/345/256/236/351/224/232_v0.1.md +0 -202
  625. package/docs/hive//346/243/200/347/264/242/346/224/266/346/225/233/345/256/236/346/265/213/344/270/216S1b/350/256/276/350/256/241_v0.1.md +0 -43
  626. package/docs/hive//346/243/200/347/264/242/347/256/227/346/263/225/345/217/243/345/276/204/345/257/271/347/205/247_v0.1.md +0 -210
  627. package/docs/hive//346/243/200/347/264/242/350/267/257/345/276/204/344/270/216/350/256/244/347/237/245/347/273/223/346/236/204/345/245/221/347/272/246_v0.1.md +0 -152
  628. package/docs/hive//350/234/202/345/267/242M6_ingest/345/256/236/346/226/275/350/256/241/345/210/222_v0.1.md +0 -47
  629. package/docs/hive//350/234/202/345/267/242/345/217/214/345/256/236/344/276/213/344/272/222/351/252/214_/350/256/276/350/256/241/345/256/232/347/250/277.md +0 -519
  630. package/docs/hive//350/234/202/345/267/242/345/267/245/344/275/234/350/256/260/345/277/206_/351/241/271/347/233/256/350/256/241/345/210/222.md +0 -85
  631. package/docs/hive//350/234/202/345/267/242/350/256/276/350/256/241_/347/220/206/350/256/272/345/257/271/351/275/220_v0.1.md +0 -191
  632. package/docs/hive//350/234/202/345/267/242/350/277/255/344/273/243_/345/256/217/350/247/202/344/270/216/347/276/244/344/275/223/350/260/203/345/272/246_v0.1.md +0 -90
  633. package/docs/images/lingshu-moonlight-covenant-poster-preview.jpg +0 -0
  634. package/docs/images/lingshu-moonlight-covenant-poster.png +0 -0
  635. package/docs/mdcg/D_meta_/345/267/245/347/250/213/345/214/226/346/226/271/346/241/210_v0.2.md +0 -216
  636. package/docs/mdcg/README/350/257/246/347/273/206/347/211/210_v0.4.10.md +0 -746
  637. package/docs/mdcg/guardrail-charter.md +0 -164
  638. package/docs/mdcg/lingshu_tutorial.html +0 -14956
  639. package/docs/mdcg/memory-assessment.html +0 -923
  640. package/docs/mdcg/memory_score.html +0 -213
  641. package/docs/mdcg/memory_score.png +0 -0
  642. package/docs/mdcg/release_v0.3.0.md +0 -36
  643. package/docs/mdcg/release_v0.4.11.md +0 -49
  644. package/docs/mdcg/release_v0.4.5.md +0 -55
  645. package/docs/mdcg/tool_table_v0.3.0.md +0 -117
  646. package/docs/mdcg//344/270/226/347/225/214/346/250/241/345/236/213/345/212/237/350/203/275/347/253/257_/344/275/277/347/224/250/344/270/216/350/277/220/347/273/264_v1.0.md +0 -384
  647. package/docs/mdcg//344/273/243/347/240/201/350/257/204/345/256/241/344/270/216/346/235/241/344/273/266/345/214/226/346/263/250/351/207/212_/345/245/221/347/272/246_v0.1.md +0 -82
  648. package/docs/mdcg//345/205/250/345/272/223/344/273/243/347/240/201/350/257/204/345/256/241/344/270/216/346/235/241/344/273/266/345/214/226/346/263/250/351/207/212_/350/256/241/345/210/222_v0.1.md +0 -600
  649. package/docs/mdcg//345/212/237/350/203/275/350/260/203/347/224/250/346/230/240/345/260/204/350/241/250_v0.1.md +0 -266
  650. package/docs/mdcg//345/215/225/345/205/203/350/207/252/346/210/221/351/224/232/347/202/271_/347/263/273/347/273/237/346/217/220/347/244/272/350/257/215/346/240/207/345/207/206_v0.3.md +0 -275
  651. package/docs/mdcg//345/217/221/345/270/203/351/227/250/347/246/201/351/223/276_v0.1.md +0 -134
  652. package/docs/mdcg//346/272/220/347/240/201/347/272/247/346/236/266/346/236/204/345/256/241/350/256/241_GPT/346/211/271/350/257/204/345/257/271/347/205/247_v1.0.md +0 -130
  653. package/docs/mdcg//347/201/265/346/236/24282/345/267/245/345/205/267_/345/212/237/350/203/275/346/225/264/347/220/206/344/270/216/350/277/201/347/247/273/346/230/240/345/260/204_v0.1.md +0 -278
  654. package/docs/mdcg//347/201/265/346/236/242MCP/345/267/245/345/205/267/346/200/273/350/241/250_v3.4.md +0 -164
  655. package/docs/mdcg//347/201/265/346/236/242_/350/207/252/346/210/221/345/261/202/345/256/232/344/271/211.md +0 -43
  656. package/docs/mdcg//347/201/265/346/236/242/344/270/211/345/261/202/346/213/206/345/210/206/350/247/204/345/210/222_v0.1.md +0 -181
  657. package/docs/mdcg//347/201/265/346/236/242/350/256/260/345/277/206/345/212/250/350/257/215/345/215/217/350/256/256_v1.0-draft.md +0 -177
  658. package/docs/mdcg//347/216/257/344/272/214_/347/231/275/347/256/261/345/241/253/345/205/205/346/265/201/346/260/264/347/272/277_v0.1.md +0 -31
  659. package/docs/mdcg//347/235/241/347/234/240/345/221/250/346/234/237_/350/277/220/347/273/264/345/211/215/346/217/220/344/270/216/347/273/264/346/212/244/346/214/207/345/215/227_v1.0.md +0 -337
  660. package/docs/mdcg//347/274/272/345/217/243/345/215/225_P0/346/224/266/345/217/243_v0.1.md +0 -270
  661. package/docs/mdcg//350/256/244/347/237/245/345/233/276_G4-G8/347/274/272/345/217/243/350/243/201/345/256/232/345/215/225_v0.1.md +0 -491
  662. package/docs/mdcg//350/256/244/347/237/245/345/233/276_MD/347/233/256/345/275/225/346/226/271/346/241/210_v0.1.md +0 -552
  663. package/docs/mdcg//350/256/244/347/237/245/345/233/276_/346/235/241/344/273/266/347/251/272/351/227/264/345/220/210/346/210/220/344/270/216/347/224/237/346/225/210/346/235/241/344/273/266/345/217/243/345/276/204_v0.1.md +0 -340
  664. package/docs/mdcg//350/256/244/347/237/245/345/233/276_/347/264/242/345/274/225/344/270/216/345/267/245/347/250/213/350/247/204/350/214/203/345/214/226_/350/256/241/345/210/222_v0.1.md +0 -624
  665. package/docs/mdcg//350/256/244/347/237/245/345/233/276/344/275/234/344/270/272/350/256/260/345/277/206/346/223/215/344/275/234/347/263/273/347/273/237_/350/257/204/344/274/260/344/270/216/350/267/257/347/272/277_v0.1.md +0 -94
  666. package/docs/mdcg//350/256/260/345/277/206/346/223/215/344/275/234/347/263/273/347/273/237_MdCGOS/344/270/216MCP/346/216/245/345/205/245_v0.1.md +0 -281
  667. package/docs/mdcg//350/267/250/347/253/257/351/252/214/350/257/201/344/270/216/345/220/214/346/255/245/345/215/217/350/256/256_v0.1.md +0 -93
  668. package/docs/plans/GridWorld/346/234/200/345/260/217/351/227/255/347/216/257/350/247/204/346/240/274_v0.1.md +0 -176
  669. package/docs/plans/stg/346/235/241/344/273/266/345/214/226/344/270/216/347/273/223/346/236/204/347/264/242/345/274/225_/350/256/276/350/256/241_v0.1.md +0 -124
  670. package/docs/plans//345/205/250/344/270/255/346/226/207/347/274/226/347/240/201/344/270/216/350/234/202/345/267/242/344/273/273/345/212/241/346/240/207/350/257/206/345/245/221/347/272/246_v2.0.md +0 -220
  671. package/docs/plans//345/221/275/345/220/215/346/262/273/347/220/206_/351/241/271/347/233/256/350/256/241/345/210/222.md +0 -81
  672. package/docs/plans//345/244/232/344/270/273/344/275/223/344/270/226/347/225/214/346/250/241/345/236/213_/345/257/271/351/275/220/350/257/204/344/274/260/344/270/216/350/220/275/345/234/260/350/256/276/350/256/241_v0.1.md +0 -141
  673. package/docs/plans//347/201/265/346/236/242/350/272/253/344/275/223/303/227/350/204/221_/344/270/226/347/225/214/346/250/241/345/236/213/345/257/271/346/216/245/350/256/276/350/256/241_v0.1.md +0 -119
  674. package/docs/plans//347/234/237/346/272/220/347/264/242/345/274/225_/351/200/232/347/224/250/346/234/272/345/210/266_v0.3.md +0 -227
  675. package/docs/plans//347/235/241/347/234/240/344/270/216/350/207/252/350/277/255/344/273/243_/345/212/237/350/203/275/344/274/230/345/214/226/350/256/276/350/256/241_v0.4.md +0 -547
  676. package/docs/plans//347/237/245/350/257/206/345/233/276/350/260/261/351/241/271/347/233/256_/344/272/244/346/216/245/346/226/207/346/241/243_20260914.md +0 -308
  677. package/docs/plans//350/234/202/345/267/242/346/250/241/345/236/213/345/257/206/351/222/245/351/205/215/347/275/256/351/235/242_v1.0.md +0 -385
  678. package/docs/plans//350/256/260/345/277/206/350/207/252/345/244/204/347/220/206/344/270/211/346/241/243/350/207/252/346/262/273_/350/256/276/350/256/241_v0.2.md +0 -207
  679. package/docs/plans//350/257/255/344/271/211/346/227/266/347/251/272/345/233/276/350/241/245/345/205/250_/344/270/226/347/225/214/346/250/241/345/236/213/345/212/237/350/203/275/347/253/257_/350/256/276/350/256/241_v0.1.md +0 -107
  680. package/docs/promo/bilibili-cover.jpg +0 -0
  681. package/docs/promo/promo-visual-1.png +0 -0
  682. package/docs/promo/promo-visual-2.png +0 -0
  683. package/docs/promo/promo-visual-3.png +0 -0
  684. package/docs/promo/promo-visual-4.png +0 -0
  685. package/docs/promo/promo-visual-5.png +0 -0
  686. package/docs/swarm//350/234/202/347/276/244/344/272/222/350/201/224_v0.1.md +0 -704
  687. package/docs/swarm//350/234/202/347/276/244/345/220/214/351/224/231/346/243/200/346/265/213/345/256/236/351/252/214/345/215/217/350/256/256_v0.1.md +0 -242
  688. package/docs/swarm//350/234/202/347/276/244/345/244/232/346/231/272/350/203/275/344/275/223_/344/275/277/347/224/250/346/212/245/345/221/212_20260913.md +0 -68
  689. package/docs/swarm//350/234/202/347/276/244/345/244/232/346/231/272/350/203/275/344/275/223_/345/212/237/350/203/275/350/257/264/346/230/216_v0.6.md +0 -130
  690. package/docs/swarm//350/234/202/347/276/244/347/233/262/345/214/272/346/240/207/350/256/260_v1.0.md +0 -89
  691. package/docs/theory//344/270/215/345/217/257/351/235/240/345/256/232/347/220/206/344/270/216/345/244/261/346/225/210/344/274/230/345/205/210/346/241/206/346/236/266_v0.3.md +0 -365
  692. package/docs/theory//344/277/241/346/201/257/345/267/256/344/270/272/344/273/200/344/271/210/345/277/205/347/204/266/345/255/230/345/234/250/344/270/224/350/207/252/347/204/266/346/211/251/345/244/247.md +0 -239
  693. package/docs/theory//345/215/225/347/272/277/347/250/213/344/270/216/346/263/250/346/204/217/345/212/233/351/233/206/344/270/255_/346/227/240/344/272/211/350/256/256/347/220/206/350/256/272/346/226/207/346/241/243_v1.0.md +0 -129
  694. package/docs/theory//345/271/266/345/217/221/345/277/205/347/204/266/346/200/247/347/220/206/350/256/272_v0.2.md +0 -134
  695. package/docs/theory//346/231/272/350/203/275/347/232/204/345/205/254/347/220/206/345/214/226/345/237/272/347/237/263.md +0 -789
  696. package/docs/theory//346/231/272/350/203/275/347/232/204/350/256/244/347/237/245/350/277/207/347/250/213.md +0 -379
  697. package/docs/theory//346/231/272/350/203/275/350/256/2723.4.md +0 -5260
  698. package/docs/theory//346/246/202/345/277/265/345/210/206/345/261/202/345/257/271/351/275/220/350/241/250_v0.1.md +0 -145
  699. package/docs/theory//347/220/206/350/256/272_/346/234/272/345/210/266_/344/273/243/347/240/201_/345/256/236/351/252/214_/347/274/272/345/217/243/347/237/251/351/230/265_v0.1.md +0 -144
  700. package/docs/theory//347/220/206/350/256/272/344/273/223/346/213/206/345/210/206/344/270/216/347/231/275/347/256/261/347/237/245/350/257/206/345/272/223/345/206/205/350/277/201_v0.1.md +0 -198
  701. package/docs/theory//347/231/275/347/256/261/346/231/272/350/203/275/346/230/257/344/273/200/344/271/210/357/274/237.md +0 -812
  702. package/docs/theory//347/231/275/347/256/261/346/231/272/350/203/275/347/263/273/345/210/227/302/267/347/254/254/344/272/224/347/257/207/357/274/232/350/256/251AI/347/234/237/346/255/243/350/243/205/344/270/212/350/256/260/345/277/206.md +0 -421
  703. package/docs/theory//350/256/244/347/237/245/344/273/243/347/220/206/344/270/216/346/224/266/346/225/233/347/273/223/346/236/204_/346/235/241/344/273/266/350/256/272/351/207/215/346/236/204_v0.1.md +0 -221
  704. package/docs/world_model//344/270/226/347/225/214/346/250/241/345/236/213_/347/245/236/347/273/217/347/275/221/347/273/234/345/272/225/345/261/202/346/236/266/346/236/204_v1.0.md +0 -237
  705. package/docs//344/270/215/345/217/257/351/235/240/346/200/247/347/220/206/350/256/272_v0.1.md +0 -343
  706. package/docs//345/217/221/345/270/203/344/273/266/345/233/236/346/272/257/350/257/264/346/230/216_v0.1.md +0 -82
  707. package/docs//345/255/230/347/256/227/344/270/200/344/275/223/346/236/266/346/236/204/345/255/246/344/271/240_/345/244/226/351/203/250/347/220/206/350/256/272/345/257/271/347/205/247/344/270/216/350/267/257/347/272/277/344/272/244/346/216/245_20260916.md +0 -98
  708. package/docs//345/255/230/347/256/227/344/270/200/344/275/223/347/245/236/347/273/217/347/275/221/347/273/234/346/236/266/346/236/204_/346/200/273/347/272/262/344/270/216/344/272/244/346/216/245_20260916.md +0 -109
  709. package/docs//347/201/265/346/236/242/350/207/252/346/210/221/346/224/271/350/277/233/345/267/245/344/275/234/350/256/241/345/210/222_/345/244/226/351/203/250/347/240/224/347/251/266/347/263/273/345/210/227/345/220/270/346/224/266_v1_20260919.md +0 -286
  710. package/docs//347/231/275/347/256/261/345/214/226/347/272/262/351/242/206_/344/270/211/351/241/271/347/233/256/345/255/246/344/271/240/346/200/273/346/236/266/346/236/204/344/270/216Ghidra/344/272/244/346/216/245_20260916.md +0 -104
  711. package/docs//347/247/244_/350/256/260/345/277/206/347/263/273/347/273/237/350/257/204/346/265/213/350/247/204/350/214/203_v2.1.md +0 -225
  712. package/docs//350/256/260/345/277/206/347/263/273/347/273/237/345/215/263/347/231/275/347/256/261/345/214/226/346/231/272/350/203/275_/346/236/266/346/236/204/345/257/271/347/205/247_v0.2.md +0 -121
  713. package/docs//350/256/260/345/277/206/347/263/273/347/273/237/345/215/263/347/231/275/347/256/261/345/214/226/346/231/272/350/203/275_/346/236/266/346/236/204/345/257/271/347/205/247_v0.3.md +0 -117
  714. package/docs//350/256/260/345/277/206/350/257/204/345/256/241/347/263/273/347/273/237_/347/253/213/351/241/271/350/256/276/350/256/241/344/270/216/346/226/275/345/267/245/344/272/244/346/216/245_20260915.md +0 -183
@@ -1,1029 +1,1053 @@
1
- # -*- coding: utf-8 -*-
2
- """md_cg · 自我状态层(SELF STATE):薄自我 + 富索引
3
-
4
- 理论约束(本仓已有文档,非外部发明):
5
- · `docs/mdcg/灵枢_自我层定义.md:6`
6
- SELF 层 = 身份 + 价值观 + 图接口,**不可遗忘**、跨会话自动加载。
7
- 自我层是**薄的**——它不该变成事件仓库。
8
- · 智能论 §十一:情绪 = 信息差二阶 d^2D/dt^2;§十:P_gap / P_trust;
9
- 情感 = 信任二阶 d^2T/dt^2。
10
-
11
- 由此定下本模块的形态:
12
-
13
- self 层只放两类一等公民(都很薄):
14
- 1. 自我状态卡(单例)——九项自我信息的**当前值 + 指针**
15
- 2. 关系节点(有向)——自我与其他智能的关系
16
- 具体细节(哪次会话 / 哪个任务 / 哪个人 / 哪个时间窗 / 哪条证据)
17
- 仍然留在原本的层里,由**认知图的标签与边**连接、索引过来。
18
-
19
- 九项自我信息 → 薄卡字段 / 富索引指向:
20
-
21
- ┌ 信息差 D d_current / d1 / d2 / emotion ← _reflection.jsonl(reflect 留痕)
22
- ├ 信任 P p_gap / p_trust / d2t / affect ← 各节点 evidence_log(verify 留痕)
23
- ├ 情绪 emotion(= d^2D/dt^2)
24
- ├ 情感 affect(= d^2T/dt^2)
25
- ├ 短期记忆 recent{n, span, roles, ptr} ← _recent.jsonl(只存摘要 + 指针)
26
- ├ 重要性 importance_self / important_refs ← 各节点 frontmatter.importance
27
- ├ 身份 identity_ref ← self 层 identity 锚点
28
- ├ 关系 relations{out,in} ← self_relation_* 关系节点
29
- └ 预测校准 hit_rate / threshold / reflect / ece ← _prediction.jsonl + evidence_log
30
-
31
- 第九项(预测校准)是「SELF = 自我描述」走向「SELF = 关于自身的预测模型」的最小一步:
32
- 它回答**我预测得准吗、该不该反思**,数据只来自 predict 的 feedback 留痕与
33
- metacognition 的 ECE 校准,样本不足一律 unknown——不新增计算,也不编造。
34
-
35
- 五个索引维度(「具体任务 / 人物关系 / 会话 / 时间 / 信任」)用 tag 命名空间落地,
36
- `index(cg, dim, value)` 从全图反查;状态卡只登记维度标签、不搬运内容:
37
-
38
- task:<slug> 具体任务
39
- person:<slug> 具体人物关系
40
- session:<id> 具体会话
41
- time:<bucket> 具体时间(YYYY-MM-DD)
42
- trust:<band> 具体信任档(low | mid | high)
43
-
44
- 一致性(`audit` 的每条判定都可重算,不依赖人的判断):
45
-
46
- 单例 同一 subject 至多一个状态卡
47
- 版本链 state_version 连续 +1;prev_state_hash 必须等于上一条留痕的 hash
48
- 时序单调 留痕时间戳不得回退
49
- 留痕对齐 卡上的 state_hash 必须等于留痕末条
50
- 派生自洽 d2/d2t 缺失时 emotion/affect 必须是 unknown(不许编造)
51
- 跨面一致 卡值与 metacognition 现算值偏差 ≤ DRIFT_TOL
52
- 身份唯一 identity_ref 必须指向存在的身份锚点
53
- 关系完整 关系两端必须存在;禁止自环
54
- 保护一致 状态卡必须「可覆盖」(否则自我认知被永久冻结)且「不可遗忘」
55
- 索引不悬空 维度标签指向的详情节点必须存在
56
-
57
- 「不可遗忘 ≠ 不可覆盖」的延伸:
58
- · 身份锚点:既不可遗忘,也不可覆盖(protect 层保护);
59
- · 自我状态卡:**不可遗忘,但必须可覆盖**——自我状态本来就要演化。
60
- 靠 `frontmatter.self_state is True` 在 protect 里获得覆盖豁免,见 protect.py。
61
- """
62
- import hashlib
63
- import json
64
- import os
65
- import re
66
- import time
67
-
68
- from . import identity, metacognition
69
- from .fsutil import append_jsonl, read_jsonl
70
-
71
- DEFAULT_SUBJECT = "self:lingshu"
72
- STATE_PREFIX = "self_state_"
73
- RELATION_PREFIX = "self_relation_"
74
- LOG_FILE = "_self_state.jsonl"
75
- TAG_STATE = "self_state"
76
- TAG_RELATION = "self_relation"
77
- SCHEMA_VERSION = 1
78
-
79
- # 跨面一致容差:卡里的 D/T 与 metacognition 现算值允许的最大偏差
80
- DRIFT_TOL = 0.05
81
- # 新鲜度:状态卡超过该秒数未刷新即视为 stale
82
- STALE_AFTER = 24 * 3600.0
83
- RECENT_WINDOW = 20
84
-
85
- # 五维索引(具体任务 / 人物关系 / 会话 / 时间 / 信任)
86
- DIMENSIONS = ("task", "person", "session", "time", "trust")
87
- TRUST_BANDS = ((0.70, "high"), (0.40, "mid"), (0.00, "low"))
88
- RELATION_TYPES = ("collaborator", "user", "peer", "mentor", "student",
89
- "adversary", "tool", "other")
90
- STATE_LINK_TYPE = "refers_to"
91
-
92
-
93
- # ---------------------------------------------------------------- 基础工具
94
-
95
- # 生效条件:对 required 形参 text,返回 str(text or "") 经正则把非中英文数字连续段折叠为下划线、strip('_') 并 lower 后的字符串(text 为假值时返回空串);
96
- def _slug(text):
97
- """归一化 id 片段:保留中英文数字,其余折叠为下划线。"""
98
- s = re.sub(r"[^0-9A-Za-z\u4e00-\u9fff]+", "_", str(text or ""))
99
- return s.strip("_").lower()
100
-
101
-
102
- # 生效条件:对 required 形参 ts,当 float(ts) 可转换且 time.localtime 不抛 OSError 时返回本地时间 "%Y-%m-%d %H:%M:%S" 格式串;当 float(ts) 抛 TypeError/ValueError 或 time.localtime 抛 OSError 时返回空串;
103
- def _iso(ts):
104
- try:
105
- return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(ts)))
106
- except (TypeError, ValueError, OSError):
107
- return ""
108
-
109
-
110
- # 生效条件:subject 未传时取模块常量 DEFAULT_SUBJECT,返回模块常量 STATE_PREFIX 拼接 _slug(subject) 的结果;
111
- def state_node_id(subject=DEFAULT_SUBJECT):
112
- """状态卡节点 id(单例:同一 subject 只有一个)。"""
113
- return STATE_PREFIX + _slug(subject)
114
-
115
-
116
- # 生效条件:对 required 形参 frm 与 to,返回模块常量 RELATION_PREFIX 拼接 _slug(frm)、"__"、_slug(to) 的字符串;
117
- def relation_node_id(frm, to):
118
- """关系节点 id(有向)。"""
119
- return f"{RELATION_PREFIX}{_slug(frm)}__{_slug(to)}"
120
-
121
-
122
- # 生效条件:对 required 形参 cg,返回 os.path.join(cg.root, LOG_FILE)(LOG_FILE 为模块常量);
123
- def log_path(cg):
124
- return os.path.join(cg.root, LOG_FILE)
125
-
126
-
127
- # 生效条件:对 required 形参 dim 与 value,返回 f"{dim}:{_slug(value)}";
128
- def dim_tag(dim, value):
129
- return f"{dim}:{_slug(value)}"
130
-
131
-
132
- # 生效条件:对 required 形参 p_trust,若 p_trust is None 或 float(p_trust) 抛 TypeError/ValueError 则返回 None;否则按模块常量 TRUST_BANDS 顺序取首个 v >= lo 的档名,均不满足返回 "low";
133
- def trust_band(p_trust):
134
- """把 P_trust 映射到信任档(索引维度之一)。"""
135
- if p_trust is None:
136
- return None
137
- try:
138
- v = float(p_trust)
139
- except (TypeError, ValueError):
140
- return None
141
- for lo, name in TRUST_BANDS:
142
- if v >= lo:
143
- return name
144
- return "low"
145
-
146
-
147
- # ---------------------------------------------------------------- 留痕
148
-
149
- # 生效条件:对 required 形参 cg 与 rec,调用 append_jsonl(log_path(cg), rec);若抛出 OSError 则静默忽略,无返回值;
150
- def _append_log(cg, rec):
151
- try:
152
- append_jsonl(log_path(cg), rec)
153
- except OSError:
154
- pass
155
-
156
-
157
- # 生效条件:对 required 形参 cg 与可选 limit/subject,读取 log_path(cg) 留痕(OSError 时为空列表);subject 为真值时只保留 r.get("subject") == subject 的记录;倒序后,limit 为真值时返回 recs[:int(limit)],limit 为假值(如 0)时返回全部倒序记录;
158
- def history(cg, limit=100, subject=None):
159
- """自我状态留痕(倒序)。"""
160
- try:
161
- recs = list(read_jsonl(log_path(cg)))
162
- except OSError:
163
- recs = []
164
- if subject:
165
- recs = [r for r in recs if r.get("subject") == subject]
166
- recs.reverse()
167
- return recs[:int(limit)] if limit else recs
168
-
169
-
170
- # 生效条件:对 required 形参 cg 与可选 subject,调用 history(cg, limit=0, subject=subject) 取全部倒序留痕;有记录时返回 recs[0](最新一条),否则返回 None;
171
- def _last_log(cg, subject=None):
172
- recs = history(cg, limit=0, subject=subject)
173
- return recs[0] if recs else None
174
-
175
-
176
- # ---------------------------------------------------------------- 读卡
177
-
178
- # 生效条件:对 required 形参 cg 与 node_id,尝试返回 cg.get(node_id);若 cg.get 抛任何异常则返回 None;
179
- def _node(cg, node_id):
180
- try:
181
- return cg.get(node_id)
182
- except Exception:
183
- return None
184
-
185
-
186
- # 生效条件:对 required 形参 cg 与 node_id,取 _node(cg, node_id) 结果(假值时用空字典)的 "frontmatter" 值;该值假值时返回空字典,否则返回该 frontmatter;
187
- def _fm_of(cg, node_id):
188
- node = _node(cg, node_id)
189
- return (node or {}).get("frontmatter") or {}
190
-
191
-
192
- # 生效条件:对 required 形参 cg 与 node_id,从 cg.index(getattr 取不到或假值时用空字典)的 "nodes" 字段(假值时用空字典)中取 node_id 对应条目;缺键返回 None;
193
- def _entry(cg, node_id):
194
- return ((getattr(cg, "index", None) or {}).get("nodes") or {}).get(node_id)
195
-
196
-
197
- # 生效条件:对 required 形参 cg 与 subject(未传时 DEFAULT_SUBJECT),若 state_node_id(subject) 在 cg.index.nodes 中不存在,或该节点没有非空 frontmatter,返回 None;否则返回由该 frontmatter 扁平化出的 dict,其中 subject 为 fm.get("state_subject") or subject,d_current/p_trust 分别从 information_gap/trust 子字典取;
198
- def snapshot(cg, subject=DEFAULT_SUBJECT):
199
- """读当前状态卡 → 扁平 dict(不存在返回 None)。只读,不写盘。"""
200
- nid = state_node_id(subject)
201
- if _entry(cg, nid) is None:
202
- return None
203
- fm = _fm_of(cg, nid)
204
- if not fm:
205
- return None
206
- out = {"node_id": nid, "subject": fm.get("state_subject") or subject,
207
- "layer": "self", "state_version": fm.get("state_version"),
208
- "state_hash": fm.get("state_hash"),
209
- "prev_state_hash": fm.get("prev_state_hash"),
210
- "state_ts": fm.get("state_ts"),
211
- "updated_at": _iso(fm.get("state_ts"))}
212
- for key in ("information_gap", "trust", "short_term", "relations",
213
- "prediction", "dimensions", "emotion", "affect",
214
- "importance_self", "important_refs", "identity_ref",
215
- "state_links"):
216
- out[key] = fm.get(key)
217
- out["d_current"] = (fm.get("information_gap") or {}).get("d_current")
218
- out["p_trust"] = (fm.get("trust") or {}).get("p_trust")
219
- return out
220
-
221
-
222
- # 生效条件:对 required 形参 state,返回对指定核心字段(subject、information_gap、trust、emotion、affect、importance_self、important_refs、identity_ref、short_term、relations、prediction、dimensions、state_links)做 sort_keys=True、ensure_ascii=False、default=str 的 JSON 序列化后 SHA-256 前 16 位十六进制(不含 state_version);
223
- def _fingerprint(state):
224
- """状态指纹:只对「会漂移的实质字段」取哈希,用于幂等刷新与版本链。
225
-
226
- 注意:**不含 state_version**——版本号是元数据,若纳入指纹则每次刷新
227
- 指纹必变,幂等判断失效(自我状态会在无信息变化时无限刷版本)。
228
- """
229
- core = {
230
- "subject": state.get("subject"),
231
- "information_gap": state.get("information_gap"),
232
- "trust": state.get("trust"),
233
- "emotion": state.get("emotion"),
234
- "affect": state.get("affect"),
235
- "importance_self": state.get("importance_self"),
236
- "important_refs": state.get("important_refs"),
237
- "identity_ref": state.get("identity_ref"),
238
- "short_term": state.get("short_term"),
239
- "relations": state.get("relations"),
240
- "prediction": state.get("prediction"),
241
- "dimensions": state.get("dimensions"),
242
- "state_links": state.get("state_links"),
243
- }
244
- blob = json.dumps(core, sort_keys=True, ensure_ascii=False, default=str)
245
- return hashlib.sha256(blob.encode("utf-8")).hexdigest()[:16]
246
-
247
-
248
- # ---------------------------------------------------------------- 聚合(九项)
249
-
250
- # 生效条件:对 required 形参 cg,返回近 int(window)(缺省 20)条反思留痕里 d_meta.unmodeled_growth 的均值(仅收数值型、bool 不计),无可用留痕时回落 d_meta.pressure(d_meta.compute(cg)),d_meta 不可用或抛异常时返回 None;
251
- def _d_meta_trend(cg, window: int = 20):
252
- """近 window 条反思留痕的 D_meta 边界压力均值(确定性函数,纯读)。
253
-
254
- 口径(智能论3.4 §2.7.0 DEV-002a):只聚合已落盘的
255
- `d_meta.unmodeled_growth`——**不合成三代理**、不参与 D_task。
256
- 留痕无该字段(旧记录/总闸关闭)时回落当前 `d_meta.compute` 的**单一
257
- 代理**值;两者皆不可用 → None(未知即未知,不编造)。
258
- """
259
- try:
260
- from . import d_meta as _d_meta
261
- vals = []
262
- for r in metacognition._reflections(cg)[-int(window):]:
263
- v = (r.get("d_meta") or {}).get("unmodeled_growth")
264
- if isinstance(v, (int, float)) and not isinstance(v, bool):
265
- vals.append(float(v))
266
- if vals:
267
- return round(sum(vals) / len(vals), 4)
268
- return _d_meta.pressure(_d_meta.compute(cg))
269
- except Exception: # noqa: BLE001
270
- return None
271
-
272
-
273
- # 生效条件:对 required 形参 cg,返回预测校准 dict;samples==0 时 ok=False、hit_rate=None 且 note 提示无预测留痕;samples>0 且 th.get("reflect") 为真时 note 建议反思,否则 note 正常;ece 与 calibration 仅在 metacognition.calibration 返回 ok 为真时给出,否则为 None;d_meta_trend 恒由 _d_meta_trend(cg) 给出(近 20 条反思的 D_meta 单代理均值,不可用时为 None);
274
- def _prediction_face(cg):
275
- """预测校准(第九项):我预测得准吗、该不该反思?
276
-
277
- 数据源(只读留痕,不新增计算负担):
278
- · `predict._hit_history` / `predict.dynamic_hit_threshold`
279
- ← `_prediction.jsonl`(predict_feedback 留痕)
280
- · `metacognition.calibration` ← evidence_log(verify 留痕)的 ECE
281
- · `d_meta.compute` / 反思留痕的 `d_meta` ← 边界压力趋势(d_meta_trend,
282
- **不合成三代理**、不参与 D_task:D_task 与 D_meta 对象不同)
283
-
284
- 诚实边界:无预测留痕 → ok=False、hit_rate=None(未知即未知);
285
- ECE 仅在 metacognition 有足够证据时给出,否则 None。绝不编造。
286
- """
287
- try:
288
- from . import predict as _predict
289
- hist = list(_predict._hit_history(cg))
290
- th = _predict.dynamic_hit_threshold(cg)
291
- # P-T-73/74 通道贝叶斯:可信度后验(随样本量向基线收缩,诚实小样本)
292
- beta = (_predict.channel_posterior(cg) or {}).get("all") or {}
293
- except Exception: # noqa: BLE001
294
- hist, th, beta = [], {}, {}
295
- samples = len(hist)
296
- hit_rate = (sum(1 for x in hist if x) / samples) if samples else None
297
- try:
298
- cal = metacognition.calibration(cg)
299
- except Exception: # noqa: BLE001
300
- cal = {}
301
- meta_trend = _d_meta_trend(cg)
302
- if samples == 0:
303
- note = "无预测留痕:先 predict_feedback() 积累命中记录"
304
- elif th.get("reflect"):
305
- note = "命中率低于动态阈值:建议反思(D-006)"
306
- else:
307
- note = "命中率正常"
308
- return {
309
- "ok": samples > 0,
310
- "samples": samples,
311
- "hit_rate": None if hit_rate is None else round(hit_rate, 4),
312
- "beta_mean": beta.get("mean"),
313
- "beta_ci95": beta.get("ci95"),
314
- "threshold": th.get("threshold"),
315
- "reflect": bool(th.get("reflect")),
316
- "ece": cal.get("ece") if cal.get("ok") else None,
317
- "calibration": cal.get("verdict") if cal.get("ok") else None,
318
- "d_meta_trend": meta_trend,
319
- "note": note,
320
- }
321
-
322
-
323
- # 生效条件:对 required 形参 cg 与 window,尝试用 cg.recent_events(limit=int(window), newest_first=False) 取记录(异常时 recs=[]),返回 n=len(recs)、span=[min(ts), max(ts)] if ts else None、roles 角色计数、ptr 为 cg.recent_log 的 basename(缺省 "_recent.jsonl");
324
- def _recent_summary(cg, window):
325
- """短期记忆:只做窗口摘要,原文仍留在 _recent.jsonl(薄自我的关键取舍)。"""
326
- try:
327
- recs = cg.recent_events(limit=int(window), newest_first=False)
328
- except Exception:
329
- recs = []
330
- ts = [float(r.get("t") or 0.0) for r in recs]
331
- roles = {}
332
- for r in recs:
333
- k = str(r.get("role") or "unknown")
334
- roles[k] = roles.get(k, 0) + 1
335
- return {"n": len(recs), "span": [min(ts), max(ts)] if ts else None,
336
- "roles": roles,
337
- "ptr": os.path.basename(getattr(cg, "recent_log", "_recent.jsonl"))}
338
-
339
-
340
- # 生效条件:对 required 形参 cg 与 subject,若 identity.profile(cg, subject) 抛异常则返回 (None, 0);否则返回 (prof.anchor.node_id(缺省 None), len(prof.get("anchors") or []));
341
- def _identity_ref(cg, subject):
342
- """身份:只存指针(锚点节点 id),锚点内容仍在 self 层原节点里。"""
343
- try:
344
- prof = identity.profile(cg, subject)
345
- except Exception:
346
- return None, 0
347
- anchors = prof.get("anchors") or []
348
- ref = (prof.get("anchor") or {}).get("node_id")
349
- return ref, len(anchors)
350
-
351
-
352
- # 生效条件:对 required 形参 cg 与 subject,遍历 cg.index.nodes 中标签含 TAG_RELATION 或以 RELATION_PREFIX 开头的节点,统计 tags 含 "rel_from:{_slug(subject)}" 的个数为 out、含 "rel_to:{_slug(subject)}" 的个数为 in,返回 {"out": out, "in": inn};
353
- def _relation_counts(cg, subject):
354
- """关系:从索引里的关系节点统计出/入度(不读文件正文)。"""
355
- slug = _slug(subject)
356
- nodes = ((getattr(cg, "index", None) or {}).get("nodes") or {})
357
- out = inn = 0
358
- for nid, e in list(nodes.items()):
359
- tags = set(e.get("tags") or [])
360
- if TAG_RELATION not in tags and not nid.startswith(RELATION_PREFIX):
361
- continue
362
- if f"rel_from:{slug}" in tags:
363
- out += 1
364
- if f"rel_to:{slug}" in tags:
365
- inn += 1
366
- return {"out": out, "in": inn}
367
-
368
-
369
- # 生效条件:对 required 形参 dimensions(假值时按空字典),只保留键 str(dim).strip().lower() 属于模块常量 DIMENSIONS 且 val 非 None 的维度;val 为 list/tuple/set 时展开,否则包装为单元素;过滤空字符串并去重后放入 out,返回 out;
370
- def _normalize_dimensions(dimensions):
371
- """维度入参 → {dim: [value...]}(只保留已知维度)。"""
372
- out = {}
373
- for dim, val in (dimensions or {}).items():
374
- d = str(dim).strip().lower()
375
- if d not in DIMENSIONS or val is None:
376
- continue
377
- vals = val if isinstance(val, (list, tuple, set)) else [val]
378
- clean = [str(v).strip() for v in vals if str(v).strip()]
379
- if clean:
380
- out.setdefault(d, [])
381
- for v in clean:
382
- if v not in out[d]:
383
- out[d].append(v)
384
- return out
385
-
386
-
387
- # 生效条件:对 required 形参 cg、subject、window、importance、important_refs、dimensions、links、old,聚合 trace/trust/recent/identity/relations/prediction 等生成薄状态 dict;emotion 与 affect 仅在对应 trace/trust ok 且二阶值为非 None 时取 emotion,否则为 "unknown";importance 为 None 时回落 old.importance_self 再回落 1.0;important_refs 为 None 时回落 old.important_refs;dimensions 归一化后为空则回落 old.dimensions,并自动追加 trust band 与今日时间;links 为 None 时回落 old.state_links;
388
- def _derive(cg, subject, window, importance, important_refs, dimensions,
389
- links, old):
390
- """聚合九项自我信息 → 薄状态(纯读,不写盘)。"""
391
- tr = metacognition.trace(cg, window=max(2, int(window)))
392
- tt = metacognition.trust(cg, window=max(3, int(window)))
393
- d2 = tr.get("d2") if tr.get("ok") else None
394
- d2t = tt.get("d2") if tt.get("ok") else None
395
- # 派生自洽:无数据即 unknown,绝不编造
396
- emotion = tr.get("emotion") if (tr.get("ok") and d2 is not None) else "unknown"
397
- affect = tt.get("emotion") if (tt.get("ok") and d2t is not None) else "unknown"
398
-
399
- information_gap = {"ok": bool(tr.get("ok")), "n": tr.get("n", 0),
400
- "d_current": tr.get("d_current"), "d1": tr.get("d1"),
401
- "d2": d2, "trend": tr.get("trend")}
402
- trust = {"ok": bool(tt.get("ok")), "n_events": tt.get("n_events", 0),
403
- "p_gap": tt.get("p_gap"), "p_trust": tt.get("p_trust"),
404
- "d1": tt.get("d1"), "d2t": d2t,
405
- "band": trust_band(tt.get("p_trust"))}
406
- short_term = _recent_summary(cg, window)
407
- identity_ref, n_anchors = _identity_ref(cg, subject)
408
- relations = _relation_counts(cg, subject)
409
-
410
- if importance is None:
411
- importance = (old or {}).get("importance_self")
412
- importance = 1.0 if importance is None else float(importance)
413
- if important_refs is None:
414
- important_refs = list((old or {}).get("important_refs") or [])
415
- important_refs = [str(x) for x in important_refs if str(x).strip()]
416
-
417
- dims = _normalize_dimensions(dimensions)
418
- if not dims:
419
- dims = dict((old or {}).get("dimensions") or {})
420
- # 信任档与时间桶自动入索引(用户点名的「具体信任」「具体时间」)
421
- if trust["band"]:
422
- dims.setdefault("trust", [])
423
- if trust["band"] not in dims["trust"]:
424
- dims["trust"].append(trust["band"])
425
- today = time.strftime("%Y-%m-%d", time.localtime())
426
- dims.setdefault("time", [])
427
- if today not in dims["time"]:
428
- dims["time"].append(today)
429
-
430
- if links is None:
431
- links = list((old or {}).get("state_links") or [])
432
-
433
- return {"subject": subject, "information_gap": information_gap,
434
- "trust": trust, "emotion": emotion, "affect": affect,
435
- "short_term": short_term, "importance_self": importance,
436
- "important_refs": important_refs, "identity_ref": identity_ref,
437
- "identity_anchors": n_anchors, "relations": relations,
438
- "prediction": _prediction_face(cg),
439
- "dimensions": dims,
440
- "state_links": [str(x) for x in links if str(x).strip()]}
441
-
442
-
443
- # ---------------------------------------------------------------- 写卡
444
-
445
- # 生效条件:对 required 形参 state,读取其 information_gap、trust、short_term、prediction、dimensions 等字段,渲染并返回末尾带换行的状态卡正文(含 D_meta 边界压力趋势一行:prediction.d_meta_trend 缺失时显示 None);span 为空时显示(无),角色为空时显示(无);
446
- def _render(state):
447
- """状态卡正文:人类可读,且与 frontmatter 字段一一对应。"""
448
- ig, tt = state["information_gap"], state["trust"]
449
- st = state["short_term"]
450
- pd = state.get("prediction") or {}
451
- dims = state["dimensions"]
452
- span = st.get("span")
453
- span_txt = f"{_iso(span[0])} ~ {_iso(span[1])}" if span else "(无)"
454
- roles = "、".join(f"{k}:{v}" for k, v in
455
- sorted((st.get("roles") or {}).items())) or "(无)"
456
- lines = [
457
- f"# 自我状态卡 · {state['subject']}",
458
- f"# 更新时间:{_iso(state.get('state_ts'))}"
459
- f"(version={state.get('state_version')})",
460
- f"# 信息差:D={ig.get('d_current')} dD/dt={ig.get('d1')} "
461
- f"d^2D/dt^2={ig.get('d2')} → 情绪={state['emotion']}"
462
- f"(趋势={ig.get('trend')})",
463
- f"# 信任:P_gap={tt.get('p_gap')} P_trust={tt.get('p_trust')} "
464
- f"d^2T/dt^2={tt.get('d2t')} → 情感={state['affect']}"
465
- f"(档={tt.get('band')})",
466
- f"# 短期记忆:{st.get('n')} 条({span_txt})角色 {roles};"
467
- f"原文见 {st.get('ptr')}",
468
- f"# 重要性:self={state['importance_self']},"
469
- f"显式重要 {len(state.get('important_refs') or [])} 条",
470
- f"# 身份:锚点 {state.get('identity_ref') or '(未设)'}"
471
- f"(共 {state.get('identity_anchors')} 条)",
472
- f"# 关系:出 {state['relations'].get('out')} / "
473
- f"入 {state['relations'].get('in')}",
474
- f"# 预测:命中率={pd.get('hit_rate')}(样本 {pd.get('samples')})"
475
- f"阈值={pd.get('threshold')} 反思={'是' if pd.get('reflect') else '否'}"
476
- f";后验可信度={pd.get('beta_mean')}"
477
- f"(95%CI {pd.get('beta_ci95')})"
478
- f";ECE={pd.get('ece')}({pd.get('calibration')})",
479
- f"# D_meta:边界压力趋势(unmodeled_growth 均值)={pd.get('d_meta_trend')}"
480
- f"(三代理分别观测、不合成单值,不参与 D_task)",
481
- "# 索引:" + ";".join(
482
- f"{d}={','.join(dims.get(d) or []) or '-'}" for d in DIMENSIONS),
483
- "# 说明:本卡是薄自我——只登记当前值与指针;具体任务/人物/会话/"
484
- "时间/信任的细节由认知图按上述索引连接,不在此搬运。",
485
- ]
486
- return "\n".join(lines) + "\n"
487
-
488
-
489
- # 生效条件:当 cg 可用时,refresh 以 subject(默认 DEFAULT_SUBJECT)和 window(默认 RECENT_WINDOW)聚合九项;若留痕末条存在且状态卡缺失或 state_version/state_hash 与留痕末条不一致,则按留痕重建元数据;若 force 为假且未触发重建且旧 state_hash 等于新指纹,返回 changed=False 的幂等跳过;否则若留痕末条存在且状态卡 state_hash(状态卡缺失时视为 None)与留痕末条不同,则 strict 为真时返回 ok=False、error='chain_broken',strict 为假时以留痕末条 hash 修复 prev_hash 并写入,最终写入时返回 changed=True 及新 state_version/state_hash;
490
- def refresh(cg, subject=DEFAULT_SUBJECT, window=RECENT_WINDOW, importance=None,
491
- important_refs=None, dimensions=None, links=None,
492
- actor="self_state", force=False, strict=False, session=None):
493
- """刷新自我状态卡(幂等):聚合九项 → 写卡 + 版本链留痕。
494
-
495
- dimensions: {"task": "...", "person": "...", "session": "...",
496
- "time": "...", "trust": "..."}(值可为列表)
497
- links: 指向具体详情节点的边(认知图连接,而非内容复制)
498
- strict: 版本链断裂时是否拒绝写入(默认修复并记录 chain_repaired)
499
- session: 会话归因(嵌套身份):并入 session 维度,不覆盖显式声明值
500
- """
501
- raw = snapshot(cg, subject)
502
- tail = _last_log(cg, subject=subject)
503
- # 卡缺失 / 被绕过 refresh 破坏(版本或 hash 对不上留痕)→ 以 append-only
504
- # 留痕为准恢复元数据(维度索引、重要性、边)。留痕是权威记录。
505
- old, rebuild = raw, False
506
- if tail and (raw is None or raw.get("state_version") is None
507
- or raw.get("state_hash") != tail.get("state_hash")):
508
- rebuild = True
509
- old = {"state_version": tail.get("version"),
510
- "state_hash": tail.get("state_hash"),
511
- "dimensions": tail.get("dimensions"),
512
- "importance_self": tail.get("importance_self"),
513
- "important_refs": tail.get("important_refs"),
514
- "state_links": tail.get("state_links"),
515
- "identity_ref": tail.get("identity_ref")}
516
- # 会话归因:把本会话并入 session 维度(不覆盖调用方显式声明的维度值)。
517
- dims_in = dict(dimensions or {})
518
- if session:
519
- vals = dims_in.get("session") or []
520
- vals = list(vals) if isinstance(vals, (list, tuple, set)) else [vals]
521
- vals = [str(v) for v in vals if str(v).strip()]
522
- if str(session) not in vals:
523
- vals.append(str(session))
524
- dims_in["session"] = vals
525
- state = _derive(cg, subject, window=window, importance=importance,
526
- important_refs=important_refs, dimensions=dims_in,
527
- links=links, old=old)
528
- card_v = int((old or {}).get("state_version") or 0)
529
- log_v = int(tail.get("version") or 0) if tail else 0
530
- version = max(card_v, log_v) + 1
531
- state["state_version"] = version
532
- fp = _fingerprint(state)
533
- if not rebuild and old and old.get("state_hash") == fp and not force:
534
- return {"ok": True, "changed": False, "subject": subject,
535
- "node_id": state_node_id(subject), "state": state,
536
- "note": "状态未变化,跳过写入(幂等)"}
537
-
538
- # 版本链:prev 必须等于上一条留痕的 hash
539
- prev_hash = (raw or {}).get("state_hash")
540
- chain_issue = None
541
- if tail is not None and prev_hash != tail.get("state_hash"):
542
- chain_issue = {
543
- "code": "chain_repaired",
544
- "why": f"prev_state_hash={prev_hash} 与留痕末条 "
545
- f"{tail.get('state_hash')} 不一致"}
546
- if strict:
547
- return {"ok": False, "changed": False, "subject": subject,
548
- "error": "chain_broken", "detail": chain_issue}
549
- prev_hash = tail.get("state_hash") # 以留痕为准修复
550
- if raw is None and tail is not None:
551
- chain_issue = {"code": "state_rebuilt",
552
- "why": "状态卡缺失但留痕存在,按留痕续链重建"}
553
- prev_hash = tail.get("state_hash")
554
-
555
- state["prev_state_hash"] = prev_hash
556
- state["state_ts"] = time.time()
557
- state["state_hash"] = _fingerprint(state)
558
-
559
- tags = [TAG_STATE, f"state_subject:{_slug(subject)}"]
560
- for d in DIMENSIONS:
561
- for v in (state["dimensions"].get(d) or []):
562
- t = dim_tag(d, v)
563
- if t not in tags:
564
- tags.append(t)
565
- edges = [{"target": t, "relation_type": STATE_LINK_TYPE,
566
- "weight": 0.6} for t in state["state_links"]]
567
-
568
- nid = state_node_id(subject)
569
- cg.add(nid, _render(state), layer="self", tags=tags, edges=edges,
570
- importance=float(state["importance_self"]), confidence=0.9,
571
- verification_basis="data", override=True, actor=actor,
572
- self_state=True, state_subject=subject, state_version=version,
573
- state_hash=state["state_hash"], prev_state_hash=prev_hash,
574
- state_ts=state["state_ts"],
575
- information_gap=state["information_gap"], trust=state["trust"],
576
- emotion=state["emotion"], affect=state["affect"],
577
- short_term=state["short_term"],
578
- importance_self=state["importance_self"],
579
- important_refs=state["important_refs"],
580
- identity_ref=state["identity_ref"], relations=state["relations"],
581
- prediction=state["prediction"],
582
- dimensions=state["dimensions"], state_links=state["state_links"])
583
-
584
- _append_log(cg, {
585
- "t": state["state_ts"], "subject": subject, "node_id": nid,
586
- "version": version, "state_hash": state["state_hash"],
587
- "prev_state_hash": prev_hash, "actor": actor,
588
- "d_current": state["information_gap"].get("d_current"),
589
- "d1": state["information_gap"].get("d1"),
590
- "d2": state["information_gap"].get("d2"),
591
- "emotion": state["emotion"],
592
- "p_gap": state["trust"].get("p_gap"),
593
- "p_trust": state["trust"].get("p_trust"),
594
- "d2t": state["trust"].get("d2t"), "affect": state["affect"],
595
- "importance_self": state["importance_self"],
596
- "important_refs": state["important_refs"],
597
- "state_links": state["state_links"],
598
- "recent_n": state["short_term"].get("n"),
599
- "identity_ref": state["identity_ref"],
600
- "relations": state["relations"],
601
- "prediction_hit_rate": (state.get("prediction") or {}).get("hit_rate"),
602
- "prediction_samples": (state.get("prediction") or {}).get("samples"),
603
- "prediction_reflect": (state.get("prediction") or {}).get("reflect"),
604
- "prediction_beta_mean": (state.get("prediction") or {}).get("beta_mean"),
605
- "dimensions": state["dimensions"], "issue": chain_issue})
606
- return {"ok": True, "changed": True, "subject": subject, "node_id": nid,
607
- "state_version": version, "state_hash": state["state_hash"],
608
- "prev_state_hash": prev_hash, "state": state,
609
- "issue": chain_issue}
610
-
611
-
612
- # ---------------------------------------------------------------- 关系
613
-
614
- # 生效条件:对 required 形参 cg、frm、to 与可选 relation_type/strength/reciprocal,若 _slug(frm) == _slug(to) 返回 {"ok": False, "error": "self_loop", ...};否则 relation_type 不在模块常量 RELATION_TYPES 时回落 "other",strength 的 float 失败时 w=0.5、成功时夹在 0.0~1.0,写入关系节点,reciprocal 为真时同时写反向,返回 ok=True 及 written 列表;
615
- def relate(cg, frm, to, relation_type="collaborator", strength=0.5,
616
- condition="", note="", reciprocal=False, actor="self_state"):
617
- """写一条有向关系(自我 ↔ 其他智能)。reciprocal=True 时同时写反向。"""
618
- rt = str(relation_type or "other").strip().lower()
619
- if rt not in RELATION_TYPES:
620
- rt = "other"
621
- if _slug(frm) == _slug(to):
622
- return {"ok": False, "error": "self_loop",
623
- "detail": "关系两端不能是同一主体(自环)"}
624
- try:
625
- w = max(0.0, min(1.0, float(strength)))
626
- except (TypeError, ValueError):
627
- w = 0.5
628
- written = []
629
- for a, b in ((frm, to), (to, frm)) if reciprocal else ((frm, to),):
630
- nid = relation_node_id(a, b)
631
- tags = [TAG_RELATION, f"rel_from:{_slug(a)}", f"rel_to:{_slug(b)}",
632
- f"relation:{rt}", f"person:{_slug(b)}",
633
- f"state_subject:{_slug(a)}"]
634
- body = (f"# 关系:{a} → {b}\n"
635
- f"# 类型:{rt}\n"
636
- f"# 强度:{w}\n"
637
- f"# 条件:{condition or '(未声明)'}\n"
638
- f"# 备注:{note or '(无)'}\n")
639
- cg.add(nid, body, layer="self", tags=tags,
640
- edges=[{"target": b, "relation_type": rt, "weight": w,
641
- "condition": condition}],
642
- importance=w, confidence=0.8, verification_basis="other",
643
- override=True, actor=actor,
644
- self_relation=True, rel_from=a, rel_to=b,
645
- relation_type=rt, strength=w, condition=condition,
646
- reciprocal=bool(reciprocal))
647
- written.append(nid)
648
- return {"ok": True, "written": written, "from": frm, "to": to,
649
- "relation_type": rt, "strength": w,
650
- "reciprocal": bool(reciprocal)}
651
-
652
-
653
- # 生效条件:对 required 形参 cg 与可选 subject/direction,遍历 cg.index.nodes 中标签含 TAG_RELATION 或以 RELATION_PREFIX 开头的节点;subject 为真值时按 _slug(subject) 过滤,direction 为 "out" 只保留出边、"in" 只保留入边、"both" 保留出或入边、其他 direction 不做方向过滤;返回按 strength(importance)降序、再按 node_id 升序排序的关系列表 out;
654
- def relations(cg, subject=None, direction="both"):
655
- """列出关系节点(按 subject 过滤出/入)。"""
656
- nodes = ((getattr(cg, "index", None) or {}).get("nodes") or {})
657
- slug = _slug(subject) if subject else None
658
- out = []
659
- for nid, e in list(nodes.items()):
660
- tags = set(e.get("tags") or [])
661
- if TAG_RELATION not in tags and not nid.startswith(RELATION_PREFIX):
662
- continue
663
- if slug:
664
- is_out = f"rel_from:{slug}" in tags
665
- is_in = f"rel_to:{slug}" in tags
666
- if direction == "out" and not is_out:
667
- continue
668
- if direction == "in" and not is_in:
669
- continue
670
- if direction == "both" and not (is_out or is_in):
671
- continue
672
- rels = [t[len("relation:"):] for t in tags if t.startswith("relation:")]
673
- frm = [t[len("rel_from:"):] for t in tags if t.startswith("rel_from:")]
674
- to = [t[len("rel_to:"):] for t in tags if t.startswith("rel_to:")]
675
- out.append({"node_id": nid, "from": frm[0] if frm else None,
676
- "to": to[0] if to else None,
677
- "relation_type": rels[0] if rels else None,
678
- "strength": e.get("importance"),
679
- "layer": e.get("layer")})
680
- out.sort(key=lambda x: (-float(x.get("strength") or 0), x["node_id"]))
681
- return out
682
-
683
-
684
- # ---------------------------------------------------------------- 索引
685
-
686
- # 生效条件:对 required 形参 cg、dim、value 与可选 limit/with_content,若 dim 小写去空白后不在模块常量 DIMENSIONS 中,返回 {"ok": False, "error": "unknown_dimension", "allowed": list(DIMENSIONS)};否则匹配 cg.index.nodes 中 tags 含 dim_tag(dim, value) 的节点,按 importance 降序、created_at 降序排序,取 hits[:int(limit)](limit=0 时切片为空),with_content 为真时附加节点 content 前 400 字符,返回 ok=True 及 count/items;
687
- def index(cg, dim, value, limit=50, with_content=False):
688
- """按五维索引反查具体详情节点(认知图连接,不是内容搬运)。"""
689
- d = str(dim or "").strip().lower()
690
- if d not in DIMENSIONS:
691
- return {"ok": False, "error": "unknown_dimension",
692
- "allowed": list(DIMENSIONS)}
693
- tag = dim_tag(d, value)
694
- nodes = ((getattr(cg, "index", None) or {}).get("nodes") or {})
695
- hits = [(nid, e) for nid, e in list(nodes.items())
696
- if tag in (e.get("tags") or [])]
697
- hits.sort(key=lambda kv: (-float(kv[1].get("importance") or 0),
698
- -float(kv[1].get("created_at") or 0),
699
- str(kv[0] or "")))
700
- items = []
701
- for nid, e in hits[:int(limit)]:
702
- item = {"node_id": nid, "layer": e.get("layer"),
703
- "importance": e.get("importance"), "tags": e.get("tags"),
704
- "path": e.get("path")}
705
- if with_content:
706
- node = _node(cg, nid) or {}
707
- item["content"] = (node.get("content") or "")[:400]
708
- items.append(item)
709
- return {"ok": True, "dimension": d, "value": str(value), "tag": tag,
710
- "count": len(hits), "items": items}
711
-
712
-
713
- # 生效条件:对 required 形参 cg 与 subject(未传时 DEFAULT_SUBJECT),若 snapshot(cg, subject) 返回假值则返回 {"ok": False, "error": "no_state", "subject": subject};否则返回 {"ok": True, "subject": subject, "dimensions": st.get("dimensions") or {}};
714
- def dimensions(cg, subject=DEFAULT_SUBJECT):
715
- """状态卡登记的五维索引标签。"""
716
- st = snapshot(cg, subject)
717
- if not st:
718
- return {"ok": False, "error": "no_state", "subject": subject}
719
- return {"ok": True, "subject": subject,
720
- "dimensions": st.get("dimensions") or {}}
721
-
722
-
723
- # ---------------------------------------------------------------- 审计
724
-
725
- # 生效条件:对 required 形参 code、severity、why,返回含这三个键并合并 **extra 的 dict;
726
- def _issue(code, severity, why, **extra):
727
- d = {"code": code, "severity": severity, "why": why}
728
- d.update(extra)
729
- return d
730
-
731
-
732
- # 生效条件:当 cg 可用时,audit 对 subject(默认 DEFAULT_SUBJECT)和 window(默认 RECENT_WINDOW)执行一致性审计;若对应状态卡不存在则返回 ok=False、verdict='absent'(含已收集的 issues);否则基于留痕历史与现算值收集 issues,按有无 error 返回 verdict='broken'、无 error 但有 warn 返回 'drift'、均无返回 'consistent',且 ok 为无 error;
733
- def audit(cg, subject=DEFAULT_SUBJECT, window=RECENT_WINDOW):
734
- """自我信息一致性审计:全部判定可重算(不依赖人的判断)。"""
735
- from . import protect as _protect
736
- issues = []
737
- nid = state_node_id(subject)
738
- nodes = ((getattr(cg, "index", None) or {}).get("nodes") or {})
739
- st = snapshot(cg, subject)
740
-
741
- # 1 单例:同 subject 的状态卡只能有一张
742
- slug = _slug(subject)
743
- cards = [n for n, e in list(nodes.items())
744
- if TAG_STATE in (e.get("tags") or [])
745
- and f"state_subject:{slug}" in (e.get("tags") or [])]
746
- if len(cards) > 1:
747
- issues.append(_issue("duplicate_state", "error",
748
- f"同一 subject 有 {len(cards)} 张状态卡",
749
- nodes=cards))
750
- if st is None:
751
- issues.append(_issue("missing_state", "warn",
752
- "状态卡不存在:先 refresh() 建立", node_id=nid))
753
- return {"ok": False, "verdict": "absent", "subject": subject,
754
- "n_issues": len(issues), "issues": issues,
755
- "checked_at": time.time()}
756
-
757
- ordered = list(reversed(history(cg, limit=0, subject=subject)))
758
-
759
- # 2 版本链:version 连续 +1,prev 必须等于上一条 hash
760
- for i in range(1, len(ordered)):
761
- p, c = ordered[i - 1], ordered[i]
762
- if c.get("version") != (p.get("version") or 0) + 1:
763
- issues.append(_issue(
764
- "version_gap", "error",
765
- f"版本不连续:{p.get('version')} → {c.get('version')}",
766
- at=c.get("t")))
767
- if c.get("prev_state_hash") != p.get("state_hash"):
768
- issues.append(_issue(
769
- "chain_broken", "error",
770
- f"留痕断链:prev={c.get('prev_state_hash')} ≠ 上一条 "
771
- f"{p.get('state_hash')}", at=c.get("t")))
772
- if float(c.get("t") or 0) < float(p.get("t") or 0):
773
- issues.append(_issue("time_regression", "error",
774
- "留痕时间戳回退", at=c.get("t")))
775
-
776
- # 3 留痕对齐:卡上的 hash 必须等于留痕末条
777
- if ordered:
778
- tail = ordered[-1]
779
- if st.get("state_hash") != tail.get("state_hash"):
780
- issues.append(_issue(
781
- "log_tail_mismatch", "error",
782
- f"卡 hash={st.get('state_hash')} ≠ 留痕末条 "
783
- f"{tail.get('state_hash')}(卡被绕过 refresh 改过?)",
784
- node_id=nid))
785
-
786
- # 4 派生自洽:无数据时必须 unknown(不许编造)
787
- ig = st.get("information_gap") or {}
788
- tt = st.get("trust") or {}
789
- if ig.get("d2") is None and st.get("emotion") not in (None, "unknown"):
790
- issues.append(_issue("fabricated_emotion", "error",
791
- f"d^2D/dt^2 缺失但 emotion={st.get('emotion')}"))
792
- if tt.get("d2t") is None and st.get("affect") not in (None, "unknown"):
793
- issues.append(_issue("fabricated_affect", "error",
794
- f"d^2T/dt^2 缺失但 affect={st.get('affect')}"))
795
-
796
- # 5 跨面一致:与 metacognition 现算值比对(drift)
797
- now = _derive(cg, subject, window=window, importance=None,
798
- important_refs=None, dimensions=None, links=None, old=None)
799
- for name, old_v, new_v in (
800
- ("d_current", ig.get("d_current"),
801
- now["information_gap"].get("d_current")),
802
- ("d2", ig.get("d2"), now["information_gap"].get("d2")),
803
- ("p_trust", tt.get("p_trust"), now["trust"].get("p_trust")),
804
- ("d2t", tt.get("d2t"), now["trust"].get("d2t"))):
805
- if old_v is None and new_v is None:
806
- continue
807
- try:
808
- if old_v is None or new_v is None or \
809
- abs(float(old_v) - float(new_v)) > DRIFT_TOL:
810
- issues.append(_issue(
811
- "drift", "warn",
812
- f"{name} 卡值={old_v} 现算={new_v}(容差 {DRIFT_TOL})",
813
- field=name))
814
- except (TypeError, ValueError):
815
- issues.append(_issue("drift", "warn",
816
- f"{name} 不可比较:{old_v} vs {new_v}",
817
- field=name))
818
-
819
- # 5b 预测面漂移:预测能力(命中率)随 predict_feedback 演化;卡值过时即为
820
- # 漂移——这是「自我模型是否跟上自身预测表现」的可重算判定。
821
- pd_old = st.get("prediction") or {}
822
- pd_new = now.get("prediction") or {}
823
- o_hr, n_hr = pd_old.get("hit_rate"), pd_new.get("hit_rate")
824
- if not (o_hr is None and n_hr is None):
825
- try:
826
- if o_hr is None or n_hr is None or \
827
- abs(float(o_hr) - float(n_hr)) > DRIFT_TOL:
828
- issues.append(_issue(
829
- "prediction_drift", "warn",
830
- f"预测命中率 卡值={o_hr} 现算={n_hr}(容差 {DRIFT_TOL})",
831
- field="hit_rate"))
832
- except (TypeError, ValueError):
833
- issues.append(_issue("prediction_drift", "warn",
834
- f"预测命中率不可比较:{o_hr} vs {n_hr}",
835
- field="hit_rate"))
836
-
837
- # 6 身份唯一:identity_ref 必须指向存在的锚点
838
- ref = st.get("identity_ref")
839
- if not ref:
840
- issues.append(_issue("identity_missing", "info",
841
- "identity_ref 为空:先在 self 层写身份锚点"))
842
- elif ref not in nodes:
843
- issues.append(_issue("identity_dangling", "error",
844
- f"identity_ref={ref} 指向不存在的节点", ref=ref))
845
-
846
- # 7 关系完整:禁止自环、禁止同一有向对重复
847
- seen_rel = {}
848
- for rel in relations(cg, subject=None):
849
- nid_r = rel["node_id"]
850
- if rel["from"] == rel["to"]:
851
- issues.append(_issue("relation_self_loop", "error",
852
- f"关系自环:{rel['from']}", node_id=nid_r))
853
- key = (rel["from"], rel["to"])
854
- if key in seen_rel:
855
- issues.append(_issue("duplicate_relation", "error",
856
- f"重复关系 {key}", node_id=nid_r))
857
- seen_rel[key] = nid_r
858
-
859
- # 8 保护一致:状态卡必须可覆盖(否则自我认知被永久冻结)且不可遗忘
860
- try:
861
- imm, why = _protect.is_immutable(cg, nid)
862
- if imm:
863
- issues.append(_issue("protection_locked", "error",
864
- f"状态卡不可覆盖:{why}(自我状态将无法演化)"))
865
- pro, _ = _protect.is_protected(cg, nid)
866
- if not pro:
867
- issues.append(_issue("protection_missing", "warn",
868
- "状态卡未受保护:自我信息可能被遗忘"))
869
- except Exception as exc: # pragma: no cover
870
- issues.append(_issue("protection_check_failed", "warn", str(exc)))
871
-
872
- # 9 索引不悬空:维度标签指向的详情节点必须存在
873
- dims = st.get("dimensions") or {}
874
- for d, vals in dims.items():
875
- if d not in DIMENSIONS:
876
- issues.append(_issue("unknown_dimension", "warn",
877
- f"未知索引维度 {d}"))
878
- continue
879
- for v in (vals or []):
880
- tag = dim_tag(d, v)
881
- holders = [n for n, e in list(nodes.items())
882
- if tag in (e.get("tags") or [])]
883
- if not holders:
884
- issues.append(_issue("dimension_orphan", "warn",
885
- f"索引 {tag} 无对应节点(悬空索引)",
886
- dimension=d, value=v))
887
-
888
- # 10 新鲜度
889
- try:
890
- age = time.time() - float(st.get("state_ts") or 0)
891
- if age > STALE_AFTER:
892
- issues.append(_issue("stale", "warn",
893
- f"状态卡 {age / 3600:.1f} 小时未刷新"))
894
- except (TypeError, ValueError):
895
- issues.append(_issue("stale", "warn", "state_ts 不可解析"))
896
-
897
- errors = [i for i in issues if i["severity"] == "error"]
898
- warns = [i for i in issues if i["severity"] == "warn"]
899
- verdict = "broken" if errors else ("drift" if warns else "consistent")
900
- return {"ok": not errors, "verdict": verdict, "subject": subject,
901
- "node_id": nid, "n_issues": len(issues),
902
- "n_errors": len(errors), "issues": issues,
903
- "state_version": st.get("state_version"),
904
- "state_hash": st.get("state_hash"), "checked_at": time.time()}
905
-
906
-
907
- # ---------------------------------------------------------------- 加载 / 概览
908
-
909
- # 生效条件:对 required 形参 cg 与可选 subject/window/auto_refresh/actor,先取 snapshot(cg, subject);若 st 为 None 且 auto_refresh 为真则 refresh 后重新 snapshot;若 st 非 None 且 auto_refresh 为真且 st.state_ts 的年龄 > 模块常量 STALE_AFTER 则 refresh 后重新 snapshot;然后取 relations、history(limit=5, subject)、dimensions,返回 ok=st is not None 及这些字段;
910
- def bootstrap(cg, subject=DEFAULT_SUBJECT, window=RECENT_WINDOW,
911
- auto_refresh=True, actor="bootstrap"):
912
- """会话启动:加载自我状态卡 + 关系 + 最近留痕 + 索引概览。
913
-
914
- 这是「跨会话自动加载自我」的入口:self 层薄卡 + 认知图连接。
915
- """
916
- st = snapshot(cg, subject)
917
- if st is None and auto_refresh:
918
- refresh(cg, subject, window=window, actor=actor)
919
- st = snapshot(cg, subject)
920
- elif st is not None and auto_refresh:
921
- # 只在漂移或过期时刷新,避免每次启动都写盘
922
- try:
923
- age = time.time() - float(st.get("state_ts") or 0)
924
- except (TypeError, ValueError):
925
- age = STALE_AFTER + 1
926
- if age > STALE_AFTER:
927
- refresh(cg, subject, window=window, actor=actor)
928
- st = snapshot(cg, subject)
929
- rels = relations(cg, subject=subject)
930
- return {"ok": st is not None, "subject": subject, "state": st,
931
- "relations": rels, "relations_count": len(rels),
932
- "recent_states": history(cg, limit=5, subject=subject),
933
- "dimensions": (st or {}).get("dimensions") or {},
934
- "loaded_at": time.time()}
935
-
936
-
937
- # 生效条件:对 required 形参 cg、out、st、session,若 session 为假值直接返回 out;否则写入 out["session"]=str(session)、out["session_registered"]=bool(s in st.dimensions.session 列表)、out["session_refs"](调用 index(cg, "session", s, limit=20) 的结果;异常时写入 count=0、degraded=True),返回 out;
938
- def _with_session_slice(cg, out, st, session):
939
- """给 summary 结果补「本会话切片」(薄卡 + 富索引,不改单例语义)。
940
-
941
- · session_registered —— 本会话是否已登记在该状态卡的 session 维度上;
942
- · session_refs —— 该维度反查到的详情节点指针(不搬运内容)。
943
- """
944
- if not session:
945
- return out
946
- s = str(session)
947
- out["session"] = s
948
- dims = (st or {}).get("dimensions") or {}
949
- out["session_registered"] = bool(s in (dims.get("session") or []))
950
- try:
951
- res = index(cg, "session", s, limit=20)
952
- out["session_refs"] = {"count": res.get("count", 0),
953
- "items": res.get("items", [])}
954
- except Exception: # noqa: BLE001
955
- out["session_refs"] = {"count": 0, "items": [], "degraded": True}
956
- return out
957
-
958
-
959
- # 生效条件:对 required 形参 cg 与可选 subject/session,取 snapshot(cg, subject);若为假值,经 _with_session_slice 返回 {"ok": False, "subject": subject, "note": "无状态卡"};否则构造含 version、d_current、emotion、p_trust、trust_band、text 等字段的 dict,再经 _with_session_slice 返回;
960
- def summary(cg, subject=DEFAULT_SUBJECT, session=None):
961
- """一句话自我状态(供 health / 面板)。
962
-
963
- session:会话归因切片。**不改变单例卡语义**——只回报「本会话是否已登记在
964
- 该卡的 session 维度上」以及该维度反查到的详情节点指针(薄卡 + 富索引)。
965
- """
966
- st = snapshot(cg, subject)
967
- if not st:
968
- return _with_session_slice(cg, {"ok": False, "subject": subject,
969
- "note": "无状态卡"}, st, session)
970
- ig, tt = st.get("information_gap") or {}, st.get("trust") or {}
971
- out = {"ok": True, "subject": subject,
972
- "version": st.get("state_version"),
973
- "updated_at": st.get("updated_at"),
974
- "d_current": ig.get("d_current"), "d2": ig.get("d2"),
975
- "emotion": st.get("emotion"),
976
- "p_trust": tt.get("p_trust"), "d2t": tt.get("d2t"),
977
- "affect": st.get("affect"),
978
- "trust_band": tt.get("band"),
979
- "recent_n": (st.get("short_term") or {}).get("n"),
980
- "relations": st.get("relations"),
981
- "identity_ref": st.get("identity_ref"),
982
- "hit_rate": (st.get("prediction") or {}).get("hit_rate"),
983
- "prediction_reflect": (st.get("prediction") or {}).get("reflect"),
984
- "text": (f"[{subject}] D={ig.get('d_current')} "
985
- f"情绪={st.get('emotion')} P_trust={tt.get('p_trust')} "
986
- f"情感={st.get('affect')} "
987
- f"短期={((st.get('short_term') or {}).get('n'))}条 "
988
- f"v{st.get('state_version')}")}
989
- return _with_session_slice(cg, out, st, session)
990
-
991
-
992
- # 生效条件:无参调用时返回模块自描述 dict,内含模块常量 SCHEMA_VERSION、DEFAULT_SUBJECT、LOG_FILE、DIMENSIONS、TRUST_BANDS、RELATION_TYPES、DRIFT_TOL、STALE_AFTER 等;
993
- def catalog():
994
- """自描述:九项自我信息 + 五维索引 + 审计规则(供协议对照验证)。"""
995
- return {
996
- "module": "self_state",
997
- "schema": SCHEMA_VERSION,
998
- "default_subject": DEFAULT_SUBJECT,
999
- "log": LOG_FILE,
1000
- "principles": [
1001
- "self 层是薄的:只放状态卡(单例)与关系节点,不搬运内容",
1002
- "具体细节留在原层,由认知图的标签/边按五维索引连接过来",
1003
- "不可遗忘 ≠ 不可覆盖:状态卡可演化,身份锚点两者皆禁",
1004
- ],
1005
- "self_info": {
1006
- "information_gap": "D/d1/d2 + emotion ← _reflection.jsonl",
1007
- "trust": "p_gap/p_trust + d2t/affect ← evidence_log",
1008
- "emotion": "d^2D/dt^2(信息差二阶)",
1009
- "affect": "d^2T/dt^2(信任二阶)",
1010
- "short_term": "窗口摘要 + 指针 ← _recent.jsonl",
1011
- "importance": "importance_self + important_refs",
1012
- "identity": "identity_ref → self 层身份锚点",
1013
- "relations": "self_relation_* 有向关系节点",
1014
- "prediction": "hit_rate/threshold/reflect + ECE ← _prediction.jsonl",
1015
- },
1016
- "dimensions": list(DIMENSIONS),
1017
- "trust_bands": [b for _lo, b in TRUST_BANDS],
1018
- "relation_types": list(RELATION_TYPES),
1019
- "audit_rules": [
1020
- "duplicate_state", "version_gap", "chain_broken",
1021
- "time_regression", "log_tail_mismatch", "fabricated_emotion",
1022
- "fabricated_affect", "drift", "prediction_drift",
1023
- "identity_missing",
1024
- "identity_dangling", "relation_self_loop", "duplicate_relation",
1025
- "protection_locked", "protection_missing", "unknown_dimension",
1026
- "dimension_orphan", "stale", "missing_state",
1027
- ],
1028
- "tolerances": {"drift": DRIFT_TOL, "stale_after_sec": STALE_AFTER},
1029
- }
1
+ # -*- coding: utf-8 -*-
2
+ """md_cg · 自我状态层(SELF STATE):薄自我 + 富索引
3
+
4
+ 理论约束(本仓已有文档,非外部发明):
5
+ · `docs/mdcg/灵枢_自我层定义.md:6`
6
+ SELF 层 = 身份 + 价值观 + 图接口,**不可遗忘**、跨会话自动加载。
7
+ 自我层是**薄的**——它不该变成事件仓库。
8
+ · 智能论 §十一:情绪 = 信息差二阶 d^2D/dt^2;§十:P_gap / P_trust;
9
+ 情感 = 信任二阶 d^2T/dt^2。
10
+
11
+ 由此定下本模块的形态:
12
+
13
+ self 层只放两类一等公民(都很薄):
14
+ 1. 自我状态卡(单例)——九项自我信息的**当前值 + 指针**
15
+ 2. 关系节点(有向)——自我与其他智能的关系
16
+ 具体细节(哪次会话 / 哪个任务 / 哪个人 / 哪个时间窗 / 哪条证据)
17
+ 仍然留在原本的层里,由**认知图的标签与边**连接、索引过来。
18
+
19
+ 九项自我信息 → 薄卡字段 / 富索引指向:
20
+
21
+ ┌ 信息差 D d_current / d1 / d2 / emotion ← _reflection.jsonl(reflect 留痕)
22
+ ├ 信任 P p_gap / p_trust / d2t / affect ← 各节点 evidence_log(verify 留痕)
23
+ ├ 情绪 emotion(= d^2D/dt^2)
24
+ ├ 情感 affect(= d^2T/dt^2)
25
+ ├ 短期记忆 recent{n, span, roles, ptr} ← _recent.jsonl(只存摘要 + 指针)
26
+ ├ 重要性 importance_self / important_refs ← 各节点 frontmatter.importance
27
+ ├ 身份 identity_ref ← self 层 identity 锚点
28
+ ├ 关系 relations{out,in} ← self_relation_* 关系节点
29
+ └ 预测校准 hit_rate / threshold / reflect / ece ← _prediction.jsonl + evidence_log
30
+
31
+ 第九项(预测校准)是「SELF = 自我描述」走向「SELF = 关于自身的预测模型」的最小一步:
32
+ 它回答**我预测得准吗、该不该反思**,数据只来自 predict 的 feedback 留痕与
33
+ metacognition 的 ECE 校准,样本不足一律 unknown——不新增计算,也不编造。
34
+
35
+ 五个索引维度(「具体任务 / 人物关系 / 会话 / 时间 / 信任」)用 tag 命名空间落地,
36
+ `index(cg, dim, value)` 从全图反查;状态卡只登记维度标签、不搬运内容:
37
+
38
+ task:<slug> 具体任务
39
+ person:<slug> 具体人物关系
40
+ session:<id> 具体会话
41
+ time:<bucket> 具体时间(YYYY-MM-DD)
42
+ trust:<band> 具体信任档(low | mid | high)
43
+
44
+ 一致性(`audit` 的每条判定都可重算,不依赖人的判断):
45
+
46
+ 单例 同一 subject 至多一个状态卡
47
+ 版本链 state_version 连续 +1;prev_state_hash 必须等于上一条留痕的 hash
48
+ 时序单调 留痕时间戳不得回退
49
+ 留痕对齐 卡上的 state_hash 必须等于留痕末条
50
+ 派生自洽 d2/d2t 缺失时 emotion/affect 必须是 unknown(不许编造)
51
+ 跨面一致 卡值与 metacognition 现算值偏差 ≤ DRIFT_TOL
52
+ 身份唯一 identity_ref 必须指向存在的身份锚点
53
+ 关系完整 关系两端必须存在;禁止自环
54
+ 保护一致 状态卡必须「可覆盖」(否则自我认知被永久冻结)且「不可遗忘」
55
+ 索引不悬空 维度标签指向的详情节点必须存在
56
+
57
+ 「不可遗忘 ≠ 不可覆盖」的延伸:
58
+ · 身份锚点:既不可遗忘,也不可覆盖(protect 层保护);
59
+ · 自我状态卡:**不可遗忘,但必须可覆盖**——自我状态本来就要演化。
60
+ 靠 `frontmatter.self_state is True` 在 protect 里获得覆盖豁免,见 protect.py。
61
+ """
62
+ import hashlib
63
+ import json
64
+ import os
65
+ import re
66
+ import time
67
+
68
+ from . import identity, metacognition
69
+ from . import fsutil
70
+ from .fsutil import append_jsonl, read_jsonl
71
+
72
+ DEFAULT_SUBJECT = "self:lingshu"
73
+ STATE_PREFIX = "self_state_"
74
+ RELATION_PREFIX = "self_relation_"
75
+ LOG_FILE = "_self_state.jsonl"
76
+ TAG_STATE = "self_state"
77
+ TAG_RELATION = "self_relation"
78
+ SCHEMA_VERSION = 1
79
+
80
+ # 跨面一致容差:卡里的 D/T 与 metacognition 现算值允许的最大偏差
81
+ DRIFT_TOL = 0.05
82
+ # 新鲜度:状态卡超过该秒数未刷新即视为 stale
83
+ STALE_AFTER = 24 * 3600.0
84
+ RECENT_WINDOW = 20
85
+
86
+ # 五维索引(具体任务 / 人物关系 / 会话 / 时间 / 信任)
87
+ DIMENSIONS = ("task", "person", "session", "time", "trust")
88
+ TRUST_BANDS = ((0.70, "high"), (0.40, "mid"), (0.00, "low"))
89
+ RELATION_TYPES = ("collaborator", "user", "peer", "mentor", "student",
90
+ "adversary", "tool", "other")
91
+ STATE_LINK_TYPE = "refers_to"
92
+
93
+
94
+ # ---------------------------------------------------------------- 基础工具
95
+
96
+ # 生效条件:对 required 形参 text,返回 str(text or "") 经正则把非中英文数字连续段折叠为下划线、strip('_') 并 lower 后的字符串(text 为假值时返回空串);
97
+ def _slug(text):
98
+ """归一化 id 片段:保留中英文数字,其余折叠为下划线。"""
99
+ s = re.sub(r"[^0-9A-Za-z\u4e00-\u9fff]+", "_", str(text or ""))
100
+ return s.strip("_").lower()
101
+
102
+
103
+ # 生效条件:对 required 形参 ts,当 float(ts) 可转换且 time.localtime 不抛 OSError 时返回本地时间 "%Y-%m-%d %H:%M:%S" 格式串;当 float(ts) 抛 TypeError/ValueError 或 time.localtime 抛 OSError 时返回空串;
104
+ def _iso(ts):
105
+ try:
106
+ return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(ts)))
107
+ except (TypeError, ValueError, OSError):
108
+ return ""
109
+
110
+
111
+ # 生效条件:subject 未传时取模块常量 DEFAULT_SUBJECT,返回模块常量 STATE_PREFIX 拼接 _slug(subject) 的结果;
112
+ def state_node_id(subject=DEFAULT_SUBJECT):
113
+ """状态卡节点 id(单例:同一 subject 只有一个)。"""
114
+ return STATE_PREFIX + _slug(subject)
115
+
116
+
117
+ # 生效条件:对 required 形参 frm 与 to,返回模块常量 RELATION_PREFIX 拼接 _slug(frm)、"__"、_slug(to) 的字符串;
118
+ def relation_node_id(frm, to):
119
+ """关系节点 id(有向)。"""
120
+ return f"{RELATION_PREFIX}{_slug(frm)}__{_slug(to)}"
121
+
122
+
123
+ # 生效条件:对 required 形参 cg,返回 os.path.join(cg.root, LOG_FILE)(LOG_FILE 为模块常量);
124
+ def log_path(cg):
125
+ return os.path.join(cg.root, LOG_FILE)
126
+
127
+
128
+ # 生效条件:对 required 形参 dim 与 value,返回 f"{dim}:{_slug(value)}";
129
+ def dim_tag(dim, value):
130
+ return f"{dim}:{_slug(value)}"
131
+
132
+
133
+ # 生效条件:对 required 形参 p_trust,若 p_trust is None 或 float(p_trust) 抛 TypeError/ValueError 则返回 None;否则按模块常量 TRUST_BANDS 顺序取首个 v >= lo 的档名,均不满足返回 "low";
134
+ def trust_band(p_trust):
135
+ """把 P_trust 映射到信任档(索引维度之一)。"""
136
+ if p_trust is None:
137
+ return None
138
+ try:
139
+ v = float(p_trust)
140
+ except (TypeError, ValueError):
141
+ return None
142
+ for lo, name in TRUST_BANDS:
143
+ if v >= lo:
144
+ return name
145
+ return "low"
146
+
147
+
148
+ # ---------------------------------------------------------------- 留痕
149
+
150
+ # 生效条件:对 required 形参 cg 与 rec,调用 append_jsonl(log_path(cg), rec);若抛出 OSError 则静默忽略,无返回值;
151
+ def _append_log(cg, rec):
152
+ try:
153
+ # #326-④:append_jsonl 不再上抛、以 False 报写失败——本处**仍容忍**(best-effort
154
+ # 簿记),但失败不再静默:源头已记 fsutil.APPEND_FAILURES + 有界 stderr 告警
155
+ # (B 面单点)。显式消费返回值:不留裸调用(守卫 AST 钉子会抓)。
156
+ # issue #443:调用方可控字段可无限长 ⇒ 单条记录先过总字节闸(超限跳过写并留痕)。
157
+ if not fsutil.bounded_record(rec):
158
+ fsutil._note_append_failure(log_path(cg),
159
+ ValueError("record_too_large: issue #443"))
160
+ return
161
+ _ok = fsutil.append_jsonl_ledger(log_path(cg), rec)
162
+ except OSError:
163
+ pass
164
+
165
+
166
+ # 生效条件:对 required 形参 cg 与可选 limit/subject,读取 log_path(cg) 留痕(OSError 时为空列表);subject 为真值时只保留 r.get("subject") == subject 的记录;倒序后,limit 为真值时返回 recs[:int(limit)],limit 为假值(如 0)时返回全部倒序记录;
167
+ def history(cg, limit=100, subject=None):
168
+ """自我状态留痕(倒序)。"""
169
+ try:
170
+ recs = list(fsutil.read_jsonl_ledger(log_path(cg)))
171
+ except OSError:
172
+ recs = []
173
+ if subject:
174
+ recs = [r for r in recs if r.get("subject") == subject]
175
+ recs.reverse()
176
+ return recs[:int(limit)] if limit else recs
177
+
178
+
179
+ # 生效条件:对 required 形参 cg 与可选 subject,调用 history(cg, limit=0, subject=subject) 取全部倒序留痕;有记录时返回 recs[0](最新一条),否则返回 None;
180
+ def _last_log(cg, subject=None):
181
+ recs = history(cg, limit=0, subject=subject)
182
+ return recs[0] if recs else None
183
+
184
+
185
+ # ---------------------------------------------------------------- 读卡
186
+
187
+ # 生效条件:对 required 形参 cg 与 node_id,尝试返回 cg.get(node_id);若 cg.get 抛任何异常则返回 None;
188
+ def _node(cg, node_id):
189
+ try:
190
+ return cg.get(node_id)
191
+ except Exception:
192
+ return None
193
+
194
+
195
+ # 生效条件:对 required 形参 cg 与 node_id,取 _node(cg, node_id) 结果(假值时用空字典)的 "frontmatter" 值;该值假值时返回空字典,否则返回该 frontmatter;
196
+ def _fm_of(cg, node_id):
197
+ node = _node(cg, node_id)
198
+ return (node or {}).get("frontmatter") or {}
199
+
200
+
201
+ # 生效条件:对 required 形参 cg 与 node_id,从 cg.index(getattr 取不到或假值时用空字典)的 "nodes" 字段(假值时用空字典)中取 node_id 对应条目;缺键返回 None;
202
+ def _entry(cg, node_id):
203
+ return ((getattr(cg, "index", None) or {}).get("nodes") or {}).get(node_id)
204
+
205
+
206
+ # 生效条件:对 required 形参 cg 与 subject(未传时 DEFAULT_SUBJECT),若 state_node_id(subject) 在 cg.index.nodes 中不存在,或该节点没有非空 frontmatter,返回 None;否则返回由该 frontmatter 扁平化出的 dict,其中 subject 为 fm.get("state_subject") or subject,d_current/p_trust 分别从 information_gap/trust 子字典取;
207
+ def snapshot(cg, subject=DEFAULT_SUBJECT):
208
+ """读当前状态卡 → 扁平 dict(不存在返回 None)。只读,不写盘。"""
209
+ nid = state_node_id(subject)
210
+ if _entry(cg, nid) is None:
211
+ return None
212
+ fm = _fm_of(cg, nid)
213
+ if not fm:
214
+ return None
215
+ out = {"node_id": nid, "subject": fm.get("state_subject") or subject,
216
+ "layer": "self", "state_version": fm.get("state_version"),
217
+ "state_hash": fm.get("state_hash"),
218
+ "prev_state_hash": fm.get("prev_state_hash"),
219
+ "state_ts": fm.get("state_ts"),
220
+ "updated_at": _iso(fm.get("state_ts"))}
221
+ for key in ("information_gap", "trust", "short_term", "relations",
222
+ "prediction", "dimensions", "emotion", "affect",
223
+ "importance_self", "important_refs", "identity_ref",
224
+ "state_links"):
225
+ out[key] = fm.get(key)
226
+ out["d_current"] = (fm.get("information_gap") or {}).get("d_current")
227
+ out["p_trust"] = (fm.get("trust") or {}).get("p_trust")
228
+ return out
229
+
230
+
231
+ # 生效条件:对 required 形参 state,返回对指定核心字段(subject、information_gap、trust、emotion、affect、importance_self、important_refs、identity_ref、short_term、relations、prediction、dimensions、state_links)做 sort_keys=True、ensure_ascii=False、default=str 的 JSON 序列化后 SHA-256 前 16 位十六进制(不含 state_version);
232
+ def _fingerprint(state):
233
+ """状态指纹:只对「会漂移的实质字段」取哈希,用于幂等刷新与版本链。
234
+
235
+ 注意:**不含 state_version**——版本号是元数据,若纳入指纹则每次刷新
236
+ 指纹必变,幂等判断失效(自我状态会在无信息变化时无限刷版本)。
237
+ """
238
+ core = {
239
+ "subject": state.get("subject"),
240
+ "information_gap": state.get("information_gap"),
241
+ "trust": state.get("trust"),
242
+ "emotion": state.get("emotion"),
243
+ "affect": state.get("affect"),
244
+ "importance_self": state.get("importance_self"),
245
+ "important_refs": state.get("important_refs"),
246
+ "identity_ref": state.get("identity_ref"),
247
+ "short_term": state.get("short_term"),
248
+ "relations": state.get("relations"),
249
+ "prediction": state.get("prediction"),
250
+ "dimensions": state.get("dimensions"),
251
+ "state_links": state.get("state_links"),
252
+ }
253
+ blob = json.dumps(core, sort_keys=True, ensure_ascii=False, default=str)
254
+ return hashlib.sha256(blob.encode("utf-8")).hexdigest()[:16]
255
+
256
+
257
+ # ---------------------------------------------------------------- 聚合(九项)
258
+
259
+ # 生效条件:对 required 形参 cg,返回近 int(window)(缺省 20)条反思留痕里 d_meta.unmodeled_growth 的均值(仅收数值型、bool 不计),无可用留痕时回落 d_meta.pressure(d_meta.compute(cg)),d_meta 不可用或抛异常时返回 None;
260
+ def _d_meta_trend(cg, window: int = 20):
261
+ """近 window 条反思留痕的 D_meta 边界压力均值(确定性函数,纯读)。
262
+
263
+ 口径(智能论3.4 §2.7.0 DEV-002a):只聚合已落盘的
264
+ `d_meta.unmodeled_growth`——**不合成三代理**、不参与 D_task。
265
+ 留痕无该字段(旧记录/总闸关闭)时回落当前 `d_meta.compute` 的**单一
266
+ 代理**值;两者皆不可用 → None(未知即未知,不编造)。
267
+ """
268
+ try:
269
+ from . import d_meta as _d_meta
270
+ vals = []
271
+ for r in metacognition._reflections(cg)[-int(window):]:
272
+ v = (r.get("d_meta") or {}).get("unmodeled_growth")
273
+ if isinstance(v, (int, float)) and not isinstance(v, bool):
274
+ vals.append(float(v))
275
+ if vals:
276
+ return round(sum(vals) / len(vals), 4)
277
+ return _d_meta.pressure(_d_meta.compute(cg))
278
+ except Exception: # noqa: BLE001
279
+ return None
280
+
281
+
282
+ # 生效条件:对 required 形参 cg,返回预测校准 dict;samples==0 时 ok=False、hit_rate=None 且 note 提示无预测留痕;samples>0 且 th.get("reflect") 为真时 note 建议反思,否则 note 正常;ece 与 calibration 仅在 metacognition.calibration 返回 ok 为真时给出,否则为 None;d_meta_trend 恒由 _d_meta_trend(cg) 给出(近 20 条反思的 D_meta 单代理均值,不可用时为 None);
283
+ def _prediction_face(cg):
284
+ """预测校准(第九项):我预测得准吗、该不该反思?
285
+
286
+ 数据源(只读留痕,不新增计算负担):
287
+ · `predict._hit_history` / `predict.dynamic_hit_threshold`
288
+ ← `_prediction.jsonl`(predict_feedback 留痕)
289
+ · `metacognition.calibration` ← evidence_log(verify 留痕)的 ECE
290
+ · `d_meta.compute` / 反思留痕的 `d_meta` ← 边界压力趋势(d_meta_trend,
291
+ **不合成三代理**、不参与 D_task:D_task 与 D_meta 对象不同)
292
+
293
+ 诚实边界:无预测留痕 → ok=False、hit_rate=None(未知即未知);
294
+ ECE 仅在 metacognition 有足够证据时给出,否则 None。绝不编造。
295
+ """
296
+ try:
297
+ from . import predict as _predict
298
+ hist = list(_predict._hit_history(cg))
299
+ th = _predict.dynamic_hit_threshold(cg)
300
+ # P-T-73/74 通道贝叶斯:可信度后验(随样本量向基线收缩,诚实小样本)
301
+ beta = (_predict.channel_posterior(cg) or {}).get("all") or {}
302
+ except Exception: # noqa: BLE001
303
+ hist, th, beta = [], {}, {}
304
+ samples = len(hist)
305
+ hit_rate = (sum(1 for x in hist if x) / samples) if samples else None
306
+ try:
307
+ cal = metacognition.calibration(cg)
308
+ except Exception: # noqa: BLE001
309
+ cal = {}
310
+ meta_trend = _d_meta_trend(cg)
311
+ if samples == 0:
312
+ note = "无预测留痕:先 predict_feedback() 积累命中记录"
313
+ elif th.get("reflect"):
314
+ note = "命中率低于动态阈值:建议反思(D-006)"
315
+ else:
316
+ note = "命中率正常"
317
+ return {
318
+ "ok": samples > 0,
319
+ "samples": samples,
320
+ "hit_rate": None if hit_rate is None else round(hit_rate, 4),
321
+ "beta_mean": beta.get("mean"),
322
+ "beta_ci95": beta.get("ci95"),
323
+ "threshold": th.get("threshold"),
324
+ "reflect": bool(th.get("reflect")),
325
+ "ece": cal.get("ece") if cal.get("ok") else None,
326
+ "calibration": cal.get("verdict") if cal.get("ok") else None,
327
+ "d_meta_trend": meta_trend,
328
+ "note": note,
329
+ }
330
+
331
+
332
+ # 生效条件:对 required 形参 cg 与 window,尝试用 cg.recent_events(limit=int(window), newest_first=False) 取记录(异常时 recs=[]),返回 n=len(recs)、span=[min(ts), max(ts)] if ts else None、roles 角色计数、ptr 为 cg.recent_log 的 basename(缺省 "_recent.jsonl");
333
+ def _recent_summary(cg, window):
334
+ """短期记忆:只做窗口摘要,原文仍留在 _recent.jsonl(薄自我的关键取舍)。"""
335
+ try:
336
+ recs = cg.recent_events(limit=int(window), newest_first=False)
337
+ except Exception:
338
+ recs = []
339
+ ts = [float(r.get("t") or 0.0) for r in recs]
340
+ roles = {}
341
+ for r in recs:
342
+ k = str(r.get("role") or "unknown")
343
+ roles[k] = roles.get(k, 0) + 1
344
+ return {"n": len(recs), "span": [min(ts), max(ts)] if ts else None,
345
+ "roles": roles,
346
+ "ptr": os.path.basename(getattr(cg, "recent_log", "_recent.jsonl"))}
347
+
348
+
349
+ # 生效条件:对 required 形参 cg 与 subject,若 identity.profile(cg, subject) 抛异常则返回 (None, 0);否则返回 (prof.anchor.node_id(缺省 None), len(prof.get("anchors") or []));
350
+ def _identity_ref(cg, subject):
351
+ """身份:只存指针(锚点节点 id),锚点内容仍在 self 层原节点里。"""
352
+ try:
353
+ prof = identity.profile(cg, subject)
354
+ except Exception:
355
+ return None, 0
356
+ anchors = prof.get("anchors") or []
357
+ ref = (prof.get("anchor") or {}).get("node_id")
358
+ return ref, len(anchors)
359
+
360
+
361
+ # 生效条件:对 required 形参 cg 与 subject,遍历 cg.index.nodes 中标签含 TAG_RELATION 或以 RELATION_PREFIX 开头的节点,统计 tags 含 "rel_from:{_slug(subject)}" 的个数为 out、含 "rel_to:{_slug(subject)}" 的个数为 in,返回 {"out": out, "in": inn};
362
+ def _relation_counts(cg, subject):
363
+ """关系:从索引里的关系节点统计出/入度(不读文件正文)。"""
364
+ slug = _slug(subject)
365
+ nodes = ((getattr(cg, "index", None) or {}).get("nodes") or {})
366
+ out = inn = 0
367
+ for nid, e in list(nodes.items()):
368
+ tags = set(e.get("tags") or [])
369
+ if TAG_RELATION not in tags and not nid.startswith(RELATION_PREFIX):
370
+ continue
371
+ if f"rel_from:{slug}" in tags:
372
+ out += 1
373
+ if f"rel_to:{slug}" in tags:
374
+ inn += 1
375
+ return {"out": out, "in": inn}
376
+
377
+
378
+ # 生效条件:对 required 形参 dimensions(假值时按空字典),只保留键 str(dim).strip().lower() 属于模块常量 DIMENSIONS 且 val 非 None 的维度;val 为 list/tuple/set 时展开,否则包装为单元素;过滤空字符串并去重后放入 out,返回 out;
379
+ def _normalize_dimensions(dimensions):
380
+ """维度入参 → {dim: [value...]}(只保留已知维度)。"""
381
+ out = {}
382
+ for dim, val in (dimensions or {}).items():
383
+ d = str(dim).strip().lower()
384
+ if d not in DIMENSIONS or val is None:
385
+ continue
386
+ vals = val if isinstance(val, (list, tuple, set)) else [val]
387
+ clean = [str(v).strip() for v in vals if str(v).strip()]
388
+ if clean:
389
+ out.setdefault(d, [])
390
+ for v in clean:
391
+ if v not in out[d]:
392
+ out[d].append(v)
393
+ return out
394
+
395
+
396
+ # 生效条件:对 required 形参 cg、subject、window、importance、important_refs、dimensions、links、old,聚合 trace/trust/recent/identity/relations/prediction 等生成薄状态 dict;emotion 与 affect 仅在对应 trace/trust ok 且二阶值为非 None 时取 emotion,否则为 "unknown";importance 为 None 时回落 old.importance_self 再回落 1.0;important_refs 为 None 时回落 old.important_refs;dimensions 归一化后为空则回落 old.dimensions,并自动追加 trust band 与今日时间;links 为 None 时回落 old.state_links;
397
+ def _derive(cg, subject, window, importance, important_refs, dimensions,
398
+ links, old):
399
+ """聚合九项自我信息 → 薄状态(纯读,不写盘)。"""
400
+ tr = metacognition.trace(cg, window=max(2, int(window)))
401
+ tt = metacognition.trust(cg, window=max(3, int(window)))
402
+ d2 = tr.get("d2") if tr.get("ok") else None
403
+ d2t = tt.get("d2") if tt.get("ok") else None
404
+ # 派生自洽:无数据即 unknown,绝不编造
405
+ emotion = tr.get("emotion") if (tr.get("ok") and d2 is not None) else "unknown"
406
+ affect = tt.get("emotion") if (tt.get("ok") and d2t is not None) else "unknown"
407
+
408
+ information_gap = {"ok": bool(tr.get("ok")), "n": tr.get("n", 0),
409
+ "d_current": tr.get("d_current"), "d1": tr.get("d1"),
410
+ "d2": d2, "trend": tr.get("trend")}
411
+ trust = {"ok": bool(tt.get("ok")), "n_events": tt.get("n_events", 0),
412
+ "p_gap": tt.get("p_gap"), "p_trust": tt.get("p_trust"),
413
+ "d1": tt.get("d1"), "d2t": d2t,
414
+ "band": trust_band(tt.get("p_trust"))}
415
+ short_term = _recent_summary(cg, window)
416
+ identity_ref, n_anchors = _identity_ref(cg, subject)
417
+ relations = _relation_counts(cg, subject)
418
+
419
+ if importance is None:
420
+ importance = (old or {}).get("importance_self")
421
+ importance = 1.0 if importance is None else float(importance)
422
+ if important_refs is None:
423
+ important_refs = list((old or {}).get("important_refs") or [])
424
+ important_refs = [str(x) for x in important_refs if str(x).strip()]
425
+
426
+ dims = _normalize_dimensions(dimensions)
427
+ if not dims:
428
+ dims = dict((old or {}).get("dimensions") or {})
429
+ # 信任档与时间桶自动入索引(用户点名的「具体信任」「具体时间」)
430
+ if trust["band"]:
431
+ dims.setdefault("trust", [])
432
+ if trust["band"] not in dims["trust"]:
433
+ dims["trust"].append(trust["band"])
434
+ today = time.strftime("%Y-%m-%d", time.localtime())
435
+ dims.setdefault("time", [])
436
+ if today not in dims["time"]:
437
+ dims["time"].append(today)
438
+
439
+ if links is None:
440
+ links = list((old or {}).get("state_links") or [])
441
+
442
+ return {"subject": subject, "information_gap": information_gap,
443
+ "trust": trust, "emotion": emotion, "affect": affect,
444
+ "short_term": short_term, "importance_self": importance,
445
+ "important_refs": important_refs, "identity_ref": identity_ref,
446
+ "identity_anchors": n_anchors, "relations": relations,
447
+ "prediction": _prediction_face(cg),
448
+ "dimensions": dims,
449
+ "state_links": [str(x) for x in links if str(x).strip()]}
450
+
451
+
452
+ # ---------------------------------------------------------------- 写卡
453
+
454
+ # 生效条件:对 required 形参 state,读取其 information_gap、trust、short_term、prediction、dimensions 等字段,渲染并返回末尾带换行的状态卡正文(含 D_meta 边界压力趋势一行:prediction.d_meta_trend 缺失时显示 None);span 为空时显示(无),角色为空时显示(无);
455
+ def _render(state):
456
+ """状态卡正文:人类可读,且与 frontmatter 字段一一对应。"""
457
+ ig, tt = state["information_gap"], state["trust"]
458
+ st = state["short_term"]
459
+ pd = state.get("prediction") or {}
460
+ dims = state["dimensions"]
461
+ span = st.get("span")
462
+ span_txt = f"{_iso(span[0])} ~ {_iso(span[1])}" if span else "(无)"
463
+ roles = "、".join(f"{k}:{v}" for k, v in
464
+ sorted((st.get("roles") or {}).items())) or "(无)"
465
+ lines = [
466
+ f"# 自我状态卡 · {state['subject']}",
467
+ f"# 更新时间:{_iso(state.get('state_ts'))}"
468
+ f"(version={state.get('state_version')})",
469
+ f"# 信息差:D={ig.get('d_current')} dD/dt={ig.get('d1')} "
470
+ f"d^2D/dt^2={ig.get('d2')} → 情绪={state['emotion']}"
471
+ f"(趋势={ig.get('trend')})",
472
+ f"# 信任:P_gap={tt.get('p_gap')} P_trust={tt.get('p_trust')} "
473
+ f"d^2T/dt^2={tt.get('d2t')} → 情感={state['affect']}"
474
+ f"(档={tt.get('band')})",
475
+ f"# 短期记忆:{st.get('n')} 条({span_txt})角色 {roles};"
476
+ f"原文见 {st.get('ptr')}",
477
+ f"# 重要性:self={state['importance_self']},"
478
+ f"显式重要 {len(state.get('important_refs') or [])} 条",
479
+ f"# 身份:锚点 {state.get('identity_ref') or '(未设)'}"
480
+ f"(共 {state.get('identity_anchors')} 条)",
481
+ f"# 关系:出 {state['relations'].get('out')} / "
482
+ f"入 {state['relations'].get('in')}",
483
+ f"# 预测:命中率={pd.get('hit_rate')}(样本 {pd.get('samples')})"
484
+ f"阈值={pd.get('threshold')} 反思={'是' if pd.get('reflect') else '否'}"
485
+ f";后验可信度={pd.get('beta_mean')}"
486
+ f"(95%CI {pd.get('beta_ci95')})"
487
+ f";ECE={pd.get('ece')}({pd.get('calibration')})",
488
+ f"# D_meta:边界压力趋势(unmodeled_growth 均值)={pd.get('d_meta_trend')}"
489
+ f"(三代理分别观测、不合成单值,不参与 D_task)",
490
+ "# 索引:" + ";".join(
491
+ f"{d}={','.join(dims.get(d) or []) or '-'}" for d in DIMENSIONS),
492
+ "# 说明:本卡是薄自我——只登记当前值与指针;具体任务/人物/会话/"
493
+ "时间/信任的细节由认知图按上述索引连接,不在此搬运。",
494
+ ]
495
+ return "\n".join(lines) + "\n"
496
+
497
+
498
+ # 生效条件:当 cg 可用时,refresh 以 subject(默认 DEFAULT_SUBJECT)和 window(默认 RECENT_WINDOW)聚合九项;若留痕末条存在且状态卡缺失或 state_version/state_hash 与留痕末条不一致,则按留痕重建元数据;若 force 为假且未触发重建且旧 state_hash 等于新指纹,返回 changed=False 的幂等跳过;否则若留痕末条存在且状态卡 state_hash(状态卡缺失时视为 None)与留痕末条不同,则 strict 为真时返回 ok=False、error='chain_broken',strict 为假时以留痕末条 hash 修复 prev_hash 并写入,最终写入时返回 changed=True 及新 state_version/state_hash;
499
+ def refresh(cg, subject=DEFAULT_SUBJECT, window=RECENT_WINDOW, importance=None,
500
+ important_refs=None, dimensions=None, links=None,
501
+ actor="self_state", force=False, strict=False, session=None):
502
+ """刷新自我状态卡(幂等):聚合九项 → 写卡 + 版本链留痕。
503
+
504
+ dimensions: {"task": "...", "person": "...", "session": "...",
505
+ "time": "...", "trust": "..."}(值可为列表)
506
+ links: 指向具体详情节点的边(认知图连接,而非内容复制)
507
+ strict: 版本链断裂时是否拒绝写入(默认修复并记录 chain_repaired)
508
+ session: 会话归因(嵌套身份):并入 session 维度,不覆盖显式声明值
509
+ """
510
+ raw = snapshot(cg, subject)
511
+ tail = _last_log(cg, subject=subject)
512
+ # 卡缺失 / 被绕过 refresh 破坏(版本或 hash 对不上留痕)→ 以 append-only
513
+ # 留痕为准恢复元数据(维度索引、重要性、边)。留痕是权威记录。
514
+ old, rebuild = raw, False
515
+ if tail and (raw is None or raw.get("state_version") is None
516
+ or raw.get("state_hash") != tail.get("state_hash")):
517
+ rebuild = True
518
+ old = {"state_version": tail.get("version"),
519
+ "state_hash": tail.get("state_hash"),
520
+ "dimensions": tail.get("dimensions"),
521
+ "importance_self": tail.get("importance_self"),
522
+ "important_refs": tail.get("important_refs"),
523
+ "state_links": tail.get("state_links"),
524
+ "identity_ref": tail.get("identity_ref")}
525
+ # 会话归因:把本会话并入 session 维度(不覆盖调用方显式声明的维度值)。
526
+ dims_in = dict(dimensions or {})
527
+ if session:
528
+ vals = dims_in.get("session") or []
529
+ vals = list(vals) if isinstance(vals, (list, tuple, set)) else [vals]
530
+ vals = [str(v) for v in vals if str(v).strip()]
531
+ if str(session) not in vals:
532
+ vals.append(str(session))
533
+ dims_in["session"] = vals
534
+ state = _derive(cg, subject, window=window, importance=importance,
535
+ important_refs=important_refs, dimensions=dims_in,
536
+ links=links, old=old)
537
+ card_v = int((old or {}).get("state_version") or 0)
538
+ log_v = int(tail.get("version") or 0) if tail else 0
539
+ version = max(card_v, log_v) + 1
540
+ state["state_version"] = version
541
+ fp = _fingerprint(state)
542
+ if not rebuild and old and old.get("state_hash") == fp and not force:
543
+ return {"ok": True, "changed": False, "subject": subject,
544
+ "node_id": state_node_id(subject), "state": state,
545
+ "note": "状态未变化,跳过写入(幂等)"}
546
+
547
+ # 版本链:prev 必须等于上一条留痕的 hash
548
+ prev_hash = (raw or {}).get("state_hash")
549
+ chain_issue = None
550
+ if tail is not None and prev_hash != tail.get("state_hash"):
551
+ chain_issue = {
552
+ "code": "chain_repaired",
553
+ "why": f"prev_state_hash={prev_hash} 与留痕末条 "
554
+ f"{tail.get('state_hash')} 不一致"}
555
+ if strict:
556
+ return {"ok": False, "changed": False, "subject": subject,
557
+ "error": "chain_broken", "detail": chain_issue}
558
+ prev_hash = tail.get("state_hash") # 以留痕为准修复
559
+ if raw is None and tail is not None:
560
+ chain_issue = {"code": "state_rebuilt",
561
+ "why": "状态卡缺失但留痕存在,按留痕续链重建"}
562
+ prev_hash = tail.get("state_hash")
563
+
564
+ state["prev_state_hash"] = prev_hash
565
+ state["state_ts"] = time.time()
566
+ state["state_hash"] = _fingerprint(state)
567
+
568
+ tags = [TAG_STATE, f"state_subject:{_slug(subject)}"]
569
+ for d in DIMENSIONS:
570
+ for v in (state["dimensions"].get(d) or []):
571
+ t = dim_tag(d, v)
572
+ if t not in tags:
573
+ tags.append(t)
574
+ edges = [{"target": t, "relation_type": STATE_LINK_TYPE,
575
+ "weight": 0.6} for t in state["state_links"]]
576
+
577
+ nid = state_node_id(subject)
578
+ # 2026-10-18:补条件空间四维。这里不是"推断内容",是**自述产生过程**——
579
+ # 状态卡由系统自身周期刷新产生,故观测位置/工具/存在约束都可如实声明。
580
+ # 此前缺这三维,导致 self 层状态卡(importance 可达 1.0)判 legacy_blindspot:
581
+ # 一张"自我状态卡"却是依据不明,与它 importance 1.0 的定位自相矛盾。
582
+ cg.add(nid, _render(state), layer="self", tags=tags, edges=edges,
583
+ condition_space={
584
+ "observation_position": "self:" + str(subject),
585
+ "observation_tool": "self_state.refresh(周期快照)",
586
+ "existence_constraint": "库内可写且状态卡非空",
587
+ },
588
+ importance=float(state["importance_self"]), confidence=0.9,
589
+ verification_basis="data", override=True, actor=actor,
590
+ self_state=True, state_subject=subject, state_version=version,
591
+ state_hash=state["state_hash"], prev_state_hash=prev_hash,
592
+ state_ts=state["state_ts"],
593
+ information_gap=state["information_gap"], trust=state["trust"],
594
+ emotion=state["emotion"], affect=state["affect"],
595
+ short_term=state["short_term"],
596
+ importance_self=state["importance_self"],
597
+ important_refs=state["important_refs"],
598
+ identity_ref=state["identity_ref"], relations=state["relations"],
599
+ prediction=state["prediction"],
600
+ dimensions=state["dimensions"], state_links=state["state_links"])
601
+
602
+ _append_log(cg, {
603
+ "t": state["state_ts"], "subject": subject, "node_id": nid,
604
+ "version": version, "state_hash": state["state_hash"],
605
+ "prev_state_hash": prev_hash, "actor": actor,
606
+ "d_current": state["information_gap"].get("d_current"),
607
+ "d1": state["information_gap"].get("d1"),
608
+ "d2": state["information_gap"].get("d2"),
609
+ "emotion": state["emotion"],
610
+ "p_gap": state["trust"].get("p_gap"),
611
+ "p_trust": state["trust"].get("p_trust"),
612
+ "d2t": state["trust"].get("d2t"), "affect": state["affect"],
613
+ "importance_self": state["importance_self"],
614
+ "important_refs": state["important_refs"],
615
+ "state_links": state["state_links"],
616
+ "recent_n": state["short_term"].get("n"),
617
+ "identity_ref": state["identity_ref"],
618
+ "relations": state["relations"],
619
+ "prediction_hit_rate": (state.get("prediction") or {}).get("hit_rate"),
620
+ "prediction_samples": (state.get("prediction") or {}).get("samples"),
621
+ "prediction_reflect": (state.get("prediction") or {}).get("reflect"),
622
+ "prediction_beta_mean": (state.get("prediction") or {}).get("beta_mean"),
623
+ "dimensions": state["dimensions"], "issue": chain_issue})
624
+ return {"ok": True, "changed": True, "subject": subject, "node_id": nid,
625
+ "state_version": version, "state_hash": state["state_hash"],
626
+ "prev_state_hash": prev_hash, "state": state,
627
+ "issue": chain_issue}
628
+
629
+
630
+ # ---------------------------------------------------------------- 关系
631
+
632
+ # 生效条件:对 required 形参 cg、frm、to 与可选 relation_type/strength/reciprocal,若 _slug(frm) == _slug(to) 返回 {"ok": False, "error": "self_loop", ...};否则 relation_type 不在模块常量 RELATION_TYPES 时回落 "other",strength 的 float 失败时 w=0.5、成功时夹在 0.0~1.0,写入关系节点,reciprocal 为真时同时写反向,返回 ok=True 及 written 列表;
633
+ def relate(cg, frm, to, relation_type="collaborator", strength=0.5,
634
+ condition="", note="", reciprocal=False, actor="self_state"):
635
+ """写一条有向关系(自我 ↔ 其他智能)。reciprocal=True 时同时写反向。"""
636
+ rt = str(relation_type or "other").strip().lower()
637
+ if rt not in RELATION_TYPES:
638
+ rt = "other"
639
+ if _slug(frm) == _slug(to):
640
+ return {"ok": False, "error": "self_loop",
641
+ "detail": "关系两端不能是同一主体(自环)"}
642
+ try:
643
+ w = max(0.0, min(1.0, float(strength)))
644
+ except (TypeError, ValueError):
645
+ w = 0.5
646
+ written = []
647
+ for a, b in ((frm, to), (to, frm)) if reciprocal else ((frm, to),):
648
+ nid = relation_node_id(a, b)
649
+ tags = [TAG_RELATION, f"rel_from:{_slug(a)}", f"rel_to:{_slug(b)}",
650
+ f"relation:{rt}", f"person:{_slug(b)}",
651
+ f"state_subject:{_slug(a)}"]
652
+ body = (f"# 关系:{a} → {b}\n"
653
+ f"# 类型:{rt}\n"
654
+ f"# 强度:{w}\n"
655
+ f"# 条件:{condition or '(未声明)'}\n"
656
+ f"# 备注:{note or '(无)'}\n")
657
+ # 2026-10-18:关系节点同样自述产生过程(由 relate 显式建立)
658
+ cg.add(nid, body, layer="self", tags=tags,
659
+ condition_space={
660
+ "observation_position": "self:%s↔%s" % (a, b),
661
+ "observation_tool": "self_state.relate(显式建边)",
662
+ "existence_constraint": condition or "关系已显式声明",
663
+ },
664
+ edges=[{"target": b, "relation_type": rt, "weight": w,
665
+ "condition": condition}],
666
+ importance=w, confidence=0.8, verification_basis="other",
667
+ override=True, actor=actor,
668
+ self_relation=True, rel_from=a, rel_to=b,
669
+ relation_type=rt, strength=w, condition=condition,
670
+ reciprocal=bool(reciprocal))
671
+ written.append(nid)
672
+ return {"ok": True, "written": written, "from": frm, "to": to,
673
+ "relation_type": rt, "strength": w,
674
+ "reciprocal": bool(reciprocal)}
675
+
676
+
677
+ # 生效条件:对 required 形参 cg 与可选 subject/direction,遍历 cg.index.nodes 中标签含 TAG_RELATION 或以 RELATION_PREFIX 开头的节点;subject 为真值时按 _slug(subject) 过滤,direction 为 "out" 只保留出边、"in" 只保留入边、"both" 保留出或入边、其他 direction 不做方向过滤;返回按 strength(importance)降序、再按 node_id 升序排序的关系列表 out;
678
+ def relations(cg, subject=None, direction="both"):
679
+ """列出关系节点(按 subject 过滤出/入)。"""
680
+ nodes = ((getattr(cg, "index", None) or {}).get("nodes") or {})
681
+ slug = _slug(subject) if subject else None
682
+ out = []
683
+ for nid, e in list(nodes.items()):
684
+ tags = set(e.get("tags") or [])
685
+ if TAG_RELATION not in tags and not nid.startswith(RELATION_PREFIX):
686
+ continue
687
+ if slug:
688
+ is_out = f"rel_from:{slug}" in tags
689
+ is_in = f"rel_to:{slug}" in tags
690
+ if direction == "out" and not is_out:
691
+ continue
692
+ if direction == "in" and not is_in:
693
+ continue
694
+ if direction == "both" and not (is_out or is_in):
695
+ continue
696
+ rels = [t[len("relation:"):] for t in tags if t.startswith("relation:")]
697
+ frm = [t[len("rel_from:"):] for t in tags if t.startswith("rel_from:")]
698
+ to = [t[len("rel_to:"):] for t in tags if t.startswith("rel_to:")]
699
+ out.append({"node_id": nid, "from": frm[0] if frm else None,
700
+ "to": to[0] if to else None,
701
+ "relation_type": rels[0] if rels else None,
702
+ "strength": e.get("importance"),
703
+ "layer": e.get("layer")})
704
+ out.sort(key=lambda x: (-float(x.get("strength") or 0), x["node_id"]))
705
+ return out
706
+
707
+
708
+ # ---------------------------------------------------------------- 索引
709
+
710
+ # 生效条件:对 required 形参 cg、dim、value 与可选 limit/with_content,若 dim 小写去空白后不在模块常量 DIMENSIONS 中,返回 {"ok": False, "error": "unknown_dimension", "allowed": list(DIMENSIONS)};否则匹配 cg.index.nodes 中 tags 含 dim_tag(dim, value) 的节点,按 importance 降序、created_at 降序排序,取 hits[:int(limit)](limit=0 时切片为空),with_content 为真时附加节点 content 前 400 字符,返回 ok=True 及 count/items;
711
+ def index(cg, dim, value, limit=50, with_content=False):
712
+ """按五维索引反查具体详情节点(认知图连接,不是内容搬运)。"""
713
+ d = str(dim or "").strip().lower()
714
+ if d not in DIMENSIONS:
715
+ return {"ok": False, "error": "unknown_dimension",
716
+ "allowed": list(DIMENSIONS)}
717
+ tag = dim_tag(d, value)
718
+ nodes = ((getattr(cg, "index", None) or {}).get("nodes") or {})
719
+ hits = [(nid, e) for nid, e in list(nodes.items())
720
+ if tag in (e.get("tags") or [])]
721
+ hits.sort(key=lambda kv: (-float(kv[1].get("importance") or 0),
722
+ -float(kv[1].get("created_at") or 0),
723
+ str(kv[0] or "")))
724
+ items = []
725
+ for nid, e in hits[:int(limit)]:
726
+ item = {"node_id": nid, "layer": e.get("layer"),
727
+ "importance": e.get("importance"), "tags": e.get("tags"),
728
+ "path": e.get("path")}
729
+ if with_content:
730
+ node = _node(cg, nid) or {}
731
+ item["content"] = (node.get("content") or "")[:400]
732
+ items.append(item)
733
+ return {"ok": True, "dimension": d, "value": str(value), "tag": tag,
734
+ "count": len(hits), "items": items}
735
+
736
+
737
+ # 生效条件:对 required 形参 cg 与 subject(未传时 DEFAULT_SUBJECT),若 snapshot(cg, subject) 返回假值则返回 {"ok": False, "error": "no_state", "subject": subject};否则返回 {"ok": True, "subject": subject, "dimensions": st.get("dimensions") or {}};
738
+ def dimensions(cg, subject=DEFAULT_SUBJECT):
739
+ """状态卡登记的五维索引标签。"""
740
+ st = snapshot(cg, subject)
741
+ if not st:
742
+ return {"ok": False, "error": "no_state", "subject": subject}
743
+ return {"ok": True, "subject": subject,
744
+ "dimensions": st.get("dimensions") or {}}
745
+
746
+
747
+ # ---------------------------------------------------------------- 审计
748
+
749
+ # 生效条件:对 required 形参 code、severity、why,返回含这三个键并合并 **extra 的 dict;
750
+ def _issue(code, severity, why, **extra):
751
+ d = {"code": code, "severity": severity, "why": why}
752
+ d.update(extra)
753
+ return d
754
+
755
+
756
+ # 生效条件:当 cg 可用时,audit 对 subject(默认 DEFAULT_SUBJECT)和 window(默认 RECENT_WINDOW)执行一致性审计;若对应状态卡不存在则返回 ok=False、verdict='absent'(含已收集的 issues);否则基于留痕历史与现算值收集 issues,按有无 error 返回 verdict='broken'、无 error 但有 warn 返回 'drift'、均无返回 'consistent',且 ok 为无 error;
757
+ def audit(cg, subject=DEFAULT_SUBJECT, window=RECENT_WINDOW):
758
+ """自我信息一致性审计:全部判定可重算(不依赖人的判断)。"""
759
+ from . import protect as _protect
760
+ issues = []
761
+ nid = state_node_id(subject)
762
+ nodes = ((getattr(cg, "index", None) or {}).get("nodes") or {})
763
+ st = snapshot(cg, subject)
764
+
765
+ # 1 单例:同 subject 的状态卡只能有一张
766
+ slug = _slug(subject)
767
+ cards = [n for n, e in list(nodes.items())
768
+ if TAG_STATE in (e.get("tags") or [])
769
+ and f"state_subject:{slug}" in (e.get("tags") or [])]
770
+ if len(cards) > 1:
771
+ issues.append(_issue("duplicate_state", "error",
772
+ f"同一 subject 有 {len(cards)} 张状态卡",
773
+ nodes=cards))
774
+ if st is None:
775
+ issues.append(_issue("missing_state", "warn",
776
+ "状态卡不存在:先 refresh() 建立", node_id=nid))
777
+ return {"ok": False, "verdict": "absent", "subject": subject,
778
+ "n_issues": len(issues), "issues": issues,
779
+ "checked_at": time.time()}
780
+
781
+ ordered = list(reversed(history(cg, limit=0, subject=subject)))
782
+
783
+ # 2 版本链:version 连续 +1,prev 必须等于上一条 hash
784
+ for i in range(1, len(ordered)):
785
+ p, c = ordered[i - 1], ordered[i]
786
+ if c.get("version") != (p.get("version") or 0) + 1:
787
+ issues.append(_issue(
788
+ "version_gap", "error",
789
+ f"版本不连续:{p.get('version')} → {c.get('version')}",
790
+ at=c.get("t")))
791
+ if c.get("prev_state_hash") != p.get("state_hash"):
792
+ issues.append(_issue(
793
+ "chain_broken", "error",
794
+ f"留痕断链:prev={c.get('prev_state_hash')} ≠ 上一条 "
795
+ f"{p.get('state_hash')}", at=c.get("t")))
796
+ if float(c.get("t") or 0) < float(p.get("t") or 0):
797
+ issues.append(_issue("time_regression", "error",
798
+ "留痕时间戳回退", at=c.get("t")))
799
+
800
+ # 3 留痕对齐:卡上的 hash 必须等于留痕末条
801
+ if ordered:
802
+ tail = ordered[-1]
803
+ if st.get("state_hash") != tail.get("state_hash"):
804
+ issues.append(_issue(
805
+ "log_tail_mismatch", "error",
806
+ f"卡 hash={st.get('state_hash')} ≠ 留痕末条 "
807
+ f"{tail.get('state_hash')}(卡被绕过 refresh 改过?)",
808
+ node_id=nid))
809
+
810
+ # 4 派生自洽:无数据时必须 unknown(不许编造)
811
+ ig = st.get("information_gap") or {}
812
+ tt = st.get("trust") or {}
813
+ if ig.get("d2") is None and st.get("emotion") not in (None, "unknown"):
814
+ issues.append(_issue("fabricated_emotion", "error",
815
+ f"d^2D/dt^2 缺失但 emotion={st.get('emotion')}"))
816
+ if tt.get("d2t") is None and st.get("affect") not in (None, "unknown"):
817
+ issues.append(_issue("fabricated_affect", "error",
818
+ f"d^2T/dt^2 缺失但 affect={st.get('affect')}"))
819
+
820
+ # 5 跨面一致:与 metacognition 现算值比对(drift)
821
+ now = _derive(cg, subject, window=window, importance=None,
822
+ important_refs=None, dimensions=None, links=None, old=None)
823
+ for name, old_v, new_v in (
824
+ ("d_current", ig.get("d_current"),
825
+ now["information_gap"].get("d_current")),
826
+ ("d2", ig.get("d2"), now["information_gap"].get("d2")),
827
+ ("p_trust", tt.get("p_trust"), now["trust"].get("p_trust")),
828
+ ("d2t", tt.get("d2t"), now["trust"].get("d2t"))):
829
+ if old_v is None and new_v is None:
830
+ continue
831
+ try:
832
+ if old_v is None or new_v is None or \
833
+ abs(float(old_v) - float(new_v)) > DRIFT_TOL:
834
+ issues.append(_issue(
835
+ "drift", "warn",
836
+ f"{name} 卡值={old_v} 现算={new_v}(容差 {DRIFT_TOL})",
837
+ field=name))
838
+ except (TypeError, ValueError):
839
+ issues.append(_issue("drift", "warn",
840
+ f"{name} 不可比较:{old_v} vs {new_v}",
841
+ field=name))
842
+
843
+ # 5b 预测面漂移:预测能力(命中率)随 predict_feedback 演化;卡值过时即为
844
+ # 漂移——这是「自我模型是否跟上自身预测表现」的可重算判定。
845
+ pd_old = st.get("prediction") or {}
846
+ pd_new = now.get("prediction") or {}
847
+ o_hr, n_hr = pd_old.get("hit_rate"), pd_new.get("hit_rate")
848
+ if not (o_hr is None and n_hr is None):
849
+ try:
850
+ if o_hr is None or n_hr is None or \
851
+ abs(float(o_hr) - float(n_hr)) > DRIFT_TOL:
852
+ issues.append(_issue(
853
+ "prediction_drift", "warn",
854
+ f"预测命中率 卡值={o_hr} 现算={n_hr}(容差 {DRIFT_TOL})",
855
+ field="hit_rate"))
856
+ except (TypeError, ValueError):
857
+ issues.append(_issue("prediction_drift", "warn",
858
+ f"预测命中率不可比较:{o_hr} vs {n_hr}",
859
+ field="hit_rate"))
860
+
861
+ # 6 身份唯一:identity_ref 必须指向存在的锚点
862
+ ref = st.get("identity_ref")
863
+ if not ref:
864
+ issues.append(_issue("identity_missing", "info",
865
+ "identity_ref 为空:先在 self 层写身份锚点"))
866
+ elif ref not in nodes:
867
+ issues.append(_issue("identity_dangling", "error",
868
+ f"identity_ref={ref} 指向不存在的节点", ref=ref))
869
+
870
+ # 7 关系完整:禁止自环、禁止同一有向对重复
871
+ seen_rel = {}
872
+ for rel in relations(cg, subject=None):
873
+ nid_r = rel["node_id"]
874
+ if rel["from"] == rel["to"]:
875
+ issues.append(_issue("relation_self_loop", "error",
876
+ f"关系自环:{rel['from']}", node_id=nid_r))
877
+ key = (rel["from"], rel["to"])
878
+ if key in seen_rel:
879
+ issues.append(_issue("duplicate_relation", "error",
880
+ f"重复关系 {key}", node_id=nid_r))
881
+ seen_rel[key] = nid_r
882
+
883
+ # 8 保护一致:状态卡必须可覆盖(否则自我认知被永久冻结)且不可遗忘
884
+ try:
885
+ imm, why = _protect.is_immutable(cg, nid)
886
+ if imm:
887
+ issues.append(_issue("protection_locked", "error",
888
+ f"状态卡不可覆盖:{why}(自我状态将无法演化)"))
889
+ pro, _ = _protect.is_protected(cg, nid)
890
+ if not pro:
891
+ issues.append(_issue("protection_missing", "warn",
892
+ "状态卡未受保护:自我信息可能被遗忘"))
893
+ except Exception as exc: # pragma: no cover
894
+ issues.append(_issue("protection_check_failed", "warn", str(exc)))
895
+
896
+ # 9 索引不悬空:维度标签指向的详情节点必须存在
897
+ dims = st.get("dimensions") or {}
898
+ for d, vals in dims.items():
899
+ if d not in DIMENSIONS:
900
+ issues.append(_issue("unknown_dimension", "warn",
901
+ f"未知索引维度 {d}"))
902
+ continue
903
+ for v in (vals or []):
904
+ tag = dim_tag(d, v)
905
+ holders = [n for n, e in list(nodes.items())
906
+ if tag in (e.get("tags") or [])]
907
+ if not holders:
908
+ issues.append(_issue("dimension_orphan", "warn",
909
+ f"索引 {tag} 无对应节点(悬空索引)",
910
+ dimension=d, value=v))
911
+
912
+ # 10 新鲜度
913
+ try:
914
+ age = time.time() - float(st.get("state_ts") or 0)
915
+ if age > STALE_AFTER:
916
+ issues.append(_issue("stale", "warn",
917
+ f"状态卡 {age / 3600:.1f} 小时未刷新"))
918
+ except (TypeError, ValueError):
919
+ issues.append(_issue("stale", "warn", "state_ts 不可解析"))
920
+
921
+ errors = [i for i in issues if i["severity"] == "error"]
922
+ warns = [i for i in issues if i["severity"] == "warn"]
923
+ verdict = "broken" if errors else ("drift" if warns else "consistent")
924
+ return {"ok": not errors, "verdict": verdict, "subject": subject,
925
+ "node_id": nid, "n_issues": len(issues),
926
+ "n_errors": len(errors), "issues": issues,
927
+ "state_version": st.get("state_version"),
928
+ "state_hash": st.get("state_hash"), "checked_at": time.time()}
929
+
930
+
931
+ # ---------------------------------------------------------------- 加载 / 概览
932
+
933
+ # 生效条件:对 required 形参 cg 与可选 subject/window/auto_refresh/actor,先取 snapshot(cg, subject);若 st 为 None 且 auto_refresh 为真则 refresh 后重新 snapshot;若 st 非 None 且 auto_refresh 为真且 st.state_ts 的年龄 > 模块常量 STALE_AFTER 则 refresh 后重新 snapshot;然后取 relations、history(limit=5, subject)、dimensions,返回 ok=st is not None 及这些字段;
934
+ def bootstrap(cg, subject=DEFAULT_SUBJECT, window=RECENT_WINDOW,
935
+ auto_refresh=True, actor="bootstrap"):
936
+ """会话启动:加载自我状态卡 + 关系 + 最近留痕 + 索引概览。
937
+
938
+ 这是「跨会话自动加载自我」的入口:self 层薄卡 + 认知图连接。
939
+ """
940
+ st = snapshot(cg, subject)
941
+ if st is None and auto_refresh:
942
+ refresh(cg, subject, window=window, actor=actor)
943
+ st = snapshot(cg, subject)
944
+ elif st is not None and auto_refresh:
945
+ # 只在漂移或过期时刷新,避免每次启动都写盘
946
+ try:
947
+ age = time.time() - float(st.get("state_ts") or 0)
948
+ except (TypeError, ValueError):
949
+ age = STALE_AFTER + 1
950
+ if age > STALE_AFTER:
951
+ refresh(cg, subject, window=window, actor=actor)
952
+ st = snapshot(cg, subject)
953
+ rels = relations(cg, subject=subject)
954
+ return {"ok": st is not None, "subject": subject, "state": st,
955
+ "relations": rels, "relations_count": len(rels),
956
+ "recent_states": history(cg, limit=5, subject=subject),
957
+ "dimensions": (st or {}).get("dimensions") or {},
958
+ "loaded_at": time.time()}
959
+
960
+
961
+ # 生效条件:对 required 形参 cg、out、st、session,若 session 为假值直接返回 out;否则写入 out["session"]=str(session)、out["session_registered"]=bool(s in st.dimensions.session 列表)、out["session_refs"](调用 index(cg, "session", s, limit=20) 的结果;异常时写入 count=0、degraded=True),返回 out;
962
+ def _with_session_slice(cg, out, st, session):
963
+ """给 summary 结果补「本会话切片」(薄卡 + 富索引,不改单例语义)。
964
+
965
+ · session_registered —— 本会话是否已登记在该状态卡的 session 维度上;
966
+ · session_refs —— 该维度反查到的详情节点指针(不搬运内容)。
967
+ """
968
+ if not session:
969
+ return out
970
+ s = str(session)
971
+ out["session"] = s
972
+ dims = (st or {}).get("dimensions") or {}
973
+ out["session_registered"] = bool(s in (dims.get("session") or []))
974
+ try:
975
+ res = index(cg, "session", s, limit=20)
976
+ out["session_refs"] = {"count": res.get("count", 0),
977
+ "items": res.get("items", [])}
978
+ except Exception: # noqa: BLE001
979
+ out["session_refs"] = {"count": 0, "items": [], "degraded": True}
980
+ return out
981
+
982
+
983
+ # 生效条件:对 required 形参 cg 与可选 subject/session,取 snapshot(cg, subject);若为假值,经 _with_session_slice 返回 {"ok": False, "subject": subject, "note": "无状态卡"};否则构造含 version、d_current、emotion、p_trust、trust_band、text 等字段的 dict,再经 _with_session_slice 返回;
984
+ def summary(cg, subject=DEFAULT_SUBJECT, session=None):
985
+ """一句话自我状态(供 health / 面板)。
986
+
987
+ session:会话归因切片。**不改变单例卡语义**——只回报「本会话是否已登记在
988
+ 该卡的 session 维度上」以及该维度反查到的详情节点指针(薄卡 + 富索引)。
989
+ """
990
+ st = snapshot(cg, subject)
991
+ if not st:
992
+ return _with_session_slice(cg, {"ok": False, "subject": subject,
993
+ "note": "无状态卡"}, st, session)
994
+ ig, tt = st.get("information_gap") or {}, st.get("trust") or {}
995
+ out = {"ok": True, "subject": subject,
996
+ "version": st.get("state_version"),
997
+ "updated_at": st.get("updated_at"),
998
+ "d_current": ig.get("d_current"), "d2": ig.get("d2"),
999
+ "emotion": st.get("emotion"),
1000
+ "p_trust": tt.get("p_trust"), "d2t": tt.get("d2t"),
1001
+ "affect": st.get("affect"),
1002
+ "trust_band": tt.get("band"),
1003
+ "recent_n": (st.get("short_term") or {}).get("n"),
1004
+ "relations": st.get("relations"),
1005
+ "identity_ref": st.get("identity_ref"),
1006
+ "hit_rate": (st.get("prediction") or {}).get("hit_rate"),
1007
+ "prediction_reflect": (st.get("prediction") or {}).get("reflect"),
1008
+ "text": (f"[{subject}] D={ig.get('d_current')} "
1009
+ f"情绪={st.get('emotion')} P_trust={tt.get('p_trust')} "
1010
+ f"情感={st.get('affect')} "
1011
+ f"短期={((st.get('short_term') or {}).get('n'))}条 "
1012
+ f"v{st.get('state_version')}")}
1013
+ return _with_session_slice(cg, out, st, session)
1014
+
1015
+
1016
+ # 生效条件:无参调用时返回模块自描述 dict,内含模块常量 SCHEMA_VERSION、DEFAULT_SUBJECT、LOG_FILE、DIMENSIONS、TRUST_BANDS、RELATION_TYPES、DRIFT_TOL、STALE_AFTER 等;
1017
+ def catalog():
1018
+ """自描述:九项自我信息 + 五维索引 + 审计规则(供协议对照验证)。"""
1019
+ return {
1020
+ "module": "self_state",
1021
+ "schema": SCHEMA_VERSION,
1022
+ "default_subject": DEFAULT_SUBJECT,
1023
+ "log": LOG_FILE,
1024
+ "principles": [
1025
+ "self 层是薄的:只放状态卡(单例)与关系节点,不搬运内容",
1026
+ "具体细节留在原层,由认知图的标签/边按五维索引连接过来",
1027
+ "不可遗忘 ≠ 不可覆盖:状态卡可演化,身份锚点两者皆禁",
1028
+ ],
1029
+ "self_info": {
1030
+ "information_gap": "D/d1/d2 + emotion ← _reflection.jsonl",
1031
+ "trust": "p_gap/p_trust + d2t/affect ← evidence_log",
1032
+ "emotion": "d^2D/dt^2(信息差二阶)",
1033
+ "affect": "d^2T/dt^2(信任二阶)",
1034
+ "short_term": "窗口摘要 + 指针 ← _recent.jsonl",
1035
+ "importance": "importance_self + important_refs",
1036
+ "identity": "identity_ref → self 层身份锚点",
1037
+ "relations": "self_relation_* 有向关系节点",
1038
+ "prediction": "hit_rate/threshold/reflect + ECE ← _prediction.jsonl",
1039
+ },
1040
+ "dimensions": list(DIMENSIONS),
1041
+ "trust_bands": [b for _lo, b in TRUST_BANDS],
1042
+ "relation_types": list(RELATION_TYPES),
1043
+ "audit_rules": [
1044
+ "duplicate_state", "version_gap", "chain_broken",
1045
+ "time_regression", "log_tail_mismatch", "fabricated_emotion",
1046
+ "fabricated_affect", "drift", "prediction_drift",
1047
+ "identity_missing",
1048
+ "identity_dangling", "relation_self_loop", "duplicate_relation",
1049
+ "protection_locked", "protection_missing", "unknown_dimension",
1050
+ "dimension_orphan", "stale", "missing_state",
1051
+ ],
1052
+ "tolerances": {"drift": DRIFT_TOL, "stale_after_sec": STALE_AFTER},
1053
+ }