Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
@ feat(brain): weave ambient personal knowledge into answers
Ruben Lütke478014bf9432
diff --git a/jarvis/brain/identity_card.py b/jarvis/brain/identity_card.pynew file mode 100644index 0000000000..04725ea26d--- /dev/null+++ b/jarvis/brain/identity_card.py@@ -0,0 +1,706 @@+"""Identity card — the standing half of ambient personal knowledge.++The per-turn wiki context (``jarvis.brain.wiki_context``) answers "is there a+note about what was just asked?". This module answers the other, cheaper+question: "who is the person asking?". A short, deterministic distillation of+the user's own profile that rides in the CACHED system-prompt prefix, so the+assistant knows whom it is talking to without paying for a retrieval, a model+call, or a per-turn prompt change.++Design constraints, all of them load-bearing:++* **No model call, ever.** The distillation is regex + string work over text+ the user already owns (AP-9/AP-11). There is no summarizer here and none may+ be added — the whole point is that ambient knowledge costs nothing per turn.+* **Hard character budget.** :data:`MAX_IDENTITY_CARD_CHARS` caps the card+ itself; the framing header is a constant. Personal knowledge that is always+ present must be small enough to always be affordable.+* **Byte-stable across turns.** The card is recomputed only when the SOURCE+ content hash changes, and the result is cached on disk under the data+ directory, so a restart does not change the cached prefix either. A block+ that changed every turn would break the provider prompt cache and cost more+ than it delivers.+* **Off the boot path (AP-26).** Nothing here runs at import time. The first+ read happens on the first prompt build; every later read is served from+ memory and re-checks its sources at most every+ :data:`DEFAULT_RECHECK_INTERVAL_S` seconds.+* **Silence beats a personal fact nobody asked for.** The mandate the wiki+ context injector carries applies unchanged here, and harder: this block is+ present on EVERY turn, so its framing has to be blunt about being background+ only. See :data:`IDENTITY_BLOCK_HEADER`.++Sources, in priority order — whichever exist, all optional:++1. The UltraWiki entity profile, through a capability-probed public seam+ (``service.user_profile_markdown()``). The seam does not exist yet; the+ probe is a ``getattr`` + ``callable`` check, so this degrades to "absent"+ until the UltraWiki side ships it. Nothing in this module reaches into an+ UltraWiki store.+2. The normal wiki's living profile page ``entities/<user-slug>.md``+ (``jarvis.memory.wiki.profile``), resolved through the canonical vault-root+ resolver.+3. ``data/core_memory.json``.++Core memory is deliberately consumed LAST. Its content is already injected+separately by the prompt builder, so it only fills whatever budget the wiki+profile left over — which for a user with no wiki at all is the whole card,+and for a user with a rich profile is nothing. Every candidate line is deduped+against what the card already says.++No profile and empty core memory produce an empty card, and an empty card+produces no block at all — a fresh install is silent, not apologetic.+"""++from __future__ import annotations++import hashlib+import json+import logging+import re+import threading+import time+from collections.abc import Mapping, Sequence+from dataclasses import dataclass+from pathlib import Path+from typing import Any++log = logging.getLogger(__name__)++__all__ = [+ "IDENTITY_BLOCK_HEADER",+ "IDENTITY_CARD_FILENAME",+ "MAX_IDENTITY_CARD_CHARS",+ "PROFILE_SECTION_PRIORITY",+ "IdentityCard",+ "IdentityCardCache",+ "collect_sources",+ "distill_identity_card",+ "identity_card_block",+ "identity_card_text",+ "render_identity_block",+ "reset_identity_card_cache",+]+++#: Hard cap on the distilled card (the framing header is extra and constant).+#: Chosen so the always-present block stays in the same order of magnitude as+#: one retrieved wiki snippet: standing knowledge must never out-cost the+#: knowledge that was actually asked for.+MAX_IDENTITY_CARD_CHARS = 600++#: Disk cache, under the data directory. Holds the rendered card plus the hash+#: of the sources it was built from — nothing that is not already in the+#: user's own notes.+IDENTITY_CARD_FILENAME = "identity_card.json"++#: How long a built card is trusted before its sources are re-read. The+#: re-read is two small file reads, and it only rebuilds when the content hash+#: actually moved, so a stale-by-minutes card is the deliberate trade against+#: touching the disk on every turn.+DEFAULT_RECHECK_INTERVAL_S = 300.0++#: Sections of the living profile page that carry identity, in the order they+#: are allowed to spend the character budget. A strict subset of+#: ``jarvis.memory.wiki.profile.PROFILE_SECTIONS`` (guarded by a parity test):+#: "Decisions" and "Sources" are episodic bookkeeping, not who someone is.+PROFILE_SECTION_PRIORITY: tuple[str, ...] = (+ "Summary",+ "Identity",+ "Preferences",+ "Work style",+ "Values",+ "Active projects",+ "Relationships",+)++#: Entries per group. One verbose section must not be able to eat the card.+_MAX_ENTRIES_PER_GROUP = 3++#: Bounded read of any single source file — a runaway profile page must not+#: turn a prompt build into a large read.+_MAX_SOURCE_CHARS = 64_000++#: Bumped when the cache-file layout changes; an older file is ignored rather+#: than misread.+_CACHE_SCHEMA_VERSION = 1++_FRONTMATTER_RE = re.compile(r"\A---\r?\n.*?\r?\n---[ \t]*\r?\n", re.DOTALL)+_HTML_COMMENT_RE = re.compile(r"<!--.*?-->", re.DOTALL)+_WIKILINK_RE = re.compile(r"\[\[([^\]|]+)(?:\|([^\]]+))?\]\]")+_MD_LINK_RE = re.compile(r"\[([^\]]*)\]\([^)]*\)")+_BULLET_RE = re.compile(r"\A\s*(?:[-*+]|\d+[.)])\s+")+_HEADING_RE = re.compile(r"\A\s{0,3}(#{1,6})\s+(.+?)\s*#*\s*\Z")+_EMPHASIS_RE = re.compile(r"[*_`~]{1,3}")+_WS_RE = re.compile(r"\s+")+_KEY_NOISE_RE = re.compile(r"[^\w]+", re.UNICODE)+++@dataclass(frozen=True, slots=True)+class IdentityCard:+ """A built card plus the fingerprint of the sources it came from."""++ text: str+ source_hash: str+ sources: tuple[str, ...] = ()++ def to_json(self) -> dict[str, Any]:+ return {+ "version": _CACHE_SCHEMA_VERSION,+ "text": self.text,+ "source_hash": self.source_hash,+ "sources": list(self.sources),+ }++ @classmethod+ def from_json(cls, raw: Mapping[str, Any]) -> IdentityCard | None:+ if int(raw.get("version", 0) or 0) != _CACHE_SCHEMA_VERSION:+ return None+ text = raw.get("text")+ source_hash = raw.get("source_hash")+ if not isinstance(text, str) or not isinstance(source_hash, str):+ return None+ sources = raw.get("sources")+ labels: tuple[str, ...] = ()+ if isinstance(sources, list):+ labels = tuple(s for s in sources if isinstance(s, str))+ return cls(text=text, source_hash=source_hash, sources=labels)+++# ---------------------------------------------------------------------------+# Text cleaning+# ---------------------------------------------------------------------------+++def _clean(value: object) -> str:+ """Flatten one Markdown-ish line into plain prose, or "" when it carries none."""+ if value is None:+ return ""+ text = str(value)+ text = _HTML_COMMENT_RE.sub(" ", text)+ text = _WIKILINK_RE.sub(lambda m: m.group(2) or m.group(1), text)+ text = _MD_LINK_RE.sub(lambda m: m.group(1), text)+ text = _BULLET_RE.sub("", text)+ text = _EMPHASIS_RE.sub("", text)+ text = text.replace("|", " ")+ text = _WS_RE.sub(" ", text).strip(" \t-–—:;")+ return text+++def _key(text: str) -> str:+ """Fold a line to a comparison key (case- and punctuation-insensitive)."""+ return _KEY_NOISE_RE.sub("", text.casefold())+++class _Collector:+ """Ordered, deduplicated groups of card entries."""++ def __init__(self) -> None:+ self._groups: dict[str, list[str]] = {}+ self._keys: list[str] = []++ def add(self, label: str, value: object) -> None:+ text = _clean(value)+ if not text:+ return+ key = _key(text)+ if not key or self._is_duplicate(key):+ return+ bucket = self._groups.setdefault(label, [])+ if len(bucket) >= _MAX_ENTRIES_PER_GROUP:+ return+ self._keys.append(key)+ bucket.append(text)++ def _is_duplicate(self, key: str) -> bool:+ for seen in self._keys:+ if key == seen:+ return True+ # Containment only counts for substantial strings: "de" inside+ # "dentist" is a coincidence, "runs a solo business" inside "runs a+ # solo business in Berlin" is a restatement.+ if min(len(key), len(seen)) >= 12 and (key in seen or seen in key):+ return True+ return False++ def groups(self) -> list[tuple[str, list[str]]]:+ return [(label, list(entries)) for label, entries in self._groups.items() if entries]+++# ---------------------------------------------------------------------------+# Source parsing+# ---------------------------------------------------------------------------+++def _strip_frontmatter(markdown: str) -> str:+ return _FRONTMATTER_RE.sub("", markdown, count=1)+++def _section_lookup() -> dict[str, str]:+ return {name.casefold(): name for name in PROFILE_SECTION_PRIORITY}+++def _collect_profile(collector: _Collector, markdown: str) -> None:+ """Read the living profile page: its H1 name plus the identity sections."""+ if not markdown.strip():+ return+ known = _section_lookup()+ section: str | None = None+ # Section content is gathered first, then spent in PRIORITY order — the+ # page's own order must not decide who gets the budget.+ gathered: dict[str, list[str]] = {}+ name = ""+ for raw_line in _strip_frontmatter(markdown).splitlines():+ heading = _HEADING_RE.match(raw_line)+ if heading is not None:+ level, title = len(heading.group(1)), _clean(heading.group(2))+ if level == 1 and not name:+ name = title+ section = known.get(title.casefold())+ continue+ if section is None:+ continue+ line = _clean(raw_line)+ if line:+ gathered.setdefault(section, []).append(line)+ if name:+ collector.add("Name", name)+ for label in PROFILE_SECTION_PRIORITY:+ for entry in gathered.get(label, []):+ collector.add(label, entry)+++def _flatten(value: Any) -> list[str]:+ """One value of a core-memory section as zero or more display strings."""+ if isinstance(value, str):+ return [value]+ if isinstance(value, Mapping):+ return [f"{k}: {v}" for k, v in value.items() if v not in (None, "", [], {})]+ if isinstance(value, Sequence):+ out: list[str] = []+ for item in value:+ out.extend(_flatten(item))+ return out+ if value is None:+ return []+ return [str(value)]+++def _collect_core_memory(collector: _Collector, data: Mapping[str, Any] | None) -> None:+ """Fill whatever budget the wiki profile left with core-memory facts.++ ``persona`` is skipped on purpose: it describes the ASSISTANT, and this+ card is about the user.+ """+ if not data:+ return+ facts = data.get("user_facts")+ if isinstance(facts, Mapping):+ for items in facts.values():+ for entry in _flatten(items):+ collector.add("Facts", entry)+ elif facts:+ for entry in _flatten(facts):+ collector.add("Facts", entry)++ prefs = data.get("preferences")+ if isinstance(prefs, Mapping):+ for pref_key, value in prefs.items():+ collector.add("Preferences", f"{pref_key}: {value}")++ projects = data.get("current_projects")+ if isinstance(projects, Mapping):+ for project, description in projects.items():+ collector.add("Active projects", f"{project}: {description}")+ elif projects:+ for entry in _flatten(projects):+ collector.add("Active projects", entry)+++# ---------------------------------------------------------------------------+# Distillation+# ---------------------------------------------------------------------------+++def distill_identity_card(+ *,+ profile_markdown: str = "",+ core_memory: Mapping[str, Any] | None = None,+ max_chars: int = MAX_IDENTITY_CARD_CHARS,+) -> str:+ """Deterministically distill the sources into a card of ``<= max_chars``.++ Pure function: same input, same output, no IO, no model call. Returns ""+ when the sources carry nothing — the caller then emits no block at all.+ """+ collector = _Collector()+ _collect_profile(collector, profile_markdown or "")+ _collect_core_memory(collector, core_memory)++ lines: list[str] = []+ used = 0+ for label, entries in collector.groups():+ prefix = f"- {label}: "+ line = ""+ for entry in entries:+ candidate = entry if not line else f"{line}; {entry}"+ projected = used + (1 if lines else 0) + len(prefix) + len(candidate)+ if projected > max_chars:+ break+ line = candidate+ if not line:+ continue+ used += (1 if lines else 0) + len(prefix) + len(line)+ lines.append(prefix + line)+ return "\n".join(lines)+++#: Framing for the always-present block. Two jobs: say that this is background+#: about the person (not a topic), and grant explicit permission to say nothing+#: about it — the standing mandate of this whole surface.+IDENTITY_BLOCK_HEADER = (+ "## About the user (ambient personal knowledge — background, never a topic)\n"+ "Standing facts about the person you are speaking with, distilled from "+ "their own notes. Let them shape an answer only where they genuinely make "+ "it better — a recommendation, a plan, a decision that depends on who is "+ "asking. Never read this block out, never mention that you have it, and "+ "never volunteer a personal detail the question did not ask for: silence "+ "beats a personal fact nobody asked for."+)+++def render_identity_block(card_text: str) -> str:+ """Wrap a card in its usage contract; "" for an empty card."""+ if not card_text or not card_text.strip():+ return ""+ return IDENTITY_BLOCK_HEADER + "\n\n" + card_text.strip()+++# ---------------------------------------------------------------------------+# Source resolution (all optional, all silent when absent)+# ---------------------------------------------------------------------------+++def _read_text(path: Path) -> str:+ try:+ with path.open("r", encoding="utf-8", errors="replace") as handle:+ return handle.read(_MAX_SOURCE_CHARS)+ except OSError:+ return ""+++def _ultrawiki_profile_markdown() -> str:+ """The UltraWiki entity profile, when that store exposes one.++ Capability probe, never a version check (AP-21): if the live service has a+ callable ``user_profile_markdown`` returning text, that text wins; anything+ else — no service, no seam, a raising seam, a non-string — is simply absent.+ """+ try:+ from jarvis.ultrawiki.service import active_search_service # noqa: PLC0415++ service = active_search_service()+ except Exception: # noqa: BLE001 — an unavailable mode is not an error+ return ""+ if service is None:+ return ""+ seam = getattr(service, "user_profile_markdown", None)+ if not callable(seam):+ return ""+ try:+ value = seam()+ except Exception: # noqa: BLE001 — a broken seam degrades to absent+ log.debug("identity card: UltraWiki profile seam failed", exc_info=True)+ return ""+ if isinstance(value, str):+ return value+ # An async seam would leak an un-awaited coroutine; close it and move on.+ close = getattr(value, "close", None)+ if callable(close):+ try:+ close()+ except Exception: # noqa: BLE001+ log.debug("identity card: could not close a non-text seam result", exc_info=True)+ return ""+++def _user_entity_slug(config: Any) -> str:+ raw = ""+ try:+ rollup = config.memory.wiki.session_rollup+ raw = str(getattr(rollup, "user_entity_slug", "") or "")+ except Exception: # noqa: BLE001 — an older/absent config is just "user"+ raw = ""+ try:+ from jarvis.memory.wiki.prompt import resolve_user_entity_slug # noqa: PLC0415++ return resolve_user_entity_slug(raw)+ except Exception: # noqa: BLE001+ slug = re.sub(r"[^a-z0-9-]+", "-", raw.strip().casefold()).strip("-")+ return slug or "user"+++def _vault_profile_path(config: Any) -> Path | None:+ try:+ from jarvis.memory.wiki.vault_root import resolve_vault_root # noqa: PLC0415++ raw = getattr(getattr(config, "wiki_integration", None), "vault_root", None)+ if raw is not None and str(raw).strip() == "":+ raw = None+ root = resolve_vault_root(raw).path+ except Exception: # noqa: BLE001 — no vault resolvable means no profile+ log.debug("identity card: vault root unresolvable", exc_info=True)+ return None+ return root / "entities" / f"{_user_entity_slug(config)}.md"+++def _core_memory_path(config: Any) -> Path | None:+ # ``[wiki_context].core_memory_path`` is an optional relocation seam for+ # hosts that keep state outside the data directory (and for tests). Absent+ # in a normal config, where the standard data-dir location applies.+ override = getattr(getattr(config, "wiki_context", None), "core_memory_path", None)+ if override:+ return Path(str(override))+ try:+ from jarvis.core.config import DATA_DIR # noqa: PLC0415+ from jarvis.memory.core_memory import CORE_MEMORY_FILENAME # noqa: PLC0415++ return Path(DATA_DIR) / CORE_MEMORY_FILENAME+ except Exception: # noqa: BLE001+ return None+++def collect_sources(config: Any = None) -> tuple[str, Mapping[str, Any] | None, tuple[str, ...]]:+ """Read every available source once. Returns ``(profile, core, labels)``.++ Never raises: an unreadable, missing or malformed source is absent, and an+ install with none of them yields ``("", None, ())``.+ """+ labels: list[str] = []+ profile = _ultrawiki_profile_markdown()+ if profile.strip():+ labels.append("ultrawiki:profile")+ else:+ path = _vault_profile_path(config)+ if path is not None:+ profile = _read_text(path)+ if profile.strip():+ labels.append(f"vault:entities/{path.stem}.md")++ core: Mapping[str, Any] | None = None+ core_path = _core_memory_path(config)+ if core_path is not None:+ raw = _read_text(core_path)+ if raw.strip():+ try:+ parsed = json.loads(raw)+ except (ValueError, TypeError):+ parsed = None+ if isinstance(parsed, Mapping):+ core = parsed+ labels.append("core_memory")+ return profile, core, tuple(labels)+++def _hash_sources(profile: str, core: Mapping[str, Any] | None) -> str:+ digest = hashlib.sha256()+ digest.update(profile.encode("utf-8", "replace"))+ digest.update(b"\x00")+ if core is not None:+ try:+ digest.update(+ json.dumps(core, sort_keys=True, ensure_ascii=False, default=str).encode(+ "utf-8", "replace"+ )+ )+ except (TypeError, ValueError): # pragma: no cover — default=str covers it+ digest.update(repr(core).encode("utf-8", "replace"))+ return digest.hexdigest()[:32]+++# ---------------------------------------------------------------------------+# Cache+# ---------------------------------------------------------------------------+++class IdentityCardCache:+ """Builds the card at most once per source change, and holds it.++ Thread-safe and IO-free on the common path: after the first build every+ call inside ``recheck_interval_s`` returns the held string without touching+ the filesystem. The disk file carries the card across restarts, so a fresh+ process serves the same bytes as the one before it and the provider prompt+ cache keeps hitting.+ """++ def __init__(+ self,+ *,+ config: Any = None,+ cache_path: Path | str | None = None,+ max_chars: int = MAX_IDENTITY_CARD_CHARS,+ recheck_interval_s: float = DEFAULT_RECHECK_INTERVAL_S,+ clock: Any = time.monotonic,+ ) -> None:+ self._config = config+ self._cache_path = Path(cache_path) if cache_path else None+ self._max_chars = int(max_chars)+ self._recheck_interval_s = float(recheck_interval_s)+ self._clock = clock+ self._lock = threading.Lock()+ self._card: IdentityCard | None = None+ self._checked_at: float | None = None+ self._disk_read = False++ # -- paths ---------------------------------------------------------++ def _path(self) -> Path | None:+ if self._cache_path is not None:+ return self._cache_path+ try:+ from jarvis.core.config import DATA_DIR # noqa: PLC0415++ self._cache_path = Path(DATA_DIR) / IDENTITY_CARD_FILENAME+ except Exception: # noqa: BLE001 — no data dir means memory-only cache+ return None+ return self._cache_path++ def _load_from_disk(self) -> IdentityCard | None:+ path = self._path()+ if path is None:+ return None+ raw = _read_text(path)+ if not raw.strip():+ return None+ try:+ parsed = json.loads(raw)+ except (ValueError, TypeError):+ return None+ if not isinstance(parsed, Mapping):+ return None+ return IdentityCard.from_json(parsed)++ def _store_to_disk(self, card: IdentityCard) -> None:+ path = self._path()+ if path is None:+ return+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(+ json.dumps(card.to_json(), ensure_ascii=False, indent=2),+ encoding="utf-8",+ )+ except OSError: # read-only install / headless container — memory is enough+ log.debug("identity card: cache not writable at %s", path, exc_info=True)++ # -- public --------------------------------------------------------++ def card(self, *, force: bool = False) -> IdentityCard:+ """The current card, rebuilding only when the source hash moved."""+ now = float(self._clock())+ with self._lock:+ if (+ not force+ and self._card is not None+ and self._checked_at is not None+ and (now - self._checked_at) < self._recheck_interval_s+ ):+ return self._card+ try:+ profile, core, labels = collect_sources(self._config)+ source_hash = _hash_sources(profile, core)+ except Exception: # noqa: BLE001 — a prompt build must never break here+ log.debug("identity card: source read failed", exc_info=True)+ self._checked_at = now+ return self._card or IdentityCard(text="", source_hash="")++ if self._card is not None and self._card.source_hash == source_hash:+ self._checked_at = now+ return self._card++ if not self._disk_read:+ self._disk_read = True+ cached = self._load_from_disk()+ if cached is not None and cached.source_hash == source_hash:+ self._card = cached+ self._checked_at = now+ return cached++ text = distill_identity_card(+ profile_markdown=profile,+ core_memory=core,+ max_chars=self._max_chars,+ )+ card = IdentityCard(text=text, source_hash=source_hash, sources=labels)+ self._store_to_disk(card)+ self._card = card+ self._checked_at = now+ log.info(+ "identity card rebuilt chars=%d sources=%s",+ len(text),+ ",".join(labels) or "none",+ )+ return card++ def text(self, *, force: bool = False) -> str:+ return self.card(force=force).text++ def block(self, *, force: bool = False) -> str:+ return render_identity_block(self.card(force=force).text)+++# ---------------------------------------------------------------------------+# Process-wide accessor (what the prompt builder calls)+# ---------------------------------------------------------------------------++_default_cache: IdentityCardCache | None = None+_default_lock = threading.Lock()+++def _cache_for(config: Any) -> IdentityCardCache:+ global _default_cache+ with _default_lock:+ if _default_cache is None:+ max_chars = MAX_IDENTITY_CARD_CHARS+ raw_max = getattr(+ getattr(config, "wiki_context", None), "identity_card_max_chars", None+ )+ try:+ if raw_max is not None:+ max_chars = max(0, min(int(raw_max), MAX_IDENTITY_CARD_CHARS))+ except (TypeError, ValueError):+ max_chars = MAX_IDENTITY_CARD_CHARS+ _default_cache = IdentityCardCache(config=config, max_chars=max_chars)+ return _default_cache+++def reset_identity_card_cache() -> None:+ """Drop the process-wide cache (tests, and an in-app source switch)."""+ global _default_cache+ with _default_lock:+ _default_cache = None+++def identity_card_text(config: Any = None) -> str:+ """The current card text, or "" when there is nothing to say."""+ try:+ return _cache_for(config).text()+ except Exception: # noqa: BLE001 — ambient knowledge never breaks a turn+ log.debug("identity card: unavailable", exc_info=True)+ return ""+++def identity_card_block(config: Any = None) -> str:+ """The framed block for the cached system-prompt prefix, or "".++ Disabled by ``[wiki_context].identity_card = false``. Safe to call on every+ prompt build: after the first call it is a lock, a clock read and a string+ return.+ """+ try:+ wiki_cfg = getattr(config, "wiki_context", None)+ if wiki_cfg is not None and not bool(getattr(wiki_cfg, "identity_card", True)):+ return ""+ return _cache_for(config).block()+ except Exception: # noqa: BLE001 — ambient knowledge never breaks a turn+ log.debug("identity card: unavailable", exc_info=True)+ return ""diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 8ef4ac849a..e1a9cd9651 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -3544,6 +3544,23 @@ class BrainManager:except Exception: # noqa: BLE001pass+ # Ambient personal knowledge: the standing identity card. A+ # precomputed, deterministic distillation of the user's own profile+ # page + core memory — no model call, hard-capped, and rebuilt only+ # when its sources change, so it stays in the CACHED prefix in both+ # prompt layouts (unlike the per-turn wiki snippets below, which move+ # to the turn context in cache-optimized mode). Absent profile =+ # empty string = no block. Defensive: ambient knowledge must never be+ # able to break a prompt build.+ try:+ from jarvis.brain.identity_card import identity_card_block++ _identity_block = identity_card_block(getattr(self, "_config", None))+ if _identity_block:+ parts.append(_identity_block)+ except Exception: # noqa: BLE001+ pass+if self._core_memory is not None:# Mandatory: re-read BEFORE rendering. Otherwise the LLM only sees# facts that existed at init time — UI additions and remember-tooldiff --git a/jarvis/brain/wiki_context.py b/jarvis/brain/wiki_context.pyindex b24c410b85..5e2adcac35 100644--- a/jarvis/brain/wiki_context.py+++ b/jarvis/brain/wiki_context.py@@ -13,9 +13,11 @@ Relevance contract (``jarvis.brain.wiki_relevance``):back is what welds unrelated personal facts onto general-knowledge answers.Three gates, in order:- 1. BEFORE searching, ``should_consult_memory`` skips turns that are not- questions about the user's own life. A general-knowledge question never- touches the vault at all — no latency, no context, no non-sequitur.+ 1. BEFORE searching, ``should_consult_memory`` skips turns that neither ask+ about the user's own life nor ask for a course of action for them+ (planning / recommendation / decision turns, where the right answer+ depends on who is asking). A general-knowledge question never touches+ the vault at all — no latency, no context, no non-sequitur.2. AFTER searching, ``relevant_hits`` drops hits that merely share a commonword with the question.3. AT injection, ``frame_context_block`` states that the notes may bediff --git a/jarvis/brain/wiki_relevance.py b/jarvis/brain/wiki_relevance.pyindex 783b670390..dd806767b0 100644--- a/jarvis/brain/wiki_relevance.py+++ b/jarvis/brain/wiki_relevance.py@@ -20,7 +20,12 @@ Three independent layers, each useful on its own:1. :func:`should_consult_memory` — BEFORE retrieval. General-knowledge anddefinitional questions with no personal marker never search at all. Saves- the search latency and removes the failure mode at its root.+ the search latency and removes the failure mode at its root. Three turn+ classes DO earn a look: explicit recollection, a personal lookup, and —+ since the ambient-knowledge pass — planning/recommendation/decision turns,+ where the right answer depends on who is asking. Widening this gate is+ safe precisely because gates 2 and 3 are unchanged: more turns get to ask+ the memory, none of them get to inject an irrelevant answer.2. :func:`relevant_hits` — AFTER retrieval. Coverage of the question's contentterms plus a within-call relative floor. Deliberately NOT an absolute scorethreshold: ``SearchHit.score`` is documented as comparable only within a@@ -54,6 +59,7 @@ from jarvis.brain.wiki_relevance_vocab import (GENERAL_KNOWLEDGE_PHRASES,LOOKUP_MARKERS,PERSONAL_MARKERS,+ PLANNING_PHRASES,RECOLLECTION_PHRASES,)@@ -104,6 +110,13 @@ _PERSONAL_RE = _alternation(PERSONAL_MARKERS)# strong enough to consult even without an ownership marker._MEMORY_RE = _alternation(RECOLLECTION_PHRASES)+# Planning / recommendation / decision phrasing. The second turn class that+# earns a lookup without a possessive: advice for THIS person depends on what+# is known about them. Checked BEFORE the general-knowledge skip, because the+# two shapes overlap ("what is the fastest way home" is both a "what is" and a+# request for a plan) and the advice reading is the one that wants context.+_PLANNING_RE = _alternation(PLANNING_PHRASES)+# General-knowledge / definitional shape. On its own this is the world's# knowledge, not the user's — the tallest-tower case. Only an ownership# marker turns it into a memory question.@@ -136,6 +149,7 @@ _SKIP_TOO_SHORT = MemoryVerdict(False, "too_short")_SKIP_GENERAL_KNOWLEDGE = MemoryVerdict(False, "general_knowledge")_SKIP_NO_PERSONAL_ANCHOR = MemoryVerdict(False, "no_personal_anchor")_CONSULT_RECOLLECTION = MemoryVerdict(True, "recollection_phrase")+_CONSULT_PLANNING = MemoryVerdict(True, "planning_advice")_CONSULT_PERSONAL_LOOKUP = MemoryVerdict(True, "personal_lookup")@@ -147,12 +161,22 @@ def should_consult_memory(user_text: str) -> MemoryVerdict:1. Too short / no words -> skip (greetings, "ok", "danke").2. Explicit recollection phrasing -> consult, even without a possessive("do you remember where we were?").- 3. General-knowledge shape WITHOUT a personal marker -> skip. This is the+ 3. Planning / recommendation / decision phrasing -> consult, also without a+ possessive ("what should I do", "what is the fastest way to X", "any+ ideas for the weekend"). Advice is where knowing the person changes the+ answer, so this turn class earns a look. Checked BEFORE step 4 because+ the two shapes overlap and the advice reading is the useful one.+ 4. General-knowledge shape WITHOUT a personal marker -> skip. This is thetallest-tower case and the whole reason the gate exists.- 4. Personal marker AND a lookup shape -> consult.- 5. Anything else -> skip, and let the brain reach for ``wiki-recall`` if it+ 5. Personal marker AND a lookup shape -> consult.+ 6. Anything else -> skip, and let the brain reach for ``wiki-recall`` if itdecides it needs the memory (see the policy note in the module docstring).+ Opening the gate is not injecting: every consult verdict still has to pass+ :func:`relevant_hits` and arrives wrapped by :func:`frame_context_block`,+ so a planning turn with nothing relevant in the vault produces exactly the+ same silence it produced before this class existed.+Never raises: an unusable input degrades to a skip verdict."""if not user_text or not user_text.strip():@@ -162,6 +186,8 @@ def should_consult_memory(user_text: str) -> MemoryVerdict:return _SKIP_TOO_SHORTif _MEMORY_RE.search(folded):return _CONSULT_RECOLLECTION+ if _PLANNING_RE.search(folded):+ return _CONSULT_PLANNINGpersonal = bool(_PERSONAL_RE.search(folded))if _WORLD_KNOWLEDGE_RE.search(folded) and not personal:return _SKIP_GENERAL_KNOWLEDGEdiff --git a/jarvis/brain/wiki_relevance_vocab.py b/jarvis/brain/wiki_relevance_vocab.pyindex 1ed35a74eb..807c1947d0 100644--- a/jarvis/brain/wiki_relevance_vocab.py+++ b/jarvis/brain/wiki_relevance_vocab.py@@ -19,6 +19,7 @@ from __future__ import annotations__all__ = ["PERSONAL_MARKERS","RECOLLECTION_PHRASES",+ "PLANNING_PHRASES","GENERAL_KNOWLEDGE_PHRASES","LOOKUP_MARKERS",]@@ -52,6 +53,51 @@ RECOLLECTION_PHRASES: tuple[str, ...] = ("te acuerdas", "recuerdas", "cuando fui", "cuando estuve",)+#: Planning / recommendation / decision shape — the second turn class that is+#: worth a memory lookup even without a possessive. "What should I do", "what+#: is the fastest way to X", "any ideas for the weekend": the user is asking+#: for a course of action, and a course of action for THIS person depends on+#: what is known about them. These fire on their own (like the recollection+#: phrases), so they are deliberately COMPOUND rather than bare superlatives:+#: "fastest way" is an advice request, "fastest animal" is a quiz question.+#: Firing here only opens the retrieval — the post-search relevance filter and+#: the framed injection still decide whether anything reaches the model, so a+#: planning turn with no matching note produces silence exactly as before.+PLANNING_PHRASES: tuple[str, ...] = (+ # de+ "was soll ich", "was sollen wir", "soll ich", "sollte ich", "sollen wir",+ "was mache ich", "was machen wir", "was tue ich",+ "wie gehe ich vor", "wie gehe ich am besten", "wie kann ich am besten",+ "am besten", "beste weg", "besten weg", "bester weg",+ "schnellste weg", "schnellsten weg", "einfachste weg", "einfachsten weg",+ "beste option", "beste moeglichkeit", "welche option",+ "hast du ideen", "irgendwelche ideen", "ideen fuer", "idee fuer",+ "vorschlaege", "vorschlag fuer", "tipps fuer", "tipp fuer",+ "empfiehl", "empfiehlst du", "empfehlen", "empfehlung",+ "was wuerdest du", "was raetst du", "rate mir",+ "lohnt sich", "lohnt es sich",+ "hilf mir", "entscheiden", "entscheidung", "plan fuer", "planen wir",+ # en+ "what should i", "what should we", "should i", "should we",+ "what do i do", "what do we do", "how should i", "how should we",+ "what would you do", "what would you recommend", "how do i best",+ "best way", "fastest way", "quickest way", "easiest way", "smartest way",+ "best option", "best approach", "which option",+ "any ideas", "some ideas", "ideas for", "any suggestions",+ "suggestions for", "any tips", "tips for", "any advice", "advice on",+ "recommend", "recommendation", "recommendations",+ "help me decide", "help me plan", "plan my", "plan for",+ "worth it", "is it worth",+ # es+ "que deberia", "deberia", "deberiamos", "que hago", "que hacemos",+ "mejor manera", "mejor forma", "mejor opcion", "mejor camino",+ "manera mas rapida", "forma mas rapida",+ "alguna idea", "algunas ideas", "ideas para", "alguna sugerencia",+ "sugerencias para", "consejos para", "algun consejo",+ "recomienda", "recomiendas", "recomendacion", "recomendaciones",+ "que harias", "vale la pena", "ayudame a decidir",+)+#: Definitional / general-knowledge shape. On its own this asks about the#: world, not about the user — the tallest-tower case. Only an ownership#: marker turns such a question into a memory question.diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex 95929d4717..7c7174fea8 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -2268,6 +2268,14 @@ class WikiContextConfig(BaseModel):# within one call, so an absolute cutoff would be noise.min_relative_score: float = 0.35+ # Ambient personal knowledge — the standing identity card+ # (jarvis/brain/identity_card.py). Unlike the per-turn snippets above this+ # is a precomputed, LLM-free distillation of the user's own profile that+ # rides in the CACHED system-prompt prefix. ``false`` removes the block+ # entirely; the cap is an upper bound only (never raises the hard 600).+ identity_card: bool = True+ identity_card_max_chars: int = 600+class VoiceConfig(BaseModel):"""Voice-flow knobs that are not STT/TTS/Trigger-specific.diff --git a/tests/unit/brain/test_ambient_knowledge_cost_guard.py b/tests/unit/brain/test_ambient_knowledge_cost_guard.pynew file mode 100644index 0000000000..8de99184af--- /dev/null+++ b/tests/unit/brain/test_ambient_knowledge_cost_guard.py@@ -0,0 +1,252 @@+"""Cost guards for ambient personal knowledge.++Ambient knowledge is only affordable because it is free per turn. Three+properties are load-bearing and each is guarded here:++1. **Zero model calls.** Neither the identity card nor the per-turn wiki+ context may reach a provider — not directly, not through a client library+ (AP-9/AP-11). Guarded twice: a network tripwire around the real code paths,+ and a source scan that keeps a client library out of the modules.+2. **Hard character budgets.** The identity card stays within+ ``MAX_IDENTITY_CARD_CHARS``; the per-turn wiki block stays within the+ injector's ``max_chars``.+3. **The widened gate still costs nothing on smalltalk.** Opening the gate for+ planning turns must not open it for "hello".+"""++from __future__ import annotations++import json+import re+import socket+import urllib.request+from dataclasses import dataclass+from pathlib import Path+from typing import Any++import httpx+import pytest++from jarvis.brain import identity_card as ic+from jarvis.brain.wiki_context import WikiContextInjector+from jarvis.brain.wiki_relevance import should_consult_memory++BASE_PROMPT = "You are the assistant."+++class ModelCallAttempted(AssertionError):+ """Raised by the tripwire — an ambient path tried to leave the process."""+++def no_network(monkeypatch: pytest.MonkeyPatch) -> None:+ """Fail loudly on any outbound call, whatever client library makes it."""++ def tripwire(*args: Any, **kwargs: Any) -> Any:+ raise ModelCallAttempted("the ambient path must never call out")++ real_connect = socket.socket.connect++ def guarded_connect(sock: socket.socket, address: Any) -> Any:+ # The Windows proactor event loop builds itself on a loopback+ # self-pipe, so loopback stays open; every provider call — including a+ # local endpoint — goes through the HTTP clients tripwired above.+ host = address[0] if isinstance(address, tuple) else address+ if str(host) in {"127.0.0.1", "::1", "localhost"}:+ return real_connect(sock, address)+ raise ModelCallAttempted("the ambient path must never call out")++ monkeypatch.setattr(httpx.Client, "send", tripwire, raising=False)+ monkeypatch.setattr(httpx.AsyncClient, "send", tripwire, raising=False)+ monkeypatch.setattr(urllib.request, "urlopen", tripwire, raising=False)+ monkeypatch.setattr(socket.socket, "connect", guarded_connect, raising=False)+ monkeypatch.setattr(socket, "create_connection", tripwire, raising=False)++[email protected](autouse=True)+def _isolated_process_cache() -> Any:+ ic.reset_identity_card_cache()+ yield+ ic.reset_identity_card_cache()+++# ---------------------------------------------------------------------------+# Fakes (tests/fakes style — recorded behaviour, not mock scaffolding)+# ---------------------------------------------------------------------------+++@dataclass(frozen=True)+class FakeHit:+ title: str+ snippet: str+ score: float+++class SpyVaultSearch:+ def __init__(self, hits: list[FakeHit] | None = None) -> None:+ self._hits = hits or []+ self.queries: list[str] = []++ def search(self, query: str, *, k: int = 5) -> list[FakeHit]:+ self.queries.append(query)+ return list(self._hits[:k])+++class FakeConfig:+ class _WikiContext:+ def __init__(self, core_memory_path: Path) -> None:+ self.core_memory_path = str(core_memory_path)+ self.identity_card = True++ class _WikiIntegration:+ def __init__(self, vault_root: Path) -> None:+ self.vault_root = vault_root++ def __init__(self, *, vault_root: Path, core_memory_path: Path) -> None:+ self.wiki_integration = self._WikiIntegration(vault_root)+ self.wiki_context = self._WikiContext(core_memory_path)+++def _seed(tmp_path: Path, *, facts: int = 4) -> FakeConfig:+ vault = tmp_path / "vault"+ page = vault / "entities" / "user.md"+ page.parent.mkdir(parents=True, exist_ok=True)+ body = ["# Test Person", "", "## Summary", ""]+ body += [f"- fact {n} about this person and how they like to work" for n in range(facts)]+ body += ["", "## Preferences", "", "- Short answers"]+ page.write_text("\n".join(body), encoding="utf-8")+ core = tmp_path / "core_memory.json"+ core.write_text(+ json.dumps({"user_facts": {"general": [f"core fact {n}" for n in range(facts)]}}),+ encoding="utf-8",+ )+ return FakeConfig(vault_root=vault, core_memory_path=core)+++# ---------------------------------------------------------------------------+# 1. Zero model calls+# ---------------------------------------------------------------------------+++def test_identity_card_build_makes_no_model_call(tmp_path: Path, no_network: None) -> None:+ cache = ic.IdentityCardCache(+ config=_seed(tmp_path),+ cache_path=tmp_path / "identity_card.json",+ recheck_interval_s=0.0,+ )+ assert "Test Person" in cache.block()+ # A second read must not even reconsider calling out.+ assert cache.block() == cache.block()+++async def test_the_per_turn_wiki_path_makes_no_model_call(no_network: None) -> None:+ search = SpyVaultSearch(+ [FakeHit(title="Weekend", snippet="hiking near the coast", score=0.9)]+ )+ injector = WikiContextInjector(search=search, latency_budget_ms=500)++ result = await injector.maybe_inject(+ user_text="Any ideas for the weekend hiking trip?",+ system_prompt=BASE_PROMPT,+ )++ assert search.queries, "the widened gate must let a planning turn retrieve"+ assert result != BASE_PROMPT+++def test_no_client_library_is_reachable_from_the_ambient_modules() -> None:+ """Structural guard: a provider SDK must not even be importable from here.++ Cheaper and more durable than any runtime assertion — it fails at review+ time, the moment someone reaches for a summarizer.+ """+ forbidden = re.compile(+ r"\b(?:anthropic|openai|google\.generativeai|genai|litellm|"+ r"httpx|requests|aiohttp|urllib\.request)\b"+ )+ import jarvis.brain.identity_card+ import jarvis.brain.wiki_relevance+ import jarvis.brain.wiki_relevance_vocab++ for module in (+ jarvis.brain.identity_card,+ jarvis.brain.wiki_relevance,+ jarvis.brain.wiki_relevance_vocab,+ ):+ source = Path(module.__file__ or "").read_text(encoding="utf-8")+ assert not forbidden.search(source), f"{module.__name__} reaches a client library"+++# ---------------------------------------------------------------------------+# 2. Hard character budgets+# ---------------------------------------------------------------------------+++def test_identity_card_respects_its_cap_on_a_huge_profile(tmp_path: Path) -> None:+ cache = ic.IdentityCardCache(+ config=_seed(tmp_path, facts=500),+ cache_path=tmp_path / "identity_card.json",+ recheck_interval_s=0.0,+ )+ card = cache.card()+ assert 0 < len(card.text) <= ic.MAX_IDENTITY_CARD_CHARS == 600+++def test_the_configured_cap_can_only_lower_the_budget(tmp_path: Path) -> None:+ config = _seed(tmp_path, facts=500)+ config.wiki_context.identity_card_max_chars = 10_000+ ic.reset_identity_card_cache()+ assert len(ic.identity_card_text(config)) <= ic.MAX_IDENTITY_CARD_CHARS+++async def test_the_per_turn_wiki_block_keeps_its_char_cap() -> None:+ """The retrieved half of ambient knowledge stays inside ``max_chars``."""+ from jarvis.brain.wiki_relevance import frame_context_block++ long_snippet = "hiking near the coast " * 200+ search = SpyVaultSearch(+ [+ FakeHit(title="Weekend one", snippet=long_snippet, score=0.9),+ FakeHit(title="Weekend two", snippet=long_snippet, score=0.8),+ ]+ )+ injector = WikiContextInjector(search=search, max_chars=200, latency_budget_ms=500)++ result = await injector.maybe_inject(+ user_text="Any ideas for the weekend hiking trip?",+ system_prompt=BASE_PROMPT,+ )++ header = frame_context_block(["x"]).split("\n\nx")[0]+ entries = result.split(header, 1)[1].strip()+ assert entries, "the block must still carry content"+ assert len(entries) <= 200+++# ---------------------------------------------------------------------------+# 3. The widened gate still costs nothing where it always cost nothing+# ---------------------------------------------------------------------------+++ "utterance",+ [+ "Hallo, wie geht es dir?", # i18n-allow: German smalltalk under test+ "thanks a lot for that",+ "Guten Morgen zusammen", # i18n-allow: German smalltalk under test+ "How tall is the Eiffel Tower?",+ "What is the fastest animal on earth?",+ ],+)+async def test_smalltalk_and_world_knowledge_never_retrieve(utterance: str) -> None:+ search = SpyVaultSearch([FakeHit(title="Weekend", snippet="hiking", score=0.9)])+ injector = WikiContextInjector(search=search, latency_budget_ms=500)++ result = await injector.maybe_inject(user_text=utterance, system_prompt=BASE_PROMPT)++ assert should_consult_memory(utterance).consult is False+ assert search.queries == [], "no retrieval, no latency, no tokens"+ assert result == BASE_PROMPTdiff --git a/tests/unit/brain/test_identity_card.py b/tests/unit/brain/test_identity_card.pynew file mode 100644index 0000000000..a7a7dce2b6--- /dev/null+++ b/tests/unit/brain/test_identity_card.py@@ -0,0 +1,414 @@+"""Guards for the ambient identity card (jarvis/brain/identity_card.py).++What the card promises: a deterministic, model-free, hard-capped distillation+of who the user is, rebuilt only when its sources change, absent and silent+when no profile exists.+"""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any++import pytest++from jarvis.brain import identity_card as ic++PROFILE = """---+type: entity+entity_kind: person+slug: nova-user+aliases: [Nova User, the user]+---++# Nova User++## Summary++Builds a voice assistant on her own; ships in the evenings.++## Identity++- Lives in **Lisbon**, originally from [[Places/Porto|Porto]]+- Speaks Portuguese and English++## Preferences++- Short answers, no filler+- Metric units++## Work style++- Deep work before noon++## Values++- Owns her own data++## Decisions++- 2026-01-04: chose SQLite over Postgres++## Sources++- session-2026-01-04+"""+++CORE_MEMORY = {+ "persona": {"name": "Assistant", "role": "orchestrator"},+ "user_facts": {"general": ["Allergic to peanuts"], "work": ["Runs a solo studio"]},+ "preferences": {"language_default": "en"},+ "current_projects": {"Ambient": "personal knowledge in the prompt"},+}+++class _FakeConfig:+ """Minimal duck-typed config (fakes, not mocks)."""++ class _WikiContext:+ def __init__(self, core_memory_path: Path | None) -> None:+ self.core_memory_path = str(core_memory_path) if core_memory_path else None+ self.identity_card = True++ class _WikiIntegration:+ def __init__(self, vault_root: Path) -> None:+ self.vault_root = vault_root++ def __init__(self, *, vault_root: Path, core_memory_path: Path | None = None) -> None:+ self.wiki_integration = self._WikiIntegration(vault_root)+ self.wiki_context = self._WikiContext(core_memory_path)+++def _write_vault_profile(root: Path, slug: str, body: str) -> Path:+ page = root / "entities" / f"{slug}.md"+ page.parent.mkdir(parents=True, exist_ok=True)+ page.write_text(body, encoding="utf-8")+ return page++[email protected](autouse=True)+def _isolated_process_cache() -> Any:+ ic.reset_identity_card_cache()+ yield+ ic.reset_identity_card_cache()+++# ---------------------------------------------------------------------------+# Distillation — deterministic, capped, flattened+# ---------------------------------------------------------------------------+++def test_profile_sections_become_a_card() -> None:+ card = ic.distill_identity_card(profile_markdown=PROFILE)++ assert "- Name: Nova User" in card+ assert "Summary:" in card+ assert "Lisbon" in card+ assert "Short answers" in card+ # Episodic bookkeeping is not identity.+ assert "SQLite" not in card+ assert "session-2026-01-04" not in card+++def test_markdown_and_wikilinks_are_flattened() -> None:+ card = ic.distill_identity_card(profile_markdown=PROFILE)++ assert "[[" not in card and "]]" not in card+ assert "**" not in card+ assert "Porto" in card, "a wikilink must keep its display text"+++def test_card_never_exceeds_the_cap() -> None:+ fat = "# Someone\n\n## Summary\n\n" + "\n".join(+ f"- fact number {n} that runs on and on and on" for n in range(200)+ )+ card = ic.distill_identity_card(profile_markdown=fat)++ assert 0 < len(card) <= ic.MAX_IDENTITY_CARD_CHARS+ assert not card.endswith(";"), "a truncated group must not end mid-list"+++def test_a_smaller_explicit_budget_is_honoured() -> None:+ card = ic.distill_identity_card(profile_markdown=PROFILE, max_chars=80)+ assert len(card) <= 80+++def test_distillation_is_deterministic() -> None:+ first = ic.distill_identity_card(profile_markdown=PROFILE, core_memory=CORE_MEMORY)+ second = ic.distill_identity_card(profile_markdown=PROFILE, core_memory=CORE_MEMORY)+ assert first == second+++def test_no_sources_yield_no_card_and_no_block() -> None:+ assert ic.distill_identity_card() == ""+ assert ic.distill_identity_card(profile_markdown=" \n\n") == ""+ assert ic.render_identity_block("") == ""+++def test_core_memory_alone_fills_the_card() -> None:+ """The fresh-install path: no wiki, still an honest card."""+ card = ic.distill_identity_card(core_memory=CORE_MEMORY)++ assert "Allergic to peanuts" in card+ assert "Runs a solo studio" in card+ assert "Ambient" in card+ # The persona describes the ASSISTANT, never the user.+ assert "orchestrator" not in card+++def test_profile_spends_the_budget_before_core_memory() -> None:+ card = ic.distill_identity_card(+ profile_markdown=PROFILE, core_memory=CORE_MEMORY, max_chars=120+ )+ assert "Nova User" in card+ assert "Allergic to peanuts" not in card+++def test_restated_facts_are_not_repeated() -> None:+ profile = "# X\n\n## Identity\n\n- Runs a solo studio in Lisbon\n"+ card = ic.distill_identity_card(profile_markdown=profile, core_memory=CORE_MEMORY)+ assert card.count("Runs a solo studio") == 1+++def test_section_priority_is_a_subset_of_the_wiki_profile_schema() -> None:+ """Anti-drift: a renamed profile section must fail here, not silently+ disappear from the card."""+ from jarvis.memory.wiki.profile import PROFILE_SECTIONS++ assert set(ic.PROFILE_SECTION_PRIORITY) <= set(PROFILE_SECTIONS)+++def test_malformed_sources_never_raise() -> None:+ for junk in ["---\nunterminated frontmatter", "## \n\n#", "\x00\x01", "#" * 500]:+ assert isinstance(ic.distill_identity_card(profile_markdown=junk), str)+ assert ic.distill_identity_card(core_memory={"user_facts": "not a dict"}) != ""+ assert isinstance(ic.distill_identity_card(core_memory={"preferences": 7}), str)+++# ---------------------------------------------------------------------------+# Framing — the standing silence mandate+# ---------------------------------------------------------------------------+++def test_block_carries_the_silence_mandate() -> None:+ block = ic.render_identity_block("- Name: Nova User")+ lowered = block.lower()++ assert "- Name: Nova User" in block+ assert "silence beats a personal fact nobody asked for" in lowered+ assert "never volunteer a personal detail the question did not ask for" in lowered+ assert "never read this block out" in lowered+++# ---------------------------------------------------------------------------+# Cache — rebuild only on a source change, survive a restart+# ---------------------------------------------------------------------------+++def _cache(tmp_path: Path, *, seed: bool = True, **kwargs: Any) -> ic.IdentityCardCache:+ vault = tmp_path / "vault"+ core = tmp_path / "core_memory.json"+ if seed:+ core.write_text(json.dumps(CORE_MEMORY), encoding="utf-8")+ _write_vault_profile(vault, "user", PROFILE)+ kwargs.setdefault("cache_path", tmp_path / "identity_card.json")+ kwargs.setdefault("recheck_interval_s", 0.0)+ return ic.IdentityCardCache(+ config=_FakeConfig(vault_root=vault, core_memory_path=core), **kwargs+ )+++def test_cache_reads_the_vault_profile_and_core_memory(tmp_path: Path) -> None:+ card = _cache(tmp_path).card()++ assert "Nova User" in card.text+ assert card.sources == ("vault:entities/user.md", "core_memory")+ assert len(card.text) <= ic.MAX_IDENTITY_CARD_CHARS+++def test_cache_rebuilds_only_when_the_source_hash_changes(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ builds: list[int] = []+ real = ic.distill_identity_card++ def counting(**kwargs: Any) -> str:+ builds.append(1)+ return real(**kwargs)++ monkeypatch.setattr(ic, "distill_identity_card", counting)++ cache = _cache(tmp_path)+ first = cache.text()+ assert len(builds) == 1++ # Re-checking unchanged sources must not rebuild, and must not move a byte+ # (the cached system-prompt prefix depends on that).+ for _ in range(3):+ assert cache.text() == first+ assert len(builds) == 1++ (tmp_path / "vault" / "entities" / "user.md").write_text(+ PROFILE.replace("Lisbon", "Madrid"), encoding="utf-8"+ )+ assert "Madrid" in cache.text()+ assert len(builds) == 2+++def test_a_held_card_is_served_without_touching_the_sources(tmp_path: Path) -> None:+ cache = _cache(tmp_path, recheck_interval_s=3600.0, clock=lambda: 0.0)+ first = cache.text()++ (tmp_path / "vault" / "entities" / "user.md").unlink()+ (tmp_path / "core_memory.json").unlink()++ assert cache.text() == first, "the recheck interval keeps the turn path IO-free"+++def test_the_disk_cache_survives_a_restart(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ first = _cache(tmp_path).text()+ assert first++ def explode(**_: Any) -> str:+ raise AssertionError("a restart must not have to rebuild an unchanged card")++ monkeypatch.setattr(ic, "distill_identity_card", explode)+ assert _cache(tmp_path, seed=False).text() == first+++def test_a_changed_source_beats_a_stale_disk_cache(tmp_path: Path) -> None:+ _cache(tmp_path).text()+ (tmp_path / "vault" / "entities" / "user.md").write_text(+ PROFILE.replace("Nova User", "Other Person"), encoding="utf-8"+ )+ assert "Other Person" in _cache(tmp_path, seed=False).text()+++def test_a_corrupt_disk_cache_is_ignored(tmp_path: Path) -> None:+ (tmp_path / "identity_card.json").write_text("{not json", encoding="utf-8")+ assert "Nova User" in _cache(tmp_path).text()+++def test_no_profile_and_no_core_memory_stay_silent(tmp_path: Path) -> None:+ cache = ic.IdentityCardCache(+ config=_FakeConfig(+ vault_root=tmp_path / "empty-vault",+ core_memory_path=tmp_path / "missing.json",+ ),+ cache_path=tmp_path / "identity_card.json",+ recheck_interval_s=0.0,+ )+ assert cache.text() == ""+ assert cache.block() == ""+++def test_an_unwritable_cache_path_degrades_silently(tmp_path: Path) -> None:+ """Read-only install / headless container: memory-only, never a crash."""+ blocked = tmp_path / "blocked"+ blocked.write_text("not a directory", encoding="utf-8")+ cache = _cache(tmp_path, cache_path=blocked / "identity_card.json")+ assert "Nova User" in cache.text()+++# ---------------------------------------------------------------------------+# Source resolution — UltraWiki seam is capability-probed, never assumed+# ---------------------------------------------------------------------------+++class _FakeUltraService:+ def __init__(self, markdown: str | None) -> None:+ self._markdown = markdown+ self.calls = 0++ def user_profile_markdown(self) -> str:+ self.calls += 1+ if self._markdown is None:+ raise RuntimeError("seam is broken")+ return self._markdown+++class _SeamlessUltraService:+ """An UltraWiki service that has no profile seam yet — today's reality."""+++def _patch_ultra(monkeypatch: pytest.MonkeyPatch, service: Any) -> None:+ import jarvis.ultrawiki.service as uw++ monkeypatch.setattr(uw, "active_search_service", lambda: service)+++def test_ultrawiki_profile_wins_when_the_seam_exists(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ service = _FakeUltraService("# Ultra Person\n\n## Identity\n\n- From the store\n")+ _patch_ultra(monkeypatch, service)++ card = _cache(tmp_path).card()++ assert "Ultra Person" in card.text+ assert "Nova User" not in card.text+ assert "ultrawiki:profile" in card.sources+ assert service.calls == 1+++ "service",+ [None, _SeamlessUltraService(), _FakeUltraService(None), _FakeUltraService("")],+)+def test_absent_or_broken_ultrawiki_seam_falls_back_to_the_vault(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, service: Any+) -> None:+ _patch_ultra(monkeypatch, service)+ assert "Nova User" in _cache(tmp_path).text()+++def test_an_async_seam_is_refused_rather_than_awaited(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ class _AsyncSeam:+ async def user_profile_markdown(self) -> str: # pragma: no cover - never awaited+ return "# Nope"++ _patch_ultra(monkeypatch, _AsyncSeam())+ assert "Nova User" in _cache(tmp_path).text()+++def test_an_unimportable_ultrawiki_is_simply_absent(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ import builtins++ real_import = builtins.__import__++ def blocked(name: str, *args: Any, **kwargs: Any) -> Any:+ if name.startswith("jarvis.ultrawiki"):+ raise ImportError(name)+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", blocked)+ assert "Nova User" in _cache(tmp_path).text()+++# ---------------------------------------------------------------------------+# Process-wide accessor + the config off switch+# ---------------------------------------------------------------------------+++def test_block_accessor_is_off_when_configured_off(tmp_path: Path) -> None:+ config = _FakeConfig(vault_root=tmp_path / "vault")+ config.wiki_context.identity_card = False+ assert ic.identity_card_block(config) == ""+++def test_accessors_never_raise_on_a_hostile_config() -> None:+ class Hostile:+ def __getattr__(self, name: str) -> Any:+ raise RuntimeError(name)++ assert ic.identity_card_block(Hostile()) == ""+ ic.reset_identity_card_cache()+ assert isinstance(ic.identity_card_text(Hostile()), str)diff --git a/tests/unit/brain/test_identity_card_in_manager.py b/tests/unit/brain/test_identity_card_in_manager.pynew file mode 100644index 0000000000..9e11332d35--- /dev/null+++ b/tests/unit/brain/test_identity_card_in_manager.py@@ -0,0 +1,100 @@+"""The identity card must actually reach the CACHED system-prompt prefix.++Companion to test_identity_card.py (which locks the distillation and the+cache). This proves the wiring: ``BrainManager._build_system_prompt`` emits the+ambient block in BOTH prompt layouts — unlike the per-turn wiki snippets, which+move to the turn context in cache-optimized mode — and emits nothing at all+when there is no profile to speak of.+"""+from __future__ import annotations++from pathlib import Path++import pytest++import jarvis.core.config as core_config+from jarvis.brain import identity_card as ic+from jarvis.brain.manager import BrainManager+from jarvis.core.config import load_config++PROFILE = """# Nova User++## Summary++Ships a voice assistant solo, mostly in the evenings.++## Preferences++- Short answers, no filler+"""++[email protected](autouse=True)+def _isolated(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ monkeypatch.setattr(core_config, "DATA_DIR", tmp_path)+ ic.reset_identity_card_cache()+ yield tmp_path+ ic.reset_identity_card_cache()+++def _manager(tmp_path: Path, *, cache_optimized: bool, profile: str | None) -> BrainManager:+ """A BrainManager with __init__ bypassed — only the attrs the prompt needs."""+ # An arbitrary slug, never the host's configured one — the wiring must not+ # depend on whose machine runs the suite.+ slug = "nova-user"+ vault = tmp_path / "vault"+ if profile is not None:+ page = vault / "entities" / f"{slug}.md"+ page.parent.mkdir(parents=True, exist_ok=True)+ page.write_text(profile, encoding="utf-8")++ m = BrainManager.__new__(BrainManager)+ m._soul = None+ m._user_profile = None+ m._people = None+ m._core_memory = None+ m._awareness_manager = None+ m._system_prompt_extra = ""+ m._wiki_context_suffix = ""+ m._reply_language = "auto"+ cfg = load_config()+ cfg.performance.cache_optimized_prompt = cache_optimized+ cfg.wiki_integration.vault_root = vault+ cfg.memory.wiki.session_rollup.user_entity_slug = slug+ m._config = cfg+ return m++[email protected]("cache_optimized", [False, True])+def test_the_card_rides_the_cached_prefix_in_both_layouts(+ tmp_path: Path, cache_optimized: bool+) -> None:+ manager = _manager(tmp_path, cache_optimized=cache_optimized, profile=PROFILE)++ prompt = manager._build_system_prompt()++ assert "Nova User" in prompt+ assert "Short answers" in prompt+ assert "silence beats a personal fact nobody asked for" in prompt.lower()+++def test_the_block_is_byte_stable_across_turns(tmp_path: Path) -> None:+ """A prefix that moved every turn would break the provider prompt cache."""+ manager = _manager(tmp_path, cache_optimized=True, profile=PROFILE)+ assert manager._build_system_prompt() == manager._build_system_prompt()+++def test_no_profile_means_no_block(tmp_path: Path) -> None:+ manager = _manager(tmp_path, cache_optimized=True, profile=None)++ prompt = manager._build_system_prompt()++ assert ic.IDENTITY_BLOCK_HEADER not in prompt+ assert "About the user" not in prompt+++def test_the_config_switch_removes_the_block(tmp_path: Path) -> None:+ manager = _manager(tmp_path, cache_optimized=True, profile=PROFILE)+ manager._config.wiki_context.identity_card = False++ assert ic.IDENTITY_BLOCK_HEADER not in manager._build_system_prompt()diff --git a/tests/unit/brain/test_wiki_relevance_planning_gate.py b/tests/unit/brain/test_wiki_relevance_planning_gate.pynew file mode 100644index 0000000000..6a3e11bc48--- /dev/null+++ b/tests/unit/brain/test_wiki_relevance_planning_gate.py@@ -0,0 +1,130 @@+"""Guards for the widened pre-turn consult gate (ambient personal knowledge).++The gate used to open for two turn classes only: explicit recollection and a+possessive lookup. A third class earns it — planning, recommendation and+decision turns ("what should I do", "what is the fastest way to X", "any ideas+for the weekend"), where the right answer depends on who is asking.++Both directions are guarded here, because a widened gate is only safe if it+stays shut where it was shut before: general-knowledge questions must still+never reach the memory, and smalltalk must still cost nothing.+"""++from __future__ import annotations++import pytest++from jarvis.brain.wiki_relevance import should_consult_memory++# ---------------------------------------------------------------------------+# Opens: planning / recommendation / decision turns+# ---------------------------------------------------------------------------+++ "utterance",+ [+ # de (CLAUDE.md §1, closed-list item 4 — speech input under test)+ "Was soll ich heute Abend machen?", # i18n-allow: German input under test+ "Wie komme ich am besten nach Berlin?", # i18n-allow: German input under test+ "Hast du Ideen fuer das Wochenende?", # i18n-allow: German input under test+ "Was ist der schnellste Weg zum Flughafen?", # i18n-allow: German input under test+ "Lohnt sich das ueberhaupt noch?", # i18n-allow: German input under test+ "Welche Option wuerdest du nehmen?", # i18n-allow: German input under test+ "Was empfiehlst du mir dazu?", # i18n-allow: German input under test+ "Hilf mir bei der Entscheidung zwischen A und B.", # i18n-allow: German input+ # en+ "What should I do this evening?",+ "What is the fastest way to the airport?",+ "Any ideas for the weekend?",+ "What's the best way to learn this?",+ "Can you recommend something for tonight?",+ "Help me decide between the two offers.",+ "Is it worth switching now?",+ "Any tips for the trip next week?",+ # es (same closed-list item 4)+ "¿Qué debería hacer este fin de semana?", # i18n-allow: Spanish input under test+ "¿Cuál es la mejor manera de llegar?", # i18n-allow: Spanish input under test+ "¿Alguna idea para la cena?", # i18n-allow: Spanish input under test+ "¿Qué me recomiendas para el viaje?", # i18n-allow: Spanish input under test+ "¿Vale la pena cambiar ahora?", # i18n-allow: Spanish input under test+ ],+)+def test_planning_turns_consult_memory(utterance: str) -> None:+ verdict = should_consult_memory(utterance)+ assert verdict.consult is True, utterance+ assert verdict.reason == "planning_advice", utterance+++def test_planning_beats_the_general_knowledge_skip() -> None:+ """"What is the fastest way home" is BOTH shapes — advice must win.++ The general-knowledge skip is matched by the leading "what is"; without an+ explicit ordering rule the advice reading would be lost.+ """+ assert should_consult_memory("What is the best way to get home?").consult is True+ assert should_consult_memory("What is the fastest way to Berlin?").consult is True+++# ---------------------------------------------------------------------------+# Stays shut: general knowledge, smalltalk, quiz superlatives+# ---------------------------------------------------------------------------+++ "utterance",+ [+ "How tall is the Eiffel Tower?",+ "Wie hoch ist der Eiffelturm?", # i18n-allow: German speech input under test+ "¿Qué es la torre más alta del mundo?", # i18n-allow: Spanish speech input under test+ "What is the tallest tower in the world?",+ "How does a diesel engine work?",+ "Who was Ada Lovelace?",+ "Explain reciprocal rank fusion.",+ "What is the capital of Peru?",+ # The reason the planning vocabulary is compound rather than a bare+ # superlative: a quiz about the world still reads as world knowledge.+ "What is the fastest animal on earth?",+ "Wie funktioniert ein Dieselmotor?", # i18n-allow: German speech input under test+ ],+)+def test_general_knowledge_still_never_consults_memory(utterance: str) -> None:+ verdict = should_consult_memory(utterance)+ assert verdict.consult is False, utterance+ assert verdict.reason == "general_knowledge", utterance+++ "utterance",+ [+ "Hallo, wie geht es dir?", # i18n-allow: German smalltalk under test+ "Guten Morgen zusammen", # i18n-allow: German smalltalk under test+ "danke dir vielmals", # i18n-allow: German smalltalk under test+ "Alles klar bei dir?", # i18n-allow: German smalltalk under test+ "Hey there, good morning",+ "thanks a lot for that",+ "ok",+ "",+ " ",+ ],+)+def test_smalltalk_never_consults_memory(utterance: str) -> None:+ assert should_consult_memory(utterance).consult is False, utterance+++def test_the_older_turn_classes_are_untouched() -> None:+ """The widening must not renumber the reasons the gate already reported."""+ assert should_consult_memory("Do you remember where we stayed?").reason == (+ "recollection_phrase"+ )+ assert should_consult_memory("What are my billing rules?").reason == (+ "personal_lookup"+ )+ assert should_consult_memory("Turn on the kitchen light").reason == (+ "no_personal_anchor"+ )+++def test_widened_gate_never_raises_on_odd_input() -> None:+ for weird in ["???", "\n\n", "🚗🚗🚗", "a b", "1 2 3 4 5", "-" * 200]:+ assert should_consult_memory(weird).consult in (True, False)