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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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