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.
- package/README.md +2 -2
- package/lib/py/bridge.py +15 -7
- package/lib/py-bridge.js +4 -3
- package/package.json +3 -2
- package/python/biocore_memory/__init__.py +21 -0
- package/python/biocore_memory/adapters/__init__.py +2 -0
- package/python/biocore_memory/adapters/astrbot.py +24 -0
- package/python/biocore_memory/adapters/dsh_cli.py +335 -0
- package/python/biocore_memory/co_recall.py +324 -0
- package/python/biocore_memory/consolidate/__init__.py +11 -0
- package/python/biocore_memory/consolidate/gated.py +104 -0
- package/python/biocore_memory/consolidate/neighbors.py +68 -0
- package/python/biocore_memory/consolidate/reflection.py +45 -0
- package/python/biocore_memory/consolidate/tree.py +95 -0
- package/python/biocore_memory/consolidate/writeback.py +181 -0
- package/python/biocore_memory/core/__init__.py +4 -0
- package/python/biocore_memory/core/config.py +127 -0
- package/python/biocore_memory/core/permissions.py +69 -0
- package/python/biocore_memory/core/types.py +116 -0
- package/python/biocore_memory/core/util.py +26 -0
- package/python/biocore_memory/embedding_local.py +447 -0
- package/python/biocore_memory/embedding_mode.py +156 -0
- package/python/biocore_memory/engine.py +2476 -0
- package/python/biocore_memory/engine_helpers.py +266 -0
- package/python/biocore_memory/event/__init__.py +3 -0
- package/python/biocore_memory/event/_types.py +16 -0
- package/python/biocore_memory/event/consistency.py +117 -0
- package/python/biocore_memory/event/extract.py +48 -0
- package/python/biocore_memory/event/media.py +111 -0
- package/python/biocore_memory/event/notes.py +85 -0
- package/python/biocore_memory/event/notes_link.py +87 -0
- package/python/biocore_memory/event/vector.py +69 -0
- package/python/biocore_memory/evict/__init__.py +3 -0
- package/python/biocore_memory/evict/adaptive.py +73 -0
- package/python/biocore_memory/evict/consequence.py +58 -0
- package/python/biocore_memory/evict/heat.py +54 -0
- package/python/biocore_memory/evict/inhibition.py +105 -0
- package/python/biocore_memory/evict/policy.py +188 -0
- package/python/biocore_memory/evict/score.py +23 -0
- package/python/biocore_memory/identity/__init__.py +6 -0
- package/python/biocore_memory/identity/api.py +99 -0
- package/python/biocore_memory/identity/history.py +9 -0
- package/python/biocore_memory/identity/ledger.py +191 -0
- package/python/biocore_memory/identity/narrative.py +358 -0
- package/python/biocore_memory/identity/snapshot.py +13 -0
- package/python/biocore_memory/identity/writeback.py +61 -0
- package/python/biocore_memory/index/__init__.py +3 -0
- package/python/biocore_memory/index/cue_index.py +80 -0
- package/python/biocore_memory/index/entities.py +85 -0
- package/python/biocore_memory/index/entity_boost.py +104 -0
- package/python/biocore_memory/index/graph.py +172 -0
- package/python/biocore_memory/recall/__init__.py +5 -0
- package/python/biocore_memory/recall/api.py +65 -0
- package/python/biocore_memory/recall/bm25.py +118 -0
- package/python/biocore_memory/recall/channels.py +98 -0
- package/python/biocore_memory/recall/complexity.py +62 -0
- package/python/biocore_memory/recall/constraints.py +75 -0
- package/python/biocore_memory/recall/embedding.py +745 -0
- package/python/biocore_memory/recall/expand.py +26 -0
- package/python/biocore_memory/recall/filters.py +40 -0
- package/python/biocore_memory/recall/fusion.py +18 -0
- package/python/biocore_memory/recall/mmr.py +70 -0
- package/python/biocore_memory/recall/ppr.py +85 -0
- package/python/biocore_memory/recall/retrieval_practice.py +102 -0
- package/python/biocore_memory/relay/__init__.py +2 -0
- package/python/biocore_memory/relay/card.py +51 -0
- package/python/biocore_memory/slots/__init__.py +18 -0
- package/python/biocore_memory/slots/admission.py +64 -0
- package/python/biocore_memory/slots/boundary.py +128 -0
- package/python/biocore_memory/slots/evict_bridge.py +106 -0
- package/python/biocore_memory/slots/registry.py +135 -0
- package/python/biocore_memory/slots/switch.py +42 -0
- package/python/biocore_memory/store/__init__.py +4 -0
- package/python/biocore_memory/store/audit.py +74 -0
- package/python/biocore_memory/store/compress.py +81 -0
- package/python/biocore_memory/store/dedupe.py +178 -0
- package/python/biocore_memory/store/json_store.py +154 -0
- package/python/biocore_memory/store/media.py +145 -0
- package/python/biocore_memory/store/provenance.py +73 -0
- package/python/biocore_memory/store/rate_limit.py +93 -0
- package/python/biocore_memory/store/security.py +107 -0
- package/python/biocore_memory/store/source_consistency.py +123 -0
- package/python/biocore_memory/store/tiering.py +61 -0
- package/python/biocore_memory/store/tiering_exec.py +50 -0
- package/python/biocore_memory/store/tombstone.py +23 -0
- package/python/biocore_memory/store/versions.py +69 -0
- package/python/biocore_memory/thread/__init__.py +2 -0
- package/python/biocore_memory/thread/card.py +58 -0
- package/python/biocore_model/__init__.py +37 -0
- package/python/biocore_model/affective_labor.py +162 -0
- package/python/biocore_model/appraisal.py +257 -0
- package/python/biocore_model/appraisal_action.py +78 -0
- package/python/biocore_model/archive_queue.py +60 -0
- package/python/biocore_model/attachment_behavior.py +130 -0
- package/python/biocore_model/attachment_regulation.py +75 -0
- package/python/biocore_model/attachment_state.py +41 -0
- package/python/biocore_model/attribution.py +73 -0
- package/python/biocore_model/attributor.py +162 -0
- package/python/biocore_model/autonomic.py +91 -0
- package/python/biocore_model/autonomy_affect.py +51 -0
- package/python/biocore_model/autonomy_check.py +67 -0
- package/python/biocore_model/autonomy_loop.py +122 -0
- package/python/biocore_model/autonomy_mode.py +114 -0
- package/python/biocore_model/autonomy_model.py +733 -0
- package/python/biocore_model/autonomy_params.py +131 -0
- package/python/biocore_model/autonomy_reason.py +73 -0
- package/python/biocore_model/autonomy_tick.py +227 -0
- package/python/biocore_model/bio_appraisal.py +49 -0
- package/python/biocore_model/bio_autonomy_state.py +171 -0
- package/python/biocore_model/bio_config.py +221 -0
- package/python/biocore_model/bio_const.py +128 -0
- package/python/biocore_model/bio_daily.py +267 -0
- package/python/biocore_model/bio_emotion.py +538 -0
- package/python/biocore_model/bio_emotion2.py +214 -0
- package/python/biocore_model/bio_goal.py +220 -0
- package/python/biocore_model/bio_identity.py +82 -0
- package/python/biocore_model/bio_noise.py +119 -0
- package/python/biocore_model/bio_physiology2.py +114 -0
- package/python/biocore_model/bio_snapshot.py +324 -0
- package/python/biocore_model/bio_state.py +272 -0
- package/python/biocore_model/bio_tick.py +310 -0
- package/python/biocore_model/bio_util.py +82 -0
- package/python/biocore_model/blocks.py +264 -0
- package/python/biocore_model/boundary.py +251 -0
- package/python/biocore_model/boundary_gate.py +188 -0
- package/python/biocore_model/commitment_extractor.py +517 -0
- package/python/biocore_model/compassion_fatigue.py +84 -0
- package/python/biocore_model/connection_bids.py +120 -0
- package/python/biocore_model/core_bridge.py +177 -0
- package/python/biocore_model/core_client.py +127 -0
- package/python/biocore_model/core_commands.py +112 -0
- package/python/biocore_model/core_mode.py +104 -0
- package/python/biocore_model/core_mode_ui.mjs +104 -0
- package/python/biocore_model/criticality.py +81 -0
- package/python/biocore_model/defense_mechanisms.py +272 -0
- package/python/biocore_model/delta_budget.py +99 -0
- package/python/biocore_model/diag_trace.py +274 -0
- package/python/biocore_model/dissonance.py +134 -0
- package/python/biocore_model/emotion_geometry.py +108 -0
- package/python/biocore_model/emotion_probe.py +209 -0
- package/python/biocore_model/entity_graph.py +931 -0
- package/python/biocore_model/entity_resolve.py +260 -0
- package/python/biocore_model/envy.py +193 -0
- package/python/biocore_model/exit_or_silence.py +230 -0
- package/python/biocore_model/expr_guard.py +24 -0
- package/python/biocore_model/expr_intent.py +77 -0
- package/python/biocore_model/expr_state.py +204 -0
- package/python/biocore_model/expr_template.py +105 -0
- package/python/biocore_model/expr_tone.py +81 -0
- package/python/biocore_model/extreme_scenarios.py +205 -0
- package/python/biocore_model/feedback_flow.py +227 -0
- package/python/biocore_model/feedback_guard.py +129 -0
- package/python/biocore_model/feedback_llm.py +163 -0
- package/python/biocore_model/feedback_memory.py +96 -0
- package/python/biocore_model/feedback_user.py +93 -0
- package/python/biocore_model/frustration_curve.py +110 -0
- package/python/biocore_model/granularity.py +283 -0
- package/python/biocore_model/graph_extract.py +248 -0
- package/python/biocore_model/graph_recall.py +221 -0
- package/python/biocore_model/intent_render.py +91 -0
- package/python/biocore_model/intero_core.py +235 -0
- package/python/biocore_model/intero_style.py +116 -0
- package/python/biocore_model/layered_memory.py +297 -0
- package/python/biocore_model/learning_probe.py +120 -0
- package/python/biocore_model/memory_dual.py +224 -0
- package/python/biocore_model/memory_forgetting.py +125 -0
- package/python/biocore_model/memory_store.py +1399 -0
- package/python/biocore_model/metacog.py +153 -0
- package/python/biocore_model/migrate.py +733 -0
- package/python/biocore_model/migrate_store.py +337 -0
- package/python/biocore_model/mind_wander.py +111 -0
- package/python/biocore_model/mood.py +48 -0
- package/python/biocore_model/narrative.py +172 -0
- package/python/biocore_model/needs_esteem.py +116 -0
- package/python/biocore_model/needs_events.py +137 -0
- package/python/biocore_model/needs_sleep.py +72 -0
- package/python/biocore_model/noise_bank.py +95 -0
- package/python/biocore_model/persona_flow.mjs +25 -0
- package/python/biocore_model/pipeline.py +240 -0
- package/python/biocore_model/pipeline_api.py +200 -0
- package/python/biocore_model/plugin_config.py +83 -0
- package/python/biocore_model/plugin_routes.py +1435 -0
- package/python/biocore_model/policy_learning.py +132 -0
- package/python/biocore_model/possible_selves.py +110 -0
- package/python/biocore_model/predictor.py +178 -0
- package/python/biocore_model/preset.py +205 -0
- package/python/biocore_model/proactive_context.py +153 -0
- package/python/biocore_model/prompt_rules.py +90 -0
- package/python/biocore_model/prospective.py +183 -0
- package/python/biocore_model/provider_fallback.py +97 -0
- package/python/biocore_model/reconstruction.py +132 -0
- package/python/biocore_model/regulation_loop.py +179 -0
- package/python/biocore_model/regulation_strategies.py +294 -0
- package/python/biocore_model/relation_stage.py +130 -0
- package/python/biocore_model/relationship_stage.py +95 -0
- package/python/biocore_model/render.py +901 -0
- package/python/biocore_model/render_guard.mjs +34 -0
- package/python/biocore_model/repair_after_boundary.py +350 -0
- package/python/biocore_model/reply_limit.py +183 -0
- package/python/biocore_model/reply_split.py +203 -0
- package/python/biocore_model/rollback.py +143 -0
- package/python/biocore_model/runtime.py +479 -0
- package/python/biocore_model/sanitize.py +200 -0
- package/python/biocore_model/scheduler.py +123 -0
- package/python/biocore_model/schema.py +120 -0
- package/python/biocore_model/secrecy.py +145 -0
- package/python/biocore_model/self_esteem.py +50 -0
- package/python/biocore_model/self_intent.py +437 -0
- package/python/biocore_model/self_interest.py +263 -0
- package/python/biocore_model/self_verification.py +178 -0
- package/python/biocore_model/services.py +78 -0
- package/python/biocore_model/situation.py +254 -0
- package/python/biocore_model/sleep_circadian.py +116 -0
- package/python/biocore_model/social_pain.py +69 -0
- package/python/biocore_model/social_repair.py +111 -0
- package/python/biocore_model/social_theory.py +131 -0
- package/python/biocore_model/source_monitoring.py +292 -0
- package/python/biocore_model/stages.py +487 -0
- package/python/biocore_model/state_tag.py +231 -0
- package/python/biocore_model/switch_groups.mjs +201 -0
- package/python/biocore_model/tabs_state.mjs +37 -0
- package/python/biocore_model/template_expr.py +252 -0
- package/python/biocore_model/tools/caps_check.mjs +23 -0
- package/python/biocore_model/tools/init_symbols_check.mjs +11 -0
- package/python/biocore_model/tools/missing_ids.mjs +16 -0
- package/python/biocore_model/tools/scope_check.mjs +19 -0
- package/python/biocore_model/topic_control.py +268 -0
- package/python/biocore_model/turn_memory.py +152 -0
- package/python/biocore_model/ui_compat.mjs +48 -0
- package/python/biocore_model/ui_settings.py +266 -0
- package/python/biocore_model/ui_settings.py.bak_authority +108 -0
- package/python/biocore_model/value_order.py +186 -0
- package/python/biocore_model/view_mode.mjs +8 -0
- package/python/biocore_model/voice_bank.py +177 -0
- package/python/biocore_model/waiting_sense.py +229 -0
- package/python/biocore_model/x_directives.py +142 -0
- package/python/biocore_runtime/__init__.py +7 -0
- package/python/biocore_runtime/pipeline.py +1915 -0
- package/python/dsh_adapter/README.md +96 -0
- package/python/dsh_adapter/adapter.py +1077 -0
- package/python/dsh_adapter/cli.py +107 -0
- package/python/dsh_adapter/data/demo_state.json +164 -0
- package/python/dsh_adapter/data/verify_state.json +164 -0
- package/python/dsh_adapter/tests/__init__.py +1 -0
- package/python/dsh_adapter/tests/test_adapter.py +494 -0
- package/ui/panel-layout.js +3 -3
- package/ui/panel.css +53 -6
- package/ui/panel.html +33 -32
- package/ui/panel.js +9 -1
- package/lib/py/__pycache__/bridge.cpython-310.pyc +0 -0
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""AstrBot engine store -> BioCore core store, read-only migration mapping.
|
|
3
|
+
|
|
4
|
+
The AstrBot plugin keeps its engine store under the plugin data directory
|
|
5
|
+
(memory.json or memory/<session>.json). The core service expects
|
|
6
|
+
<store>/memory.json with entries carrying id/text/ts/role/tags/importance/pin/
|
|
7
|
+
client_scope. This module maps the known fields, reports everything unknown and
|
|
8
|
+
never writes the source. Dry-run is the default; apply=True writes the target
|
|
9
|
+
atomically and refuses to overwrite a non-empty target unless force=True.
|
|
10
|
+
|
|
11
|
+
Standard library only; no AstrBot import; no network.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import argparse
|
|
16
|
+
import hashlib
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import sys
|
|
20
|
+
import tempfile
|
|
21
|
+
from datetime import datetime, timezone
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
SOURCE_ENV = "BIOCORE_ASTROBOT_STORE"
|
|
25
|
+
DATA_ENV = "BIOCORE_ASTROBOT_DATA"
|
|
26
|
+
TARGET_SCHEMA = 1
|
|
27
|
+
CORE_KEYS = ("id", "text", "ts", "role", "tags", "importance", "pin", "client_scope", "valid_at")
|
|
28
|
+
# Rich engine fields handled explicitly (not "unmapped").
|
|
29
|
+
HANDLED_EXTRA = {"vector", "embedding_model", "vector_model"}
|
|
30
|
+
# engine field -> core field (known, intentional mapping only)
|
|
31
|
+
FIELD_MAP = {
|
|
32
|
+
"id": "id",
|
|
33
|
+
"text": "text",
|
|
34
|
+
"ts": "ts",
|
|
35
|
+
"role": "role",
|
|
36
|
+
"importance": "importance",
|
|
37
|
+
"pin": "pin",
|
|
38
|
+
"scope": "client_scope",
|
|
39
|
+
"valid_at": "valid_at",
|
|
40
|
+
"tags": "tags",
|
|
41
|
+
}
|
|
42
|
+
OPTIONAL_DEFAULTS = {"role": "user", "tags": [], "importance": 0.5, "pin": False, "client_scope": "global"}
|
|
43
|
+
REQUIRED_FIELDS = ("text",)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _candidate_data_dirs():
|
|
47
|
+
here = Path(__file__).resolve()
|
|
48
|
+
home = Path.home()
|
|
49
|
+
candidates = [
|
|
50
|
+
home / ".astrbot_launcher" / "instances",
|
|
51
|
+
home / "Desktop" / "plugin_data",
|
|
52
|
+
here.parents[2] / "plugin_data",
|
|
53
|
+
]
|
|
54
|
+
return candidates
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def detect_source(candidates=None):
|
|
58
|
+
"""Locate the AstrBot engine store (file or data dir); None when absent."""
|
|
59
|
+
env = str(os.environ.get(SOURCE_ENV) or "").strip()
|
|
60
|
+
if env:
|
|
61
|
+
path = Path(env).expanduser()
|
|
62
|
+
if path.exists():
|
|
63
|
+
return str(path)
|
|
64
|
+
roots = []
|
|
65
|
+
data_override = str(os.environ.get(DATA_ENV) or "").strip()
|
|
66
|
+
if data_override:
|
|
67
|
+
roots.append(Path(data_override).expanduser())
|
|
68
|
+
for candidate in candidates or _candidate_data_dirs():
|
|
69
|
+
try:
|
|
70
|
+
root = Path(candidate)
|
|
71
|
+
if not root.exists():
|
|
72
|
+
continue
|
|
73
|
+
if root.name == "plugin_data":
|
|
74
|
+
roots.extend(sorted(root.glob("astrbot_plugin_biocore_standalone")))
|
|
75
|
+
else:
|
|
76
|
+
roots.extend(sorted(root.glob("*/core/data/plugin_data/astrbot_plugin_biocore_standalone")))
|
|
77
|
+
except Exception:
|
|
78
|
+
continue
|
|
79
|
+
for root in roots:
|
|
80
|
+
try:
|
|
81
|
+
direct = root / "memory.json"
|
|
82
|
+
if direct.is_file():
|
|
83
|
+
return str(direct)
|
|
84
|
+
memory_dir = root / "memory"
|
|
85
|
+
if memory_dir.is_dir() and any(memory_dir.glob("*.json")):
|
|
86
|
+
return str(memory_dir)
|
|
87
|
+
if root.is_dir() and any(root.glob("*.json")) and root.name == "memory":
|
|
88
|
+
return str(root)
|
|
89
|
+
except Exception:
|
|
90
|
+
continue
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _source_files(source):
|
|
95
|
+
path = Path(source)
|
|
96
|
+
if path.is_file():
|
|
97
|
+
return [path]
|
|
98
|
+
if path.is_dir():
|
|
99
|
+
files = sorted(path.glob("*.json")) if path.name == "memory" else sorted(path.glob("memory/*.json"))
|
|
100
|
+
return [file for file in files if file.is_file()]
|
|
101
|
+
return []
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def load_source(source):
|
|
105
|
+
"""Read engine entries from a file/dir; returns (entries, meta)."""
|
|
106
|
+
files = _source_files(source)
|
|
107
|
+
entries = []
|
|
108
|
+
corrupt = 0
|
|
109
|
+
for path in files:
|
|
110
|
+
try:
|
|
111
|
+
with open(path, "r", encoding="utf-8") as handle:
|
|
112
|
+
doc = json.load(handle)
|
|
113
|
+
except Exception:
|
|
114
|
+
corrupt += 1
|
|
115
|
+
continue
|
|
116
|
+
rows = doc.get("entries") if isinstance(doc, dict) else None
|
|
117
|
+
if isinstance(rows, list):
|
|
118
|
+
entries.extend(row for row in rows if isinstance(row, dict))
|
|
119
|
+
meta = {"source": str(source), "files": len(files), "corrupt_files": corrupt, "source_entries": len(entries)}
|
|
120
|
+
return entries, meta
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _core_scope(entry):
|
|
124
|
+
value = str(entry.get("client_scope") or entry.get("scope") or "default").strip()
|
|
125
|
+
if not value or value in ("default", "global", "all"):
|
|
126
|
+
return "global"
|
|
127
|
+
if value.startswith("session:"):
|
|
128
|
+
return value
|
|
129
|
+
return "global"
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _core_id(entry):
|
|
133
|
+
raw = entry.get("id")
|
|
134
|
+
if raw not in (None, ""):
|
|
135
|
+
return str(raw)[:64]
|
|
136
|
+
seed = "|".join([str(entry.get("text") or ""), str(entry.get("ts") or ""), str(entry.get("role") or "")])
|
|
137
|
+
return hashlib.sha1(seed.encode("utf-8")).hexdigest()[:12]
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def convert(entries):
|
|
141
|
+
"""Map engine entries to core entries; returns (core_entries, report)."""
|
|
142
|
+
rows = entries if isinstance(entries, list) else []
|
|
143
|
+
core_entries = []
|
|
144
|
+
unmapped = {}
|
|
145
|
+
missing = {}
|
|
146
|
+
generated_ids = 0
|
|
147
|
+
skipped = 0
|
|
148
|
+
vectors_migrated = 0
|
|
149
|
+
vectors_dropped = 0
|
|
150
|
+
for entry in rows:
|
|
151
|
+
if not isinstance(entry, dict):
|
|
152
|
+
skipped += 1
|
|
153
|
+
continue
|
|
154
|
+
if not str(entry.get("text") or "").strip():
|
|
155
|
+
for name in REQUIRED_FIELDS:
|
|
156
|
+
missing[name] = missing.get(name, 0) + 1
|
|
157
|
+
skipped += 1
|
|
158
|
+
continue
|
|
159
|
+
mapped = {}
|
|
160
|
+
for source_key, target_key in FIELD_MAP.items():
|
|
161
|
+
if source_key in entry:
|
|
162
|
+
mapped[target_key] = entry[source_key]
|
|
163
|
+
for key in entry.keys():
|
|
164
|
+
if key not in FIELD_MAP and key not in HANDLED_EXTRA:
|
|
165
|
+
unmapped[key] = unmapped.get(key, 0) + 1
|
|
166
|
+
core = {
|
|
167
|
+
"id": _core_id(entry),
|
|
168
|
+
"text": str(entry.get("text")).strip(),
|
|
169
|
+
"ts": _as_float(entry.get("ts"), 0.0),
|
|
170
|
+
"role": str(entry.get("role") or OPTIONAL_DEFAULTS["role"]),
|
|
171
|
+
"tags": _as_list(entry.get("tags"), OPTIONAL_DEFAULTS["tags"]),
|
|
172
|
+
"importance": _as_float(entry.get("importance"), OPTIONAL_DEFAULTS["importance"]),
|
|
173
|
+
"pin": bool(entry.get("pin", OPTIONAL_DEFAULTS["pin"])),
|
|
174
|
+
"client_scope": _core_scope(entry),
|
|
175
|
+
}
|
|
176
|
+
if "valid_at" in entry and entry.get("valid_at") is not None:
|
|
177
|
+
core["valid_at"] = _as_float(entry.get("valid_at"), None)
|
|
178
|
+
# Vector passthrough: only when every component is a finite real number.
|
|
179
|
+
vector = entry.get("vector")
|
|
180
|
+
if isinstance(vector, (list, tuple)) and vector:
|
|
181
|
+
clean = []
|
|
182
|
+
ok = True
|
|
183
|
+
for item in vector:
|
|
184
|
+
if isinstance(item, bool) or not isinstance(item, (int, float)):
|
|
185
|
+
ok = False
|
|
186
|
+
break
|
|
187
|
+
number = float(item)
|
|
188
|
+
if not _is_finite(number):
|
|
189
|
+
ok = False
|
|
190
|
+
break
|
|
191
|
+
clean.append(number)
|
|
192
|
+
if ok and clean:
|
|
193
|
+
core["vector"] = clean
|
|
194
|
+
model = entry.get("embedding_model") or entry.get("vector_model")
|
|
195
|
+
if model:
|
|
196
|
+
core["vector_model"] = str(model)[:120]
|
|
197
|
+
vectors_migrated += 1
|
|
198
|
+
else:
|
|
199
|
+
vectors_dropped += 1
|
|
200
|
+
if not entry.get("id"):
|
|
201
|
+
generated_ids += 1
|
|
202
|
+
core_entries.append(core)
|
|
203
|
+
report = {
|
|
204
|
+
"source_entries": len(rows),
|
|
205
|
+
"converted": len(core_entries),
|
|
206
|
+
"skipped": skipped,
|
|
207
|
+
"generated_ids": generated_ids,
|
|
208
|
+
"vectors_migrated": vectors_migrated,
|
|
209
|
+
"vectors_dropped": vectors_dropped,
|
|
210
|
+
"unmapped_fields": unmapped,
|
|
211
|
+
"missing_required": missing,
|
|
212
|
+
"sample": core_entries[:3],
|
|
213
|
+
}
|
|
214
|
+
return core_entries, report
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _is_finite(value):
|
|
218
|
+
try:
|
|
219
|
+
number = float(value)
|
|
220
|
+
except Exception:
|
|
221
|
+
return False
|
|
222
|
+
return number == number and number not in (float('inf'), float('-inf'))
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _as_float(value, default):
|
|
226
|
+
try:
|
|
227
|
+
return float(value)
|
|
228
|
+
except Exception:
|
|
229
|
+
return default
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _as_list(value, default):
|
|
233
|
+
if isinstance(value, list):
|
|
234
|
+
return [str(item) for item in value]
|
|
235
|
+
if value in (None, ""):
|
|
236
|
+
return list(default)
|
|
237
|
+
return [str(value)]
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _target_doc(core_entries, source, meta):
|
|
241
|
+
return {
|
|
242
|
+
"entries": core_entries,
|
|
243
|
+
"tombstones": [],
|
|
244
|
+
"schema_version": TARGET_SCHEMA,
|
|
245
|
+
"meta": {
|
|
246
|
+
"migration": "astrbot-engine-to-biocore-core",
|
|
247
|
+
"source": str(source or ""),
|
|
248
|
+
"migrated_at": datetime.now(timezone.utc).isoformat(),
|
|
249
|
+
"source_files": meta.get("files"),
|
|
250
|
+
},
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _atomic_write_json(path, data):
|
|
255
|
+
path = Path(path)
|
|
256
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
257
|
+
handle = tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=str(path.parent), delete=False, suffix=".tmp")
|
|
258
|
+
try:
|
|
259
|
+
json.dump(data, handle, ensure_ascii=False, indent=1)
|
|
260
|
+
handle.flush()
|
|
261
|
+
os.fsync(handle.fileno())
|
|
262
|
+
handle.close()
|
|
263
|
+
os.replace(handle.name, str(path))
|
|
264
|
+
finally:
|
|
265
|
+
try:
|
|
266
|
+
if not handle.closed:
|
|
267
|
+
handle.close()
|
|
268
|
+
if os.path.exists(handle.name):
|
|
269
|
+
os.remove(handle.name)
|
|
270
|
+
except Exception:
|
|
271
|
+
pass
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def run(src=None, dst=None, apply=False, force=False):
|
|
275
|
+
"""Dry-run by default; apply=True writes the target atomically."""
|
|
276
|
+
source = src or detect_source()
|
|
277
|
+
result = {"ok": bool(source), "dry_run": not bool(apply), "applied": False,
|
|
278
|
+
"source": source or "", "target": str(dst or ""),
|
|
279
|
+
"source_entries": 0, "converted": 0, "skipped": 0, "generated_ids": 0,
|
|
280
|
+
"vectors_migrated": 0, "vectors_dropped": 0,
|
|
281
|
+
"unmapped_fields": {}, "missing_required": {}, "sample": [],
|
|
282
|
+
"corrupt_files": 0, "error": ""}
|
|
283
|
+
if not source or not _source_files(source):
|
|
284
|
+
result["error"] = "source_not_found"
|
|
285
|
+
result["ok"] = False
|
|
286
|
+
return result
|
|
287
|
+
entries, meta = load_source(source)
|
|
288
|
+
result.update({"source_entries": meta.get("source_entries", 0),
|
|
289
|
+
"corrupt_files": meta.get("corrupt_files", 0)})
|
|
290
|
+
core_entries, report = convert(entries)
|
|
291
|
+
result.update({key: report[key] for key in ("source_entries", "converted", "skipped", "generated_ids",
|
|
292
|
+
"vectors_migrated", "vectors_dropped",
|
|
293
|
+
"unmapped_fields", "missing_required", "sample")})
|
|
294
|
+
if meta.get("corrupt_files"):
|
|
295
|
+
result["error"] = "corrupt_source"
|
|
296
|
+
return result
|
|
297
|
+
if not apply:
|
|
298
|
+
return result
|
|
299
|
+
if not dst:
|
|
300
|
+
result["error"] = "target_required"
|
|
301
|
+
return result
|
|
302
|
+
target = Path(dst)
|
|
303
|
+
try:
|
|
304
|
+
if target.exists() and target.stat().st_size > 0 and not force:
|
|
305
|
+
result["error"] = "target_not_empty"
|
|
306
|
+
return result
|
|
307
|
+
except Exception:
|
|
308
|
+
pass
|
|
309
|
+
try:
|
|
310
|
+
_atomic_write_json(target, _target_doc(core_entries, source, meta))
|
|
311
|
+
except Exception as error:
|
|
312
|
+
result["error"] = "write_failed: " + str(error)
|
|
313
|
+
return result
|
|
314
|
+
result["applied"] = True
|
|
315
|
+
result["dry_run"] = False
|
|
316
|
+
return result
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def main(argv=None):
|
|
320
|
+
parser = argparse.ArgumentParser(description="Map AstrBot engine memory store to BioCore core schema (dry-run by default)")
|
|
321
|
+
parser.add_argument("--dry-run", action="store_true", help="report only (default)")
|
|
322
|
+
parser.add_argument("--apply", action="store_true", help="write the target store")
|
|
323
|
+
parser.add_argument("--force", action="store_true", help="allow overwriting a non-empty target")
|
|
324
|
+
parser.add_argument("--src", default="", help="engine store file or memory dir")
|
|
325
|
+
parser.add_argument("--dst", default="", help="core memory.json path")
|
|
326
|
+
args = parser.parse_args(argv)
|
|
327
|
+
result = run(src=args.src or None, dst=args.dst or None, apply=bool(args.apply and not args.dry_run), force=args.force)
|
|
328
|
+
try:
|
|
329
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
330
|
+
except Exception:
|
|
331
|
+
pass
|
|
332
|
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
333
|
+
return 0 if result.get("ok") else 1
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
if __name__ == "__main__":
|
|
337
|
+
sys.exit(main())
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""HUMAN-4 mind wandering: sample what the mind drifts to.
|
|
3
|
+
|
|
4
|
+
When no external task is active the internal stream drifts toward open loops
|
|
5
|
+
and ruminated topics. Sampling is deterministic for a given (seed, now) and
|
|
6
|
+
biased by each candidate's tension and the current rumination level.
|
|
7
|
+
|
|
8
|
+
Literature
|
|
9
|
+
Mason 2007 (default-mode mind wandering), Christoff 2016 (spontaneous
|
|
10
|
+
thought), Smallwood & Schooler 2015 (wandering and meta-awareness),
|
|
11
|
+
Nolen-Hoeksema 1991 (rumination recurrence), Carver & Scheier 1998 (open
|
|
12
|
+
goals keep pulling attention), Powers 1973 (control error pulls focus),
|
|
13
|
+
Gross 1998 (strategies alter where attention lands), Anderson 2007 (base
|
|
14
|
+
level activation), Cowan 2001 (focus capacity).
|
|
15
|
+
|
|
16
|
+
Constraints: pure functions, stdlib only, no IO, no main import, time injected;
|
|
17
|
+
the candidate list is never mutated.
|
|
18
|
+
"""
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import hashlib
|
|
22
|
+
|
|
23
|
+
BASE_WEIGHT = 1.0
|
|
24
|
+
RUMINATION_GAIN = 1.5
|
|
25
|
+
DEFAULT_LIMIT = 1
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _num(value, default=0.0):
|
|
29
|
+
try:
|
|
30
|
+
return float(value)
|
|
31
|
+
except Exception:
|
|
32
|
+
return float(default)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _unit(seed, now, salt=""):
|
|
36
|
+
key = ("%s|%s|%s" % (seed, now, salt)).encode("utf-8")
|
|
37
|
+
digest = hashlib.sha256(key).digest()
|
|
38
|
+
return int.from_bytes(digest[:8], "big") / float(1 << 64)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _clamped(value, lo, hi):
|
|
42
|
+
try:
|
|
43
|
+
return max(lo, min(hi, float(value)))
|
|
44
|
+
except Exception:
|
|
45
|
+
return lo
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def weights(loops, rumination=0.0):
|
|
49
|
+
"""Per-candidate weight: base + gain*rumination*(0.5 + tension)."""
|
|
50
|
+
rum = _clamped(rumination, 0.0, 1.0)
|
|
51
|
+
out = []
|
|
52
|
+
for item in loops or []:
|
|
53
|
+
row = item if isinstance(item, dict) else {"topic": str(item)}
|
|
54
|
+
tension = _clamped(row.get("tension", 0.0), 0.0, 1.0)
|
|
55
|
+
weight = BASE_WEIGHT + RUMINATION_GAIN * rum * (0.5 + tension)
|
|
56
|
+
out.append(round(weight, 4))
|
|
57
|
+
return out
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def choose(loops, rumination=0.0, seed=0, now=0.0):
|
|
61
|
+
"""Weighted deterministic sample; returns {topic, index, weight, total} or None."""
|
|
62
|
+
rows = [row if isinstance(row, dict) else {"topic": str(row)} for row in (loops or [])]
|
|
63
|
+
ws = weights(rows, rumination)
|
|
64
|
+
total = sum(ws)
|
|
65
|
+
if not rows or total <= 0.0:
|
|
66
|
+
return None
|
|
67
|
+
point = _unit(seed, now, "wander") * total
|
|
68
|
+
cursor = 0.0
|
|
69
|
+
picked_index = len(rows) - 1
|
|
70
|
+
for index, weight in enumerate(ws):
|
|
71
|
+
cursor += weight
|
|
72
|
+
if point <= cursor:
|
|
73
|
+
picked_index = index
|
|
74
|
+
break
|
|
75
|
+
row = rows[picked_index]
|
|
76
|
+
return {"topic": str(row.get("topic") or ""), "index": picked_index,
|
|
77
|
+
"weight": ws[picked_index], "total": round(total, 4),
|
|
78
|
+
"tension": _clamped(row.get("tension", 0.0), 0.0, 1.0)}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def wander(loops, rumination=0.0, seed=0, now=0.0, limit=DEFAULT_LIMIT):
|
|
82
|
+
"""Draw up to limit distinct topics (first is the strongest pull)."""
|
|
83
|
+
rows = [row if isinstance(row, dict) else {"topic": str(row)} for row in (loops or [])]
|
|
84
|
+
out = []
|
|
85
|
+
remaining = list(range(len(rows)))
|
|
86
|
+
count = max(0, int(limit))
|
|
87
|
+
for draw in range(min(count, len(rows))):
|
|
88
|
+
ws = weights([rows[index] for index in remaining], rumination)
|
|
89
|
+
total = sum(ws)
|
|
90
|
+
if total <= 0.0:
|
|
91
|
+
break
|
|
92
|
+
point = _unit(seed, now, "wander:%d" % draw) * total
|
|
93
|
+
cursor = 0.0
|
|
94
|
+
pick_at = len(remaining) - 1
|
|
95
|
+
for offset, weight in enumerate(ws):
|
|
96
|
+
cursor += weight
|
|
97
|
+
if point <= cursor:
|
|
98
|
+
pick_at = offset
|
|
99
|
+
break
|
|
100
|
+
index = remaining.pop(pick_at)
|
|
101
|
+
out.append({"topic": str(rows[index].get("topic") or ""), "index": index,
|
|
102
|
+
"weight": round(ws[pick_at], 4)})
|
|
103
|
+
return out
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def seeded(seed, now=0):
|
|
107
|
+
"""Convenience: which of three fixed candidates a seed drifts to."""
|
|
108
|
+
loops = [{"topic": "work", "tension": 0.2},
|
|
109
|
+
{"topic": "friend", "tension": 0.6},
|
|
110
|
+
{"topic": "rest", "tension": 0.1}]
|
|
111
|
+
return choose(loops, rumination=0.0, seed=seed, now=now)
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""BIO-4: slow mood variable (biological layer). Pure functions only."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
RATE = 0.05
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def clamp(value, low=-1.0, high=1.0):
|
|
9
|
+
return max(low, min(high, float(value)))
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def mood_update(mood, v, a, dt=0.0, rate=RATE, now=None):
|
|
13
|
+
data = dict(mood or {"valence": 0.0, "arousal": 0.0})
|
|
14
|
+
if now is not None and float(now) <= float(data.get("last_tick_ts", 0.0) or 0.0):
|
|
15
|
+
return data
|
|
16
|
+
data["valence"] = round(clamp(data.get("valence", 0.0) + rate * (float(v or 0.0) - float(data.get("valence", 0.0)))), 4)
|
|
17
|
+
data["arousal"] = round(clamp(data.get("arousal", 0.0) + rate * (float(a or 0.0) - float(data.get("arousal", 0.0)))), 4)
|
|
18
|
+
if now is not None:
|
|
19
|
+
data["last_tick_ts"] = float(now)
|
|
20
|
+
return data
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def label(mood):
|
|
24
|
+
data = mood or {}
|
|
25
|
+
v = float(data.get("valence", 0.0) or 0.0)
|
|
26
|
+
a = float(data.get("arousal", 0.0) or 0.0)
|
|
27
|
+
if v <= 0 and a >= 0.5:
|
|
28
|
+
return "低落"
|
|
29
|
+
if v > 0 and a >= 0.5:
|
|
30
|
+
return "愉快"
|
|
31
|
+
if v > 0:
|
|
32
|
+
return "平静偏正"
|
|
33
|
+
return "平静"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def mood_view(mood):
|
|
37
|
+
data = dict(mood or {"valence": 0.0, "arousal": 0.0})
|
|
38
|
+
return {"valence": round(float(data.get("valence", 0.0) or 0.0), 3),
|
|
39
|
+
"arousal": round(float(data.get("arousal", 0.0) or 0.0), 3),
|
|
40
|
+
"label": label(data)}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def ticks_to_target(start, target, rate=RATE, threshold=0.05):
|
|
44
|
+
import math
|
|
45
|
+
distance = abs(float(target) - float(start))
|
|
46
|
+
if distance <= threshold or rate <= 0:
|
|
47
|
+
return 0
|
|
48
|
+
return int(math.ceil(math.log(threshold / distance) / math.log(1 - rate)))
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Narrative: turning key events into an autobiography, with three checks.
|
|
3
|
+
|
|
4
|
+
Input is a stream of key events. Output is:
|
|
5
|
+
|
|
6
|
+
- entries: a few chapter-like lines (theme + what happened), newest first
|
|
7
|
+
- consistency: share of events whose sign agrees with their theme's tone
|
|
8
|
+
- contradiction: share of same-theme pairs that pull opposite ways
|
|
9
|
+
- repair: share of negative events followed by a positive one in time
|
|
10
|
+
|
|
11
|
+
The three numbers are what the panel shows: is her story coherent, where does
|
|
12
|
+
it contradict itself, and has she been able to come back from the bad parts.
|
|
13
|
+
|
|
14
|
+
Pure functions only: no IO, no host imports, no LLM calls.
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
THEME_BY_KIND = {
|
|
19
|
+
"rupture": "关系裂缝", "repair": "修复", "gift": "被善待",
|
|
20
|
+
"loss": "失去", "becoming": "成长", "promise": "约定",
|
|
21
|
+
}
|
|
22
|
+
DEFAULT_THEME = "日常"
|
|
23
|
+
MAX_ENTRIES = 6
|
|
24
|
+
REPAIR_WINDOW_S = 7 * 24 * 3600.0
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _num(value, default=0.0):
|
|
28
|
+
try:
|
|
29
|
+
num = float(value)
|
|
30
|
+
except Exception:
|
|
31
|
+
return default
|
|
32
|
+
if num != num:
|
|
33
|
+
return default
|
|
34
|
+
return num
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _clamp(value, low=0.0, high=1.0):
|
|
38
|
+
return max(low, min(high, _num(value, low)))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _events(events):
|
|
42
|
+
out = []
|
|
43
|
+
for index, raw in enumerate(events or []):
|
|
44
|
+
if not isinstance(raw, dict):
|
|
45
|
+
continue
|
|
46
|
+
text = str(raw.get("text") or raw.get("summary") or "").strip()
|
|
47
|
+
if not text:
|
|
48
|
+
continue
|
|
49
|
+
kind = str(raw.get("kind") or "")
|
|
50
|
+
out.append({
|
|
51
|
+
"id": str(raw.get("id") or "e%d" % index),
|
|
52
|
+
"ts": _num(raw.get("ts"), 0.0),
|
|
53
|
+
"text": text[:80],
|
|
54
|
+
"kind": kind,
|
|
55
|
+
"theme": THEME_BY_KIND.get(kind, DEFAULT_THEME),
|
|
56
|
+
"valence": max(-1.0, min(1.0, _num(raw.get("valence"), 0.0))),
|
|
57
|
+
"importance": _clamp(raw.get("importance", 0.5)),
|
|
58
|
+
})
|
|
59
|
+
out.sort(key=lambda row: row["ts"])
|
|
60
|
+
return out
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def entries(events, limit=MAX_ENTRIES):
|
|
64
|
+
"""Compress the stream into chapter lines (newest first, deduped)."""
|
|
65
|
+
rows = _events(events)
|
|
66
|
+
limit = max(1, int(_num(limit, MAX_ENTRIES)))
|
|
67
|
+
picked = []
|
|
68
|
+
seen = set()
|
|
69
|
+
ranked = sorted(rows, key=lambda r: (r["importance"], r["ts"]), reverse=True)
|
|
70
|
+
for row in ranked:
|
|
71
|
+
key = (row["theme"], row["text"][:24])
|
|
72
|
+
if key in seen:
|
|
73
|
+
continue
|
|
74
|
+
seen.add(key)
|
|
75
|
+
picked.append({"theme": row["theme"], "text": row["text"],
|
|
76
|
+
"ts": row["ts"], "valence": row["valence"]})
|
|
77
|
+
if len(picked) >= limit:
|
|
78
|
+
break
|
|
79
|
+
picked.sort(key=lambda row: row["ts"], reverse=True)
|
|
80
|
+
return picked
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _themes(rows):
|
|
84
|
+
out = {}
|
|
85
|
+
for row in rows:
|
|
86
|
+
out.setdefault(row["theme"], []).append(row)
|
|
87
|
+
return out
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def consistency(events):
|
|
91
|
+
"""Weighted share of events agreeing with their theme tone (0-1)."""
|
|
92
|
+
rows = _events(events)
|
|
93
|
+
if not rows:
|
|
94
|
+
return 0.0
|
|
95
|
+
total = 0.0
|
|
96
|
+
agree = 0.0
|
|
97
|
+
for theme, group in _themes(rows).items():
|
|
98
|
+
signed = sum(row["valence"] * row["importance"] for row in group)
|
|
99
|
+
tone = 1.0 if signed >= 0 else -1.0
|
|
100
|
+
for row in group:
|
|
101
|
+
weight = row["importance"]
|
|
102
|
+
total += weight
|
|
103
|
+
if row["valence"] == 0 or (row["valence"] > 0) == (tone > 0):
|
|
104
|
+
agree += weight
|
|
105
|
+
if total <= 0:
|
|
106
|
+
return 0.0
|
|
107
|
+
return round(_clamp(agree / total), 3)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def contradiction(events):
|
|
111
|
+
"""Share of same-theme pairs pulling opposite ways (0-1)."""
|
|
112
|
+
rows = _events(events)
|
|
113
|
+
pairs = 0
|
|
114
|
+
opposite = 0
|
|
115
|
+
for theme, group in _themes(rows).items():
|
|
116
|
+
for i in range(len(group)):
|
|
117
|
+
for j in range(i + 1, len(group)):
|
|
118
|
+
a, b = group[i], group[j]
|
|
119
|
+
if a["valence"] == 0 or b["valence"] == 0:
|
|
120
|
+
continue
|
|
121
|
+
pairs += 1
|
|
122
|
+
if (a["valence"] > 0) != (b["valence"] > 0):
|
|
123
|
+
opposite += 1
|
|
124
|
+
if pairs <= 0:
|
|
125
|
+
return 0.0
|
|
126
|
+
return round(_clamp(opposite / pairs), 3)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def repair(events, window_s=REPAIR_WINDOW_S):
|
|
130
|
+
"""Share of negative events followed by a positive one in time."""
|
|
131
|
+
rows = _events(events)
|
|
132
|
+
window = max(0.0, _num(window_s, REPAIR_WINDOW_S))
|
|
133
|
+
negatives = [row for row in rows if row["valence"] < 0]
|
|
134
|
+
if not negatives:
|
|
135
|
+
return 0.0
|
|
136
|
+
healed = 0
|
|
137
|
+
for row in negatives:
|
|
138
|
+
later = [other for other in rows
|
|
139
|
+
if other["valence"] > 0
|
|
140
|
+
and (other["theme"] == row["theme"]
|
|
141
|
+
or other["kind"] == "repair")
|
|
142
|
+
and 0 <= other["ts"] - row["ts"] <= window]
|
|
143
|
+
if later:
|
|
144
|
+
healed += 1
|
|
145
|
+
return round(_clamp(healed / len(negatives)), 3)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def summarize(events, flags=None):
|
|
149
|
+
"""Everything the panel needs for one narrative refresh."""
|
|
150
|
+
flags = flags if isinstance(flags, dict) else {}
|
|
151
|
+
enabled = bool(flags.get("enabled", True))
|
|
152
|
+
rows = _events(events)
|
|
153
|
+
return {
|
|
154
|
+
"enabled": enabled,
|
|
155
|
+
"entries": entries(rows) if enabled else [],
|
|
156
|
+
"metrics": {
|
|
157
|
+
"consistency": consistency(rows) if enabled else 0.0,
|
|
158
|
+
"contradiction": contradiction(rows) if enabled else 0.0,
|
|
159
|
+
"repair": repair(rows) if enabled else 0.0,
|
|
160
|
+
},
|
|
161
|
+
"events": len(rows),
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def directives(result, contradiction_high=0.4):
|
|
166
|
+
"""Bounded hint: a contradictory story invites one clarification."""
|
|
167
|
+
if not isinstance(result, dict) or not result.get("enabled", True):
|
|
168
|
+
return {"tone": "", "allow_clarify": False}
|
|
169
|
+
metrics = result.get("metrics") or {}
|
|
170
|
+
messy = _clamp(metrics.get("contradiction", 0.0)) >= contradiction_high
|
|
171
|
+
return {"tone": ("可以补一句把话说圆" if messy else ""),
|
|
172
|
+
"allow_clarify": bool(messy)}
|