dsh-biocore 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (245) hide show
  1. package/README.md +11 -0
  2. package/lib/core-worker.js +268 -0
  3. package/lib/index.js +160 -70
  4. package/lib/modules/autonomy.js +125 -0
  5. package/lib/modules/cache-stats.js +48 -0
  6. package/lib/modules/core-turn.js +24 -6
  7. package/lib/modules/expression-inject.js +0 -10
  8. package/lib/modules/expression-refresh.js +0 -9
  9. package/lib/modules/memory-capture.js +2 -1
  10. package/lib/modules/memory-inject.js +50 -5
  11. package/lib/modules/memory-tools.js +7 -4
  12. package/lib/modules/python-env.js +46 -0
  13. package/lib/modules/safety-gate.js +0 -3
  14. package/lib/modules/series.js +54 -0
  15. package/lib/modules/switch.js +16 -0
  16. package/lib/py-bridge.js +81 -15
  17. package/package.json +1 -1
  18. package/python/biocore_memory/core/config.py +138 -127
  19. package/python/biocore_memory/engine.py +2653 -2476
  20. package/python/biocore_memory/recall/embedding.py +129 -0
  21. package/python/biocore_memory/recall/feedback.py +202 -0
  22. package/python/biocore_model/preference_drift.py +255 -0
  23. package/python/biocore_model/tests/__init__.py +1 -0
  24. package/python/biocore_model/tests/core_mode_ui_check.mjs +63 -0
  25. package/python/biocore_model/tests/core_status_check.mjs +29 -0
  26. package/python/biocore_model/tests/dom_safe_check.mjs +22 -0
  27. package/python/biocore_model/tests/leak_samples_run.py +18 -0
  28. package/python/biocore_model/tests/orb_ring_check.mjs +20 -0
  29. package/python/biocore_model/tests/panel_html_check.mjs +63 -0
  30. package/python/biocore_model/tests/persona_flow_check.mjs +17 -0
  31. package/python/biocore_model/tests/render_guard_check.mjs +19 -0
  32. package/python/biocore_model/tests/switch_groups_check.mjs +94 -0
  33. package/python/biocore_model/tests/tabs_state_check.mjs +24 -0
  34. package/python/biocore_model/tests/test_affective_labor.py +102 -0
  35. package/python/biocore_model/tests/test_appraisal.py +137 -0
  36. package/python/biocore_model/tests/test_appraisal_action.py +55 -0
  37. package/python/biocore_model/tests/test_arch_convergence.py +35 -0
  38. package/python/biocore_model/tests/test_attachment_behavior.py +95 -0
  39. package/python/biocore_model/tests/test_attachment_regulation.py +63 -0
  40. package/python/biocore_model/tests/test_attachment_state.py +29 -0
  41. package/python/biocore_model/tests/test_attribution.py +56 -0
  42. package/python/biocore_model/tests/test_attributor.py +108 -0
  43. package/python/biocore_model/tests/test_autonomic.py +69 -0
  44. package/python/biocore_model/tests/test_autonomy_accumulator.py +84 -0
  45. package/python/biocore_model/tests/test_autonomy_affect.py +62 -0
  46. package/python/biocore_model/tests/test_autonomy_blame.py +44 -0
  47. package/python/biocore_model/tests/test_autonomy_caps.py +29 -0
  48. package/python/biocore_model/tests/test_autonomy_check.py +40 -0
  49. package/python/biocore_model/tests/test_autonomy_clingy.py +41 -0
  50. package/python/biocore_model/tests/test_autonomy_cooldown_selfcontact.py +138 -0
  51. package/python/biocore_model/tests/test_autonomy_frustration.py +42 -0
  52. package/python/biocore_model/tests/test_autonomy_hourly_limit.py +46 -0
  53. package/python/biocore_model/tests/test_autonomy_loop.py +64 -0
  54. package/python/biocore_model/tests/test_autonomy_mode.py +37 -0
  55. package/python/biocore_model/tests/test_autonomy_model.py +60 -0
  56. package/python/biocore_model/tests/test_autonomy_model_v2.py +68 -0
  57. package/python/biocore_model/tests/test_autonomy_module_text.py +104 -0
  58. package/python/biocore_model/tests/test_autonomy_params.py +163 -0
  59. package/python/biocore_model/tests/test_autonomy_reason.py +34 -0
  60. package/python/biocore_model/tests/test_autonomy_self.py +153 -0
  61. package/python/biocore_model/tests/test_autonomy_send_gate.py +38 -0
  62. package/python/biocore_model/tests/test_autonomy_silence.py +37 -0
  63. package/python/biocore_model/tests/test_autonomy_status.py +35 -0
  64. package/python/biocore_model/tests/test_autonomy_test_trigger.py +24 -0
  65. package/python/biocore_model/tests/test_autonomy_tick.py +148 -0
  66. package/python/biocore_model/tests/test_autonomy_v4.py +64 -0
  67. package/python/biocore_model/tests/test_autonomy_v5.py +43 -0
  68. package/python/biocore_model/tests/test_autonomy_v7.py +48 -0
  69. package/python/biocore_model/tests/test_autonomy_v_theta.py +85 -0
  70. package/python/biocore_model/tests/test_batch1_wiring.py +231 -0
  71. package/python/biocore_model/tests/test_batch2_wiring.py +231 -0
  72. package/python/biocore_model/tests/test_batch3_wiring.py +223 -0
  73. package/python/biocore_model/tests/test_bio_tick.py +202 -0
  74. package/python/biocore_model/tests/test_boundary.py +183 -0
  75. package/python/biocore_model/tests/test_boundary_gate.py +295 -0
  76. package/python/biocore_model/tests/test_brain_split.py +99 -0
  77. package/python/biocore_model/tests/test_co_recall.py +350 -0
  78. package/python/biocore_model/tests/test_commitment_extractor.py +197 -0
  79. package/python/biocore_model/tests/test_compassion_fatigue.py +84 -0
  80. package/python/biocore_model/tests/test_connection_bids.py +69 -0
  81. package/python/biocore_model/tests/test_core_bridge.py +88 -0
  82. package/python/biocore_model/tests/test_core_bridge_episode.py +14 -0
  83. package/python/biocore_model/tests/test_core_bridge_forget.py +17 -0
  84. package/python/biocore_model/tests/test_core_bridge_identity.py +15 -0
  85. package/python/biocore_model/tests/test_core_bridge_media.py +17 -0
  86. package/python/biocore_model/tests/test_core_bridge_relation.py +17 -0
  87. package/python/biocore_model/tests/test_core_bridge_summary.py +17 -0
  88. package/python/biocore_model/tests/test_core_client.py +156 -0
  89. package/python/biocore_model/tests/test_core_commands.py +146 -0
  90. package/python/biocore_model/tests/test_core_mode.py +161 -0
  91. package/python/biocore_model/tests/test_core_state.py +240 -0
  92. package/python/biocore_model/tests/test_criticality.py +61 -0
  93. package/python/biocore_model/tests/test_cross_session_copy.py +67 -0
  94. package/python/biocore_model/tests/test_debug_values.py +169 -0
  95. package/python/biocore_model/tests/test_defense_mechanisms.py +177 -0
  96. package/python/biocore_model/tests/test_delta_budget.py +157 -0
  97. package/python/biocore_model/tests/test_diag_trace.py +201 -0
  98. package/python/biocore_model/tests/test_directives_compat.py +698 -0
  99. package/python/biocore_model/tests/test_dissonance.py +97 -0
  100. package/python/biocore_model/tests/test_drift_sign.py +87 -0
  101. package/python/biocore_model/tests/test_embedding_fallback.py +277 -0
  102. package/python/biocore_model/tests/test_embedding_local.py +279 -0
  103. package/python/biocore_model/tests/test_embedding_mode.py +175 -0
  104. package/python/biocore_model/tests/test_embedding_modes.py +342 -0
  105. package/python/biocore_model/tests/test_emotion_geometry.py +114 -0
  106. package/python/biocore_model/tests/test_emotion_probe.py +214 -0
  107. package/python/biocore_model/tests/test_emotion_probe_concurrency.py +128 -0
  108. package/python/biocore_model/tests/test_entity_graph.py +198 -0
  109. package/python/biocore_model/tests/test_entity_resolve.py +446 -0
  110. package/python/biocore_model/tests/test_envy.py +173 -0
  111. package/python/biocore_model/tests/test_exit_or_silence.py +209 -0
  112. package/python/biocore_model/tests/test_expr_guard.py +1 -0
  113. package/python/biocore_model/tests/test_expr_intent.py +66 -0
  114. package/python/biocore_model/tests/test_expr_state.py +66 -0
  115. package/python/biocore_model/tests/test_expr_template.py +71 -0
  116. package/python/biocore_model/tests/test_expr_tone.py +41 -0
  117. package/python/biocore_model/tests/test_extreme_scenarios.py +147 -0
  118. package/python/biocore_model/tests/test_feedback_flow.py +185 -0
  119. package/python/biocore_model/tests/test_feedback_guard.py +65 -0
  120. package/python/biocore_model/tests/test_feedback_llm.py +59 -0
  121. package/python/biocore_model/tests/test_feedback_llm_inferred.py +140 -0
  122. package/python/biocore_model/tests/test_feedback_memory.py +63 -0
  123. package/python/biocore_model/tests/test_feedback_user.py +61 -0
  124. package/python/biocore_model/tests/test_frustration_curve.py +66 -0
  125. package/python/biocore_model/tests/test_global_bio_state.py +116 -0
  126. package/python/biocore_model/tests/test_governance.py +181 -0
  127. package/python/biocore_model/tests/test_granularity.py +133 -0
  128. package/python/biocore_model/tests/test_graph_extract.py +224 -0
  129. package/python/biocore_model/tests/test_graph_recall.py +226 -0
  130. package/python/biocore_model/tests/test_graph_sqlite.py +298 -0
  131. package/python/biocore_model/tests/test_growth.py +301 -0
  132. package/python/biocore_model/tests/test_intent_render.py +60 -0
  133. package/python/biocore_model/tests/test_intero_regulation.py +224 -0
  134. package/python/biocore_model/tests/test_intero_style.py +146 -0
  135. package/python/biocore_model/tests/test_item3_numeric.py +105 -0
  136. package/python/biocore_model/tests/test_item6_numeric.py +116 -0
  137. package/python/biocore_model/tests/test_layered_memory.py +174 -0
  138. package/python/biocore_model/tests/test_leak_guard.py +75 -0
  139. package/python/biocore_model/tests/test_learning_probe.py +93 -0
  140. package/python/biocore_model/tests/test_life_loop.py +222 -0
  141. package/python/biocore_model/tests/test_life_loop_10s.py +131 -0
  142. package/python/biocore_model/tests/test_local_embedding_health.py +258 -0
  143. package/python/biocore_model/tests/test_memory_affect_encoding.py +79 -0
  144. package/python/biocore_model/tests/test_memory_backend.py +332 -0
  145. package/python/biocore_model/tests/test_memory_dedup.py +316 -0
  146. package/python/biocore_model/tests/test_memory_dual.py +219 -0
  147. package/python/biocore_model/tests/test_memory_dual_wiring.py +219 -0
  148. package/python/biocore_model/tests/test_memory_feedback.py +241 -0
  149. package/python/biocore_model/tests/test_memory_fixes.py +84 -0
  150. package/python/biocore_model/tests/test_memory_forgetting.py +58 -0
  151. package/python/biocore_model/tests/test_memory_inject.py +211 -0
  152. package/python/biocore_model/tests/test_memory_mood_recall.py +118 -0
  153. package/python/biocore_model/tests/test_memory_store.py +372 -0
  154. package/python/biocore_model/tests/test_metacog.py +103 -0
  155. package/python/biocore_model/tests/test_migrate.py +245 -0
  156. package/python/biocore_model/tests/test_migrate_store.py +194 -0
  157. package/python/biocore_model/tests/test_mind_wander.py +65 -0
  158. package/python/biocore_model/tests/test_mood.py +35 -0
  159. package/python/biocore_model/tests/test_narrative.py +114 -0
  160. package/python/biocore_model/tests/test_needs_esteem.py +51 -0
  161. package/python/biocore_model/tests/test_needs_events.py +205 -0
  162. package/python/biocore_model/tests/test_needs_sleep.py +54 -0
  163. package/python/biocore_model/tests/test_noise_bank.py +54 -0
  164. package/python/biocore_model/tests/test_numeric_schema.py +98 -0
  165. package/python/biocore_model/tests/test_output_protocol.py +65 -0
  166. package/python/biocore_model/tests/test_page_debug.py +147 -0
  167. package/python/biocore_model/tests/test_page_status_autonomy.py +215 -0
  168. package/python/biocore_model/tests/test_pipeline.py +345 -0
  169. package/python/biocore_model/tests/test_pipeline_api.py +192 -0
  170. package/python/biocore_model/tests/test_pipeline_mode.py +222 -0
  171. package/python/biocore_model/tests/test_plugin_config.py +85 -0
  172. package/python/biocore_model/tests/test_policy_learning.py +116 -0
  173. package/python/biocore_model/tests/test_possible_selves.py +88 -0
  174. package/python/biocore_model/tests/test_predictor.py +227 -0
  175. package/python/biocore_model/tests/test_preference_drift.py +142 -0
  176. package/python/biocore_model/tests/test_preset.py +142 -0
  177. package/python/biocore_model/tests/test_proactive_context.py +70 -0
  178. package/python/biocore_model/tests/test_proactive_history.py +90 -0
  179. package/python/biocore_model/tests/test_proactive_memory.py +141 -0
  180. package/python/biocore_model/tests/test_proactive_send_record.py +88 -0
  181. package/python/biocore_model/tests/test_probe_contract.py +71 -0
  182. package/python/biocore_model/tests/test_prospective.py +154 -0
  183. package/python/biocore_model/tests/test_provider_fallback.py +89 -0
  184. package/python/biocore_model/tests/test_reconstruction.py +111 -0
  185. package/python/biocore_model/tests/test_regulation_strategies.py +228 -0
  186. package/python/biocore_model/tests/test_relation_stage.py +114 -0
  187. package/python/biocore_model/tests/test_relationship_stage.py +59 -0
  188. package/python/biocore_model/tests/test_release_140.py +55 -0
  189. package/python/biocore_model/tests/test_repair_after_boundary.py +249 -0
  190. package/python/biocore_model/tests/test_reply_limit.py +86 -0
  191. package/python/biocore_model/tests/test_reply_limit_persist.py +48 -0
  192. package/python/biocore_model/tests/test_reply_split.py +52 -0
  193. package/python/biocore_model/tests/test_reply_split_astrbot.py +66 -0
  194. package/python/biocore_model/tests/test_reply_split_inject.py +53 -0
  195. package/python/biocore_model/tests/test_rerank.py +229 -0
  196. package/python/biocore_model/tests/test_rollback.py +175 -0
  197. package/python/biocore_model/tests/test_runtime.py +175 -0
  198. package/python/biocore_model/tests/test_runtime_active.py +205 -0
  199. package/python/biocore_model/tests/test_runtime_pipeline.py +1583 -0
  200. package/python/biocore_model/tests/test_runtime_proactive.py +231 -0
  201. package/python/biocore_model/tests/test_scheduler.py +79 -0
  202. package/python/biocore_model/tests/test_secrecy.py +105 -0
  203. package/python/biocore_model/tests/test_self_esteem.py +45 -0
  204. package/python/biocore_model/tests/test_self_intent.py +347 -0
  205. package/python/biocore_model/tests/test_self_interest.py +183 -0
  206. package/python/biocore_model/tests/test_self_layer_wiring.py +198 -0
  207. package/python/biocore_model/tests/test_self_verification.py +113 -0
  208. package/python/biocore_model/tests/test_situation.py +142 -0
  209. package/python/biocore_model/tests/test_sleep_circadian.py +41 -0
  210. package/python/biocore_model/tests/test_social_pain.py +49 -0
  211. package/python/biocore_model/tests/test_social_repair.py +67 -0
  212. package/python/biocore_model/tests/test_social_theory.py +78 -0
  213. package/python/biocore_model/tests/test_source_monitoring.py +204 -0
  214. package/python/biocore_model/tests/test_speak_like_group.py +36 -0
  215. package/python/biocore_model/tests/test_stages.py +226 -0
  216. package/python/biocore_model/tests/test_state_tag.py +86 -0
  217. package/python/biocore_model/tests/test_template_expr.py +65 -0
  218. package/python/biocore_model/tests/test_text_inference.py +70 -0
  219. package/python/biocore_model/tests/test_theta_params.py +115 -0
  220. package/python/biocore_model/tests/test_topic_control.py +200 -0
  221. package/python/biocore_model/tests/test_turn_memory.py +105 -0
  222. package/python/biocore_model/tests/test_turn_memory_panel.py +174 -0
  223. package/python/biocore_model/tests/test_ui_settings.py +84 -0
  224. package/python/biocore_model/tests/test_ui_settings_authority.py +179 -0
  225. package/python/biocore_model/tests/test_user_appraisal_async.py +155 -0
  226. package/python/biocore_model/tests/test_user_classify.py +122 -0
  227. package/python/biocore_model/tests/test_value_order.py +117 -0
  228. package/python/biocore_model/tests/test_voice_bank.py +105 -0
  229. package/python/biocore_model/tests/test_waiting_sense.py +216 -0
  230. package/python/biocore_model/tests/test_x_directives.py +101 -0
  231. package/python/biocore_model/tests/ui_compat_check.mjs +22 -0
  232. package/python/biocore_model/tests/view_mode_check.mjs +17 -0
  233. package/python/biocore_runtime/autonomy.py +208 -0
  234. package/python/biocore_runtime/core_state.py +302 -0
  235. package/python/biocore_runtime/governance.py +495 -0
  236. package/python/biocore_runtime/growth.py +528 -0
  237. package/python/biocore_runtime/pipeline.py +850 -23
  238. package/python/biocore_runtime/relationship_state.py +214 -0
  239. package/python/biocore_runtime/self_layer.py +103 -0
  240. package/python/biocore_runtime/service.py +162 -0
  241. package/python/biocore_runtime/standby.py +472 -0
  242. package/ui/panel-layout.js +83 -39
  243. package/ui/panel.css +885 -743
  244. package/ui/panel.html +356 -296
  245. package/ui/panel.js +739 -865
@@ -0,0 +1,316 @@
1
+ # -*- coding: utf-8 -*-
2
+ """task-147: memory dedupe (text_hash unique key + semantic second pass)."""
3
+ import json
4
+ import sqlite3
5
+ import tempfile
6
+ import types
7
+ import unittest
8
+ from pathlib import Path
9
+
10
+ from biocore_model import memory_store as ms
11
+
12
+ VEC_A = [1.0, 0.0, 0.0, 0.0]
13
+ VEC_NEAR = [0.92, 0.391918, 0.0, 0.0] # cosine ~0.92 with VEC_A
14
+
15
+
16
+ def _entry(text, ts=100.0, importance=0.5, hits=1, access=1,
17
+ vector=None, eid=None, **extra):
18
+ entry = {"text": text, "ts": ts, "importance": importance,
19
+ "hits": hits, "access_count": access,
20
+ "vector": list(vector) if vector else None, "role": "user"}
21
+ if eid:
22
+ entry["id"] = eid
23
+ entry.update(extra)
24
+ return entry
25
+
26
+
27
+ def _append_save(store, session, entries):
28
+ """Full-doc save (what main does): keep existing rows, append new entries."""
29
+ doc = store.load_doc(session)
30
+ doc["entries"] = list(doc.get("entries") or []) + list(entries)
31
+ return store.save_doc(session, doc)
32
+
33
+
34
+ def _legacy_db(path, session="s1"):
35
+ """Create a pre-dedupe (schema v4, no text_hash) SQLite file."""
36
+ path = Path(path)
37
+ path.parent.mkdir(parents=True, exist_ok=True)
38
+ conn = sqlite3.connect(str(path))
39
+ conn.executescript("""
40
+ CREATE TABLE entries(
41
+ id TEXT PRIMARY KEY, session TEXT NOT NULL, seq INTEGER NOT NULL DEFAULT 0,
42
+ text TEXT, role TEXT, ts REAL, importance REAL, vector BLOB,
43
+ storage_s REAL, retrieval_s REAL, access_count INTEGER, hits INTEGER,
44
+ inhibition REAL, suppression_count INTEGER, memory_tier TEXT,
45
+ memory_source TEXT, memory_confidence REAL, arousal_at_encoding REAL,
46
+ hidden INTEGER, tags TEXT, raw TEXT
47
+ );
48
+ CREATE TABLE session_docs(session TEXT PRIMARY KEY, doc TEXT, updated_at REAL);
49
+ CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT);
50
+ """)
51
+ return conn
52
+
53
+
54
+ def _insert_legacy(conn, session, rows):
55
+ for seq, entry in enumerate(rows):
56
+ conn.execute(
57
+ "INSERT OR REPLACE INTO entries(id, session, seq, text, role, ts, "
58
+ "importance, vector, access_count, hits, memory_tier, "
59
+ "memory_source, raw) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",
60
+ (entry.get("id") or "e%d" % seq, session, seq,
61
+ entry.get("text"), "user", entry.get("ts", 0.0),
62
+ entry.get("importance", 0.5),
63
+ ms.encode_vector(entry.get("vector")),
64
+ int(entry.get("access_count", 1)), int(entry.get("hits", 0)),
65
+ "warm", "direct",
66
+ json.dumps({k: v for k, v in entry.items() if k != "vector"})))
67
+ conn.commit()
68
+
69
+
70
+ class TextHashTest(unittest.TestCase):
71
+ def test_normalize_and_hash(self):
72
+ self.assertEqual(ms.normalize_text(" 今天 很累!"), "今天很累")
73
+ self.assertEqual(ms.text_hash("今天 很累!"),
74
+ ms.text_hash("今天很累"))
75
+ self.assertNotEqual(ms.text_hash("今天很累"),
76
+ ms.text_hash("今天很开心"))
77
+
78
+ def test_same_text_written_twice_merges(self):
79
+ with tempfile.TemporaryDirectory() as tmp:
80
+ store = ms.open_store(tmp)
81
+ try:
82
+ store.save_doc("s", {"entries": [
83
+ _entry("今天很累", ts=100.0, importance=0.4, hits=1)]})
84
+ store.save_doc("s", {"entries": [
85
+ _entry("今天很累", ts=50.0, importance=0.9, hits=2)]})
86
+ self.assertEqual(store.stats()["entries"], 1)
87
+ entry = store.load_doc("s")["entries"][0]
88
+ self.assertEqual(entry["ts"], 50.0) # earliest
89
+ self.assertAlmostEqual(entry["importance"], 0.9) # higher
90
+ self.assertEqual(entry["hits"], 3) # summed
91
+ self.assertEqual(entry["access_count"], 2)
92
+ self.assertTrue(entry["text_hash"])
93
+ finally:
94
+ store.close()
95
+
96
+ def test_normalized_duplicate_merges(self):
97
+ with tempfile.TemporaryDirectory() as tmp:
98
+ store = ms.open_store(tmp)
99
+ try:
100
+ store.save_doc("s", {"entries": [
101
+ _entry("今天,很累!"), _entry(" 今天 很累 ") ]})
102
+ self.assertEqual(store.stats()["entries"], 1)
103
+ finally:
104
+ store.close()
105
+
106
+ def test_unique_index_blocks_direct_duplicate(self):
107
+ with tempfile.TemporaryDirectory() as tmp:
108
+ store = ms.open_store(tmp)
109
+ try:
110
+ store.save_doc("s", {"entries": [_entry("同一句")]})
111
+ self.assertTrue(store._has_index(ms.TEXT_HASH_INDEX))
112
+ row = store._conn.execute(
113
+ "SELECT id, text_hash FROM entries").fetchone()
114
+ with self.assertRaises(sqlite3.IntegrityError):
115
+ store._conn.execute(
116
+ "INSERT INTO entries(id, session, text_hash) "
117
+ "VALUES(?,?,?)", ("dup", "s", row[1]))
118
+ store._conn.commit()
119
+ finally:
120
+ store.close()
121
+
122
+
123
+ class SemanticDedupTest(unittest.TestCase):
124
+ def test_semantic_paraphrase_merges(self):
125
+ with tempfile.TemporaryDirectory() as tmp:
126
+ store = ms.open_store(tmp)
127
+ try:
128
+ store.save_doc("s", {"entries": [
129
+ _entry("我很开心", ts=100.0, vector=[1.0, 0.001, 0, 0])]})
130
+ report = _append_save(store, "s", [
131
+ _entry("我很开心呀", ts=200.0, vector=[0.999, 0.0, 0, 0])])
132
+ self.assertEqual(store.stats()["entries"], 1)
133
+ self.assertGreaterEqual(report["semantic_merged"], 1)
134
+ entry = store.load_doc("s")["entries"][0]
135
+ self.assertEqual(entry["ts"], 100.0)
136
+ self.assertEqual(entry["hits"], 2)
137
+ finally:
138
+ store.close()
139
+
140
+ def test_cosine_090_095_not_merged(self):
141
+ with tempfile.TemporaryDirectory() as tmp:
142
+ store = ms.open_store(tmp)
143
+ captured = []
144
+ original = ms.logger
145
+ ms.logger = types.SimpleNamespace(
146
+ info=lambda *a, **k: captured.append(a),
147
+ warning=lambda *a, **k: None,
148
+ debug=lambda *a, **k: None)
149
+ try:
150
+ store.save_doc("s", {"entries": [
151
+ _entry("我有点开心", vector=VEC_A)]})
152
+ report = _append_save(store, "s", [
153
+ _entry("我有点开心呢", vector=VEC_NEAR)])
154
+ self.assertEqual(store.stats()["entries"], 2)
155
+ self.assertEqual(report["semantic_merged"], 0)
156
+ self.assertGreaterEqual(report["near_merge"], 1)
157
+ self.assertEqual(ms.cosine(VEC_A, VEC_NEAR) >= 0.90, True)
158
+ self.assertEqual(ms.cosine(VEC_A, VEC_NEAR) < 0.95, True)
159
+ self.assertTrue(any("near-merge" in " ".join(map(str, row))
160
+ for row in captured))
161
+ finally:
162
+ ms.logger = original
163
+ store.close()
164
+
165
+ def test_doc_internal_duplicates_merge(self):
166
+ with tempfile.TemporaryDirectory() as tmp:
167
+ store = ms.open_store(tmp)
168
+ try:
169
+ store.save_doc("s", {"entries": [
170
+ _entry("同一句"), _entry("同一句。")]})
171
+ self.assertEqual(store.stats()["entries"], 1)
172
+ mirror = json.loads(
173
+ (Path(tmp) / "s.json").read_text(encoding="utf-8"))
174
+ self.assertEqual(len(mirror["entries"]), 1)
175
+ self.assertIn("text_hash", mirror["entries"][0])
176
+ finally:
177
+ store.close()
178
+
179
+ def test_save_is_idempotent_for_same_doc(self):
180
+ with tempfile.TemporaryDirectory() as tmp:
181
+ store = ms.open_store(tmp)
182
+ try:
183
+ doc = {"entries": [_entry("一天", ts=10.0, hits=2,
184
+ access=3)]}
185
+ store.save_doc("s", doc)
186
+ first = store.load_doc("s")["entries"][0]
187
+ doc2 = {"entries": [_entry("一天", ts=10.0, hits=2,
188
+ access=3, id=first["id"])]}
189
+ store.save_doc("s", doc2)
190
+ second = store.load_doc("s")["entries"][0]
191
+ self.assertEqual(store.stats()["entries"], 1)
192
+ self.assertEqual(second["hits"], 2) # no inflation
193
+ self.assertEqual(second["access_count"], 3)
194
+ finally:
195
+ store.close()
196
+
197
+
198
+ class MergeFieldTest(unittest.TestCase):
199
+ def test_merge_field_values(self):
200
+ with tempfile.TemporaryDirectory() as tmp:
201
+ store = ms.open_store(tmp)
202
+ try:
203
+ store.save_doc("s", {"entries": [
204
+ _entry("同句", ts=300.0, importance=0.3, hits=1,
205
+ access=1)]})
206
+ store.save_doc("s", {"entries": [
207
+ _entry("同句", ts=100.0, importance=0.8, hits=4,
208
+ access=2)]})
209
+ entry = store.load_doc("s")["entries"][0]
210
+ self.assertEqual(entry["ts"], 100.0)
211
+ self.assertAlmostEqual(entry["importance"], 0.8)
212
+ self.assertEqual(entry["hits"], 5)
213
+ self.assertEqual(entry["access_count"], 3)
214
+ finally:
215
+ store.close()
216
+
217
+
218
+ class MigrationCleanupTest(unittest.TestCase):
219
+ def _rows(self):
220
+ return [
221
+ _entry("今天很累", ts=100.0, importance=0.4, hits=1,
222
+ access=1, vector=VEC_A),
223
+ _entry("今天很累。", ts=50.0, importance=0.9, hits=2,
224
+ access=1, vector=VEC_A),
225
+ _entry("我很开心", ts=200.0, importance=0.5, hits=1,
226
+ access=1, vector=[0.0, 1.0, 0.0, 0.0]),
227
+ _entry("我很开心呀", ts=250.0, importance=0.7, hits=3,
228
+ access=2, vector=[0.0, 0.999, 0.0, 0.0]),
229
+ _entry("我有点开心", ts=260.0, importance=0.5, hits=1,
230
+ access=1, vector=VEC_NEAR),
231
+ _entry("别的事", ts=300.0, importance=0.5, hits=1,
232
+ access=1, vector=[0.0, 0.0, 1.0, 0.0]),
233
+ ]
234
+
235
+ def test_migration_merges_and_reports(self):
236
+ with tempfile.TemporaryDirectory() as tmp:
237
+ db = Path(tmp) / ms.SQLITE_FILE
238
+ conn = _legacy_db(db)
239
+ try:
240
+ _insert_legacy(conn, "s1", self._rows())
241
+ finally:
242
+ conn.close()
243
+ store = ms.open_store(tmp)
244
+ try:
245
+ report = store.migration_report
246
+ self.assertTrue(report.get("ran"))
247
+ self.assertEqual(report.get("merged_pairs"), 2)
248
+ self.assertEqual(report.get("deleted_rows"), 2)
249
+ self.assertEqual(store.stats()["entries"], 4)
250
+ self.assertTrue(store._has_index(ms.TEXT_HASH_INDEX))
251
+ # rows are merged into the earliest row (ts=50 is e1)
252
+ merged = store.get_entry("s1", "e1")
253
+ self.assertEqual(merged["ts"], 50.0)
254
+ self.assertAlmostEqual(merged["importance"], 0.9)
255
+ self.assertEqual(merged["hits"], 3)
256
+ # 0.90-0.95 pair is kept separate
257
+ self.assertIsNotNone(store.get_entry("s1", "e4"))
258
+ finally:
259
+ store.close()
260
+
261
+ def test_migration_backup_exists(self):
262
+ with tempfile.TemporaryDirectory() as tmp:
263
+ db = Path(tmp) / ms.SQLITE_FILE
264
+ conn = _legacy_db(db)
265
+ try:
266
+ _insert_legacy(conn, "s1", self._rows())
267
+ finally:
268
+ conn.close()
269
+ store = ms.open_store(tmp)
270
+ try:
271
+ backup = store.migration_report.get("backup")
272
+ self.assertTrue(backup)
273
+ self.assertTrue(Path(backup).is_dir())
274
+ self.assertGreater(len(list(Path(backup).iterdir())), 0)
275
+ finally:
276
+ store.close()
277
+
278
+ def test_migration_idempotent(self):
279
+ with tempfile.TemporaryDirectory() as tmp:
280
+ db = Path(tmp) / ms.SQLITE_FILE
281
+ conn = _legacy_db(db)
282
+ try:
283
+ _insert_legacy(conn, "s1", self._rows())
284
+ finally:
285
+ conn.close()
286
+ store = ms.open_store(tmp)
287
+ try:
288
+ first = store.stats()["entries"]
289
+ finally:
290
+ store.close()
291
+ store = ms.open_store(tmp)
292
+ try:
293
+ self.assertFalse(store.migration_report.get("ran"))
294
+ self.assertEqual(store.stats()["entries"], first)
295
+ finally:
296
+ store.close()
297
+
298
+
299
+ class MirrorSyncTest(unittest.TestCase):
300
+ def test_json_mirror_matches_deduped_rows(self):
301
+ with tempfile.TemporaryDirectory() as tmp:
302
+ store = ms.open_store(tmp)
303
+ try:
304
+ store.save_doc("s", {"entries": [
305
+ _entry("镜像同步"), _entry("镜像同步!")]})
306
+ mirror = json.loads(
307
+ (Path(tmp) / "s.json").read_text(encoding="utf-8"))
308
+ self.assertEqual(len(mirror["entries"]), 1)
309
+ self.assertEqual(mirror["entries"][0]["text"], "镜像同步")
310
+ self.assertTrue(mirror["entries"][0]["text_hash"])
311
+ finally:
312
+ store.close()
313
+
314
+
315
+ if __name__ == "__main__":
316
+ unittest.main()
@@ -0,0 +1,219 @@
1
+ # -*- coding: utf-8 -*-
2
+ """MD-1 memory_dual tests: formulas, testing effect, selection, forgetting."""
3
+ import math
4
+ import unittest
5
+
6
+ from biocore_model import memory_dual as md
7
+
8
+ NOW = 1_700_000_000.0
9
+
10
+
11
+ def entry(**kw):
12
+ base = {"id": "e1", "text": "hello", "storage_s": 0.5, "retrieval_s": 0.5,
13
+ "access_count": 0, "last_access_ts": NOW, "created_ts": NOW,
14
+ "arousal_at_encoding": 0.5, "open_loop": False}
15
+ base.update(kw)
16
+ return base
17
+
18
+
19
+ class DecayTest(unittest.TestCase):
20
+ def test_power_law_1h(self):
21
+ self.assertAlmostEqual(md.decay(1.0, 1.0), math.pow(1 + 1 / 24.0, -0.5), places=12)
22
+ self.assertAlmostEqual(md.decay(1.0, 1.0), 0.979796, places=6)
23
+
24
+ def test_power_law_24h(self):
25
+ self.assertAlmostEqual(md.decay(1.0, 24.0), 0.707107, places=6)
26
+
27
+ def test_power_law_7d(self):
28
+ self.assertAlmostEqual(md.decay(1.0, 168.0), 0.353553, places=6)
29
+
30
+ def test_zero_dt_and_scaling(self):
31
+ self.assertEqual(md.decay(0.42, 0.0), 0.42)
32
+ self.assertAlmostEqual(md.decay(0.8, 24.0), 0.8 * 0.707107, places=6)
33
+ self.assertGreater(md.decay(0.8, 1.0), md.decay(0.8, 24.0))
34
+
35
+
36
+ class EncodeTest(unittest.TestCase):
37
+ def test_defaults(self):
38
+ row = md.encode("海边", NOW)
39
+ self.assertEqual(row["storage_s"], 0.35)
40
+ self.assertEqual(row["retrieval_s"], 0.35)
41
+ self.assertEqual(row["access_count"], 0)
42
+ self.assertEqual(row["last_access_ts"], NOW)
43
+ self.assertFalse(row["open_loop"])
44
+ self.assertFalse(row["hidden"])
45
+
46
+ def test_arousal_raises_initial_storage(self):
47
+ low = md.encode("low", NOW, arousal=0.0)
48
+ high = md.encode("high", NOW, arousal=1.0)
49
+ self.assertAlmostEqual(high["storage_s"], 0.70, places=4)
50
+ self.assertGreater(high["storage_s"], low["storage_s"])
51
+ self.assertEqual(high["retrieval_s"], high["storage_s"])
52
+
53
+ def test_arousal_clamped(self):
54
+ self.assertAlmostEqual(md.encode("x", NOW, arousal=5.0)["storage_s"], 0.70, places=4)
55
+ self.assertAlmostEqual(md.encode("x", NOW, arousal=-3.0)["storage_s"], 0.35, places=4)
56
+
57
+ def test_open_loop_flag(self):
58
+ self.assertTrue(md.encode("todo", NOW, open_loop=True)["open_loop"])
59
+
60
+
61
+ class RecallTest(unittest.TestCase):
62
+ def test_testing_effect_storage_gain(self):
63
+ row = entry(storage_s=0.4, retrieval_s=0.3, access_count=0, last_access_ts=0.0)
64
+ out = md.on_recall(row, NOW)
65
+ self.assertAlmostEqual(out["storage_s"], 0.46, places=4) # +0.1*(1-0.4)
66
+ self.assertAlmostEqual(out["retrieval_s"], 0.65, places=4) # +0.35
67
+ self.assertEqual(out["access_count"], 1)
68
+ self.assertEqual(out["last_access_ts"], NOW)
69
+
70
+ def test_retrieval_capped_at_one(self):
71
+ out = md.on_recall(entry(retrieval_s=0.9, last_access_ts=0.0), NOW)
72
+ self.assertEqual(out["retrieval_s"], 1.0)
73
+
74
+ def test_idempotent_same_now(self):
75
+ row = entry(storage_s=0.4, retrieval_s=0.3, last_access_ts=0.0)
76
+ first = md.on_recall(row, NOW)
77
+ second = md.on_recall(first, NOW)
78
+ self.assertEqual(second["storage_s"], first["storage_s"])
79
+ self.assertEqual(second["retrieval_s"], first["retrieval_s"])
80
+ self.assertEqual(second["access_count"], 1)
81
+
82
+ def test_does_not_mutate_input(self):
83
+ row = entry(storage_s=0.4, retrieval_s=0.3, last_access_ts=0.0)
84
+ before = dict(row)
85
+ md.on_recall(row, NOW)
86
+ self.assertEqual(row, before)
87
+
88
+ def test_new_now_applies_again(self):
89
+ first = md.on_recall(entry(last_access_ts=0.0), NOW)
90
+ second = md.on_recall(first, NOW + 60)
91
+ self.assertEqual(second["access_count"], 2)
92
+ self.assertGreater(second["storage_s"], first["storage_s"])
93
+
94
+
95
+ class ScoreTest(unittest.TestCase):
96
+ def test_context_weight(self):
97
+ row = entry()
98
+ full = md.score(row, NOW, context_match=1.0)
99
+ half = md.score(row, NOW, context_match=0.25)
100
+ self.assertAlmostEqual(half / full, 0.5, places=6) # 0.25 ** 0.5
101
+
102
+ def test_open_loop_bonus(self):
103
+ closed = md.score(entry(open_loop=False), NOW)
104
+ opened = md.score(entry(open_loop=True), NOW)
105
+ self.assertAlmostEqual(opened / closed, 1.15, places=6)
106
+
107
+ def test_frequency_term(self):
108
+ low = md.score(entry(access_count=0), NOW)
109
+ high = md.score(entry(access_count=3), NOW)
110
+ expected = 1.0 + 0.3 * math.log1p(3)
111
+ self.assertAlmostEqual(high / low, expected, places=6)
112
+
113
+ def test_decays_over_time(self):
114
+ row = entry(retrieval_s=0.6)
115
+ s0 = md.score(row, NOW)
116
+ s24 = md.score(row, NOW + 24 * 3600)
117
+ s72 = md.score(row, NOW + 72 * 3600)
118
+ self.assertGreater(s0, s24)
119
+ self.assertGreater(s24, s72)
120
+
121
+ def test_hidden_scores_zero(self):
122
+ self.assertEqual(md.score(entry(hidden=True), NOW), 0.0)
123
+
124
+
125
+ class SelectTest(unittest.TestCase):
126
+ def _rows(self):
127
+ return [
128
+ entry(id="strong", text="strong", storage_s=0.9, retrieval_s=0.9,
129
+ last_access_ts=NOW),
130
+ entry(id="recent", text="recent", storage_s=0.6, retrieval_s=0.6,
131
+ last_access_ts=NOW - 3600),
132
+ entry(id="open", text="open", storage_s=0.5, retrieval_s=0.5,
133
+ open_loop=True, last_access_ts=NOW - 24 * 3600),
134
+ entry(id="old", text="old", storage_s=0.4, retrieval_s=0.4,
135
+ last_access_ts=NOW - 30 * 24 * 3600),
136
+ entry(id="hidden", text="hidden", retrieval_s=0.9, hidden=True),
137
+ ]
138
+
139
+ def test_sorted_and_limited(self):
140
+ out = md.select(self._rows(), NOW, limit=3)
141
+ ids = [row["id"] for row in out["picked"]]
142
+ self.assertEqual(len(ids), 3)
143
+ self.assertNotIn("hidden", ids)
144
+ scores = [row["score"] for row in out["picked"]]
145
+ self.assertEqual(scores, sorted(scores, reverse=True))
146
+ self.assertEqual(ids[0], "strong")
147
+
148
+ def test_min_score_filters(self):
149
+ rows = [entry(id="weak", retrieval_s=0.01, last_access_ts=NOW - 90 * 24 * 3600)]
150
+ out = md.select(rows, NOW, min_score=0.12)
151
+ self.assertEqual(out["picked"], [])
152
+ self.assertEqual(out["skipped"][0]["reason"], "below_min_score")
153
+
154
+ def test_skipped_reason_for_limit(self):
155
+ out = md.select(self._rows(), NOW, limit=1)
156
+ reasons = {row["id"]: row["reason"] for row in out["skipped"]}
157
+ self.assertEqual(reasons["hidden"], "hidden")
158
+ self.assertIn("limit", reasons.values())
159
+
160
+ def test_context_dict_per_entry(self):
161
+ rows = [entry(id="a", retrieval_s=0.5), entry(id="b", retrieval_s=0.5)]
162
+ out = md.select(rows, NOW, context={"a": 1.0, "b": 0.01})
163
+ self.assertEqual(out["picked"][0]["id"], "a")
164
+ self.assertNotIn("b", [row["id"] for row in out["picked"]])
165
+
166
+
167
+ class ForgetTest(unittest.TestCase):
168
+ def test_marks_hidden_without_deleting(self):
169
+ rows = [entry(id="faint", retrieval_s=0.10),
170
+ entry(id="solid", retrieval_s=0.50)]
171
+ out = md.forget(rows, NOW)
172
+ self.assertEqual(len(out["entries"]), 2) # nothing deleted
173
+ by_id = {row["id"]: row for row in out["entries"]}
174
+ self.assertTrue(by_id["faint"]["hidden"])
175
+ self.assertFalse(by_id["solid"].get("hidden"))
176
+ self.assertEqual(out["forgotten_ids"], ["faint"])
177
+ self.assertNotIn("hidden", rows[0]) # input untouched
178
+
179
+ def test_idempotent_second_call(self):
180
+ rows = [entry(id="faint", retrieval_s=0.10)]
181
+ first = md.forget(rows, NOW)
182
+ second = md.forget(first["entries"], NOW)
183
+ self.assertEqual(first["forgotten_ids"], ["faint"])
184
+ self.assertEqual(second["forgotten_ids"], [])
185
+
186
+
187
+ class TimeEvolutionTest(unittest.TestCase):
188
+ def test_ten_memories_three_horizons(self):
189
+ rows = []
190
+ for index in range(10):
191
+ rows.append(entry(
192
+ id="m%02d" % (index + 1), text="memory-%d" % index,
193
+ storage_s=0.35 + 0.035 * index,
194
+ retrieval_s=0.35 + 0.035 * index,
195
+ last_access_ts=NOW - (index * 6) * 3600,
196
+ open_loop=(index % 3 == 0),
197
+ ))
198
+ early = md.select(rows, NOW, limit=4)
199
+ day = md.select(rows, NOW + 24 * 3600, limit=4)
200
+ three = md.select(rows, NOW + 72 * 3600, limit=4)
201
+ early_scores = {row["id"]: row["score"] for row in early["picked"]}
202
+ day_scores = {row["id"]: row["score"] for row in day["picked"]}
203
+ three_scores = {row["id"]: row["score"] for row in three["picked"]}
204
+ common = set(early_scores) & set(three_scores)
205
+ if common:
206
+ sample = sorted(common)[0]
207
+ self.assertGreater(early_scores[sample], three_scores[sample])
208
+ self.assertNotEqual(early_scores, day_scores)
209
+ self.assertLessEqual(max(three_scores.values()) if three_scores else 1.0,
210
+ max(early_scores.values()))
211
+
212
+ def test_forget_after_long_gap(self):
213
+ rows = [entry(id="m1", retrieval_s=0.30, last_access_ts=NOW)]
214
+ out = md.forget(rows, NOW + 30 * 24 * 3600)
215
+ self.assertIn("m1", out["forgotten_ids"])
216
+
217
+
218
+ if __name__ == "__main__":
219
+ unittest.main()