Skip to content

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.

feat(memory): save "remember this" to MEMORY.md during the conversation

rubenluetke10-beepdb21edea404f
diff --git a/docs/jarvis-learning.md b/docs/jarvis-learning.md
index 059879cc68..bec5c44c38 100644
--- a/docs/jarvis-learning.md
+++ b/docs/jarvis-learning.md
@@ -22,11 +22,22 @@ Jarvis itself, tuned for a voice assistant.
states a preference, corrects Jarvis, or names a plan, goal or deadline.
Requests and questions ("play some music", "what's the weather") are not
marked. A conversation with no marked turn never reaches a model.
-3. **Explicit requests (free, immediate).** "Remember that X" / "merk dir X"
- is saved at once in the user's own words with the date, without a model,
- so it cannot be lost to a provider failure. Only a bare "remember that",
- which points at something said before, is reviewed right away with the
- turn before it.
+3. **Explicit requests (immediate, always MEMORY.md).** The conversation
+ model saves "remember X" / "merk dir X" itself, while the conversation
+ runs, through the `remember` tool (`jarvis/plugins/tool/remember.py`):
+ one self-contained sentence, dated, into `society/jarvis/MEMORY.md` with
+ `origin: user` and importance 10. On GPT-Live the tool sits in the voice
+ tool set (`BrainSupervisorToolGateway._voice_tools`; the router stays a
+ pure dispatcher, ADR-0011) and the session instructions carry
+ `REMEMBER_DIRECTIVE` plus the learned snapshot, so a call both sees what
+ earlier conversations saved and saves a new request before it ends. As a
+ free fallback the loop finds the request in the user's own words, without
+ a model: at the start of a turn ("remember that X") or after what it
+ points at ("I want short reports. Remember that."), where the sentence
+ before it becomes the entry. A request the tool already saved is not
+ filed twice (the turn named the tool, or a tool save in the last six
+ hours covers it). Only a bare "remember that" with nothing before it in
+ the turn is reviewed right away with the turn before it.
4. **Review (one small call per conversation).** When a call ends
(`VoiceSessionEnded`), the conversation has been quiet for
`idle_review_seconds` (default 300), or after `review_every_turns`
@@ -131,7 +142,10 @@ update, so they stay small: `user_budget_chars` 1,500 and `memory_budget_chars`
1,000 by default (about 650 tokens together at most; the compact realtime
profile for small local models uses half). One entry is one short sentence,
at most 300 characters. Entries beyond the prompt budget stay on disk; the most
-important and most recent ones reach the prompt.
+important and most recent ones reach the prompt. Explicit entries (`origin:
+user`) do not count against `memory_budget_chars`: they render first, under
+"What the user asked you to remember", within their own 2,000-character
+allowance (`EXPLICIT_PROMPT_CHARS`, half in the compact profile).
Compaction (`compact.py`) keeps the files themselves small:
@@ -143,7 +157,9 @@ Compaction (`compact.py`) keeps the files themselves small:
sources and invents nothing: every number and link, every capitalised name
and at least 60 percent of its words come from the sources. An entry is
dropped as outdated only when it names a date that has passed; lasting
- facts such as birthdays are kept. The cooldown survives restarts
+ facts such as birthdays are kept. Explicit entries are never shown to the
+ merging model: they are the user's, and their date prefix would otherwise
+ read as a passed deadline. The cooldown survives restarts
(`.learning-state.json`).
3. **Hard ceiling.** A review may not grow a notebook past 125 percent of its
budget (a replace that does not grow it is fine). Only an explicit
diff --git a/jarvis/brain/tool_gateway.py b/jarvis/brain/tool_gateway.py
index f16ba1c8f7..a726ee3320 100644
--- a/jarvis/brain/tool_gateway.py
+++ b/jarvis/brain/tool_gateway.py
@@ -108,6 +108,7 @@ class BrainSupervisorToolGateway:
from jarvis.plugins.tool.appshot import AppshotTool
from jarvis.plugins.tool.live_screen import LiveScreenTool
from jarvis.plugins.tool.product_help import ProductHelpTool
+ from jarvis.plugins.tool.remember import RememberTool
tools = self._live_tools()
context = peek_computer_use_context()
@@ -127,6 +128,10 @@ class BrainSupervisorToolGateway:
# The live prompt carries only a short product brief; exact how-to
# answers come from the built-in guide on demand.
tools["product_help"] = ProductHelpTool()
+ # A spoken "remember this" in a live call is saved while the call
+ # runs, into the MEMORY.md every later conversation reads. Voice-only
+ # like the tools above: the router stays a pure dispatcher (ADR-0011).
+ tools["remember"] = RememberTool()
if self._workspace_tool is not None:
# Live delegates coding to one addressed service. The old prompt
# tools silently choose an ambient pane and cannot safely coexist.
diff --git a/jarvis/live/session.py b/jarvis/live/session.py
index 5f036569b9..2051e222bd 100644
--- a/jarvis/live/session.py
+++ b/jarvis/live/session.py
@@ -25,20 +25,38 @@ log = logging.getLogger(__name__)
def _identity(config: Any) -> str:
- """Who the assistant is (wake-word name + SOUL.md); ``""`` on a fault.
+ """Who the assistant is (wake-word name + SOUL.md) and what it remembers.
- ``""`` makes the session config fall back to the nameless directive, so
- an identity fault never blocks a call.
+ ``""`` on an identity fault makes the session config fall back to the
+ nameless directive, so an identity fault never blocks a call.
"""
try:
from jarvis.brain.identity import identity_block
# maintain: the live tool set holds update_soul, so the call itself
# keeps SOUL.md current (no separate review call for the character).
- return identity_block(config, maintain=True)
+ identity = identity_block(config, maintain=True)
except Exception: # noqa: BLE001 — never block a call on the identity block
log.warning("live voice: identity block unavailable", exc_info=True)
return ""
+ return identity + _memory()
+
+
+def _memory() -> str:
+ """The remember directive and Jarvis' notebooks; ``""`` on a fault.
+
+ A GPT-Live call sees what earlier calls and chats saved to MEMORY.md and
+ USER.md, and saves a new "remember this" while the call runs (through
+ the remember tool) instead of only after it ends.
+ """
+ try:
+ from jarvis.memory.learning.notebook import memory_block
+
+ block = memory_block()
+ except Exception: # noqa: BLE001 — never block a call on the notebooks
+ log.warning("live voice: memory notebooks unavailable", exc_info=True)
+ return ""
+ return "\n\n" + block if block else ""
#: Smallest gap between two live snapshots of one streaming reasoning summary.
diff --git a/jarvis/memory/learning/loop.py b/jarvis/memory/learning/loop.py
index e901005fcf..0fc3a23e02 100644
--- a/jarvis/memory/learning/loop.py
+++ b/jarvis/memory/learning/loop.py
@@ -34,7 +34,6 @@ import logging
import time
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
-from datetime import date
from typing import Any, Final
from jarvis.memory.learning.notebook import JarvisNotebook
@@ -238,6 +237,9 @@ class JarvisLearningLoop:
conversation = self._conversations[key] = _Conversation()
conversation.last_seen = time.monotonic()
request = requested_memory(turn.user)
+ if request is not None and "remember" in turn.tools:
+ # The conversation model already saved it through the remember tool.
+ request = None
# A self-contained request is saved right here; only a bare "remember
# that" still needs the model to see what "that" was.
signal = request == "" or (request is None and has_signal(turn.user))
@@ -422,30 +424,17 @@ class JarvisLearningLoop:
return 1 if written is not None else 0
def _keep_request(self, said: str, content: str) -> int:
- """Save an explicit remember request in the user's own words, dated."""
- from jarvis.memory.learning.guard import MAX_ENTRY_CHARS, refusal
- from jarvis.society.memory_books import classify
-
- prefix = f"{date.today().isoformat()} (the user's words): "
- room = MAX_ENTRY_CHARS - len(prefix)
- if len(content) > room:
- content = content[: room - 1].rsplit(" ", 1)[0] + "…"
- text = prefix + content
- if refusal(text):
- log.info("learning: explicit remember request refused by the guard")
+ """Save an explicit remember request in the user's own words, dated.
+
+ A full notebook never refuses it (it merges later); a request the
+ remember tool already saved in this conversation is not filed twice.
+ """
+ try:
+ change = self.notebook.keep_explicit(content, evidence=said)
+ except (ValueError, OSError) as exc: # filelock.Timeout is an OSError subclass too
+ log.info("learning: explicit remember request not saved — %s", exc)
return 0
- return self._write(
- target="user" if classify(content) == "user" else "memory",
- operation="add",
- text=text,
- importance=9,
- origin="user",
- evidence=said,
- source="explicit remember request",
- # The user asked for it: a full notebook merges later, it never
- # refuses this.
- enforce_budget=False,
- )
+ return 1 if change is not None else 0
async def _remember(self, said: str, content: str) -> None:
if await asyncio.to_thread(self._keep_request, said, content):
@@ -491,7 +480,13 @@ class JarvisLearningLoop:
async def _merge(self, target: str, rows: list[Any], used: int, budget: int) -> int:
from jarvis.memory.learning import compact
+ from jarvis.memory.learning.notebook import EXPLICIT_ORIGIN
+ # What the user asked to remember is theirs: never merged, never
+ # expired (its date prefix would otherwise read as a passed deadline).
+ rows = [e for e in rows if getattr(e, "origin", "") != EXPLICIT_ORIGIN]
+ if len(rows) < 2:
+ return 0
prompt = compact.build_prompt(rows, target=target, used=used, budget=budget)
self.compact_calls += 1
log.info("learning: compacting %s (%d/%d chars)", target, used, budget)
diff --git a/jarvis/memory/learning/notebook.py b/jarvis/memory/learning/notebook.py
index 5c65ac10fc..d990d62460 100644
--- a/jarvis/memory/learning/notebook.py
+++ b/jarvis/memory/learning/notebook.py
@@ -23,6 +23,7 @@ from __future__ import annotations
import json
import logging
import os
+import re
import threading
import time
from dataclasses import dataclass
@@ -61,6 +62,33 @@ _TITLES: Final[dict[str, str]] = {
"user": "### Who the user is (USER.md)",
"memory": "### Your working notes (MEMORY.md)",
}
+_EXPLICIT_TITLE: Final[str] = "### What the user asked you to remember (MEMORY.md)"
+
+#: ``origin`` of an entry the user explicitly asked Jarvis to remember. Such an
+#: entry always lives in MEMORY.md, outranks anything a review inferred, is
+#: never merged or expired by compaction, and has its own prompt allowance.
+EXPLICIT_ORIGIN: Final[str] = "user"
+EXPLICIT_IMPORTANCE: Final[int] = 10
+#: Prompt characters reserved for explicit entries, on top of MEMORY.md's budget.
+EXPLICIT_PROMPT_CHARS: Final[int] = 2_000
+#: How long a save through the remember tool keeps the deterministic fallback
+#: from filing the same request a second time (a GPT-Live call reaches the
+#: loop as one turn when it ends, long after the tool saved it).
+_TOOL_SAVE_WINDOW_S: Final[float] = 6 * 3_600.0
+#: Share of a request's content words a tool save must cover to count as it.
+_SAME_REQUEST_SHARE: Final[float] = 0.6
+_CONTENT_WORD: Final = re.compile(r"[^\W\d_]{4,}")
+
+#: The memory contract every conversation surface states next to the snapshot.
+REMEMBER_DIRECTIVE: Final[str] = (
+ "Long-term memory: when the user explicitly asks you to remember or note something "
+ "for future conversations (for example 'remember', "
+ "'merk dir', 'notier dir'), " # i18n-allow: input vocabulary
+ "call the remember tool right away with one self-contained sentence in the user's "
+ "language that still makes sense in a later conversation: resolve 'this' or 'that' "
+ "from the conversation. Say it is saved only after the tool succeeded. What it "
+ "stores is shown under 'What you have learned so far' in every later conversation."
+)
@dataclass(frozen=True, slots=True)
@@ -99,6 +127,8 @@ class JarvisNotebook:
self._cache: dict[bool, str] = {}
self._signature: tuple[float, ...] | None = None
self._checked_at = 0.0
+ #: ``(monotonic time, saved content, what the user said)`` per tool save.
+ self._tool_saves: list[tuple[float, str, str]] = []
# ── files ────────────────────────────────────────────────────────────
@@ -128,10 +158,21 @@ class JarvisNotebook:
return Soul.load(self.soul_path).learned()
def usage(self, entries: dict[str, list[Any]] | None = None) -> dict[str, tuple[int, int]]:
- """``target -> (chars used, budget)`` as the reviewer sees it."""
+ """``target -> (chars used, budget)`` as the reviewer sees it.
+
+ Explicit entries have their own allowance, so what the user asked to
+ remember never crowds out what a review may still add or merge.
+ """
books = entries if entries is not None else self.entries()
return {
- target: (sum(len(e.text) + 2 for e in books[target]), self.budgets[target])
+ target: (
+ sum(
+ len(e.text) + 2
+ for e in books[target]
+ if getattr(e, "origin", "") != EXPLICIT_ORIGIN
+ ),
+ self.budgets[target],
+ )
for target in TARGETS
}
@@ -213,6 +254,76 @@ class JarvisNotebook:
self.invalidate()
return change
+ def keep_explicit(
+ self,
+ content: str,
+ *,
+ evidence: str = "",
+ source: str = "explicit remember request",
+ via_tool: bool = False,
+ ) -> Change | None:
+ """Save what the user explicitly asked to remember into MEMORY.md, dated.
+
+ ``via_tool`` is the conversation model calling the remember tool with
+ a self-contained sentence; otherwise ``content`` is the user's own
+ words, found by the deterministic fallback. That fallback returns
+ ``None`` for a request the tool already saved. A full notebook never
+ refuses an explicit request; the guard (secrets, oversized text)
+ does, with a ``ValueError``.
+ """
+ from datetime import date
+
+ from jarvis.memory.learning.guard import MAX_ENTRY_CHARS, refusal
+
+ content = " ".join(str(content or "").split())
+ if not content:
+ raise ValueError("there is nothing to remember")
+ label = "asked to remember" if via_tool else "the user's words"
+ prefix = f"{date.today().isoformat()} ({label}): "
+ room = MAX_ENTRY_CHARS - len(prefix)
+ if len(content) > room:
+ content = content[: room - 1].rsplit(" ", 1)[0] + "…"
+ text = prefix + content
+ reason = refusal(text)
+ if reason:
+ raise ValueError(reason)
+ if not via_tool and self._saved_by_tool(content, evidence):
+ return None
+ change = self.apply(
+ target="memory",
+ operation="add",
+ text=text,
+ importance=EXPLICIT_IMPORTANCE,
+ origin=EXPLICIT_ORIGIN,
+ evidence=evidence,
+ source=source,
+ enforce_budget=False,
+ )
+ if via_tool:
+ now = time.monotonic()
+ with self._lock:
+ self._tool_saves = [
+ s for s in self._tool_saves if now - s[0] < _TOOL_SAVE_WINDOW_S
+ ][-31:] + [(now, content, evidence)]
+ return change
+
+ def _saved_by_tool(self, content: str, said: str) -> bool:
+ """Did the remember tool already save this request during the conversation?"""
+ from jarvis.memory.learning.compact import _norm
+
+ now = time.monotonic()
+ with self._lock:
+ saves = [s for s in self._tool_saves if now - s[0] < _TOOL_SAVE_WINDOW_S]
+ wanted = _norm(content)
+ words = {w[:4] for w in _CONTENT_WORD.findall(wanted)}
+ for _at, saved, evidence in saves:
+ if wanted and (wanted in _norm(evidence) or wanted in _norm(saved)):
+ return True
+ covered = words & {w[:4] for w in _CONTENT_WORD.findall(_norm(saved))}
+ if words and len(covered) / len(words) >= _SAME_REQUEST_SHARE:
+ return True
+ return False
+
def _edit_soul(
self, text: str, *, operation: str, entry_id: str, importance: int, origin: str
) -> bool:
@@ -343,9 +454,21 @@ class JarvisNotebook:
if not any(books.get(target) for target in BOOK_TARGETS):
return ""
parts = [_HEADER]
+ # What the user asked to be remembered comes first and never competes
+ # with what a review inferred for the regular budget.
+ explicit = [e for e in books.get("memory", []) if e.origin == EXPLICIT_ORIGIN]
+ if explicit:
+ allowance = EXPLICIT_PROMPT_CHARS // (2 if compact else 1)
+ selected, omitted = select_entries(explicit, max_chars=allowance)
+ selected.sort(key=lambda e: e.revision)
+ parts.append(_EXPLICIT_TITLE)
+ parts.append("\n".join("- " + " ".join(e.text.split()) for e in selected))
+ if omitted:
+ parts.append(f"({omitted} older requests are not shown.)")
for target in BOOK_TARGETS:
budget = self.budgets[target] // (2 if compact else 1)
- selected, omitted = select_entries(books[target], max_chars=budget)
+ rows = [e for e in books[target] if e.origin != EXPLICIT_ORIGIN or target != "memory"]
+ selected, omitted = select_entries(rows, max_chars=budget)
if not selected:
continue
# Oldest first within what fits: the notebook reads as a story.
@@ -430,6 +553,28 @@ def snapshot_block(*, compact: bool = False) -> str:
return notebook.snapshot(compact=compact)
+def memory_block(*, compact: bool = False) -> str:
+ """:data:`REMEMBER_DIRECTIVE` plus the snapshot, for a surface with the remember tool."""
+ if _active is None:
+ return ""
+ learned = snapshot_block(compact=compact)
+ return REMEMBER_DIRECTIVE + ("\n\n" + learned if learned else "")
+
+
+def remember_explicitly(
+ content: str, *, evidence: str = "", source: str = "remember tool"
+) -> Change | None:
+ """The remember tool's write: one explicit request into MEMORY.md.
+
+ Raises ``LookupError`` while the notebook is not running and
+ ``ValueError`` when the guard refuses the text.
+ """
+ notebook = _active
+ if notebook is None:
+ raise LookupError("Jarvis' notebook is not running")
+ return notebook.keep_explicit(content, evidence=evidence, source=source, via_tool=True)
+
+
def notebook_from_config(config: Any) -> JarvisNotebook:
"""Build the notebook for ``config``'s vault, name and budgets."""
from jarvis.brain.assistant_name import resolve_assistant_name
diff --git a/jarvis/plugins/tool/remember.py b/jarvis/plugins/tool/remember.py
index 78a000c8a6..14e67fba64 100644
--- a/jarvis/plugins/tool/remember.py
+++ b/jarvis/plugins/tool/remember.py
@@ -1,10 +1,18 @@
-"""remember tool: user says "merk dir X" (English: "remember X") → the fact # i18n-allow (quotes a DE voice-trigger example a user might say)
-is persisted into core memory.
+"""remember tool: the user says "remember X" → X is saved to Jarvis' MEMORY.md.
-Risk tier: safe — only writes to the local JSON file.
+Every later conversation (voice, chat) shows it in its prompt.
+
+The notebook lives in the Society lead's folder of the vault
+(``society/jarvis/MEMORY.md``, see :mod:`jarvis.memory.learning.notebook`),
+so the person can read and edit it in the app or in Obsidian. Without a
+running notebook (a headless test, a boot that disabled learning) the fact
+goes to the legacy core-memory file instead, so the request is never lost.
+
+Risk tier: safe — only writes local files.
"""
from __future__ import annotations
+import asyncio
from typing import Any
from jarvis.core.config import DATA_DIR
@@ -15,16 +23,22 @@ class RememberTool:
name: str = "remember"
risk_tier: str = "safe"
description: str = (
- "Stores a fact in persistent core memory. Automatically injected "
- "into the system prompt on the next brain call."
+ "Save something the user explicitly asked you to remember for future "
+ "conversations into Jarvis' long-term MEMORY.md. Pass one self-contained "
+ "sentence in the user's language that still makes sense later (resolve "
+ "'this' or 'that'). Every later conversation sees it."
)
schema: dict[str, Any] = {
"type": "object",
"properties": {
- "fact": {"type": "string", "description": "The fact to remember (short sentence)"},
+ "fact": {
+ "type": "string",
+ "description": "What to remember, as one self-contained sentence.",
+ },
"category": {
"type": "string",
- "description": "Category (e.g. 'identity', 'preference', 'project')",
+ "description": "Optional label (e.g. 'preference', 'project'); "
+ "used only by the legacy fallback store.",
"default": "general",
},
},
@@ -32,20 +46,32 @@ class RememberTool:
}
async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:
- from jarvis.memory import CORE_MEMORY_FILENAME, CoreMemory
+ from jarvis.memory.learning.notebook import remember_explicitly
- fact = (args.get("fact") or "").strip()
- category = (args.get("category") or "general").strip()
+ fact = " ".join(str(args.get("fact") or "").split())
if not fact:
return ToolResult(success=False, output=None, error="fact is missing")
-
+ said = str(getattr(ctx, "user_utterance", "") or "")
try:
+ change = await asyncio.to_thread(remember_explicitly, fact, evidence=said)
+ except LookupError:
+ return await self._legacy(fact, str(args.get("category") or "general").strip())
+ except (ValueError, OSError) as exc:
+ return ToolResult(success=False, output=None, error=f"not saved: {exc}")
+ if change is None:
+ return ToolResult(success=True, output=f"Already in MEMORY.md: {fact}")
+ return ToolResult(success=True, output=f"Saved to MEMORY.md: {fact}")
+
+ @staticmethod
+ async def _legacy(fact: str, category: str) -> ToolResult:
+ from jarvis.memory import CORE_MEMORY_FILENAME, CoreMemory
+
+ def _write() -> None:
mem = CoreMemory.load(DATA_DIR / CORE_MEMORY_FILENAME)
- mem.add_fact(fact, category=category)
- except Exception as exc: # noqa: BLE001
- return ToolResult(success=False, output=None, error=str(exc))
+ mem.add_fact(fact, category=category or "general")
- return ToolResult(
- success=True,
- output=f"Remembered: [{category}] {fact}",
- )
+ try:
+ await asyncio.to_thread(_write)
+ except Exception as exc: # noqa: BLE001 — reported to the caller as a failed save
+ return ToolResult(success=False, output=None, error=str(exc))
+ return ToolResult(success=True, output=f"Remembered: [{category}] {fact}")
diff --git a/jarvis/society/memory_intent.py b/jarvis/society/memory_intent.py
index 263610d1f2..271bffa282 100644
--- a/jarvis/society/memory_intent.py
+++ b/jarvis/society/memory_intent.py
@@ -31,17 +31,48 @@ def user_evidence(event: dict[str, Any]) -> str:
]
-def requested_memory(text: str) -> str | None:
- """None means no request; an empty string needs context instead of a guessed fact."""
- match = _REMEMBER.fullmatch(text)
+#: "Remember that not" declines; "remember not to call late" is a request.
+_NEGATED = re.compile(
+ r"^(?:(?:das|dies|es|this|that|it|eso)\s+(?:nicht|not|no)|nicht)\b", # i18n-allow
+ re.IGNORECASE,
+)
+#: One spoken or typed sentence: the request may sit anywhere in a longer turn.
+_SENTENCE_END = re.compile(r"(?<=[.!?])\s+")
+
+
+def _request_in(sentence: str) -> str | None:
+ match = _REMEMBER.fullmatch(sentence)
if not match:
return None
content = match["content"].strip()
if _REFERENCE_ONLY.fullmatch(content):
return ""
+ if _NEGATED.match(content):
+ return None
return re.sub(r"^that\s+", "", content, flags=re.IGNORECASE)
+def requested_memory(text: str) -> str | None:
+ """None means no request; an empty string needs context instead of a guessed fact.
+
+ The request may open the turn ("Remember that I ...") or follow what it
+ points at ("I want short reports. Remember that."): a bare "remember
+ that" then takes the sentence just before it in the same turn.
+ """
+ whole = _request_in(text)
+ if whole:
+ return whole
+ sentences = [part.strip() for part in _SENTENCE_END.split(text or "") if part.strip()]
+ for index, sentence in enumerate(sentences):
+ content = _request_in(sentence)
+ if content is None:
+ continue
+ if content == "" and index > 0:
+ return sentences[index - 1].rstrip(" .!")
+ return content
+ return whole
+
+
def has_write_receipt(events: list[dict[str, Any]]) -> bool:
names = {
str(e.get("payload", {}).get("call_id")): e.get("payload", {}).get("name")
diff --git a/tests/unit/memory/learning/test_explicit_memory.py b/tests/unit/memory/learning/test_explicit_memory.py
new file mode 100644
index 0000000000..287139084a
--- /dev/null
+++ b/tests/unit/memory/learning/test_explicit_memory.py
@@ -0,0 +1,271 @@
+"""An explicit "remember this" lands in MEMORY.md and stays there.
+
+Real notebook files under ``tmp_path``; the conversation model's side is the
+real remember tool, the background side the real learning loop with a
+scripted reviewer and compactor. No provider, no mocks.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jarvis.memory.learning import notebook as notebook_module
+from jarvis.memory.learning.loop import JarvisLearningLoop
+from jarvis.memory.learning.notebook import (
+ EXPLICIT_IMPORTANCE,
+ EXPLICIT_ORIGIN,
+ REMEMBER_DIRECTIVE,
+ JarvisNotebook,
+ memory_block,
+)
+from jarvis.memory.learning.review import Turn
+from jarvis.plugins.tool.remember import RememberTool
+from jarvis.society.memory_intent import requested_memory
+
+
+def book(tmp_path: Path) -> JarvisNotebook:
+ return JarvisNotebook(tmp_path / "vault", budgets={"user": 600, "memory": 600})
+
+
[email protected](autouse=True)
+def _no_active_notebook():
+ notebook_module.set_active(None)
+ yield
+ notebook_module.set_active(None)
+
+
+async def _no_review(prompt: str) -> list[dict[str, Any]]:
+ del prompt
+ return []
+
+
+async def _drain(loop: JarvisLearningLoop) -> None:
+ for _ in range(50):
+ if not loop._tasks:
+ return
+ await asyncio.sleep(0.01)
+ raise AssertionError("background work did not finish")
+
+
+def _memory(book: JarvisNotebook) -> list[Any]:
+ return book.entries()["memory"]
+
+
+# ── recognizing the request ────────────────────────────────────────────────
+
+
+ ("said", "wanted"),
+ [
+ ("Remember that I take my coffee black.", "I take my coffee black."),
+ # The request follows what it points at, in the same turn.
+ (
+ "I want agents briefed to work on their own. Remember that.",
+ "I want agents briefed to work on their own",
+ ),
+ (
+ "Ich will kurze Berichte. Merk dir das bitte!", # i18n-allow
+ "Ich will kurze Berichte", # i18n-allow
+ ),
+ # Mid-turn, after something unrelated.
+ ("Okay, great. Remember: my brother is called Tim.", "my brother is called Tim."),
+ ("Remember not to call me after nine.", "not to call me after nine."),
+ # A bare reference with nothing before it still asks the model.
+ ("Remember that.", ""),
+ # Declining or asking is no request.
+ ("Merk dir das nicht.", None), # i18n-allow
+ ("Can you tell me what you remember about me?", None),
+ ("What time is it? Thanks.", None),
+ ],
+)
+def test_a_remember_request_is_found_where_people_put_it(said: str, wanted: str | None) -> None:
+ assert requested_memory(said) == wanted
+
+
+# ── the notebook ───────────────────────────────────────────────────────────
+
+
+def test_an_explicit_request_always_lands_in_memory_md(book: JarvisNotebook) -> None:
+ # Reads like a profile fact, but the user asked for it: MEMORY.md.
+ book.keep_explicit("I am allergic to peanuts.", evidence="remember I am allergic")
+
+ [entry] = _memory(book)
+ assert book.entries()["user"] == []
+ assert entry.text.endswith("(the user's words): I am allergic to peanuts.")
+ assert entry.origin == EXPLICIT_ORIGIN
+ assert entry.importance == EXPLICIT_IMPORTANCE
+ assert (book.folder / "MEMORY.md").read_text(encoding="utf-8").count("peanuts") == 1
+
+
+def test_a_secret_is_never_remembered(book: JarvisNotebook) -> None:
+ with pytest.raises(ValueError):
+ book.keep_explicit("my key is sk-" + "a" * 48)
+ assert _memory(book) == []
+
+
+def test_explicit_entries_reach_the_prompt_beyond_the_regular_budget(
+ book: JarvisNotebook,
+) -> None:
+ for n in range(4):
+ book.keep_explicit(f"Project {n} ships from the {'east ' * 25}warehouse.")
+ book.apply(target="memory", operation="add", text="The user's printer is in the attic.")
+
+ text = book.render()
+
+ # 4 x ~180 chars is past MEMORY.md's 600-char budget, yet all are shown,
+ # in their own section, before what a review inferred.
+ assert text.count("ships from the") == 4
+ assert text.index("What the user asked you to remember") < text.index(
+ "The user's printer is in the attic."
+ )
+
+
+def test_compaction_never_merges_or_expires_an_explicit_entry(book: JarvisNotebook) -> None:
+ seen: list[dict[str, Any]] = []
+
+ async def compactor(prompt: str) -> dict[str, Any]:
+ data = json.loads(prompt)
+ seen.append(data)
+ return {"merged": [], "outdated": [e["entry_id"] for e in data["entries"]]}
+
+ for n in range(3):
+ book.keep_explicit(f"Remember item {n}: {'details ' * 20}")
+ # Enough inferred notes to pass the fill trigger on their own.
+ for n in range(4):
+ book.apply(
+ target="memory", operation="add", text=f"A note from {'review ' * 15}number {n}."
+ )
+ loop = JarvisLearningLoop(book, _no_review, compactor=compactor)
+
+ asyncio.run(loop.compact(force=True))
+
+ explicit = [e for e in _memory(book) if e.origin == EXPLICIT_ORIGIN]
+ assert len(explicit) == 3
+ # The merging model is never even shown them (their date prefix would
+ # read as a passed deadline).
+ assert seen and all("Remember item" not in e["text"] for e in seen[0]["entries"])
+
+
+def test_the_memory_block_states_the_contract_and_the_notes(book: JarvisNotebook) -> None:
+ assert memory_block() == ""
+ notebook_module.set_active(book)
+ assert memory_block() == REMEMBER_DIRECTIVE
+ book.keep_explicit("The user's dog is called Bruno.")
+
+ block = memory_block()
+
+ assert block.startswith(REMEMBER_DIRECTIVE)
+ assert "The user's dog is called Bruno." in block
+
+
+def test_a_gpt_live_call_carries_the_memory(book: JarvisNotebook) -> None:
+ from jarvis.live.config import LiveConfig
+ from jarvis.live.session import _memory as live_memory
+
+ notebook_module.set_active(book)
+ book.keep_explicit("The user's dog is called Bruno.")
+
+ wire = LiveConfig(configured=True, backend_model="m").session_config(
+ language="de", tools=[], identity="You are George." + live_memory()
+ )
+
+ for instructions in (wire["instructions"], wire["delegation"]["responses"]["instructions"]):
+ assert "The user's dog is called Bruno." in instructions
+ assert "remember tool" in instructions
+
+
+# ── the remember tool ──────────────────────────────────────────────────────
+
+
+async def test_the_remember_tool_saves_into_memory_md(book: JarvisNotebook) -> None:
+ notebook_module.set_active(book)
+ ctx = SimpleNamespace(user_utterance="remember that my dog is called Bruno")
+
+ result = await RememberTool().execute({"fact": "The user's dog is called Bruno."}, ctx)
+ again = await RememberTool().execute({"fact": "The user's dog is called Bruno."}, ctx)
+
+ assert result.success and "MEMORY.md" in result.output
+ assert again.success and again.output.startswith("Already")
+ [entry] = _memory(book)
+ assert "(asked to remember): The user's dog is called Bruno." in entry.text
+ assert entry.origin == EXPLICIT_ORIGIN
+
+
+async def test_without_a_notebook_the_tool_falls_back_to_core_memory(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from jarvis.memory import CORE_MEMORY_FILENAME, CoreMemory
+ from jarvis.plugins.tool import remember
+
+ monkeypatch.setattr(remember, "DATA_DIR", tmp_path)
+
+ result = await RememberTool().execute({"fact": "Tea, not coffee."}, None)
+
+ assert result.success
+ assert "Tea, not coffee." in json.dumps(
+ CoreMemory.load(tmp_path / CORE_MEMORY_FILENAME).model_dump()
+ if hasattr(CoreMemory, "model_dump")
+ else (tmp_path / CORE_MEMORY_FILENAME).read_text(encoding="utf-8"),
+ ensure_ascii=False,
+ )
+
+
+async def test_a_call_the_tool_already_saved_is_not_filed_twice(book: JarvisNotebook) -> None:
+ """GPT-Live reaches the loop as ONE turn when the call ends, long after the tool saved."""
+ notebook_module.set_active(book)
+ said = (
+ "Can you open the workspace? Thanks. I want agents briefed so they can work "
+ "on their own. Remember that. And now check the build."
+ )
+ await RememberTool().execute(
+ {"fact": "The user wants agents briefed so they can work on their own."},
+ SimpleNamespace(user_utterance="I want agents briefed so they can work on their own."),
+ )
+ loop = JarvisLearningLoop(book, _no_review, idle_review_seconds=0)
+
+ loop.record("voice:call", Turn(user=said, assistant="Done."))
+ await _drain(loop)
+
+ assert len(_memory(book)) == 1
+
+
+async def test_a_request_the_tool_did_not_see_is_still_saved(book: JarvisNotebook) -> None:
+ loop = JarvisLearningLoop(book, _no_review, idle_review_seconds=0)
+
+ loop.record("chat:c", Turn(user="I only drink tea. Remember that.", assistant="Okay."))
+ await _drain(loop)
+
+ [entry] = _memory(book)
+ assert entry.text.endswith("(the user's words): I only drink tea")
+
+
+async def test_a_turn_that_used_the_tool_is_not_saved_again(book: JarvisNotebook) -> None:
+ loop = JarvisLearningLoop(book, _no_review, idle_review_seconds=0)
+
+ loop.record(
+ "chat:c",
+ Turn(user="Remember that I only drink tea.", assistant="Saved.", tools=("remember",)),
+ )
+ await _drain(loop)
+
+ assert _memory(book) == []
+
+
+# ── the voice tool set ─────────────────────────────────────────────────────
+
+
+def test_voice_calls_get_the_remember_tool_and_workers_do_not() -> None:
+ from jarvis.brain.tool_gateway import BrainSupervisorToolGateway
+
+ manager = SimpleNamespace(_tools={}, _config=SimpleNamespace(computer_use=None))
+ gateway = BrainSupervisorToolGateway(manager)
+
+ assert "remember" in {d.name for d in gateway.voice_catalog()}
+ assert "remember" not in {d.name for d in gateway.catalog()}