nexo-brain 5.9.0 → 5.10.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nexo-brain",
3
- "version": "5.9.0",
3
+ "version": "5.10.0",
4
4
  "description": "Local cognitive runtime for Claude Code \u2014 persistent memory, overnight learning, doctor diagnostics, personal scripts, recovery-aware jobs, startup preflight, and optional dashboard/power helper.",
5
5
  "author": {
6
6
  "name": "NEXO Brain",
package/README.md CHANGED
@@ -18,7 +18,11 @@
18
18
 
19
19
  [Watch the overview video](https://nexo-brain.com/watch/) · [Watch on YouTube](https://www.youtube.com/watch?v=i2lkGhKyVqI) · [Open the infographic](https://nexo-brain.com/assets/nexo-brain-infographic-v5.png)
20
20
 
21
- Version `5.9.0` is the current packaged-runtime line: every Claude/Codex invocation now flows through a central **resonance map** and a **unified session log**. Four tiers (`MAXIMO` / `ALTO` / `MEDIO` / `BAJO`) each resolve to a concrete `(model, reasoning_effort)` pair per backend. User-facing callers (`nexo chat`, Desktop new conversation, interactive `nexo update`) honour the user's `default_resonance` preference; system-owned callers (deep-sleep, evolution, catchup, GBP posts, …) run at a fixed tier chosen per caller in `src/resonance_map.py` — the user's preference never downgrades a cron we decided needs `MAXIMO`. Unknown callers raise `UnregisteredCallerError`. Migration #41 adds `caller`, `session_type`, `started_at`, `ended_at`, `pid`, `resonance_tier` to `automation_runs`; interactive sessions record a row at spawn (with `ended_at=NULL`) and update it on close, so the Brain now has a single source of truth for every Claude/Codex call regardless of origin. New `nexo preferences --resonance` CLI. New MCP tools `nexo_session_log_create` / `nexo_session_log_close` let NEXO Desktop (which spawns `claude` directly from its TypeScript process) feed the same log.
21
+ Version `5.10.0` is the current packaged-runtime line: fixes the deep-sleep extract bloat that made Session 1 take ~57 minutes on some installs (new `bare_mode` on `run_automation_prompt` wires `claude --bare` for JSON-only extractor callers ~4.3× faster per child, sourced from `ANTHROPIC_API_KEY` env or `~/.claude/anthropic-api-key.txt`). `caller=` is now **mandatory** on `run_automation_prompt` — no silent fallback; every automation subprocess traces back to a registered caller with a deliberate tier. Five personal scripts (`personal/email-monitor`, `personal/github-monitor`, `personal/post-x`, `personal/followup-runner`, `personal/orchestrator-v2`) joined the resonance map with tiers picked per caller based on what each one does. gbp/* marketing posts bumped from `medio` to `alto` (public-facing copy, quality first over speed). 65 legacy protocol debts bulk-resolved as part of the audit the patterns that generated them are structurally closed by mandatory `caller=` + unified session log + bare_mode.
22
+
23
+ Previously in `5.9.1`: adds `default_resonance` to `brain/calibration.json` via the Desktop-facing schema (`nexo schema --json`), so NEXO Desktop's Preferences dialog renders a select with `Máximo` / `Alto (recomendado)` / `Medio` / `Bajo` automatically — no Desktop release needed. `resolve_tier_for_caller` reads calibration first and falls back to the legacy `schedule.json` location. `nexo preferences --resonance` writes both. The UI control only affects interactive sessions (`nexo chat`, Desktop new conversation, interactive `nexo update`); crons and background processes stay pinned per caller in `resonance_map.py`.
24
+
25
+ Previously in `5.9.0`: every Claude/Codex invocation now flows through a central **resonance map** and a **unified session log**. Four tiers (`MAXIMO` / `ALTO` / `MEDIO` / `BAJO`) each resolve to a concrete `(model, reasoning_effort)` pair per backend. User-facing callers (`nexo chat`, Desktop new conversation, interactive `nexo update`) honour the user's `default_resonance` preference; system-owned callers (deep-sleep, evolution, catchup, GBP posts, …) run at a fixed tier chosen per caller in `src/resonance_map.py` — the user's preference never downgrades a cron we decided needs `MAXIMO`. Unknown callers raise `UnregisteredCallerError`. Migration #41 adds `caller`, `session_type`, `started_at`, `ended_at`, `pid`, `resonance_tier` to `automation_runs`; interactive sessions record a row at spawn (with `ended_at=NULL`) and update it on close, so the Brain now has a single source of truth for every Claude/Codex call regardless of origin. New `nexo preferences --resonance` CLI. New MCP tools `nexo_session_log_create` / `nexo_session_log_close` let NEXO Desktop (which spawns `claude` directly from its TypeScript process) feed the same log.
22
26
 
23
27
  Previously in `5.8.2`: the Brain core no longer auto-classifies `followups` and `reminders` on behalf of agents. v5.8.0's `classify_task()` heuristic (NEXO-specific ID prefixes `NF-PROTOCOL-*` / `NF-DS-*` / `NF-AUDIT-*`, Spanish user-verbs `debes` / `revisar` / `firmar`, agent keywords `monitor` / `auditoría diaria` / `checkpoint`) was fine for NEXO's own DB but bled convention into every third-party agent plugged into the shared Brain. The core now persists `internal=0` and `owner=NULL` when the caller omits them, and clients that want automatic classification (NEXO Desktop does, via its `_legacyClassifyOwner` helpers) compute it themselves and pass the result. Migration #40 keeps the columns + indexes; rows already backfilled by v5.8.0 keep their values. `normalise_owner` still explicitly rejects the string `"nexo"` so legacy hardcoding cannot sneak back in.
24
28
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nexo-brain",
3
- "version": "5.9.0",
3
+ "version": "5.10.0",
4
4
  "mcpName": "io.github.wazionapps/nexo",
5
5
  "description": "NEXO Brain \u2014 Shared brain for AI agents. Persistent memory, semantic RAG, natural forgetting, metacognitive guard, trust scoring, 150+ MCP tools. Works with Claude Code, Codex, Claude Desktop & any MCP client. 100% local, free.",
6
6
  "homepage": "https://nexo-brain.com",
@@ -792,6 +792,52 @@ def _build_enforcement_system_prompt() -> str:
792
792
  return "\n".join(lines) if (must_rules or should_rules) else ""
793
793
 
794
794
 
795
+ _ANTHROPIC_API_KEY_SEARCH_PATHS = (
796
+ Path.home() / ".claude" / "anthropic-api-key.txt",
797
+ Path.home() / ".nexo" / "config" / "anthropic-api-key.txt",
798
+ )
799
+
800
+
801
+ def _resolve_anthropic_api_key() -> str:
802
+ """Locate an Anthropic API key for bare-mode invocations.
803
+
804
+ ``claude --bare`` skips macOS Keychain auth entirely, so the child
805
+ must find the API key in ``ANTHROPIC_API_KEY`` or via ``apiKeyHelper``.
806
+ Rather than forcing the operator to export the key in every shell, we
807
+ check the two conventional NEXO locations:
808
+
809
+ ~/.claude/anthropic-api-key.txt
810
+ ~/.nexo/config/anthropic-api-key.txt
811
+
812
+ Returns the trimmed key string, or "" if none is available. Callers
813
+ that want to run in bare mode must fall back to non-bare execution
814
+ when this returns empty.
815
+ """
816
+ env_key = os.environ.get("ANTHROPIC_API_KEY", "").strip()
817
+ if env_key:
818
+ return env_key
819
+ for path in _ANTHROPIC_API_KEY_SEARCH_PATHS:
820
+ try:
821
+ if path.is_file():
822
+ key = path.read_text().strip()
823
+ if key:
824
+ return key
825
+ except OSError:
826
+ continue
827
+ return ""
828
+
829
+
830
+ # Callers for which bare_mode=True is safe. The child's only allowed_tools
831
+ # must be file/grep/shell (no ``mcp__nexo__*``), otherwise --bare's opt-out
832
+ # of plugin sync / MCP bootstrap breaks the run. Extract/synthesize fit
833
+ # this profile: they read transcripts + shared-context and emit JSON, no
834
+ # NEXO tool calls.
835
+ BARE_MODE_SAFE_CALLERS: frozenset[str] = frozenset({
836
+ "deep-sleep/extract",
837
+ "deep-sleep/synthesize",
838
+ })
839
+
840
+
795
841
  def run_automation_prompt(
796
842
  prompt: str,
797
843
  *,
@@ -807,6 +853,7 @@ def run_automation_prompt(
807
853
  append_system_prompt: str = "",
808
854
  allowed_tools: str = "",
809
855
  extra_args: list[str] | tuple[str, ...] | None = None,
856
+ bare_mode: bool | None = None,
810
857
  ) -> subprocess.CompletedProcess:
811
858
  prefs = load_client_preferences()
812
859
  selected_backend = backend or resolve_automation_backend(preferences=prefs)
@@ -822,35 +869,40 @@ def run_automation_prompt(
822
869
  reasoning_effort = profile["reasoning_effort"]
823
870
  selected_backend = _resolve_available_backend(selected_backend, preferences=prefs)
824
871
 
825
- # Resonance map takes over model+effort decisions when the caller is
826
- # registered. Explicit model/effort arguments still win (required for
827
- # edge cases like the fallback JSON-conversion call inside extract.py
828
- # that asks a shorter/cheaper follow-up).
829
- resonance_tier = ""
830
- if caller and not model and not reasoning_effort:
831
- try:
832
- from resonance_map import (
833
- resolve_model_and_effort,
834
- resolve_tier_for_caller,
835
- UnregisteredCallerError,
836
- )
837
- user_default = ""
838
- if isinstance(prefs, dict):
839
- user_default = str(prefs.get("default_resonance") or "").strip()
840
- resonance_tier = resolve_tier_for_caller(
841
- caller, user_default=user_default or None
842
- )
843
- mapped_model, mapped_effort = resolve_model_and_effort(
844
- caller, selected_backend, user_default=user_default or None
845
- )
846
- if mapped_model:
847
- model = mapped_model
848
- if mapped_effort:
849
- reasoning_effort = mapped_effort
850
- except (ImportError, UnregisteredCallerError):
851
- # Unknown caller during a transitional release: fall back to
852
- # the legacy task_profile / model_defaults resolution below.
853
- pass
872
+ # Resonance map decides (model, effort) for every call. ``caller`` is
873
+ # MANDATORY every script that invokes the automation backend must be
874
+ # registered in src/resonance_map.py so its reasoning budget is a
875
+ # deliberate choice rather than an accident of the global default.
876
+ #
877
+ # Explicit ``model`` or ``reasoning_effort`` arguments still override
878
+ # the mapped value (required for edge cases like the fallback JSON-
879
+ # conversion call inside extract.py that runs on a shorter budget).
880
+ from resonance_map import (
881
+ resolve_model_and_effort,
882
+ resolve_tier_for_caller,
883
+ UnregisteredCallerError,
884
+ )
885
+ if not caller:
886
+ raise UnregisteredCallerError(
887
+ "run_automation_prompt requires caller=. Register a new entry in "
888
+ "src/resonance_map.py under USER_FACING_CALLERS or "
889
+ "SYSTEM_OWNED_CALLERS and pass the id here."
890
+ )
891
+ user_default = ""
892
+ if isinstance(prefs, dict):
893
+ user_default = str(prefs.get("default_resonance") or "").strip()
894
+ # This raises UnregisteredCallerError if caller is unknown — the
895
+ # same fail-closed rule we wanted. No silent fallback.
896
+ resonance_tier = resolve_tier_for_caller(
897
+ caller, user_default=user_default or None
898
+ )
899
+ mapped_model, mapped_effort = resolve_model_and_effort(
900
+ caller, selected_backend, user_default=user_default or None
901
+ )
902
+ if mapped_model and not model:
903
+ model = mapped_model
904
+ if mapped_effort and not reasoning_effort:
905
+ reasoning_effort = mapped_effort
854
906
 
855
907
  enforcement_fragment = _build_enforcement_system_prompt()
856
908
  if enforcement_fragment:
@@ -877,6 +929,39 @@ def run_automation_prompt(
877
929
  raise AutomationBackendUnavailableError(
878
930
  "Claude Code automation backend selected but `claude` is not installed."
879
931
  )
932
+
933
+ # bare_mode: when the caller only needs the model (no MCP tool
934
+ # calls, no CLAUDE.md context, no plugins) we pass Claude CLI's
935
+ # --bare flag. That skips hooks, LSP, plugin sync, CLAUDE.md
936
+ # auto-discovery, keychain reads, and background prefetches —
937
+ # reducing the per-invocation overhead from ~9s to ~2s on 2.1.x.
938
+ # Concretely: deep-sleep/extract was running 57min on Session 1
939
+ # because each extract attempt inherited ~15KB of NEXO CLAUDE.md
940
+ # system prompt it did not need. With --bare that extraction
941
+ # completes in seconds.
942
+ #
943
+ # Selection rules:
944
+ # - bare_mode=True explicit → trust the caller.
945
+ # - bare_mode=None (default) + caller in BARE_MODE_SAFE_CALLERS
946
+ # → auto-enable.
947
+ # - bare_mode=False → never.
948
+ # - --bare disables keychain auth, so we must provide an
949
+ # ANTHROPIC_API_KEY. If one cannot be located, fall back to
950
+ # normal mode with a warning on stderr rather than failing.
951
+ resolved_bare = False
952
+ if bare_mode is True:
953
+ resolved_bare = True
954
+ elif bare_mode is None and caller in BARE_MODE_SAFE_CALLERS:
955
+ resolved_bare = True
956
+
957
+ bare_api_key = ""
958
+ if resolved_bare:
959
+ bare_api_key = _resolve_anthropic_api_key()
960
+ if not bare_api_key:
961
+ # Silent fallback: we would rather take the slower path
962
+ # than force the caller to fail-closed on an env quirk.
963
+ resolved_bare = False
964
+
880
965
  # Headless claude -p does NOT reliably honour permissions.allow from
881
966
  # settings.json for MCP tool calls — it can stall waiting for an
882
967
  # approval that will never come in non-interactive mode. All NEXO
@@ -885,7 +970,15 @@ def run_automation_prompt(
885
970
  # so the process actually runs instead of zombying. Interactive
886
971
  # sessions (`nexo chat`) never go through this code path and keep
887
972
  # their normal approval prompts.
888
- cmd = [claude_bin, "-p", prompt, "--dangerously-skip-permissions"]
973
+ cmd = [claude_bin, "-p", prompt]
974
+ if resolved_bare:
975
+ cmd.append("--bare")
976
+ # Guarantee the child sees the API key regardless of how the
977
+ # parent's env was sanitized by _headless_env.
978
+ run_env = dict(run_env)
979
+ run_env["ANTHROPIC_API_KEY"] = bare_api_key
980
+ else:
981
+ cmd.append("--dangerously-skip-permissions")
889
982
  if resolved_model:
890
983
  cmd.extend(["--model", resolved_model])
891
984
  if resolved_effort:
package/src/cli.py CHANGED
@@ -1099,6 +1099,34 @@ def _clients_sync(args):
1099
1099
  return 0 if result.get("ok") else 1
1100
1100
 
1101
1101
 
1102
+ def _write_calibration_default_resonance(tier: str) -> None:
1103
+ """Persist ``preferences.default_resonance`` in ``brain/calibration.json``.
1104
+
1105
+ NEXO Desktop's preferences UI reads from calibration.json (matches the
1106
+ rest of the user-facing knobs — autonomy, communication, assistant_name,
1107
+ …). This helper keeps the CLI path writing to both calibration.json
1108
+ AND schedule.json so the two surfaces never disagree.
1109
+ """
1110
+ cal_path = NEXO_HOME / "brain" / "calibration.json"
1111
+ try:
1112
+ cal_path.parent.mkdir(parents=True, exist_ok=True)
1113
+ if cal_path.exists():
1114
+ data = json.loads(cal_path.read_text())
1115
+ if not isinstance(data, dict):
1116
+ data = {}
1117
+ else:
1118
+ data = {}
1119
+ prefs = data.get("preferences")
1120
+ if not isinstance(prefs, dict):
1121
+ prefs = {}
1122
+ prefs["default_resonance"] = tier
1123
+ data["preferences"] = prefs
1124
+ cal_path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n")
1125
+ except Exception as exc: # best-effort; schedule.json still has the value
1126
+ print(f"[NEXO] Warning: could not update calibration.json: {exc}",
1127
+ file=sys.stderr)
1128
+
1129
+
1102
1130
  def _preferences(args):
1103
1131
  """Read or change user preferences stored in schedule.json.
1104
1132
 
@@ -1110,7 +1138,11 @@ def _preferences(args):
1110
1138
  load_client_preferences,
1111
1139
  save_client_preferences,
1112
1140
  )
1113
- from resonance_map import DEFAULT_RESONANCE, TIERS
1141
+ from resonance_map import (
1142
+ DEFAULT_RESONANCE,
1143
+ TIERS,
1144
+ _load_user_default_resonance,
1145
+ )
1114
1146
 
1115
1147
  prefs = load_client_preferences()
1116
1148
  if not isinstance(prefs, dict):
@@ -1125,26 +1157,37 @@ def _preferences(args):
1125
1157
  file=sys.stderr,
1126
1158
  )
1127
1159
  return 2
1160
+ # Write to schedule.json (legacy CLI location)…
1128
1161
  save_client_preferences(default_resonance=tier)
1162
+ # …and to calibration.json (where NEXO Desktop's preferences UI
1163
+ # reads/writes). Keeping both in sync means the two surfaces agree.
1164
+ _write_calibration_default_resonance(tier)
1129
1165
  prefs = load_client_preferences()
1130
1166
 
1131
- current_resonance = str(
1167
+ calibration_value = _load_user_default_resonance()
1168
+ schedule_value = str(
1132
1169
  (prefs.get("default_resonance") if isinstance(prefs, dict) else "")
1133
- or DEFAULT_RESONANCE
1134
- )
1170
+ or ""
1171
+ ).strip().lower()
1172
+ current_resonance = calibration_value or schedule_value or DEFAULT_RESONANCE
1135
1173
 
1136
1174
  if args.show or args.resonance:
1175
+ is_explicit = bool(calibration_value or schedule_value)
1137
1176
  payload = {
1138
1177
  "default_resonance": current_resonance,
1139
- "default_resonance_is_explicit": isinstance(prefs, dict)
1140
- and bool(prefs.get("default_resonance")),
1178
+ "default_resonance_is_explicit": is_explicit,
1179
+ "default_resonance_source": (
1180
+ "calibration.json" if calibration_value
1181
+ else ("schedule.json" if schedule_value else "default")
1182
+ ),
1141
1183
  "available_tiers": list(TIERS),
1142
1184
  }
1143
1185
  if args.json:
1144
1186
  print(json.dumps(payload, indent=2, ensure_ascii=False))
1145
1187
  else:
1146
1188
  print(f"default_resonance = {current_resonance}")
1147
- if not payload["default_resonance_is_explicit"]:
1189
+ print(f" source: {payload['default_resonance_source']}")
1190
+ if not is_explicit:
1148
1191
  print(f" (inherited from DEFAULT_RESONANCE; run "
1149
1192
  f"`nexo preferences --resonance alto` to set explicitly)")
1150
1193
  return 0
@@ -191,6 +191,34 @@ def _schema_fields() -> list[dict]:
191
191
  {"value": "verbose", "label": {"es": "Detallado", "en": "Verbose"}},
192
192
  ],
193
193
  },
194
+ {
195
+ "path": "preferences.default_resonance",
196
+ "file": "calibration.json",
197
+ "label": {"es": "Resonancia por defecto", "en": "Default resonance"},
198
+ "type": "select",
199
+ "group": "preferences",
200
+ "default": "alto",
201
+ "hint": {
202
+ "es": (
203
+ "Potencia del modelo para sesiones interactivas (nexo chat y "
204
+ "nueva conversación en Desktop). Los crons y procesos de fondo "
205
+ "(deep sleep, evolution, etc.) ignoran esta preferencia — los "
206
+ "definimos nosotros en resonance_map.py por calidad."
207
+ ),
208
+ "en": (
209
+ "Model power for interactive sessions (nexo chat and Desktop "
210
+ "new conversation). Crons and background processes (deep sleep, "
211
+ "evolution, etc.) ignore this preference — we pin them per "
212
+ "caller in resonance_map.py based on quality needs."
213
+ ),
214
+ },
215
+ "options": [
216
+ {"value": "maximo", "label": {"es": "Máximo", "en": "Maximum"}},
217
+ {"value": "alto", "label": {"es": "Alto (recomendado)", "en": "High (recommended)"}},
218
+ {"value": "medio", "label": {"es": "Medio", "en": "Medium"}},
219
+ {"value": "bajo", "label": {"es": "Bajo", "en": "Low"}},
220
+ ],
221
+ },
194
222
  {
195
223
  "path": "meta.role",
196
224
  "file": "calibration.json",
@@ -143,14 +143,25 @@ SYSTEM_OWNED_CALLERS: dict[str, str] = {
143
143
  "tools/drive_search": "medio",
144
144
 
145
145
  # ---- Marketing automation ---------------------------------------------
146
- # These produce short copy; we could run them at BAJO for speed, but the
147
- # output is user-visible on a public surface, so we lean MEDIO for safety
148
- # against embarrassing outputs.
149
- "gbp/daily_post": "medio",
150
- "gbp/post_wazion": "medio",
151
- "gbp/post_psicologa": "medio",
152
- "gbp/monthly_audit": "medio",
153
- "gbp/reviews_watch": "medio",
146
+ # These post to Google Business Profile on behalf of Francisco's
147
+ # businesses. Short copy, but user-visible on a public surface; a
148
+ # mediocre post embarrasses the brand. Running them ALTO even though
149
+ # it's ~200 chars keeps the output quality tight.
150
+ "gbp/daily_post": "alto",
151
+ "gbp/post_wazion": "alto",
152
+ "gbp/post_psicologa": "alto",
153
+ "gbp/monthly_audit": "alto",
154
+ "gbp/reviews_watch": "alto",
155
+
156
+ # ---- Personal scripts (operators' own LaunchAgents) -------------------
157
+ # Francisco + Maria ship the same set of personal scripts via
158
+ # ~/.nexo/scripts (installed per-user, not through the core manifest).
159
+ # They all call into mcp__nexo__* so they cannot run under --bare.
160
+ "personal/email-monitor": "alto", # answer real user emails, quality matters
161
+ "personal/github-monitor": "alto", # reason about issues/PRs, not mechanical
162
+ "personal/post-x": "alto", # public-facing copy
163
+ "personal/followup-runner": "alto", # executes due followups, output is user-visible
164
+ "personal/orchestrator-v2": "maximo", # autonomous orchestration, critical reasoning
154
165
  }
155
166
 
156
167
  ALL_REGISTERED_CALLERS: frozenset[str] = frozenset(
@@ -174,6 +185,48 @@ class UnregisteredCallerError(ValueError):
174
185
  # Resolution
175
186
  # ---------------------------------------------------------------------------
176
187
 
188
+ def _load_user_default_resonance() -> str:
189
+ """Resolve the user's ``default_resonance`` preference.
190
+
191
+ Reads ``calibration.json`` first (``preferences.default_resonance``, the
192
+ location NEXO Desktop's preferences UI writes to) and falls back to
193
+ ``schedule.json`` (``default_resonance``, the location the CLI used to
194
+ write to in v5.9.0). Returns an empty string if neither source has a
195
+ valid tier — callers should treat empty as "no preference".
196
+ """
197
+ import json as _json
198
+ import os as _os
199
+ from pathlib import Path as _Path
200
+
201
+ home = _Path(_os.environ.get("NEXO_HOME", str(_Path.home() / ".nexo")))
202
+
203
+ # calibration.json (Desktop UI writes here)
204
+ cal_path = home / "brain" / "calibration.json"
205
+ try:
206
+ if cal_path.exists():
207
+ cal = _json.loads(cal_path.read_text())
208
+ prefs = cal.get("preferences") if isinstance(cal, dict) else None
209
+ if isinstance(prefs, dict):
210
+ tier = str(prefs.get("default_resonance") or "").strip().lower()
211
+ if tier in TIERS:
212
+ return tier
213
+ except (OSError, _json.JSONDecodeError):
214
+ pass
215
+
216
+ # schedule.json (CLI legacy)
217
+ sched_path = home / "config" / "schedule.json"
218
+ try:
219
+ if sched_path.exists():
220
+ sched = _json.loads(sched_path.read_text())
221
+ tier = str((sched or {}).get("default_resonance") or "").strip().lower()
222
+ if tier in TIERS:
223
+ return tier
224
+ except (OSError, _json.JSONDecodeError):
225
+ pass
226
+
227
+ return ""
228
+
229
+
177
230
  def resolve_tier_for_caller(caller: str, user_default: str | None = None) -> str:
178
231
  """Return the resonance tier that should apply to ``caller``.
179
232
 
@@ -181,6 +234,9 @@ def resolve_tier_for_caller(caller: str, user_default: str | None = None) -> str
181
234
  if the user has no preference recorded).
182
235
  - System-owned callers resolve to their fixed tier.
183
236
  - Unknown callers raise ``UnregisteredCallerError``.
237
+
238
+ When ``user_default`` is not passed, the function looks it up from the
239
+ calibration.json preferences first and schedule.json second.
184
240
  """
185
241
  if not caller:
186
242
  raise UnregisteredCallerError(
@@ -188,7 +244,10 @@ def resolve_tier_for_caller(caller: str, user_default: str | None = None) -> str
188
244
  "in src/resonance_map.py so its reasoning budget is deliberate."
189
245
  )
190
246
  if caller in USER_FACING_CALLERS:
191
- tier = (user_default or DEFAULT_RESONANCE).strip().lower()
247
+ resolved_default = user_default
248
+ if resolved_default is None:
249
+ resolved_default = _load_user_default_resonance()
250
+ tier = (resolved_default or DEFAULT_RESONANCE).strip().lower()
192
251
  if tier not in TIERS:
193
252
  tier = DEFAULT_RESONANCE
194
253
  return tier