mirror of
https://github.com/Memo-2023/mana-monorepo.git
synced 2026-05-20 09:33:39 +02:00
chore(mana): citycorners + food + wardrobe aus unified-App entfernen
Citycorners-Reste vom vorherigen Sprint mit committet. food → Nutriphi,
wardrobe → Werdrobe sind als Standalone-Apps live; die mana.how-unified-
App trägt die Modul-Surfaces nicht mehr.
Gelöscht / abgebaut:
- Module: apps/mana/.../modules/{food,wardrobe} + Routen + Locales
- Landing-Apps: apps/{food,citycorners}/ Top-Level
- Backend: apps/api/src/modules/{food,wardrobe} + MCP-Tools log_meal /
nutrition_summary, picture-routes verifyMediaOwnership-Allowlist
- shared-branding: APP_BRANDING, APP_ICONS, MANA_APPS, Logos, Onboarding
- shared-ai, mana-tool-registry, credits, shared-types/spaces,
shared-utils/analytics, spiral-db/MANA_APP_INDEX, website-blocks
- Cross-Module: Body-CalorieWeightChart, Comic-CharacterPicker-Wardrobe,
website-Embed wardrobe.outfits, DaySnapshot.nutrition, FoodEventType,
MealLogged/Meal*-Streaks/Goals/Companion/Trigger, AI-Agent-Policy,
GoalEditor MealLogged, MyDay/RitualRunner/Rules nutrition-Refs,
Crypto-Registry meals/wardrobeGarments/wardrobeOutfits
- Generic: PlaceCategory 'food' (places + geocoding + Locales),
spaces.ts 'food'/'wardrobe' Modul-IDs
- Infrastruktur: cloudflared, docker-compose CORS, nginx-Landing,
prometheus-Probe, load-tests, package.json dev-Scripts,
generate-env, mac-mini/build-landings, dependabot
Dexie v62 Migration:
- droppt meals, goals, foodFavorites, mealTags, wardrobeGarments,
wardrobeOutfits Tabellen
- entfernt wardrobeOutfitId / wardrobeGarmentId aus images-Index
- Upgrade-Callback strippt die toten FK-Properties aus alten image-Rows
Test/Doku:
- module-registry.test.ts: Snapshot refresht auf aktuellen Stand mit
56 Modulen (vorher 32, statisch eingefroren pre-refactor). Plus
LEGACY_TABLES-Exclusion für nicht-mehr-registrierte Tabellen aus
cards/citycorners/moodlit/rituals/wishes/who.
- streaks.test.ts: MealLogged-Test in TaskCompleted-Test umgebaut
- apps/mana/CLAUDE.md: food-Refs in AI-Tool-Tabelle und
AiProposalInbox-Liste entfernt
- validate-i18n-keys.mjs + validate-no-recursive-turbo.mjs:
existsSync-Guard, damit die Skripte mit gestaged-aber-rm'ten Dateien
klarkommen
mana-web svelte-check 0 errors / 7436 files, betroffene Tests grün
(streaks, dashboard, module-registry), validate:pg-schema,
validate:turbo, validate:i18n-parity grün.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
932bd98d84
commit
ae04c9e194
260 changed files with 234 additions and 21506 deletions
|
|
@ -1,220 +0,0 @@
|
|||
/**
|
||||
* Food module — Meal analysis (Gemini Vision via mana-llm) + recommendations.
|
||||
*
|
||||
* CRUD for meals, goals, favorites is handled by mana-sync. This module
|
||||
* owns the server-only operations: photo upload to mana-media, structured
|
||||
* AI analysis using the Vercel AI SDK (`generateObject`) against the
|
||||
* shared Zod schema in @mana/shared-types, and a small rule-based
|
||||
* recommendation engine.
|
||||
*
|
||||
* Why generateObject + Zod instead of raw fetch?
|
||||
* - Runtime validation of the AI response — if Gemini drifts on a
|
||||
* field, we throw at the boundary instead of corrupting downstream
|
||||
* state. The frontend never sees malformed data.
|
||||
* - Provider-portable structured outputs: the AI SDK translates one
|
||||
* Zod schema into OpenAI strict json_schema / Anthropic tool-use /
|
||||
* Gemini response_schema depending on which backend mana-llm routes
|
||||
* to. We don't have to know which.
|
||||
* - Single source of truth: the same MealAnalysisSchema is consumed
|
||||
* by the unified web app via `z.infer<typeof MealAnalysisSchema>`,
|
||||
* so changes here propagate end-to-end without manual sync.
|
||||
*/
|
||||
|
||||
import { Hono } from 'hono';
|
||||
import { generateObject } from 'ai';
|
||||
import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
|
||||
import {
|
||||
AI_SCHEMA_VERSION,
|
||||
MealAnalysisSchema,
|
||||
type AiResponseEnvelope,
|
||||
type MealAnalysis,
|
||||
} from '@mana/shared-types';
|
||||
import { logger, type AuthVariables } from '@mana/shared-hono';
|
||||
import { MANA_LLM } from '@mana/shared-ai';
|
||||
|
||||
const LLM_URL = process.env.MANA_LLM_URL || 'http://localhost:3025';
|
||||
// mana-llm resolves this alias to a healthy vision model (chain in
|
||||
// services/mana-llm/aliases.yaml). To swap the chain, edit the YAML
|
||||
// and SIGHUP — no service redeploy here.
|
||||
const VISION_MODEL = MANA_LLM.VISION;
|
||||
|
||||
const llm = createOpenAICompatible({
|
||||
name: 'mana-llm',
|
||||
// mana-llm exposes /v1/chat/completions (see services/mana-llm/CLAUDE.md +
|
||||
// src/main.py:125). The AI SDK's openai-compatible adapter appends
|
||||
// /chat/completions to baseURL, so baseURL ends in /v1.
|
||||
baseURL: `${LLM_URL}/v1`,
|
||||
// Tell the AI SDK that mana-llm honours OpenAI-style strict
|
||||
// json_schema response_format. Without this, generateObject() falls
|
||||
// back to a tool-call mode that Ollama-backed models don't support
|
||||
// reliably and the response fails to validate against the Zod schema.
|
||||
// mana-llm's Ollama provider translates response_format → Ollama's
|
||||
// native `format` field (services/mana-llm/src/providers/ollama.py)
|
||||
// so this is honoured end-to-end.
|
||||
supportsStructuredOutputs: true,
|
||||
});
|
||||
|
||||
const ANALYSIS_PROMPT = `Du bist ein Ernährungsexperte. Analysiere die Mahlzeit und gib strukturierte Nährwertdaten zurück. Schätze realistische Portionsgrößen und Kalorien. Antworte auf Deutsch.`;
|
||||
|
||||
/**
|
||||
* Provider hints attached to the system message. Forward-compat:
|
||||
*
|
||||
* - anthropic.cacheControl: ephemeral system-prompt caching. NO-OP today
|
||||
* because (a) we route to Gemini via mana-llm and (b) the prompt is
|
||||
* ~50 tokens — well under Anthropic's 1024-token cache minimum. Becomes
|
||||
* active automatically when mana-llm routes to Claude AND the prompt
|
||||
* grows (e.g. once we attach per-user dietary preferences as system
|
||||
* context, which would push us past the threshold).
|
||||
*
|
||||
* Kept here so the day we flip the backend, we don't have to revisit
|
||||
* every route to enable caching — it just starts working.
|
||||
*/
|
||||
const SYSTEM_CACHE_HINT = {
|
||||
anthropic: { cacheControl: { type: 'ephemeral' as const } },
|
||||
};
|
||||
|
||||
/** Wrap a validated AI object in the standard wire-format envelope. */
|
||||
function envelope(data: MealAnalysis): AiResponseEnvelope<MealAnalysis> {
|
||||
return { schemaVersion: AI_SCHEMA_VERSION, data };
|
||||
}
|
||||
|
||||
const routes = new Hono<{ Variables: AuthVariables }>();
|
||||
|
||||
// ─── Photo Upload (server-only: S3 storage via mana-media) ───
|
||||
|
||||
routes.post('/photos/upload', async (c) => {
|
||||
const userId = c.get('userId');
|
||||
const formData = await c.req.formData();
|
||||
const file = formData.get('file') as File | null;
|
||||
|
||||
if (!file) return c.json({ error: 'No file provided' }, 400);
|
||||
if (file.size > 10 * 1024 * 1024) return c.json({ error: 'File too large (max 10MB)' }, 400);
|
||||
|
||||
try {
|
||||
const { uploadImageToMedia } = await import('../../lib/media');
|
||||
const buffer = await file.arrayBuffer();
|
||||
const result = await uploadImageToMedia(buffer, file.name, { app: 'food', userId });
|
||||
|
||||
return c.json(
|
||||
{
|
||||
mediaId: result.id,
|
||||
publicUrl: result.urls.original,
|
||||
thumbnailUrl: result.urls.thumbnail || result.urls.original,
|
||||
storagePath: result.id,
|
||||
},
|
||||
201
|
||||
);
|
||||
} catch (err) {
|
||||
logger.error('food.upload_failed', {
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
return c.json({ error: 'Upload failed' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// ─── Photo Analysis (Gemini Vision on uploaded URL) ──────────
|
||||
|
||||
routes.post('/analysis/photo', async (c) => {
|
||||
const { photoUrl } = await c.req.json();
|
||||
if (!photoUrl) return c.json({ error: 'photoUrl required' }, 400);
|
||||
|
||||
try {
|
||||
const { object } = await generateObject({
|
||||
model: llm(VISION_MODEL),
|
||||
schema: MealAnalysisSchema,
|
||||
messages: [
|
||||
{
|
||||
role: 'system',
|
||||
content: ANALYSIS_PROMPT,
|
||||
providerOptions: SYSTEM_CACHE_HINT,
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{ type: 'text', text: 'Analysiere diese Mahlzeit.' },
|
||||
{ type: 'image', image: new URL(photoUrl) },
|
||||
],
|
||||
},
|
||||
],
|
||||
temperature: 0.3,
|
||||
});
|
||||
return c.json(envelope(object));
|
||||
} catch (err) {
|
||||
logger.error('food.photo_analysis_failed', {
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
return c.json({ error: 'Analysis failed' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// ─── Text Analysis (Gemini on a free-text meal description) ──
|
||||
|
||||
routes.post('/analysis/text', async (c) => {
|
||||
const { description } = await c.req.json();
|
||||
if (!description) return c.json({ error: 'description required' }, 400);
|
||||
|
||||
try {
|
||||
const { object } = await generateObject({
|
||||
model: llm(VISION_MODEL),
|
||||
schema: MealAnalysisSchema,
|
||||
messages: [
|
||||
{
|
||||
role: 'system',
|
||||
content: ANALYSIS_PROMPT,
|
||||
providerOptions: SYSTEM_CACHE_HINT,
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: `Analysiere diese Mahlzeit: ${description}`,
|
||||
},
|
||||
],
|
||||
temperature: 0.3,
|
||||
});
|
||||
return c.json(envelope(object));
|
||||
} catch (err) {
|
||||
logger.error('food.text_analysis_failed', {
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
return c.json({ error: 'Analysis failed' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// ─── Recommendations (server-only: rule engine) ──────────────
|
||||
|
||||
routes.post('/recommendations/generate', async (c) => {
|
||||
const { dailyNutrition } = await c.req.json();
|
||||
const hints: Array<{ type: string; priority: string; message: string; nutrient?: string }> = [];
|
||||
|
||||
if (dailyNutrition) {
|
||||
if (dailyNutrition.protein < 25) {
|
||||
hints.push({
|
||||
type: 'hint',
|
||||
priority: 'medium',
|
||||
message:
|
||||
'Deine Proteinzufuhr ist niedrig. Versuche Hülsenfrüchte, Eier oder Joghurt einzubauen.',
|
||||
nutrient: 'protein',
|
||||
});
|
||||
}
|
||||
if (dailyNutrition.fiber < 10) {
|
||||
hints.push({
|
||||
type: 'hint',
|
||||
priority: 'medium',
|
||||
message: 'Mehr Ballaststoffe! Vollkornprodukte, Gemüse und Obst helfen.',
|
||||
nutrient: 'fiber',
|
||||
});
|
||||
}
|
||||
if (dailyNutrition.sugar > 50) {
|
||||
hints.push({
|
||||
type: 'hint',
|
||||
priority: 'high',
|
||||
message:
|
||||
'Dein Zuckerkonsum ist hoch. Achte auf versteckten Zucker in Getränken und Fertigprodukten.',
|
||||
nutrient: 'sugar',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return c.json({ recommendations: hints });
|
||||
});
|
||||
|
||||
export { routes as foodRoutes };
|
||||
|
|
@ -1,41 +0,0 @@
|
|||
/**
|
||||
* Moodlit module — Preset moods library
|
||||
* Ported from apps/moodlit/apps/server
|
||||
*
|
||||
* Local-first for user moods/sequences.
|
||||
* This module serves the default preset library.
|
||||
*/
|
||||
|
||||
import { Hono } from 'hono';
|
||||
|
||||
const DEFAULT_MOODS = [
|
||||
{ id: 'fire', name: 'Fire', colors: ['#ff6b35', '#f72585', '#ff006e'], animation: 'flicker' },
|
||||
{ id: 'breath', name: 'Breath', colors: ['#4361ee', '#3a0ca3', '#7209b7'], animation: 'pulse' },
|
||||
{
|
||||
id: 'northern-lights',
|
||||
name: 'Northern Lights',
|
||||
colors: ['#06d6a0', '#118ab2', '#073b4c'],
|
||||
animation: 'aurora',
|
||||
},
|
||||
{ id: 'thunder', name: 'Thunder', colors: ['#14213d', '#fca311', '#e5e5e5'], animation: 'flash' },
|
||||
{
|
||||
id: 'sunset',
|
||||
name: 'Sunset',
|
||||
colors: ['#ff6b6b', '#feca57', '#ff9ff3'],
|
||||
animation: 'gradient',
|
||||
},
|
||||
{ id: 'ocean', name: 'Ocean', colors: ['#0077b6', '#00b4d8', '#90e0ef'], animation: 'wave' },
|
||||
{ id: 'forest', name: 'Forest', colors: ['#2d6a4f', '#40916c', '#52b788'], animation: 'sway' },
|
||||
{
|
||||
id: 'lavender',
|
||||
name: 'Lavender',
|
||||
colors: ['#7b2cbf', '#9d4edd', '#c77dff'],
|
||||
animation: 'pulse',
|
||||
},
|
||||
];
|
||||
|
||||
const routes = new Hono();
|
||||
|
||||
routes.get('/presets', (c) => c.json(DEFAULT_MOODS));
|
||||
|
||||
export { routes as moodlitRoutes };
|
||||
|
|
@ -254,11 +254,8 @@ routes.post('/generate', async (c) => {
|
|||
// image input natively. Replicate/local fallback is a later milestone.
|
||||
|
||||
// OpenAI gpt-image-1 / gpt-image-2 accept up to 16 reference images per
|
||||
// edit call. We clamp at 8 to cover the Wardrobe try-on workflow — one
|
||||
// face-ref + one body-ref + up to six garment photos (top/bottom/shoes/
|
||||
// outerwear + two accessories) — while keeping credit exposure and
|
||||
// upload payload size predictable. Pre-wardrobe the cap was 4; bumped
|
||||
// in docs/plans/wardrobe-module.md M1.
|
||||
// edit call. We clamp at 8 to keep credit exposure and upload payload
|
||||
// size predictable.
|
||||
const MAX_REFERENCE_IMAGES = 8;
|
||||
|
||||
routes.post('/generate-with-reference', async (c) => {
|
||||
|
|
@ -318,18 +315,14 @@ routes.post('/generate-with-reference', async (c) => {
|
|||
}
|
||||
|
||||
// Ownership check before we spend credits or burn OpenAI quota.
|
||||
// References span three upload tags today:
|
||||
// - `me` — face/body portraits from the profile module
|
||||
// - `wardrobe` — garment photos (M4 try-on flow)
|
||||
// - `comic` — comic-specific anchor / backdrop uploads
|
||||
// (slot reserved for M6+; no writer lands in
|
||||
// this app today, M1 character refs come from
|
||||
// me + wardrobe only).
|
||||
// References span two upload tags today:
|
||||
// - `me` — face/body portraits from the profile module
|
||||
// - `comic` — comic-specific anchor / backdrop uploads
|
||||
// Anything outside these apps is treated as not-owned regardless of
|
||||
// mana-media's own view.
|
||||
try {
|
||||
const { verifyMediaOwnership } = await import('../../lib/media');
|
||||
await verifyMediaOwnership(userId, refIds, ['me', 'wardrobe', 'comic']);
|
||||
await verifyMediaOwnership(userId, refIds, ['me', 'comic']);
|
||||
} catch (err) {
|
||||
const e = err as Error & { status?: number; missing?: string[] };
|
||||
if (e.status === 404) {
|
||||
|
|
|
|||
|
|
@ -1,55 +0,0 @@
|
|||
/**
|
||||
* Wardrobe module — server endpoints.
|
||||
*
|
||||
* Thin wrapper around mana-media for garment photo uploads. Plan:
|
||||
* docs/plans/wardrobe-module.md M1. No logic beyond tagging uploads
|
||||
* as `app='wardrobe'` so a later `GET /api/v1/media?app=wardrobe&...`
|
||||
* query can enumerate a user's garment pool without scanning every
|
||||
* media reference.
|
||||
*
|
||||
* Try-on generation does NOT live here — it reuses the Picture
|
||||
* module's POST /api/v1/picture/generate-with-reference endpoint
|
||||
* with MAX_REFERENCE_IMAGES bumped to 8 so face + body + garments
|
||||
* fit into one call.
|
||||
*/
|
||||
|
||||
import { Hono } from 'hono';
|
||||
import type { AuthVariables } from '@mana/shared-hono';
|
||||
|
||||
const routes = new Hono<{ Variables: AuthVariables }>();
|
||||
|
||||
// Same 10MB cap as the other photo-upload endpoints (profile me-images,
|
||||
// picture uploads). Phone-camera PNG/HEIC routinely comes in under 6MB.
|
||||
const MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
routes.post('/garments/upload', async (c) => {
|
||||
const userId = c.get('userId');
|
||||
const formData = await c.req.formData();
|
||||
const file = formData.get('file') as File | null;
|
||||
|
||||
if (!file) return c.json({ error: 'No file' }, 400);
|
||||
if (file.size > MAX_UPLOAD_BYTES) return c.json({ error: 'Max 10MB' }, 400);
|
||||
|
||||
try {
|
||||
const { uploadImageToMedia } = await import('../../lib/media');
|
||||
const buffer = await file.arrayBuffer();
|
||||
const result = await uploadImageToMedia(buffer, file.name, {
|
||||
app: 'wardrobe',
|
||||
userId,
|
||||
});
|
||||
|
||||
return c.json(
|
||||
{
|
||||
mediaId: result.id,
|
||||
storagePath: result.id,
|
||||
publicUrl: result.urls.original,
|
||||
thumbnailUrl: result.urls.thumbnail,
|
||||
},
|
||||
201
|
||||
);
|
||||
} catch (_err) {
|
||||
return c.json({ error: 'Upload failed' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
export { routes as wardrobeRoutes };
|
||||
Loading…
Add table
Add a link
Reference in a new issue