dsh-biocore 0.2.0 → 0.3.0

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,301 @@
1
+ # -*- coding: utf-8 -*-
2
+ """task-220: growth metrics + read-only consolidation dry-run."""
3
+ import json
4
+ import tempfile
5
+ import unittest
6
+ from pathlib import Path
7
+
8
+ from biocore_runtime import growth
9
+
10
+
11
+ NOW = 1700000000.0
12
+
13
+
14
+ def write_json(path, data):
15
+ path = Path(path)
16
+ path.parent.mkdir(parents=True, exist_ok=True)
17
+ path.write_text(json.dumps(data, ensure_ascii=False, indent=2),
18
+ encoding="utf-8")
19
+
20
+
21
+ def memory(entry_id, text, ts=NOW, importance=0.5, affect=None):
22
+ row = {"id": entry_id, "text": text, "role": "user", "ts": ts,
23
+ "importance": importance, "hits": 1}
24
+ if affect is not None:
25
+ row["affect"] = affect
26
+ return row
27
+
28
+
29
+ def trace_row(ts, ids, top=None, intent=""):
30
+ mem = {"recalled_ids": list(ids), "captured_id": ""}
31
+ if top is not None:
32
+ mem["top_score"] = top
33
+ return {"ts": ts, "session_id": "s1", "state_delta": [],
34
+ "intent": {"kind": intent, "weight": 0.0, "reason": ""},
35
+ "constraints": {}, "length": {"scale": 1.0, "source": "state"},
36
+ "gate": {"action": "pass", "rule": "", "label": ""},
37
+ "memory": mem, "modules": {"ran": [], "skipped": []}}
38
+
39
+
40
+ class StoreCase(unittest.TestCase):
41
+ def setUp(self):
42
+ self.tmp = tempfile.TemporaryDirectory()
43
+ self.root = Path(self.tmp.name) / "store"
44
+
45
+ def tearDown(self):
46
+ self.tmp.cleanup()
47
+
48
+ def build(self, entries=None, state=None, traces=None,
49
+ relationship=None, flags=None, history=None):
50
+ session = self.root / "sessions" / "s1"
51
+ write_json(session / "memory.json",
52
+ {"session_id": "s1", "entries": entries or []})
53
+ write_json(session / "state.json", state or {"v": 0.2, "a": 0.4})
54
+ if traces:
55
+ trace_file = self.root / "traces" / "s1.jsonl"
56
+ trace_file.parent.mkdir(parents=True, exist_ok=True)
57
+ trace_file.write_text("\n".join(
58
+ json.dumps(row, ensure_ascii=False) for row in traces) + "\n",
59
+ encoding="utf-8")
60
+ if relationship is not None:
61
+ write_json(self.root / "relationship.json",
62
+ {"schema_version": 1, "version": 3,
63
+ "updated_ts": NOW, "relationship": relationship})
64
+ if flags is not None:
65
+ write_json(self.root / "flags.json", flags)
66
+ if history is not None:
67
+ (self.root / "growth_history.jsonl").write_text(
68
+ "\n".join(json.dumps(row, ensure_ascii=False)
69
+ for row in history) + "\n", encoding="utf-8")
70
+ return str(self.root)
71
+
72
+ def snapshot(self):
73
+ files = {}
74
+ base = self.root / "sessions"
75
+ for path in sorted(base.rglob("*")):
76
+ if path.is_file():
77
+ files[str(path)] = path.read_bytes()
78
+ return files
79
+
80
+
81
+ class SwitchTest(StoreCase):
82
+ def test_default_off(self):
83
+ self.assertFalse(growth.enabled({}))
84
+ self.assertTrue(growth.enabled({}, {"BIOCORE_GROWTH_REPORT": "1"}))
85
+ self.assertTrue(growth.enabled({"growth_report": True}))
86
+ self.assertFalse(growth.enabled({"growth_report": False},
87
+ {"BIOCORE_GROWTH_REPORT": "1"}))
88
+
89
+ def test_disabled_writes_no_report(self):
90
+ store = self.build(entries=[memory("a", "hello")])
91
+ out = growth.consolidate(store, now=NOW)
92
+ self.assertFalse(out["ok"])
93
+ self.assertEqual(out["reason"], "disabled")
94
+ self.assertFalse((Path(store) / "consolidate_report.json").exists())
95
+
96
+
97
+ class MetricsTest(StoreCase):
98
+ def test_empty_store(self):
99
+ store = self.build()
100
+ out = growth.metrics(store, now=NOW)
101
+ self.assertEqual(out["memory"]["total"], 0)
102
+ self.assertEqual(out["memory"]["with_affect_ratio"], 0.0)
103
+ self.assertEqual(out["recall"]["hits_total"], 0)
104
+ self.assertIsNone(out["recall"]["avg_top_score"])
105
+ self.assertEqual(out["narrative"]["top_intents"], [])
106
+ self.assertEqual(out["relation"]["change_7d"],
107
+ {"trust": 0.0, "closeness": 0.0})
108
+ self.assertEqual(out["relation"]["change_basis"], "no_history")
109
+
110
+ def test_fields_present(self):
111
+ store = self.build(entries=[memory("a", "hello")])
112
+ out = growth.metrics(store, now=NOW)
113
+ for key in ("total", "added_this_week", "avg_importance",
114
+ "with_affect", "with_affect_ratio"):
115
+ self.assertIn(key, out["memory"])
116
+ for key in ("hits_total", "mood_match_hits", "avg_top_score",
117
+ "score_source"):
118
+ self.assertIn(key, out["recall"])
119
+ for key in ("trust", "closeness", "change_7d", "change_basis"):
120
+ self.assertIn(key, out["relation"])
121
+ self.assertIn("top_intents", out["narrative"])
122
+ for key in growth.LEARNING_FLAGS:
123
+ self.assertIn(key, out["flags"])
124
+
125
+ def test_memory_metrics(self):
126
+ store = self.build(entries=[
127
+ memory("a", "one", ts=NOW - 86400, importance=0.6,
128
+ affect={"valence": 0.4, "arousal": 0.5}),
129
+ memory("b", "two", ts=NOW - 2 * 86400, importance=0.8,
130
+ affect={"valence": -0.3, "arousal": 0.6}),
131
+ memory("c", "three", ts=NOW - 10 * 86400, importance=0.4),
132
+ ])
133
+ out = growth.metrics(store, now=NOW)["memory"]
134
+ self.assertEqual(out["total"], 3)
135
+ self.assertEqual(out["added_this_week"], 2)
136
+ self.assertAlmostEqual(out["avg_importance"], 0.6, places=4)
137
+ self.assertEqual(out["with_affect"], 2)
138
+ self.assertAlmostEqual(out["with_affect_ratio"], 0.6667, places=3)
139
+
140
+ def test_recall_metrics(self):
141
+ store = self.build(
142
+ entries=[
143
+ memory("a", "one", affect={"valence": 0.8, "arousal": 0.7}),
144
+ memory("b", "two", affect={"valence": -0.8, "arousal": 0.1}),
145
+ memory("c", "three", affect={"valence": -0.9, "arousal": 0.2}),
146
+ ],
147
+ state={"v": 0.8, "a": 0.7},
148
+ traces=[trace_row(NOW - 30, ["a", "b"], top=0.8, intent="陪伴"),
149
+ trace_row(NOW - 20, ["c"], intent="陪伴"),
150
+ trace_row(NOW - 10, [], intent="好奇")])
151
+ out = growth.metrics(store, now=NOW)["recall"]
152
+ self.assertEqual(out["hits_total"], 3)
153
+ self.assertEqual(out["mood_match_hits"], 1)
154
+ self.assertAlmostEqual(out["avg_top_score"], 0.8, places=4)
155
+ self.assertEqual(out["score_source"], "trace")
156
+
157
+ def test_avg_top_score_unavailable(self):
158
+ store = self.build(
159
+ entries=[memory("a", "one")],
160
+ traces=[trace_row(NOW, ["a"])])
161
+ out = growth.metrics(store, now=NOW)["recall"]
162
+ self.assertIsNone(out["avg_top_score"])
163
+ self.assertEqual(out["score_source"], "unavailable")
164
+
165
+ def test_narrative_top3(self):
166
+ store = self.build(entries=[memory("a", "one")], traces=[
167
+ trace_row(NOW - 40, [], intent="陪伴"),
168
+ trace_row(NOW - 30, [], intent="陪伴"),
169
+ trace_row(NOW - 20, [], intent="好奇"),
170
+ trace_row(NOW - 10, [], intent="好奇"),
171
+ trace_row(NOW, [], intent="关心"),
172
+ ])
173
+ rows = growth.metrics(store, now=NOW)["narrative"]["top_intents"]
174
+ self.assertEqual(rows[0], {"kind": "陪伴", "count": 2})
175
+ self.assertEqual(len(rows), 3)
176
+
177
+ def test_relation_change_7d(self):
178
+ store = self.build(
179
+ relationship={"trust": 0.60, "closeness": 0.58},
180
+ history=[{"ts": NOW - 10 * 86400, "trust": 0.50,
181
+ "closeness": 0.50},
182
+ {"ts": NOW - 2 * 86400, "trust": 0.55,
183
+ "closeness": 0.52}])
184
+ out = growth.metrics(store, now=NOW)["relation"]
185
+ self.assertAlmostEqual(out["change_7d"]["trust"], 0.10, places=4)
186
+ self.assertAlmostEqual(out["change_7d"]["closeness"], 0.08, places=4)
187
+ self.assertEqual(out["change_basis"], "seven_day")
188
+
189
+ def test_relation_change_uses_oldest_sample(self):
190
+ store = self.build(
191
+ relationship={"trust": 0.60, "closeness": 0.50},
192
+ history=[{"ts": NOW - 2 * 86400, "trust": 0.55,
193
+ "closeness": 0.45}])
194
+ out = growth.metrics(store, now=NOW)["relation"]
195
+ self.assertAlmostEqual(out["change_7d"]["trust"], 0.05, places=4)
196
+ self.assertEqual(out["change_basis"], "oldest_sample")
197
+
198
+ def test_flags_from_parent_data_dir(self):
199
+ store = self.build(entries=[memory("a", "hello")])
200
+ write_json(Path(store).parent / "flags.json",
201
+ {"memory_feedback": True})
202
+ out = growth.metrics(store, now=NOW)["flags"]["memory_feedback"]
203
+ self.assertEqual(out, {"enabled": True, "source": "flags.json"})
204
+
205
+ def test_flags_sources(self):
206
+ store = self.build(flags={"mood_recall": True})
207
+ out = growth.metrics(
208
+ store, now=NOW, flags={"affect_encoding": True},
209
+ env={"BIOCORE_PREFERENCE_DRIFT": "1"})["flags"]
210
+ self.assertEqual(out["mood_recall"],
211
+ {"enabled": True, "source": "flags.json"})
212
+ self.assertEqual(out["affect_encoding"],
213
+ {"enabled": True, "source": "flags"})
214
+ self.assertEqual(out["preference_drift"],
215
+ {"enabled": True, "source": "env"})
216
+ self.assertEqual(out["memory_feedback"],
217
+ {"enabled": False, "source": "default"})
218
+
219
+
220
+ class ConsolidateTest(StoreCase):
221
+ def test_dry_run_does_not_write_memory(self):
222
+ store = self.build(entries=[
223
+ memory("a", "注意安全", ts=NOW - 30),
224
+ memory("b", "出门注意安全", ts=NOW - 20),
225
+ memory("c", "记得注意安全", ts=NOW - 10),
226
+ ])
227
+ before = self.snapshot()
228
+ growth.consolidate(store, now=NOW, enabled=True)
229
+ self.assertEqual(self.snapshot(), before)
230
+
231
+ def test_report_is_written(self):
232
+ store = self.build(entries=[memory("a", "注意安全")])
233
+ out = growth.consolidate(store, now=NOW, enabled=True)
234
+ path = Path(store) / "consolidate_report.json"
235
+ self.assertTrue(path.exists())
236
+ report = json.loads(path.read_text(encoding="utf-8"))
237
+ self.assertEqual(report["schema"], "bc.consolidate_report.v1")
238
+ self.assertTrue(report["dry_run"])
239
+ self.assertFalse(report["memory_written"])
240
+ self.assertIn("candidates", report)
241
+ self.assertEqual(out["report"], report)
242
+ self.assertTrue((Path(store) / "growth_history.jsonl").exists())
243
+
244
+ def test_idempotent_same_day(self):
245
+ store = self.build(
246
+ entries=[memory("a", "注意安全", ts=NOW - 30),
247
+ memory("b", "注意安全", ts=NOW - 20)],
248
+ relationship={"trust": 0.8, "closeness": 0.7})
249
+ first = growth.consolidate(store, now=NOW, enabled=True)["report"]
250
+ second = growth.consolidate(store, now=NOW, enabled=True)["report"]
251
+ self.assertEqual(first, second)
252
+ lines = (Path(store) / "growth_history.jsonl").read_text(
253
+ encoding="utf-8").strip().splitlines()
254
+ self.assertEqual(len(lines), 1)
255
+
256
+ def test_repeated_topic_candidate(self):
257
+ store = self.build(entries=[
258
+ memory("a", "注意安全", ts=NOW - 30),
259
+ memory("b", "出门注意安全", ts=NOW - 20),
260
+ memory("c", "记得注意安全", ts=NOW - 10),
261
+ ])
262
+ report = growth.consolidate(store, now=NOW, enabled=True)["report"]
263
+ topic = [row for row in report["candidates"]
264
+ if row["kind"] == "repeated_topic"]
265
+ self.assertTrue(topic)
266
+ self.assertEqual(topic[0]["topic"], "安全")
267
+ self.assertEqual(topic[0]["count"], 3)
268
+ self.assertEqual(topic[0]["dimension"], "security")
269
+ self.assertEqual(report["counts"]["repeated_topic"], len(topic))
270
+
271
+ def test_stable_relation_candidate(self):
272
+ store = self.build(
273
+ entries=[memory("a", "hello")],
274
+ relationship={"trust": 0.72, "closeness": 0.66,
275
+ "conflict": 0.05, "days_known": 12,
276
+ "attachment_style": "secure"})
277
+ report = growth.consolidate(store, now=NOW, enabled=True)["report"]
278
+ stable = [row for row in report["candidates"]
279
+ if row["kind"] == "stable_relation"]
280
+ self.assertEqual(len(stable), 1)
281
+ self.assertAlmostEqual(stable[0]["trust"], 0.72, places=4)
282
+ self.assertIn("12", stable[0]["fact"])
283
+
284
+ def test_low_relation_has_no_candidate(self):
285
+ store = self.build(
286
+ entries=[memory("a", "hello")],
287
+ relationship={"trust": 0.4, "closeness": 0.5})
288
+ report = growth.consolidate(store, now=NOW, enabled=True)["report"]
289
+ self.assertEqual(report["counts"]["stable_relation"], 0)
290
+
291
+ def test_empty_store_report(self):
292
+ store = self.build()
293
+ report = growth.consolidate(store, now=NOW, enabled=True)["report"]
294
+ self.assertEqual(report["candidates"], [])
295
+ self.assertEqual(report["episodes"]["scanned"], 0)
296
+ self.assertEqual(report["counts"],
297
+ {"repeated_topic": 0, "stable_relation": 0})
298
+
299
+
300
+ if __name__ == "__main__":
301
+ unittest.main()
@@ -0,0 +1,60 @@
1
+ # -*- coding: utf-8 -*-
2
+ """HUMAN-6 intent rendering tests: tendency text without numbers/emotion words."""
3
+ import unittest
4
+
5
+ from biocore_model import intent_render as ir
6
+
7
+ ACTIONS = ("approach", "share", "question", "withdraw", "repair", "rest")
8
+
9
+
10
+ class RenderTest(unittest.TestCase):
11
+ def test_every_action_has_phrase(self):
12
+ for action in ACTIONS:
13
+ text = ir.render({"action": action})
14
+ self.assertEqual(text, ir.PHRASES[action])
15
+
16
+ def test_no_digits(self):
17
+ for action in ACTIONS:
18
+ self.assertTrue(ir.check(ir.render({"action": action}, tone="3 天后"))["ok"])
19
+
20
+ def test_no_emotion_words(self):
21
+ for action in ACTIONS:
22
+ text = ir.render({"action": action}, tone="难过 5 分", guard="别生气")
23
+ result = ir.check(text)
24
+ self.assertTrue(result["ok"], text)
25
+
26
+ def test_unknown_action_fallback(self):
27
+ self.assertIn(ir.FALLBACK, ir.render({"action": "explode"}))
28
+
29
+ def test_empty_intent_safe(self):
30
+ self.assertTrue(ir.render(None))
31
+ self.assertTrue(ir.render({}))
32
+
33
+ def test_deterministic(self):
34
+ self.assertEqual(ir.render({"action": "repair"}, tone="慢一点"),
35
+ ir.render({"action": "repair"}, tone="慢一点"))
36
+
37
+
38
+ class CheckSanitizeTest(unittest.TestCase):
39
+ def test_check_detects_problems(self):
40
+ result = ir.check("我有点难过 3 分")
41
+ self.assertFalse(result["ok"])
42
+ self.assertTrue(result["digits"])
43
+ self.assertIn("难过", result["emotion_words"])
44
+
45
+ def test_check_clean_text(self):
46
+ self.assertTrue(ir.check("想和你说说话")["ok"])
47
+
48
+ def test_sanitize_removes(self):
49
+ text = ir.sanitize("焦虑 12 分,想靠近")
50
+ self.assertTrue(ir.check(text)["ok"])
51
+
52
+ def test_tendency_mapping(self):
53
+ self.assertEqual(ir.tendency({"action": "approach"}), "approach")
54
+ self.assertEqual(ir.tendency({"action": "withdraw"}), "withdraw")
55
+ self.assertEqual(ir.tendency({"action": "rest"}), "withdraw")
56
+ self.assertEqual(ir.tendency(None), "neutral")
57
+
58
+
59
+ if __name__ == "__main__":
60
+ unittest.main()
@@ -0,0 +1,224 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Interoception core + regulation loop tests (formulas, bands, actions)."""
3
+ import math
4
+ import unittest
5
+
6
+ from biocore_model import intero_core as ic
7
+ from biocore_model import regulation_loop as rl
8
+
9
+ STATE = {"stress": 0.5, "arousal": 0.6, "sleep_debt": 0.4, "conflict": 0.2,
10
+ "v": 0.2, "social": 0.6, "trust": 0.7, "closeness": 0.5,
11
+ "sadness": 0.3, "allostatic_load": 0.2, "energy": 0.4,
12
+ "loneliness": 0.5, "noise": 0.3}
13
+
14
+ GOOD = {"tension": 0.30, "warmth": 0.60, "heaviness": 0.30, "clarity": 0.70}
15
+ SHUT = {"tension": 0.10, "warmth": 0.05, "heaviness": 0.05, "clarity": 0.05}
16
+ OPEN = {"tension": 0.95, "warmth": 0.95, "heaviness": 0.95, "clarity": 0.95}
17
+
18
+
19
+ class FormulaTest(unittest.TestCase):
20
+ def test_four_dimensions_exact(self):
21
+ out = ic.target(STATE)
22
+ self.assertAlmostEqual(out["tension"], 0.475, places=4)
23
+ self.assertAlmostEqual(out["warmth"], 0.605, places=4)
24
+ self.assertAlmostEqual(out["heaviness"], 0.35, places=4)
25
+ self.assertAlmostEqual(out["clarity"], 0.70, places=4)
26
+
27
+ def test_formula_matches_spec(self):
28
+ x = ic.inputs(STATE)
29
+ expect_tension = (0.45 * x["stress"] + 0.25 * x["arousal"]
30
+ + 0.20 * x["sleep_debt"] + 0.10 * x["conflict"])
31
+ expect_warmth = (0.40 * ((x["v"] + 1.0) / 2.0) + 0.25 * x["social"]
32
+ + 0.20 * x["trust"] + 0.15 * x["closeness"])
33
+ expect_heavy = (0.40 * x["sadness"] + 0.30 * x["allostatic_load"]
34
+ + 0.20 * (1.0 - x["energy"]) + 0.10 * x["loneliness"])
35
+ expect_clarity = (0.40 * (1.0 - x["noise"]) + 0.30 * (1.0 - x["sleep_debt"])
36
+ + 0.30 * (1.0 - abs(x["arousal"] - 0.5) * 2.0))
37
+ out = ic.target(STATE)
38
+ self.assertAlmostEqual(out["tension"], round(expect_tension, 4))
39
+ self.assertAlmostEqual(out["warmth"], round(expect_warmth, 4))
40
+ self.assertAlmostEqual(out["heaviness"], round(expect_heavy, 4))
41
+ self.assertAlmostEqual(out["clarity"], round(expect_clarity, 4))
42
+
43
+ def test_clamped_boundaries(self):
44
+ out = ic.target({"stress": 5, "arousal": -3, "sleep_debt": -2,
45
+ "conflict": 9, "v": -9, "social": 9, "trust": -4,
46
+ "closeness": 9, "sadness": 9, "allostatic_load": -1,
47
+ "energy": -9, "loneliness": 9, "noise": 9})
48
+ for dim in ic.DIMS:
49
+ self.assertGreaterEqual(out[dim], 0.0)
50
+ self.assertLessEqual(out[dim], 1.0)
51
+
52
+ def test_defaults_on_empty_state(self):
53
+ out = ic.target({})
54
+ self.assertAlmostEqual(out["tension"], 0.125, places=4)
55
+ self.assertAlmostEqual(out["warmth"], 0.50, places=4)
56
+ self.assertAlmostEqual(out["heaviness"], 0.09, places=4)
57
+ self.assertAlmostEqual(out["clarity"], 1.00, places=4)
58
+
59
+ def test_arousal_alias_and_label_fallbacks(self):
60
+ self.assertAlmostEqual(ic.inputs({"a": 0.9})["arousal"], 0.9)
61
+ sad = ic.inputs({"labels": {"emotion": "sadness"}, "intensity": 0.8})
62
+ self.assertAlmostEqual(sad["sadness"], 0.8)
63
+ lone = ic.inputs({"labels": {"emotion": "loneliness"}, "intensity": 0.6})
64
+ self.assertAlmostEqual(lone["loneliness"], 0.6)
65
+
66
+ def test_noise_dict_is_averaged(self):
67
+ self.assertAlmostEqual(ic.inputs({"noise": {"a": 0.2, "b": -0.4}})["noise"], 0.3)
68
+
69
+
70
+ class UpdateTest(unittest.TestCase):
71
+ def test_ema_moves_toward_target(self):
72
+ prev = dict(GOOD)
73
+ new = ic.update(prev, STATE, dt_hours=1.0, rate=0.25)
74
+ alpha = 1.0 - math.exp(-0.25)
75
+ goal = ic.target(STATE)
76
+ for dim in ic.DIMS:
77
+ expect = round(prev[dim] + alpha * (goal[dim] - prev[dim]), 4)
78
+ self.assertAlmostEqual(new[dim], expect, places=4)
79
+
80
+ def test_zero_dt_is_identity(self):
81
+ prev = {"tension": 0.1, "warmth": 0.7, "heaviness": 0.2, "clarity": 0.9}
82
+ out = ic.update(prev, STATE, dt_hours=0.0)
83
+ for dim in ic.DIMS:
84
+ self.assertAlmostEqual(out[dim], prev[dim])
85
+
86
+ def test_same_now_is_idempotent(self):
87
+ prev = {"tension": 0.1, "warmth": 0.7, "heaviness": 0.2,
88
+ "clarity": 0.9, "ts": 1000.0}
89
+ out = ic.update(prev, STATE, dt_hours=1.0, now=1000.0)
90
+ for dim in ic.DIMS:
91
+ self.assertAlmostEqual(out[dim], prev[dim])
92
+ self.assertEqual(out["ts"], 1000.0)
93
+
94
+ def test_dt_derived_from_now_and_ts(self):
95
+ prev = {"tension": 0.1, "warmth": 0.7, "heaviness": 0.2,
96
+ "clarity": 0.9, "ts": 0.0}
97
+ a = ic.update(prev, STATE, dt_hours=1.0)
98
+ b = ic.update(prev, STATE, now=3600.0)
99
+ for dim in ic.DIMS:
100
+ self.assertAlmostEqual(a[dim], b[dim])
101
+
102
+ def test_converges_after_many_steps(self):
103
+ cur = {"tension": 0.0, "warmth": 0.0, "heaviness": 0.0, "clarity": 0.0}
104
+ goal = ic.target(STATE)
105
+ for _ in range(200):
106
+ cur = ic.update(cur, STATE, dt_hours=1.0, rate=0.25)
107
+ for dim in ic.DIMS:
108
+ self.assertAlmostEqual(cur[dim], goal[dim], places=2)
109
+
110
+
111
+ class DiscomfortTest(unittest.TestCase):
112
+ def test_inside_band_is_zero(self):
113
+ self.assertEqual(ic.discomfort(GOOD)["total"], 0.0)
114
+ self.assertEqual(ic.discomfort(GOOD)["parts"], dict.fromkeys(ic.DIMS, 0.0))
115
+
116
+ def test_outside_band_positive_and_bounded(self):
117
+ shut = ic.discomfort(SHUT)
118
+ self.assertGreater(shut["total"], 0.0)
119
+ self.assertLessEqual(shut["total"], 1.0)
120
+ self.assertGreater(shut["parts"]["tension"], 0.0)
121
+ self.assertGreater(shut["parts"]["warmth"], 0.0)
122
+
123
+ def test_extremes_are_bounded_and_high(self):
124
+ self.assertGreater(ic.discomfort(OPEN)["total"], 0.6)
125
+ worst = {"tension": 1.0, "warmth": 0.0, "heaviness": 1.0, "clarity": 0.0}
126
+ self.assertAlmostEqual(ic.discomfort(worst)["total"], 1.0, places=2)
127
+
128
+ def test_setpoint_override(self):
129
+ override = {"comfort": {"tension": 0.90}, "band": {"tension": 0.05}}
130
+ flat = ic.discomfort(GOOD)
131
+ moved = ic.discomfort(GOOD, override)
132
+ self.assertGreater(moved["total"], flat["total"])
133
+
134
+ def test_view_shape(self):
135
+ out = ic.view(SHUT)
136
+ for dim in ic.DIMS:
137
+ self.assertIn(dim, out)
138
+ self.assertIn("discomfort", out)
139
+ self.assertAlmostEqual(out["discomfort"], ic.discomfort(SHUT)["total"])
140
+
141
+
142
+ class ChooseActionTest(unittest.TestCase):
143
+ def _pick(self, intero, context=None):
144
+ out = rl.choose_action(intero, context)
145
+ self.assertIn(out["action"], rl.ACTIONS)
146
+ self.assertTrue(out["reason"])
147
+ self.assertGreaterEqual(out["expected_gain"], 0.0)
148
+ self.assertLessEqual(out["expected_gain"], 1.0)
149
+ return out["action"]
150
+
151
+ def test_conflict_plus_tension_repairs(self):
152
+ self.assertEqual(self._pick({"tension": 0.80, "warmth": 0.40,
153
+ "heaviness": 0.20, "clarity": 0.70},
154
+ {"conflict": 0.6}), "repair")
155
+
156
+ def test_tense_but_warm_approaches(self):
157
+ self.assertEqual(self._pick({"tension": 0.70, "warmth": 0.50,
158
+ "heaviness": 0.20, "clarity": 0.70},
159
+ {"conflict": 0.0}), "approach")
160
+
161
+ def test_heavy_exhausted_rests(self):
162
+ self.assertEqual(self._pick({"tension": 0.30, "warmth": 0.50,
163
+ "heaviness": 0.80, "clarity": 0.60},
164
+ {"energy": 0.10}), "rest")
165
+
166
+ def test_heavy_low_energy_withdraws(self):
167
+ self.assertEqual(self._pick({"tension": 0.30, "warmth": 0.50,
168
+ "heaviness": 0.80, "clarity": 0.60},
169
+ {"energy": 0.30}), "withdraw")
170
+
171
+ def test_unclear_asks(self):
172
+ self.assertEqual(self._pick({"tension": 0.30, "warmth": 0.55,
173
+ "heaviness": 0.20, "clarity": 0.20},
174
+ {"conflict": 0.4}), "question")
175
+
176
+ def test_cold_no_conflict_shares(self):
177
+ self.assertEqual(self._pick({"tension": 0.30, "warmth": 0.20,
178
+ "heaviness": 0.20, "clarity": 0.80},
179
+ {"conflict": 0.0}), "share")
180
+
181
+ def test_unclear_cold_shares(self):
182
+ self.assertEqual(self._pick({"tension": 0.30, "warmth": 0.40,
183
+ "heaviness": 0.20, "clarity": 0.20},
184
+ {"conflict": 0.0}), "share")
185
+
186
+ def test_warm_defaults_to_approach(self):
187
+ self.assertEqual(self._pick({"tension": 0.20, "warmth": 0.85,
188
+ "heaviness": 0.10, "clarity": 0.90}), "approach")
189
+
190
+
191
+ class OutcomeEfficacyTest(unittest.TestCase):
192
+ def test_outcome_improved(self):
193
+ out = rl.outcome(SHUT, GOOD, "repair")
194
+ self.assertLess(out["delta_discomfort"], 0)
195
+ self.assertTrue(out["success"])
196
+ self.assertEqual(out["action"], "repair")
197
+
198
+ def test_outcome_worse(self):
199
+ out = rl.outcome(GOOD, SHUT, "share")
200
+ self.assertGreater(out["delta_discomfort"], 0)
201
+ self.assertFalse(out["success"])
202
+
203
+ def test_outcome_accepts_discomfort_dicts(self):
204
+ before = ic.discomfort(SHUT)
205
+ after = ic.discomfort(GOOD)
206
+ out = rl.outcome(before, after, "rest")
207
+ self.assertTrue(out["success"])
208
+
209
+ def test_efficacy_prior_and_ewma(self):
210
+ self.assertAlmostEqual(rl.efficacy([], "approach"), 0.5)
211
+ self.assertAlmostEqual(rl.efficacy([("approach", True)], "approach"), 0.625)
212
+ self.assertAlmostEqual(
213
+ rl.efficacy([("approach", True), ("approach", False)], "approach"), 0.4688)
214
+ self.assertAlmostEqual(rl.efficacy([("share", False)], "approach"), 0.5)
215
+
216
+ def test_efficacy_dict_rows_and_bounds(self):
217
+ rows = [{"action": "rest", "success": True} for _ in range(20)]
218
+ self.assertGreater(rl.efficacy(rows, "rest"), 0.9)
219
+ self.assertLessEqual(rl.efficacy(rows, "rest"), 1.0)
220
+ self.assertEqual(rl.sample("rest", True)["action"], "rest")
221
+
222
+
223
+ if __name__ == "__main__":
224
+ unittest.main()