From 3dbf1e8c56030173ad30756c3b2c4f546ddc7c6d Mon Sep 17 00:00:00 2001 From: javis-bot Date: Wed, 11 Nov 2026 13:32:36 +0900 Subject: [PATCH] feat(nutrition): meals belong to the person who logged them - meals.user_id (v1 databases gain it on open, DEFAULT '' keeps their meals the single user's); insert_meal, get_meals_between and delete_meal take the person, and delete only removes that person's meal. - turn_state.set_user / ToolContext.user_id carry the asker; logMeal, fetchMeals and deleteMeal use it. The v2 brain sets it for each reply. - Tests: two people never see or delete each other's meals, no user is v1's single user, and a v1 database opens with its meals kept. Co-Authored-By: Claude Opus 5.5 --- src/jarvis/memory/db.py | 27 +++-- src/jarvis/reply/turn_state.py | 13 +++ src/jarvis/tools/base.py | 10 +- .../tools/builtin/nutrition/delete_meal.py | 2 +- .../tools/builtin/nutrition/fetch_meals.py | 2 +- .../tools/builtin/nutrition/log_meal.py | 5 +- .../tools/builtin/nutrition/log_meal.spec.md | 8 ++ src/voice_worker/brain.py | 14 ++- src/voice_worker/voice_worker.spec.md | 2 + tests/test_tools.py | 4 +- tests/test_voice_worker_brain.py | 25 +++++ .../builtin/nutrition/test_delete_meal.py | 2 +- .../builtin/nutrition/test_meals_per_user.py | 98 +++++++++++++++++++ 13 files changed, 193 insertions(+), 19 deletions(-) create mode 100644 tests/tools/builtin/nutrition/test_meals_per_user.py diff --git a/src/jarvis/memory/db.py b/src/jarvis/memory/db.py index fcdb6d7..6ad5425 100644 --- a/src/jarvis/memory/db.py +++ b/src/jarvis/memory/db.py @@ -27,7 +27,9 @@ CREATE TABLE IF NOT EXISTS meals ( sodium_mg REAL, potassium_mg REAL, micros_json TEXT, - confidence REAL + confidence REAL, + -- Who logged it (v2: Discord user ID). '' is v1's single user. + user_id TEXT NOT NULL DEFAULT '' ); -- Conversation summaries for diary/memory system @@ -127,6 +129,11 @@ class Database: with self._lock: cur = self.conn.cursor() cur.executescript(_SCHEMA_SQL) + # v1 databases have no meals.user_id; their meals are the single user's (''). + cols = {r[1] for r in cur.execute("PRAGMA table_info(meals)").fetchall()} + if "user_id" not in cols: + cur.execute("ALTER TABLE meals ADD COLUMN user_id TEXT NOT NULL DEFAULT ''") + cur.execute("CREATE INDEX IF NOT EXISTS meals_user_ts ON meals(user_id, ts_utc)") if self.is_vss_enabled: cur.executescript(_VSS_SCHEMA_SQL) self.conn.commit() @@ -290,13 +297,14 @@ class Database: potassium_mg: Optional[float] = None, micros_json: Optional[str] = None, confidence: Optional[float] = None, + user_id: str = "", ) -> int: with self._lock: cur = self.conn.cursor() cur.execute( """ - INSERT INTO meals(ts_utc, source_app, description, calories_kcal, protein_g, carbs_g, fat_g, fiber_g, sugar_g, sodium_mg, potassium_mg, micros_json, confidence) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + INSERT INTO meals(ts_utc, source_app, description, calories_kcal, protein_g, carbs_g, fat_g, fiber_g, sugar_g, sodium_mg, potassium_mg, micros_json, confidence, user_id) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( ts_utc, @@ -312,28 +320,31 @@ class Database: potassium_mg, micros_json, confidence, + user_id or "", ), ) self.conn.commit() return int(cur.lastrowid) - def get_meals_between(self, ts_utc_min: str, ts_utc_max: str) -> list[sqlite3.Row]: + def get_meals_between(self, ts_utc_min: str, ts_utc_max: str, user_id: str = "") -> list[sqlite3.Row]: + """Meals of one person (``user_id``; '' is v1's single user) in the time range.""" with self._lock: cur = self.conn.cursor() rows = cur.execute( """ SELECT * FROM meals - WHERE ts_utc >= ? AND ts_utc <= ? + WHERE ts_utc >= ? AND ts_utc <= ? AND user_id = ? ORDER BY ts_utc ASC """, - (ts_utc_min, ts_utc_max), + (ts_utc_min, ts_utc_max, user_id or ""), ).fetchall() return rows - def delete_meal(self, meal_id: int) -> bool: + def delete_meal(self, meal_id: int, user_id: str = "") -> bool: + """Delete a meal only when it belongs to ``user_id``.""" with self._lock: cur = self.conn.cursor() - cur.execute("DELETE FROM meals WHERE id = ?", (meal_id,)) + cur.execute("DELETE FROM meals WHERE id = ? AND user_id = ?", (meal_id, user_id or "")) self.conn.commit() return cur.rowcount > 0 diff --git a/src/jarvis/reply/turn_state.py b/src/jarvis/reply/turn_state.py index 7af4ace..9447d59 100644 --- a/src/jarvis/reply/turn_state.py +++ b/src/jarvis/reply/turn_state.py @@ -15,6 +15,10 @@ broadcasting : Optional[bool] broadcast_action : Optional[str] A directive ("start"/"stop") recorded by the setBroadcast tool for the bridge to return to the bot, which owns the actual broadcast. +user : Optional[str] + v2: the Discord user ID of the person asking, set by the voice worker's + brain. Tools that keep personal data (meals) store and read it under this + person. None is v1's single user. """ from __future__ import annotations @@ -29,6 +33,15 @@ def reset() -> None: """Clear per-turn state. Call at the start of each request.""" _state.broadcasting = None _state.broadcast_action = None + _state.user = None + + +def set_user(user_id: Optional[str]) -> None: + _state.user = user_id + + +def get_user() -> Optional[str]: + return getattr(_state, "user", None) def set_broadcasting(value: Optional[bool]) -> None: diff --git a/src/jarvis/tools/base.py b/src/jarvis/tools/base.py index ab9456d..51f4fae 100644 --- a/src/jarvis/tools/base.py +++ b/src/jarvis/tools/base.py @@ -23,6 +23,7 @@ class ToolContext: user_print: Callable[[str], None], language: Optional[str] = None, broadcasting: Optional[bool] = None, + user_id: str = "", ): self.db = db self.cfg = cfg @@ -44,6 +45,9 @@ class ToolContext: # ``None`` means "no signal" (evals, text entry, older bot): callers # fall back to the master flag so behaviour is unchanged. self.broadcasting = broadcasting + # v2: the person asking (Discord user ID); '' is v1's single user. + # Personal data (meals) is stored and read under this person only. + self.user_id = user_id class Tool(ABC): @@ -115,10 +119,11 @@ class Tool(ABC): # thread-local state (set by the bridge) rather than threaded through # the whole engine call chain. Absent (eval / unit test) -> None. try: - from jarvis.reply.turn_state import get_broadcasting + from jarvis.reply.turn_state import get_broadcasting, get_user broadcasting = get_broadcasting() + user_id = get_user() or "" except Exception: - broadcasting = None + broadcasting, user_id = None, "" context = ToolContext( db=db, cfg=cfg, @@ -129,5 +134,6 @@ class Tool(ABC): user_print=user_print, language=language, broadcasting=broadcasting, + user_id=user_id, ) return self.run(tool_args, context) diff --git a/src/jarvis/tools/builtin/nutrition/delete_meal.py b/src/jarvis/tools/builtin/nutrition/delete_meal.py index 6e8c0b8..937f35b 100644 --- a/src/jarvis/tools/builtin/nutrition/delete_meal.py +++ b/src/jarvis/tools/builtin/nutrition/delete_meal.py @@ -40,7 +40,7 @@ class DeleteMealTool(Tool): is_deleted = False if mid is not None: try: - is_deleted = context.db.delete_meal(mid) + is_deleted = context.db.delete_meal(mid, user_id=getattr(context, "user_id", "") or "") except Exception: is_deleted = False debug_log(f"DELETE_MEAL: id={mid} deleted={is_deleted}", "nutrition") diff --git a/src/jarvis/tools/builtin/nutrition/fetch_meals.py b/src/jarvis/tools/builtin/nutrition/fetch_meals.py index 5baa98c..7e9b478 100644 --- a/src/jarvis/tools/builtin/nutrition/fetch_meals.py +++ b/src/jarvis/tools/builtin/nutrition/fetch_meals.py @@ -103,7 +103,7 @@ class FetchMealsTool(Tool): context.user_print("📖 Retrieving your meals…") since, until = _normalize_time_range(args if isinstance(args, dict) else None) debug_log(f"fetchMeals: range since={since} until={until}", "nutrition") - meals = context.db.get_meals_between(since, until) + meals = context.db.get_meals_between(since, until, user_id=getattr(context, "user_id", "") or "") debug_log(f"fetchMeals: count={len(meals)}", "nutrition") summary = summarize_meals([dict(r) for r in meals]) # Return raw meal summary for profile processing diff --git a/src/jarvis/tools/builtin/nutrition/log_meal.py b/src/jarvis/tools/builtin/nutrition/log_meal.py index 0826f5f..bdd7125 100644 --- a/src/jarvis/tools/builtin/nutrition/log_meal.py +++ b/src/jarvis/tools/builtin/nutrition/log_meal.py @@ -46,7 +46,7 @@ def _safe_float(x: Any) -> Optional[float]: -def extract_and_log_meal(db: Database, cfg: Any, original_text: str, source_app: str) -> Optional[str]: +def extract_and_log_meal(db: Database, cfg: Any, original_text: str, source_app: str, user_id: str = "") -> Optional[str]: """ Uses the chat model to extract a structured meal from the redacted user text, logs it to DB, and returns a short user-facing confirmation + healthy follow-ups. @@ -90,6 +90,7 @@ def extract_and_log_meal(db: Database, cfg: Any, original_text: str, source_app: potassium_mg=_safe_float(data.get("potassium_mg")), micros_json=json.dumps(data.get("micros")) if isinstance(data.get("micros"), dict) else None, confidence=_safe_float(data.get("confidence")), + user_id=user_id, ) # Build a brief confirmation + guidance cals = data.get("calories_kcal") @@ -184,7 +185,7 @@ class LogMealTool(Tool): for attempt in range(context.max_retries + 1): try: debug_log(f"logMeal: extracting from text (attempt {attempt+1}/{context.max_retries+1})", "nutrition") - meal_summary = extract_and_log_meal(context.db, context.cfg, original_text=extract_text, source_app=("stdin" if context.cfg.use_stdin else "unknown")) + meal_summary = extract_and_log_meal(context.db, context.cfg, original_text=extract_text, source_app=("stdin" if context.cfg.use_stdin else "unknown"), user_id=getattr(context, "user_id", "") or "") if meal_summary: debug_log("logMeal: extraction+log succeeded", "nutrition") return ToolExecutionResult(success=True, reply_text=meal_summary) diff --git a/src/jarvis/tools/builtin/nutrition/log_meal.spec.md b/src/jarvis/tools/builtin/nutrition/log_meal.spec.md index bf84f00..f4f4801 100644 --- a/src/jarvis/tools/builtin/nutrition/log_meal.spec.md +++ b/src/jarvis/tools/builtin/nutrition/log_meal.spec.md @@ -93,6 +93,14 @@ Logged via `Database.insert_meal(...)`, which uses parameterised SQL. `"unknown"`. Optional fields (potassium, micros, confidence) are stored as NULL when missing. +Each meal belongs to one person (`meals.user_id`). The v2 voice worker's +brain sets the asker for the turn (`turn_state.set_user`, read into +`ToolContext.user_id`); `logMeal` stores under that person, and +`fetchMeals` / `deleteMeal` only see and delete that person's meals, so +people sharing the assistant never see each other's meals. Without a user +(v1, one person) the ID is `''`. v1 databases gain the column on open +(`ALTER TABLE ... DEFAULT ''`), so their meals stay the single user's. + ### Reply shape On success the tool returns: diff --git a/src/voice_worker/brain.py b/src/voice_worker/brain.py index f6115f6..520235f 100644 --- a/src/voice_worker/brain.py +++ b/src/voice_worker/brain.py @@ -128,13 +128,23 @@ class JarvisBrain: return mem def reply(self, user: str, text: str, history: HistoryContext) -> Optional[str]: + from jarvis.reply import turn_state from jarvis.reply.engine import run_reply_engine t0 = time.perf_counter() # legacy_memory=False: v1's profile, diary and graph belong to one user; several people # share this assistant, so only the asker's scoped history may reach the prompt. - answer = Muted.run(run_reply_engine, self.db, self.cfg, None, text, self._memory(user), - language=self.language, history=history, legacy_memory=False) + def turn(): + # Tools with personal data (meals) read the asker from the turn state. + turn_state.reset() + turn_state.set_user(user) + try: + return run_reply_engine(self.db, self.cfg, None, text, self._memory(user), + language=self.language, history=history, legacy_memory=False) + finally: + turn_state.reset() + + answer = Muted.run(turn) debug_log(f"brain reply user={user} ok={bool(answer)} ms={(time.perf_counter() - t0) * 1000:.0f}", "voice_worker") return answer diff --git a/src/voice_worker/voice_worker.spec.md b/src/voice_worker/voice_worker.spec.md index 7a7f1c6..27fc222 100644 --- a/src/voice_worker/voice_worker.spec.md +++ b/src/voice_worker/voice_worker.spec.md @@ -223,6 +223,8 @@ which carry Discord's own time. memory (tool carry-over) across replies. The brain runs the reply engine with v1's single-user memory off (`legacy_memory=False`: no warm profile, diary or graph), because several people share this assistant and only the asker's scoped history may reach the prompt. + The asker is set in `jarvis.reply.turn_state` for the turn, so tools that keep personal data + (meals) store and read it under that person only. - While a reply runs, the process's stdout and stderr are muted: the v1 engine and its tools print questions, answers, tool arguments and memory text, also from helper threads. The worker's own log (`voice_worker/log.py`) writes to the original stderr and keeps working. diff --git a/tests/test_tools.py b/tests/test_tools.py index 290851b..bd6ff99 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -19,10 +19,10 @@ class DummyCfg: class DummyDB: - def get_meals_between(self, since, until): + def get_meals_between(self, since, until, user_id=""): return [] - def delete_meal(self, mid: int) -> bool: + def delete_meal(self, mid: int, user_id: str = "") -> bool: return mid == 1 diff --git a/tests/test_voice_worker_brain.py b/tests/test_voice_worker_brain.py index 029e5ba..0d0d247 100644 --- a/tests/test_voice_worker_brain.py +++ b/tests/test_voice_worker_brain.py @@ -344,3 +344,28 @@ def test_the_brain_turns_off_the_single_user_memory(tmp_path, monkeypatch): monkeypatch.setattr(engine, "run_reply_engine", fake_engine) brain_mod.JarvisBrain().reply("100", "q", HistoryContext()) assert seen["legacy_memory"] is False + + +@pytest.mark.unit +def test_the_brain_tells_tools_who_is_asking(tmp_path, monkeypatch): + pytest.importorskip("mcp") # the real brain needs the jarvis dependencies (--brain) + from jarvis.memory.history import HistoryContext + from jarvis.reply import turn_state + from voice_worker import brain as brain_mod + + cfg = tmp_path / "config.json" + cfg.write_text(json.dumps({"db_path": str(tmp_path / "jarvis.db")})) + monkeypatch.setenv("JARVIS_CONFIG_PATH", str(cfg)) + seen = [] + + def fake_engine(db, cfg, tts, text, mem, language=None, history=None, legacy_memory=True): + seen.append(turn_state.get_user()) + return "ok" + + import jarvis.reply.engine as engine + monkeypatch.setattr(engine, "run_reply_engine", fake_engine) + b = brain_mod.JarvisBrain() + b.reply("100", "q", HistoryContext()) + b.reply("200", "q", HistoryContext()) + assert seen == ["100", "200"] + assert turn_state.get_user() is None # nothing left behind on this thread diff --git a/tests/tools/builtin/nutrition/test_delete_meal.py b/tests/tools/builtin/nutrition/test_delete_meal.py index 8e81fcf..ff4d239 100644 --- a/tests/tools/builtin/nutrition/test_delete_meal.py +++ b/tests/tools/builtin/nutrition/test_delete_meal.py @@ -35,7 +35,7 @@ class TestDeleteMealTool: assert isinstance(result, ToolExecutionResult) assert result.success is True assert "Meal deleted" in result.reply_text - self.context.db.delete_meal.assert_called_once_with(123) + self.context.db.delete_meal.assert_called_once_with(123, user_id="") def test_run_failure(self): """Test meal deletion failure.""" diff --git a/tests/tools/builtin/nutrition/test_meals_per_user.py b/tests/tools/builtin/nutrition/test_meals_per_user.py new file mode 100644 index 0000000..6fa9736 --- /dev/null +++ b/tests/tools/builtin/nutrition/test_meals_per_user.py @@ -0,0 +1,98 @@ +"""Meals belong to the person who logged them (v2: several people share one assistant). + +The v2 brain sets the asker for the turn (jarvis.reply.turn_state.set_user). logMeal stores the +meal under that person, fetchMeals and deleteMeal only see that person's meals. Without a user +(v1, one person) every meal is the single user's, as before. A v1 database without the column +opens unchanged and keeps its meals. +""" + +import json +import sqlite3 +from unittest.mock import patch + +import pytest + +from jarvis.memory.db import Database +from jarvis.reply import turn_state +from jarvis.tools.builtin.nutrition.delete_meal import DeleteMealTool +from jarvis.tools.builtin.nutrition.fetch_meals import FetchMealsTool +from jarvis.tools.builtin.nutrition.log_meal import LogMealTool + + +class Cfg: + ollama_base_url = "http://x" + ollama_chat_model = "m" + llm_chat_timeout_sec = 5 + use_stdin = False + voice_debug = True + + +def _meal_json(desc): + return json.dumps({"description": desc, "calories_kcal": 500, "protein_g": 20, "carbs_g": 50, + "fat_g": 10, "confidence": 0.8}) + + +def run(tool, db, args, user): + turn_state.reset() + turn_state.set_user(user) + try: + return tool.execute(db=db, cfg=Cfg(), tool_args=args, system_prompt="", original_prompt="", + redacted_text=(args or {}).get("meal", ""), max_retries=0, + user_print=lambda m: None) + finally: + turn_state.reset() + + +@pytest.fixture +def db(tmp_path): + d = Database(str(tmp_path / "j.db"), None) + yield d + d.close() + + +def log(db, user, desc): + with patch("jarvis.tools.builtin.nutrition.log_meal.call_llm_direct", return_value=_meal_json(desc)): + return run(LogMealTool(), db, {"meal": desc}, user) + + +def test_each_person_sees_only_their_own_meals(db): + assert log(db, "alice", "bibimbap").success + assert log(db, "bob", "pizza").success + alice = run(FetchMealsTool(), db, {}, "alice").reply_text + bob = run(FetchMealsTool(), db, {}, "bob").reply_text + assert "bibimbap" in alice and "pizza" not in alice + assert "pizza" in bob and "bibimbap" not in bob + + +def test_nobody_deletes_someone_elses_meal(db): + log(db, "alice", "bibimbap") + meal_id = db.conn.execute("SELECT id FROM meals").fetchone()[0] + assert not run(DeleteMealTool(), db, {"id": meal_id}, "bob").success + assert "bibimbap" in run(FetchMealsTool(), db, {}, "alice").reply_text + assert run(DeleteMealTool(), db, {"id": meal_id}, "alice").success + assert "bibimbap" not in (run(FetchMealsTool(), db, {}, "alice").reply_text or "") + + +def test_without_a_user_it_is_the_single_v1_user(db): + log(db, None, "toast") + assert "toast" in run(FetchMealsTool(), db, {}, None).reply_text + assert "toast" not in (run(FetchMealsTool(), db, {}, "alice").reply_text or "") + + +def test_a_v1_database_opens_and_keeps_its_meals(tmp_path): + path = str(tmp_path / "old.db") + con = sqlite3.connect(path) + con.execute("CREATE TABLE meals (id INTEGER PRIMARY KEY, ts_utc TEXT NOT NULL, source_app TEXT NOT NULL, " + "description TEXT NOT NULL, calories_kcal REAL, protein_g REAL, carbs_g REAL, fat_g REAL, " + "fiber_g REAL, sugar_g REAL, sodium_mg REAL, potassium_mg REAL, micros_json TEXT, confidence REAL)") + con.execute("INSERT INTO meals(ts_utc, source_app, description, calories_kcal) VALUES " + "(strftime('%Y-%m-%dT%H:%M:%f+00:00','now'), 'x', 'old porridge', 300)") + con.commit() + con.close() + d = Database(path, None) + try: + assert "old porridge" in run(FetchMealsTool(), d, {}, None).reply_text + log(d, "alice", "new salad") + assert "new salad" in run(FetchMealsTool(), d, {}, "alice").reply_text + finally: + d.close()