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 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-11 13:32:36 +09:00
parent b3dcd12ec9
commit 3dbf1e8c56
13 changed files with 193 additions and 19 deletions

View File

@@ -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

View File

@@ -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

View File

@@ -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."""

View File

@@ -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()