dsh-biocore 0.1.0 → 0.1.2

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 (250) hide show
  1. package/README.md +2 -2
  2. package/lib/py/bridge.py +15 -7
  3. package/lib/py-bridge.js +4 -3
  4. package/package.json +3 -2
  5. package/python/biocore_memory/__init__.py +21 -0
  6. package/python/biocore_memory/adapters/__init__.py +2 -0
  7. package/python/biocore_memory/adapters/astrbot.py +24 -0
  8. package/python/biocore_memory/adapters/dsh_cli.py +335 -0
  9. package/python/biocore_memory/co_recall.py +324 -0
  10. package/python/biocore_memory/consolidate/__init__.py +11 -0
  11. package/python/biocore_memory/consolidate/gated.py +104 -0
  12. package/python/biocore_memory/consolidate/neighbors.py +68 -0
  13. package/python/biocore_memory/consolidate/reflection.py +45 -0
  14. package/python/biocore_memory/consolidate/tree.py +95 -0
  15. package/python/biocore_memory/consolidate/writeback.py +181 -0
  16. package/python/biocore_memory/core/__init__.py +4 -0
  17. package/python/biocore_memory/core/config.py +127 -0
  18. package/python/biocore_memory/core/permissions.py +69 -0
  19. package/python/biocore_memory/core/types.py +116 -0
  20. package/python/biocore_memory/core/util.py +26 -0
  21. package/python/biocore_memory/embedding_local.py +447 -0
  22. package/python/biocore_memory/embedding_mode.py +156 -0
  23. package/python/biocore_memory/engine.py +2476 -0
  24. package/python/biocore_memory/engine_helpers.py +266 -0
  25. package/python/biocore_memory/event/__init__.py +3 -0
  26. package/python/biocore_memory/event/_types.py +16 -0
  27. package/python/biocore_memory/event/consistency.py +117 -0
  28. package/python/biocore_memory/event/extract.py +48 -0
  29. package/python/biocore_memory/event/media.py +111 -0
  30. package/python/biocore_memory/event/notes.py +85 -0
  31. package/python/biocore_memory/event/notes_link.py +87 -0
  32. package/python/biocore_memory/event/vector.py +69 -0
  33. package/python/biocore_memory/evict/__init__.py +3 -0
  34. package/python/biocore_memory/evict/adaptive.py +73 -0
  35. package/python/biocore_memory/evict/consequence.py +58 -0
  36. package/python/biocore_memory/evict/heat.py +54 -0
  37. package/python/biocore_memory/evict/inhibition.py +105 -0
  38. package/python/biocore_memory/evict/policy.py +188 -0
  39. package/python/biocore_memory/evict/score.py +23 -0
  40. package/python/biocore_memory/identity/__init__.py +6 -0
  41. package/python/biocore_memory/identity/api.py +99 -0
  42. package/python/biocore_memory/identity/history.py +9 -0
  43. package/python/biocore_memory/identity/ledger.py +191 -0
  44. package/python/biocore_memory/identity/narrative.py +358 -0
  45. package/python/biocore_memory/identity/snapshot.py +13 -0
  46. package/python/biocore_memory/identity/writeback.py +61 -0
  47. package/python/biocore_memory/index/__init__.py +3 -0
  48. package/python/biocore_memory/index/cue_index.py +80 -0
  49. package/python/biocore_memory/index/entities.py +85 -0
  50. package/python/biocore_memory/index/entity_boost.py +104 -0
  51. package/python/biocore_memory/index/graph.py +172 -0
  52. package/python/biocore_memory/recall/__init__.py +5 -0
  53. package/python/biocore_memory/recall/api.py +65 -0
  54. package/python/biocore_memory/recall/bm25.py +118 -0
  55. package/python/biocore_memory/recall/channels.py +98 -0
  56. package/python/biocore_memory/recall/complexity.py +62 -0
  57. package/python/biocore_memory/recall/constraints.py +75 -0
  58. package/python/biocore_memory/recall/embedding.py +745 -0
  59. package/python/biocore_memory/recall/expand.py +26 -0
  60. package/python/biocore_memory/recall/filters.py +40 -0
  61. package/python/biocore_memory/recall/fusion.py +18 -0
  62. package/python/biocore_memory/recall/mmr.py +70 -0
  63. package/python/biocore_memory/recall/ppr.py +85 -0
  64. package/python/biocore_memory/recall/retrieval_practice.py +102 -0
  65. package/python/biocore_memory/relay/__init__.py +2 -0
  66. package/python/biocore_memory/relay/card.py +51 -0
  67. package/python/biocore_memory/slots/__init__.py +18 -0
  68. package/python/biocore_memory/slots/admission.py +64 -0
  69. package/python/biocore_memory/slots/boundary.py +128 -0
  70. package/python/biocore_memory/slots/evict_bridge.py +106 -0
  71. package/python/biocore_memory/slots/registry.py +135 -0
  72. package/python/biocore_memory/slots/switch.py +42 -0
  73. package/python/biocore_memory/store/__init__.py +4 -0
  74. package/python/biocore_memory/store/audit.py +74 -0
  75. package/python/biocore_memory/store/compress.py +81 -0
  76. package/python/biocore_memory/store/dedupe.py +178 -0
  77. package/python/biocore_memory/store/json_store.py +154 -0
  78. package/python/biocore_memory/store/media.py +145 -0
  79. package/python/biocore_memory/store/provenance.py +73 -0
  80. package/python/biocore_memory/store/rate_limit.py +93 -0
  81. package/python/biocore_memory/store/security.py +107 -0
  82. package/python/biocore_memory/store/source_consistency.py +123 -0
  83. package/python/biocore_memory/store/tiering.py +61 -0
  84. package/python/biocore_memory/store/tiering_exec.py +50 -0
  85. package/python/biocore_memory/store/tombstone.py +23 -0
  86. package/python/biocore_memory/store/versions.py +69 -0
  87. package/python/biocore_memory/thread/__init__.py +2 -0
  88. package/python/biocore_memory/thread/card.py +58 -0
  89. package/python/biocore_model/__init__.py +37 -0
  90. package/python/biocore_model/affective_labor.py +162 -0
  91. package/python/biocore_model/appraisal.py +257 -0
  92. package/python/biocore_model/appraisal_action.py +78 -0
  93. package/python/biocore_model/archive_queue.py +60 -0
  94. package/python/biocore_model/attachment_behavior.py +130 -0
  95. package/python/biocore_model/attachment_regulation.py +75 -0
  96. package/python/biocore_model/attachment_state.py +41 -0
  97. package/python/biocore_model/attribution.py +73 -0
  98. package/python/biocore_model/attributor.py +162 -0
  99. package/python/biocore_model/autonomic.py +91 -0
  100. package/python/biocore_model/autonomy_affect.py +51 -0
  101. package/python/biocore_model/autonomy_check.py +67 -0
  102. package/python/biocore_model/autonomy_loop.py +122 -0
  103. package/python/biocore_model/autonomy_mode.py +114 -0
  104. package/python/biocore_model/autonomy_model.py +733 -0
  105. package/python/biocore_model/autonomy_params.py +131 -0
  106. package/python/biocore_model/autonomy_reason.py +73 -0
  107. package/python/biocore_model/autonomy_tick.py +227 -0
  108. package/python/biocore_model/bio_appraisal.py +49 -0
  109. package/python/biocore_model/bio_autonomy_state.py +171 -0
  110. package/python/biocore_model/bio_config.py +221 -0
  111. package/python/biocore_model/bio_const.py +128 -0
  112. package/python/biocore_model/bio_daily.py +267 -0
  113. package/python/biocore_model/bio_emotion.py +538 -0
  114. package/python/biocore_model/bio_emotion2.py +214 -0
  115. package/python/biocore_model/bio_goal.py +220 -0
  116. package/python/biocore_model/bio_identity.py +82 -0
  117. package/python/biocore_model/bio_noise.py +119 -0
  118. package/python/biocore_model/bio_physiology2.py +114 -0
  119. package/python/biocore_model/bio_snapshot.py +324 -0
  120. package/python/biocore_model/bio_state.py +272 -0
  121. package/python/biocore_model/bio_tick.py +310 -0
  122. package/python/biocore_model/bio_util.py +82 -0
  123. package/python/biocore_model/blocks.py +264 -0
  124. package/python/biocore_model/boundary.py +251 -0
  125. package/python/biocore_model/boundary_gate.py +188 -0
  126. package/python/biocore_model/commitment_extractor.py +517 -0
  127. package/python/biocore_model/compassion_fatigue.py +84 -0
  128. package/python/biocore_model/connection_bids.py +120 -0
  129. package/python/biocore_model/core_bridge.py +177 -0
  130. package/python/biocore_model/core_client.py +127 -0
  131. package/python/biocore_model/core_commands.py +112 -0
  132. package/python/biocore_model/core_mode.py +104 -0
  133. package/python/biocore_model/core_mode_ui.mjs +104 -0
  134. package/python/biocore_model/criticality.py +81 -0
  135. package/python/biocore_model/defense_mechanisms.py +272 -0
  136. package/python/biocore_model/delta_budget.py +99 -0
  137. package/python/biocore_model/diag_trace.py +274 -0
  138. package/python/biocore_model/dissonance.py +134 -0
  139. package/python/biocore_model/emotion_geometry.py +108 -0
  140. package/python/biocore_model/emotion_probe.py +209 -0
  141. package/python/biocore_model/entity_graph.py +931 -0
  142. package/python/biocore_model/entity_resolve.py +260 -0
  143. package/python/biocore_model/envy.py +193 -0
  144. package/python/biocore_model/exit_or_silence.py +230 -0
  145. package/python/biocore_model/expr_guard.py +24 -0
  146. package/python/biocore_model/expr_intent.py +77 -0
  147. package/python/biocore_model/expr_state.py +204 -0
  148. package/python/biocore_model/expr_template.py +105 -0
  149. package/python/biocore_model/expr_tone.py +81 -0
  150. package/python/biocore_model/extreme_scenarios.py +205 -0
  151. package/python/biocore_model/feedback_flow.py +227 -0
  152. package/python/biocore_model/feedback_guard.py +129 -0
  153. package/python/biocore_model/feedback_llm.py +163 -0
  154. package/python/biocore_model/feedback_memory.py +96 -0
  155. package/python/biocore_model/feedback_user.py +93 -0
  156. package/python/biocore_model/frustration_curve.py +110 -0
  157. package/python/biocore_model/granularity.py +283 -0
  158. package/python/biocore_model/graph_extract.py +248 -0
  159. package/python/biocore_model/graph_recall.py +221 -0
  160. package/python/biocore_model/intent_render.py +91 -0
  161. package/python/biocore_model/intero_core.py +235 -0
  162. package/python/biocore_model/intero_style.py +116 -0
  163. package/python/biocore_model/layered_memory.py +297 -0
  164. package/python/biocore_model/learning_probe.py +120 -0
  165. package/python/biocore_model/memory_dual.py +224 -0
  166. package/python/biocore_model/memory_forgetting.py +125 -0
  167. package/python/biocore_model/memory_store.py +1399 -0
  168. package/python/biocore_model/metacog.py +153 -0
  169. package/python/biocore_model/migrate.py +733 -0
  170. package/python/biocore_model/migrate_store.py +337 -0
  171. package/python/biocore_model/mind_wander.py +111 -0
  172. package/python/biocore_model/mood.py +48 -0
  173. package/python/biocore_model/narrative.py +172 -0
  174. package/python/biocore_model/needs_esteem.py +116 -0
  175. package/python/biocore_model/needs_events.py +137 -0
  176. package/python/biocore_model/needs_sleep.py +72 -0
  177. package/python/biocore_model/noise_bank.py +95 -0
  178. package/python/biocore_model/persona_flow.mjs +25 -0
  179. package/python/biocore_model/pipeline.py +240 -0
  180. package/python/biocore_model/pipeline_api.py +200 -0
  181. package/python/biocore_model/plugin_config.py +83 -0
  182. package/python/biocore_model/plugin_routes.py +1435 -0
  183. package/python/biocore_model/policy_learning.py +132 -0
  184. package/python/biocore_model/possible_selves.py +110 -0
  185. package/python/biocore_model/predictor.py +178 -0
  186. package/python/biocore_model/preset.py +205 -0
  187. package/python/biocore_model/proactive_context.py +153 -0
  188. package/python/biocore_model/prompt_rules.py +90 -0
  189. package/python/biocore_model/prospective.py +183 -0
  190. package/python/biocore_model/provider_fallback.py +97 -0
  191. package/python/biocore_model/reconstruction.py +132 -0
  192. package/python/biocore_model/regulation_loop.py +179 -0
  193. package/python/biocore_model/regulation_strategies.py +294 -0
  194. package/python/biocore_model/relation_stage.py +130 -0
  195. package/python/biocore_model/relationship_stage.py +95 -0
  196. package/python/biocore_model/render.py +901 -0
  197. package/python/biocore_model/render_guard.mjs +34 -0
  198. package/python/biocore_model/repair_after_boundary.py +350 -0
  199. package/python/biocore_model/reply_limit.py +183 -0
  200. package/python/biocore_model/reply_split.py +203 -0
  201. package/python/biocore_model/rollback.py +143 -0
  202. package/python/biocore_model/runtime.py +479 -0
  203. package/python/biocore_model/sanitize.py +200 -0
  204. package/python/biocore_model/scheduler.py +123 -0
  205. package/python/biocore_model/schema.py +120 -0
  206. package/python/biocore_model/secrecy.py +145 -0
  207. package/python/biocore_model/self_esteem.py +50 -0
  208. package/python/biocore_model/self_intent.py +437 -0
  209. package/python/biocore_model/self_interest.py +263 -0
  210. package/python/biocore_model/self_verification.py +178 -0
  211. package/python/biocore_model/services.py +78 -0
  212. package/python/biocore_model/situation.py +254 -0
  213. package/python/biocore_model/sleep_circadian.py +116 -0
  214. package/python/biocore_model/social_pain.py +69 -0
  215. package/python/biocore_model/social_repair.py +111 -0
  216. package/python/biocore_model/social_theory.py +131 -0
  217. package/python/biocore_model/source_monitoring.py +292 -0
  218. package/python/biocore_model/stages.py +487 -0
  219. package/python/biocore_model/state_tag.py +231 -0
  220. package/python/biocore_model/switch_groups.mjs +201 -0
  221. package/python/biocore_model/tabs_state.mjs +37 -0
  222. package/python/biocore_model/template_expr.py +252 -0
  223. package/python/biocore_model/tools/caps_check.mjs +23 -0
  224. package/python/biocore_model/tools/init_symbols_check.mjs +11 -0
  225. package/python/biocore_model/tools/missing_ids.mjs +16 -0
  226. package/python/biocore_model/tools/scope_check.mjs +19 -0
  227. package/python/biocore_model/topic_control.py +268 -0
  228. package/python/biocore_model/turn_memory.py +152 -0
  229. package/python/biocore_model/ui_compat.mjs +48 -0
  230. package/python/biocore_model/ui_settings.py +266 -0
  231. package/python/biocore_model/ui_settings.py.bak_authority +108 -0
  232. package/python/biocore_model/value_order.py +186 -0
  233. package/python/biocore_model/view_mode.mjs +8 -0
  234. package/python/biocore_model/voice_bank.py +177 -0
  235. package/python/biocore_model/waiting_sense.py +229 -0
  236. package/python/biocore_model/x_directives.py +142 -0
  237. package/python/biocore_runtime/__init__.py +7 -0
  238. package/python/biocore_runtime/pipeline.py +1915 -0
  239. package/python/dsh_adapter/README.md +96 -0
  240. package/python/dsh_adapter/adapter.py +1077 -0
  241. package/python/dsh_adapter/cli.py +107 -0
  242. package/python/dsh_adapter/data/demo_state.json +164 -0
  243. package/python/dsh_adapter/data/verify_state.json +164 -0
  244. package/python/dsh_adapter/tests/__init__.py +1 -0
  245. package/python/dsh_adapter/tests/test_adapter.py +494 -0
  246. package/ui/panel-layout.js +3 -3
  247. package/ui/panel.css +53 -6
  248. package/ui/panel.html +33 -32
  249. package/ui/panel.js +9 -1
  250. package/lib/py/__pycache__/bridge.cpython-310.pyc +0 -0
@@ -0,0 +1,99 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Identity write orchestration (engine delegates here; store version-chained)."""
3
+ from __future__ import annotations
4
+ from ..core.config import MAX_STEP, SAME_DIRECTION_MIN
5
+ from ..core.util import clamp01, now_ts, sha12
6
+ from .writeback import (evidence_count, is_identity, is_major_trigger,
7
+ writeback_decision)
8
+
9
+
10
+ def _target(store, entry_id=None, trigger=None):
11
+ if entry_id:
12
+ return store.find(entry_id)
13
+ identities = [e for e in store.entries if isinstance(e, dict) and is_identity(e)]
14
+ if not identities:
15
+ return None
16
+ needle = str(trigger or "")
17
+ for entry in identities:
18
+ if needle and needle[:20] in str(entry.get("text") or ""):
19
+ return entry
20
+ return identities[0]
21
+
22
+
23
+ def _legacy(store, enabled, state, entry_id, direction=1, step=0.01, major_event=False):
24
+ if not enabled:
25
+ return {"allowed": False, "reason": "disabled", "applied": 0.0}
26
+ entry = store.find(entry_id)
27
+ if entry is None:
28
+ return {"allowed": False, "reason": "missing", "applied": 0.0}
29
+ if not is_identity(entry):
30
+ return {"allowed": False, "reason": "not_identity", "applied": 0.0}
31
+ allowed, applied, new_state, reason = writeback_decision(
32
+ state.get(str(entry_id)), direction=direction,
33
+ major_event=major_event, step=step if step is not None else 0.01)
34
+ state[str(entry_id)] = new_state
35
+ if not allowed:
36
+ return {"allowed": False, "reason": reason, "applied": 0.0}
37
+ current = clamp01(entry.get("identity_weight", 0.0))
38
+ store.update(entry_id,
39
+ identity_weight=round(clamp01(current + applied), 4),
40
+ identity_writeback_ts=now_ts())
41
+ return {"allowed": True, "reason": reason, "applied": round(applied, 4),
42
+ "history": len(entry.get("previous_versions") or [])}
43
+
44
+
45
+ def write(store, enabled, state, trigger=None, evidence=None, delta=0.0,
46
+ entry_id=None, direction=1, step=None, major_event=False, now=0.0):
47
+ """New API trigger/evidence/delta, with legacy entry_id compatibility."""
48
+ legacy = (evidence is None and entry_id is None and trigger is not None
49
+ and store.find(trigger) is not None)
50
+ if legacy:
51
+ return _legacy(store, enabled, state, trigger, direction=direction,
52
+ step=step if step is not None else delta,
53
+ major_event=major_event)
54
+ if not enabled:
55
+ return {"allowed": False, "reason": "disabled", "applied": 0.0}
56
+ evid = list(evidence or [])
57
+ major = bool(major_event or is_major_trigger(trigger))
58
+ target = _target(store, entry_id=entry_id, trigger=trigger)
59
+ if target is None:
60
+ if not (major or evidence_count(evid, delta) >= SAME_DIRECTION_MIN):
61
+ return {"allowed": False, "reason": "need_more_same_direction",
62
+ "evidence_count": evidence_count(evid, delta), "applied": 0.0}
63
+ text = str(trigger or "identity")[:120]
64
+ target = store.add({"id": sha12(text + str(now)),
65
+ "text": text, "role": "system", "ts": now,
66
+ "self_defining": True, "importance": 0.8,
67
+ "memory_source": "identity_trigger"})
68
+ if target is None:
69
+ return {"allowed": False, "reason": "missing", "applied": 0.0}
70
+ if not is_identity(target):
71
+ return {"allowed": False, "reason": "not_identity", "applied": 0.0}
72
+ stored = target.get("identity_evidence")
73
+ combined = ([x for x in stored if isinstance(x, dict)]
74
+ if isinstance(stored, list) else []) + [x for x in evid]
75
+ count = evidence_count(combined, delta)
76
+ if not (major or count >= SAME_DIRECTION_MIN):
77
+ store.update(target.get("id"), identity_evidence=combined[-20:])
78
+ return {"allowed": False, "reason": "need_more_same_direction",
79
+ "evidence_count": count, "applied": 0.0,
80
+ "target_id": str(target.get("id") or "")}
81
+ try:
82
+ amount = max(-MAX_STEP, min(MAX_STEP, float(delta or 0.0)))
83
+ except Exception:
84
+ amount = 0.0
85
+ if amount == 0:
86
+ amount = 0.01
87
+ current = clamp01(target.get("identity_weight", 0.0))
88
+ history = target.get("identity_history")
89
+ history = list(history) if isinstance(history, list) else []
90
+ history.append({"ts": now_ts(now), "trigger": str(trigger or "")[:80],
91
+ "evidence": combined[-20:], "delta": round(amount, 4)})
92
+ store.update(target.get("id"),
93
+ identity_weight=round(clamp01(current + amount), 4),
94
+ identity_evidence=combined[-20:], identity_history=history[-20:],
95
+ identity_writeback_ts=now_ts(now))
96
+ return {"allowed": True, "reason": "major_event" if major else "same_direction_3",
97
+ "applied": round(amount, 4), "evidence_count": count,
98
+ "target_id": str(target.get("id") or ""),
99
+ "history": len(store.find(target.get("id")).get("previous_versions") or [])}
@@ -0,0 +1,9 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Identity version-chain helpers (read-only view)."""
3
+ from __future__ import annotations
4
+
5
+
6
+ def history_rows(entry):
7
+ e = entry if isinstance(entry, dict) else {}
8
+ rows = e.get("previous_versions")
9
+ return [dict(x) for x in rows if isinstance(x, dict)] if isinstance(rows, list) else []
@@ -0,0 +1,191 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Relationship ledger: write relation events as system memory entries.
3
+
4
+ Conflicts, repairs and milestones become role="system" entries with
5
+ source="relation_ledger" carrying kind / trust_delta / conflict_delta.
6
+ Writes are idempotent per (kind, day): the same kind of relationship change is
7
+ recorded at most once per day, so replays never duplicate the ledger.
8
+
9
+ Interface:
10
+ append_entry(store, event, now=None, enabled=None)
11
+ -> {"written": [id], "skipped": [...], "kind": str, "day": str}
12
+ store: MemoryStore-like object (entries list + add()) or {"entries": []};
13
+ event: {kind?, trust_delta?, conflict_delta?, ts?, day?, session?,
14
+ scope?, text?, summary?}; a missing kind is inferred from the
15
+ delta signs (conflict / repair / milestone).
16
+
17
+ The module is disabled by default (LEDGER_ENABLED=False): callers gate on
18
+ 'enabled' before writing. No IO, no LLM, no host imports; the caller decides
19
+ when to store.save().
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import time
24
+
25
+ from ..core.util import clamp01, now_ts, sha12
26
+
27
+ enabled = False
28
+ LEDGER_ENABLED = enabled
29
+ SOURCE = "relation_ledger"
30
+ KINDS = ("conflict", "repair", "milestone")
31
+ MAX_DELTA = 1.0
32
+ TEXT_MAX = 200
33
+
34
+ _KIND_ALIASES = {
35
+ "conflict": ("conflict", "clash", "rupture", "冲突", "矛盾", "争执"),
36
+ "repair": ("repair", "reconcile", "apology", "修复", "和解", "道歉"),
37
+ "milestone": ("milestone", "turning_point", "promise", "里程碑", "转折", "承诺"),
38
+ }
39
+ _LABELS = {"conflict": "冲突", "repair": "修复", "milestone": "里程碑"}
40
+
41
+
42
+ def _rows(store):
43
+ try:
44
+ rows = getattr(store, "entries", None)
45
+ if isinstance(rows, list):
46
+ return rows
47
+ except Exception:
48
+ pass
49
+ if isinstance(store, dict):
50
+ rows = store.get("entries")
51
+ return rows if isinstance(rows, list) else []
52
+ try:
53
+ return list(store or [])
54
+ except TypeError:
55
+ return []
56
+
57
+
58
+ def _add(store, entry):
59
+ try:
60
+ fn = getattr(store, "add", None)
61
+ if callable(fn):
62
+ return fn(entry)
63
+ if isinstance(store, dict):
64
+ store.setdefault("entries", []).append(entry)
65
+ return entry
66
+ store.append(entry)
67
+ return entry
68
+ except Exception:
69
+ return None
70
+
71
+
72
+ def _event_value(event, key, default=None):
73
+ if isinstance(event, dict):
74
+ if event.get(key) is not None:
75
+ return event.get(key)
76
+ metadata = event.get("metadata")
77
+ if isinstance(metadata, dict) and metadata.get(key) is not None:
78
+ return metadata.get(key)
79
+ return default
80
+ return getattr(event, key, default)
81
+
82
+
83
+ def _delta(value):
84
+ try:
85
+ value = float(value or 0.0)
86
+ except (TypeError, ValueError):
87
+ return 0.0
88
+ if value != value or value in (float("inf"), float("-inf")):
89
+ return 0.0
90
+ return round(max(-MAX_DELTA, min(MAX_DELTA, value)), 4)
91
+
92
+
93
+ def _day(ts):
94
+ if ts <= 0.0:
95
+ return "unknown"
96
+ try:
97
+ return time.strftime("%Y-%m-%d", time.gmtime(ts))
98
+ except (OverflowError, OSError, ValueError):
99
+ return "unknown"
100
+
101
+
102
+ def _kind(event, trust_delta, conflict_delta):
103
+ raw = str(_event_value(event, "kind", "") or "").strip().lower()
104
+ for kind in KINDS:
105
+ aliases = _KIND_ALIASES.get(kind, ())
106
+ if raw == kind or raw in aliases or any(alias in raw for alias in aliases):
107
+ return kind
108
+ if conflict_delta > 0.0 or trust_delta < 0.0:
109
+ return "conflict"
110
+ if conflict_delta < 0.0 or trust_delta > 0.0:
111
+ return "repair"
112
+ return "milestone"
113
+
114
+
115
+ def _text(event, kind, trust_delta, conflict_delta):
116
+ raw = _event_value(event, "text") or _event_value(event, "summary") or ""
117
+ text = " ".join(str(raw or "").split())
118
+ if not text:
119
+ text = "关系账本 %s:trust %+0.2f / conflict %+0.2f" % (
120
+ _LABELS.get(kind, kind), trust_delta, conflict_delta)
121
+ return text[:TEXT_MAX]
122
+
123
+
124
+ def _existing(rows, kind, day):
125
+ for entry in rows:
126
+ if not isinstance(entry, dict):
127
+ continue
128
+ if str(entry.get("source") or "") != SOURCE:
129
+ continue
130
+ metadata = entry.get("metadata")
131
+ metadata = metadata if isinstance(metadata, dict) else {}
132
+ entry_kind = str(entry.get("kind") or metadata.get("kind") or "")
133
+ entry_day = str(entry.get("day") or metadata.get("day") or "")
134
+ if entry_kind == kind and entry_day == day:
135
+ return entry
136
+ return None
137
+
138
+
139
+ def append_entry(store, event, now=None, enabled=None):
140
+ """Append one idempotent (kind, day) relationship-ledger entry."""
141
+ result = {"written": [], "skipped": []}
142
+ if enabled is False:
143
+ result["skipped"].append({"reason": "disabled"})
144
+ return result
145
+ if store is None:
146
+ result["skipped"].append({"reason": "invalid_store"})
147
+ return result
148
+ trust_delta = _delta(_event_value(event, "trust_delta", 0.0))
149
+ conflict_delta = _delta(_event_value(event, "conflict_delta", 0.0))
150
+ kind = _kind(event, trust_delta, conflict_delta)
151
+ try:
152
+ stamp = float(_event_value(event, "ts", 0.0) or 0.0)
153
+ except (TypeError, ValueError):
154
+ stamp = 0.0
155
+ if stamp <= 0.0:
156
+ stamp = now_ts(now)
157
+ day = str(_event_value(event, "day") or "") or _day(stamp)
158
+ rows = _rows(store)
159
+ duplicate = _existing(rows, kind, day)
160
+ if duplicate is not None:
161
+ result["skipped"].append({"reason": "duplicate",
162
+ "id": str(duplicate.get("id") or ""),
163
+ "kind": kind, "day": day})
164
+ return result
165
+ importance = round(clamp01(0.5 + 0.2 * (abs(trust_delta)
166
+ + abs(conflict_delta))), 4)
167
+ entry = {"id": SOURCE + "_" + sha12(kind + "|" + day),
168
+ "text": _text(event, kind, trust_delta, conflict_delta),
169
+ "role": "system", "source": SOURCE, "ts": stamp,
170
+ "importance": importance, "kind": kind,
171
+ "trust_delta": trust_delta, "conflict_delta": conflict_delta,
172
+ "day": day,
173
+ "metadata": {"origin": SOURCE, "kind": kind, "day": day,
174
+ "trust_delta": trust_delta,
175
+ "conflict_delta": conflict_delta,
176
+ "event_id": str(_event_value(event, "id") or "")}}
177
+ for key in ("session", "scope"):
178
+ value = _event_value(event, key)
179
+ if value:
180
+ entry[key] = str(value)
181
+ added = _add(store, entry)
182
+ if not isinstance(added, dict):
183
+ result["skipped"].append({"reason": "add_failed"})
184
+ return result
185
+ result["written"].append(str(added.get("id") or entry["id"]))
186
+ result["kind"] = kind
187
+ result["day"] = day
188
+ return result
189
+
190
+
191
+ __all__ = ["enabled", "LEDGER_ENABLED", "append_entry", "SOURCE", "KINDS"]
@@ -0,0 +1,358 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Narrative-identity update after consolidation (pure; default OFF).
3
+
4
+ Narrative identity integrates past and present into a story (McAdams & McLean
5
+ 2013). A narrative is rewritten only when one theme repeats across time:
6
+ >= MIN_ENTRIES same-theme memories spanning >= MIN_SPAN_DAYS days. Each update
7
+ appends the previous section to a bounded version chain, so the old narrative
8
+ is retained and rollback is possible.
9
+
10
+ Interface:
11
+ theme_of(entry) -> str
12
+ group_entries(entries) -> {theme: [entries]}
13
+ theme_span_days(entries) -> float
14
+ narrative_text(theme, entries) -> str
15
+ narrative_candidate(entries) -> dict | None
16
+ section(identity) -> {text, theme, version, history, entry_ids, ts}
17
+ plan_update(identity, entries, now=None, enabled=None) -> dict
18
+ apply_update(store, identity_id=None, entries=None, now=None, enabled=None)
19
+ plan_rollback(identity, version=None, now=None, enabled=None) -> dict
20
+ apply_rollback(store, identity_id=None, version=None, now=None, enabled=None)
21
+
22
+ Disabled by default (NARRATIVE_ENABLED=False): callers gate on 'enabled' or
23
+ pass enabled=True. No IO, no LLM, no host imports; apply_* only mutate the
24
+ given store and never call store.save().
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import time
29
+
30
+ from ..core.util import now_ts
31
+ from .writeback import is_identity
32
+
33
+ enabled = False
34
+ NARRATIVE_ENABLED = enabled
35
+ MIN_ENTRIES = 3
36
+ MIN_SPAN_DAYS = 7.0
37
+ MAX_VERSIONS = 20
38
+ MAX_NARRATIVE = 200
39
+ THEME_MAX = 24
40
+ SNIPPET_MAX = 40
41
+ SECONDS_PER_DAY = 86400.0
42
+ FIELD_TEXT = "identity_narrative"
43
+ FIELD_THEME = "identity_narrative_theme"
44
+ FIELD_VERSION = "identity_narrative_version"
45
+ FIELD_HISTORY = "identity_narrative_history"
46
+ FIELD_ENTRY_IDS = "identity_narrative_entry_ids"
47
+ FIELD_UPDATED_TS = "identity_narrative_updated_ts"
48
+
49
+
50
+ def _num(value, default=0.0):
51
+ try:
52
+ value = float(value)
53
+ except (TypeError, ValueError):
54
+ return default
55
+ return default if value != value else value
56
+
57
+
58
+ def _compact(value, limit=0):
59
+ text = " ".join(str(value or "").split())
60
+ return text[:limit] if limit else text
61
+
62
+
63
+ def _on(enabled):
64
+ return NARRATIVE_ENABLED if enabled is None else bool(enabled)
65
+
66
+
67
+ def _row(entry):
68
+ if isinstance(entry, dict):
69
+ return entry
70
+ if hasattr(entry, "to_dict"):
71
+ try:
72
+ row = entry.to_dict()
73
+ except Exception:
74
+ return None
75
+ return row if isinstance(row, dict) else None
76
+ return None
77
+
78
+
79
+ def _rows(entries):
80
+ if isinstance(entries, dict):
81
+ entries = entries.get("entries") or []
82
+ rows, seen = [], set()
83
+ try:
84
+ items = list(entries or [])
85
+ except TypeError:
86
+ return []
87
+ for entry in items:
88
+ row = _row(entry)
89
+ if row is not None and id(row) not in seen:
90
+ seen.add(id(row))
91
+ rows.append(row)
92
+ return rows
93
+
94
+
95
+ def theme_of(entry):
96
+ """Return the deterministic theme key of one entry ('' when unknown)."""
97
+ row = _row(entry)
98
+ if row is None:
99
+ return ""
100
+ candidates = [row]
101
+ cue = row.get("cue_index")
102
+ if isinstance(cue, dict):
103
+ candidates.append(cue)
104
+ if isinstance(row.get("metadata"), dict):
105
+ candidates.append(row["metadata"])
106
+ for source in candidates:
107
+ for key in ("theme", "topic", "identity_theme", "event_name"):
108
+ value = _compact(source.get(key), THEME_MAX)
109
+ if value:
110
+ return value
111
+ for key in ("tags", "entities"):
112
+ values = row.get(key)
113
+ if isinstance(values, (list, tuple)) and values:
114
+ first = values[0]
115
+ if isinstance(first, dict):
116
+ first = first.get("name") or first.get("text") or ""
117
+ value = _compact(first, THEME_MAX)
118
+ if value:
119
+ return value
120
+ return ""
121
+
122
+
123
+ def group_entries(entries):
124
+ """Group entries by theme; each group is sorted by (ts, id)."""
125
+ groups = {}
126
+ for row in _rows(entries):
127
+ theme = theme_of(row)
128
+ if theme:
129
+ groups.setdefault(theme, []).append(row)
130
+ result = {}
131
+ for theme in sorted(groups):
132
+ rows = groups[theme]
133
+ rows.sort(key=lambda e: (_num(e.get("ts"), 0.0), str(e.get("id") or "")))
134
+ result[theme] = rows
135
+ return result
136
+
137
+
138
+ def theme_span_days(entries):
139
+ """Return max-ts minus min-ts in days (0.0 when fewer than two stamps)."""
140
+ stamps = [_num(row.get("ts"), 0.0) for row in _rows(entries)]
141
+ stamps = [stamp for stamp in stamps if stamp > 0.0]
142
+ if len(stamps) < 2:
143
+ return 0.0
144
+ return round((max(stamps) - min(stamps)) / SECONDS_PER_DAY, 4)
145
+
146
+
147
+ def _day(ts):
148
+ if ts <= 0.0:
149
+ return ""
150
+ try:
151
+ return time.strftime("%Y-%m-%d", time.gmtime(ts))
152
+ except (OverflowError, OSError, ValueError):
153
+ return ""
154
+
155
+
156
+ def narrative_text(theme, entries):
157
+ """Build a bounded deterministic narrative sentence for one theme."""
158
+ rows = sorted(_rows(entries),
159
+ key=lambda e: (_num(e.get("ts"), 0.0), str(e.get("id") or "")))
160
+ if not rows:
161
+ return ""
162
+ snippets = []
163
+ for row in (rows[0], rows[-1]):
164
+ text = _compact(row.get("text"), SNIPPET_MAX)
165
+ if text and text not in snippets:
166
+ snippets.append(text)
167
+ span = int(round(theme_span_days(rows)))
168
+ first = _day(_num(rows[0].get("ts"), 0.0))
169
+ last = _day(_num(rows[-1].get("ts"), 0.0))
170
+ tail = "%d 条,跨度 %d 天" % (len(rows), span)
171
+ if first and last:
172
+ tail += "(%s → %s)" % (first, last)
173
+ body = " → ".join(snippets) if snippets else "多次出现"
174
+ return ("关于「%s」:%s;%s" % (theme, body, tail))[:MAX_NARRATIVE]
175
+
176
+
177
+ def narrative_candidate(entries):
178
+ """Return the strongest theme meeting (>=3 entries, >=7 days) or None."""
179
+ candidates = []
180
+ groups = group_entries(entries)
181
+ for theme in sorted(groups):
182
+ rows = groups[theme]
183
+ span = theme_span_days(rows)
184
+ if len(rows) < MIN_ENTRIES or span < MIN_SPAN_DAYS:
185
+ continue
186
+ candidates.append({
187
+ "theme": theme, "count": len(rows), "span_days": span,
188
+ "entry_ids": [str(row.get("id") or "") for row in rows
189
+ if str(row.get("id") or "")],
190
+ "first_ts": _num(rows[0].get("ts"), 0.0),
191
+ "last_ts": _num(rows[-1].get("ts"), 0.0),
192
+ "text": narrative_text(theme, rows)})
193
+ if not candidates:
194
+ return None
195
+ candidates.sort(key=lambda c: (-c["count"], -c["span_days"], c["theme"]))
196
+ return candidates[0]
197
+
198
+
199
+ def _history(row):
200
+ raw = row.get(FIELD_HISTORY) if isinstance(row, dict) else None
201
+ items = []
202
+ for item in raw if isinstance(raw, list) else []:
203
+ if not isinstance(item, dict):
204
+ continue
205
+ items.append({
206
+ "version": int(max(0.0, _num(item.get("version"), 0.0))),
207
+ "text": _compact(item.get("text"), MAX_NARRATIVE),
208
+ "theme": _compact(item.get("theme"), THEME_MAX),
209
+ "ts": _num(item.get("ts"), 0.0),
210
+ "entry_ids": [str(x) for x in (item.get("entry_ids") or [])
211
+ if str(x)]})
212
+ return items[-MAX_VERSIONS:]
213
+
214
+
215
+ def section(identity):
216
+ """Return the normalized narrative section of an identity record/dict."""
217
+ row = _row(identity) or {}
218
+ return {"text": _compact(row.get(FIELD_TEXT) or row.get("narrative"),
219
+ MAX_NARRATIVE),
220
+ "theme": _compact(row.get(FIELD_THEME), THEME_MAX),
221
+ "version": int(max(0.0, _num(row.get(FIELD_VERSION), 0.0))),
222
+ "history": _history(row),
223
+ "entry_ids": [str(x) for x in (row.get(FIELD_ENTRY_IDS) or [])
224
+ if str(x)],
225
+ "ts": _num(row.get(FIELD_UPDATED_TS), 0.0)}
226
+
227
+
228
+ def _next_version(current):
229
+ versions = [current["version"]] + [item["version"]
230
+ for item in current["history"]]
231
+ return max(versions) + 1
232
+
233
+
234
+ def _supersede(current, now):
235
+ history = list(current["history"])
236
+ if current["text"]:
237
+ history.append({"version": current["version"], "text": current["text"],
238
+ "theme": current["theme"], "ts": current["ts"],
239
+ "entry_ids": current["entry_ids"]})
240
+ return history[-MAX_VERSIONS:]
241
+
242
+
243
+ def plan_update(identity, entries, now=None, enabled=None):
244
+ """Return a pure update plan: {updated, allowed, reason, version, patch}."""
245
+ result = {"updated": False, "allowed": False, "reason": "", "version": 0,
246
+ "candidate": None, "patch": {}}
247
+ if not _on(enabled):
248
+ result["reason"] = "disabled"
249
+ return result
250
+ candidate = narrative_candidate(entries)
251
+ if candidate is None:
252
+ result["reason"] = "threshold_not_met"
253
+ return result
254
+ current = section(identity)
255
+ if (current["theme"] == candidate["theme"]
256
+ and current["text"] == candidate["text"]):
257
+ result["reason"] = "unchanged"
258
+ return result
259
+ version = _next_version(current)
260
+ result.update({
261
+ "updated": True, "allowed": True, "reason": "updated",
262
+ "version": version, "candidate": candidate,
263
+ "patch": {FIELD_TEXT: candidate["text"], FIELD_THEME: candidate["theme"],
264
+ FIELD_VERSION: version,
265
+ FIELD_HISTORY: _supersede(current, now),
266
+ FIELD_ENTRY_IDS: candidate["entry_ids"],
267
+ FIELD_UPDATED_TS: round(now_ts(now), 3)}})
268
+ return result
269
+
270
+
271
+ def plan_rollback(identity, version=None, now=None, enabled=None):
272
+ """Return a pure rollback plan to a history version (latest by default)."""
273
+ result = {"updated": False, "allowed": False, "reason": "", "version": 0,
274
+ "patch": {}}
275
+ if not _on(enabled):
276
+ result["reason"] = "disabled"
277
+ return result
278
+ current = section(identity)
279
+ if not current["history"]:
280
+ result["reason"] = "no_history"
281
+ return result
282
+ target = current["history"][-1]
283
+ if version is not None:
284
+ wanted = int(_num(version, 0.0))
285
+ target = None
286
+ for item in reversed(current["history"]):
287
+ if item["version"] == wanted:
288
+ target = item
289
+ break
290
+ if target is None:
291
+ result["reason"] = "version_not_found"
292
+ return result
293
+ result.update({
294
+ "updated": True, "allowed": True, "reason": "rolled_back",
295
+ "version": target["version"],
296
+ "patch": {FIELD_TEXT: target["text"], FIELD_THEME: target["theme"],
297
+ FIELD_VERSION: target["version"],
298
+ FIELD_HISTORY: _supersede(current, now),
299
+ FIELD_ENTRY_IDS: target["entry_ids"],
300
+ FIELD_UPDATED_TS: round(now_ts(now), 3)}})
301
+ return result
302
+
303
+
304
+ def _apply_plan(store, identity_id, planner, **kwargs):
305
+ rows = getattr(store, "entries", None)
306
+ if not isinstance(rows, list):
307
+ rows = store.get("entries") if isinstance(store, dict) else []
308
+ target = None
309
+ for row in rows or []:
310
+ if not isinstance(row, dict):
311
+ continue
312
+ if identity_id is not None:
313
+ if str(row.get("id") or "") == str(identity_id):
314
+ target = row
315
+ break
316
+ elif is_identity(row):
317
+ target = row
318
+ break
319
+ if target is None:
320
+ return {"updated": False, "allowed": False, "id": "",
321
+ "reason": "missing_identity", "version": 0, "patch": {}}
322
+ plan = planner(target, **kwargs)
323
+ result = {"updated": plan["updated"], "allowed": plan["allowed"],
324
+ "id": str(target.get("id") or ""), "reason": plan["reason"],
325
+ "version": plan["version"], "patch": plan["patch"]}
326
+ if plan["allowed"]:
327
+ fn = getattr(store, "update", None)
328
+ applied = None
329
+ try:
330
+ applied = fn(result["id"], **plan["patch"]) if callable(fn) else None
331
+ except Exception:
332
+ applied = None
333
+ if not callable(fn):
334
+ target.update(plan["patch"])
335
+ applied = target
336
+ if not isinstance(applied, dict):
337
+ result.update({"updated": False, "allowed": False,
338
+ "reason": "update_failed"})
339
+ return result
340
+
341
+
342
+ def apply_update(store, identity_id=None, entries=None, now=None, enabled=None):
343
+ """Plan + apply one narrative update on the first/target identity record."""
344
+ return _apply_plan(store, identity_id, plan_update, entries=entries,
345
+ now=now, enabled=enabled)
346
+
347
+
348
+ def apply_rollback(store, identity_id=None, version=None, now=None, enabled=None):
349
+ """Plan + apply one narrative rollback on the target identity record."""
350
+ return _apply_plan(store, identity_id, plan_rollback, version=version,
351
+ now=now, enabled=enabled)
352
+
353
+
354
+ __all__ = ["enabled", "NARRATIVE_ENABLED", "theme_of", "group_entries",
355
+ "theme_span_days", "narrative_text", "narrative_candidate",
356
+ "section", "plan_update", "apply_update", "plan_rollback",
357
+ "apply_rollback", "MIN_ENTRIES", "MIN_SPAN_DAYS", "MAX_VERSIONS",
358
+ "MAX_NARRATIVE"]
@@ -0,0 +1,13 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Read-only identity snapshot."""
3
+ from __future__ import annotations
4
+ from .writeback import is_identity
5
+
6
+
7
+ def identity_snapshot(entries):
8
+ rows = [e for e in (entries or []) if isinstance(e, dict) and is_identity(e)]
9
+ rows.sort(key=lambda e: float(e.get("importance", 0.0) or 0.0), reverse=True)
10
+ return {"count": len(rows),
11
+ "ids": [str(e.get("id") or "") for e in rows[:20]],
12
+ "texts": [str(e.get("text") or "")[:80] for e in rows[:5]],
13
+ "version": 1}