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

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