Commit graph

2784 commits

Author SHA1 Message Date
Till JS
5480a8dfdf feat(mana/web/nutriphi): global quick-input adapter for the search bar
Adds nutriphi to the unified quick-input registry so the global search
bar gains meal-aware behaviour whenever the user is on a /nutriphi route.

Adapter contract (mirrors planta / todo / calendar):

  - onSearch: decrypts meals (description is in the encrypted allowlist)
    and substring-matches by description, sorted newest-first, capped at 10
  - onCreate: parses an optional meal-type prefix from the query
    ("frühstück: müsli mit beeren", "snack: apfel", english + ASCII
    variants accepted) and falls back to suggestMealType() based on
    time-of-day when no prefix is given
  - onParseCreate: shows a preview line so users see which meal type
    will be picked before they hit enter

Persistence goes through mealMutations.create — same code path the
workbench card uses, so encryption + sync work for free.

Tests: 13 cases covering parser branches (German + English prefixes,
case insensitivity, time-of-day fallback for the three meal windows,
edge cases like unknown prefixes, far-away colons, empty descriptions
after a prefix). Parser is exported to keep the test independent of
the adapter's network-touching hooks.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 16:14:37 +02:00
Till JS
68d1bda7e5 fix(news-ingester): drop unused @mana/shared-hono workspace dep
Was copied verbatim from mana-credits' template but not actually
imported anywhere in src/. Removing it lets the Docker build's bun
install resolve from npm only — workspace:* refs need the full
monorepo context which the Dockerfile doesn't copy.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 16:11:58 +02:00
Till JS
c9e16243c8 feat(shared-llm): bump mana-server default model to gemma4:e4b
Two surprises came out of "why do we still use Gemma 3 instead of 4":

1. The hardcoded default in ManaServerBackend was `gemma3:4b`, which
   was even smaller than mana-llm's actual server-side default of
   `gemma3:12b`. My initial guess from docs/LOCAL_LLM_MODELS.md was
   conservative.

2. The mana-llm OLLAMA_URL points at host.docker.internal:13434,
   which is NOT the Mac Mini's local Ollama — it's a Python TCP
   forwarder (~/gpu-proxy.py) that proxies to 192.168.178.11:11434
   on the Windows GPU server. So title generation has been running
   on the RTX 3090 the whole time, not on the M4 Metal GPU. The
   Mac Mini's brew-installed ollama 0.15.4 wasn't even being used
   for inference — only as a CLI to inspect the proxied Ollama.

To get to Gemma 4, both Ollama instances needed an upgrade:
  - Mac Mini brew  : 0.15.4 → 0.20.4 (cosmetic, the binary isn't on
                     the inference path; upgraded for consistency)
  - GPU server     : 0.18.2 → 0.20.4 via winget. Required restarting
                     the daemon via the OllamaServe scheduled task
                     that was already configured.

Then `ollama pull gemma4:e4b` on the GPU server (9.6 GB, ~10 min on
the LAN). Verified end-to-end via the proxy with a real chat
completion request to mana-llm — gemma4:e4b answered with a clean
4-word German title for a sample voice memo prompt:

  prompt: "Erstelle einen kurzen 3-Wort Titel für: Es ist ein
           schöner Tag heute am 9. April"
  → "Schöner Tag, neuntes April"

Changes in this commit:

  packages/shared-llm/src/backends/mana-server.ts
    - defaultModel: 'gemma3:4b' → 'gemma4:e4b'
    - Updated docstring to explain why E4B is the right Mana-Server
      tier default: 9.6 GB on disk, 128K context, "Effective 4B"
      arch punches above its weight class for German prompts, and
      the family stays consistent with the browser tier (Gemma 4
      E2B is the smaller sibling) so the source label and prompt
      behavior remain coherent across tiers.

  apps/mana/apps/web/src/lib/modules/memoro/views/DetailView.svelte
    - TITLE_SOURCE_LABELS map updated:
        browser     → "Auf deinem Gerät (Gemma 4 E2B)" (was "(Gemma 4)")
        mana-server → "Mana-Server (Gemma 4 E4B)" (was "(gemma3:4b)")
    - The label now reflects that BOTH the browser and the mana-server
      tier are running Gemma 4 variants, which is more honest than
      the previous mix.

Did NOT change:
  - The Ollama OLLAMA_DEFAULT_MODEL env var in docker-compose.macmini.yml
    (still gemma3:12b). That's the fallback for callers who don't
    specify a model in their request. Our generate-title task always
    sends an explicit model string, so it's unaffected. Bumping the
    global default is a separate decision — it would change behavior
    for the playground module and any other consumer that relies on
    the implicit fallback.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 16:06:33 +02:00
Till JS
df72a92b4c test(mana/web): consistency guard for workbench-registry ↔ MANA_APPS
Adds the test that would have caught the inventar↔inventory drift
months earlier (commit 45790ffbb fixed the actual mismatch). Walks
both directions:

  1. Every workbench-registered app must have a MANA_APPS entry, OR
     be in the WORKBENCH_ONLY allowlist (currently `automations`,
     `playground` — internal devtools we don't want in marketing).

  2. Every MANA_APPS entry must be registered in the workbench, OR
     be in the BRANDING_ONLY allowlist (`mana` itself, standalone
     subdomains like `arcade`, "Coming Soon" placeholders like
     `wisekeep`/`mail`/`events`, and modules whose workbench
     integration is still pending like `guides`/`who`).

Plus a regression guard that fails loudly if anyone reintroduces
`inventar` as an id in either registry.

The point: every future drift between the two registries forces the
contributor to either fix it on the spot or explicitly classify the
new entry in one of the allowlists with a comment. No more silent
fail-open tier-gating.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 16:05:17 +02:00
Till JS
c184991b3a feat(mana/web/nutriphi): inline text + photo quick-add in workbench ListView
The workbench card was read-only — users had to navigate to /nutriphi/add
to log anything. Now the card has a quick-add bar in the toolbar slot:

  - Text input → Enter or send button → mealMutations.create() with
    suggestMealType() (no AI round-trip; users get instant persistence
    and can edit nutrition later from the detail page)
  - 📷 button → file picker (capture=environment for mobile camera) →
    photoMutations.uploadAndAnalyze → mealMutations.createFromPhoto with
    the full Gemini result (foods + thumbnail + confidence)
  - Toast on success ("📷 Mahlzeit hinzugefügt · KI 87%") and on error

Item rendering also got a small upgrade:
  - Each row is now a link to /nutriphi/[id] (matches the rest of the
    nutriphi pages now that the detail route exists)
  - Thumbnail shown next to the row when present (uses photoThumbnailUrl
    for bandwidth)
  - 📷 indicator badge for photo-mode meals

Pre-existing bug fix in passing: the goals query was reading from the
non-existent table 'nutriphiGoals' instead of 'goals' (the actual table
name from module.config.ts), so the calorie target was never visible
in the workbench card. Switched to 'goals'.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 16:05:13 +02:00
Till JS
e579e292cc feat(mana/web/news): workbench ListView + dashboard widget
Surfaces News in two extra entry points beyond the dedicated /news
route. The workbench ListView is a compact ranked-feed view designed
for the AppPage carousel slot — it boots the same feed-cache poll, runs
the same scoreArticle pipeline, but renders smaller cards and skips the
onboarding wizard (un-onboarded users get a CTA pointing them at /news
instead). The NewsUnreadWidget shows the top three ranked unread
articles on the dashboard, sharing the exact same engine inputs so the
ordering matches the main feed. WidgetType + WIDGET_REGISTRY get the
new 'news-unread' entry, and dashboard.widgets.news_unread is added to
all five locale files.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 15:54:57 +02:00
Till JS
8167d265a7 feat(mana/web/news): web routes + i18n locales
Adds the seven (app)/news/* routes: layout that boots the feed-cache
poll, main page with the 3-step onboarding wizard and the ranked feed
with reaction buttons, dual-source reader at /news/[id], saved reading
list with category filter strip + inline category editor + 3 tabs
(unread/favorites/archive), /news/add for ad-hoc URL paste,
/news/preferences for topics/languages/weight reset, /news/sources
for per-source block toggles. Five locale JSON files (de/en/es/fr/it,
~60 keys each) for the eventual $_('news.…') refactor.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 15:54:25 +02:00
Till JS
de7e359580 feat(mana/web/news): client data layer + module library
Adds the local-first News module: 5 Dexie tables (newsArticles,
newsCategories, newsPreferences, newsReactions, newsCachedFeed) with
the cached pool intentionally outside the sync map, four mutation
stores (articles, categories, preferences, reactions, feed-cache),
typed DTOs + queries with decryption-aware liveQueries, the api.ts
client for /api/v1/news/{feed,extract}, and the pure feed-engine that
scores articles by recency × topicWeight × sourceWeight and applies
reaction-driven weight updates client-side.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 15:53:52 +02:00
Till JS
9ef97a1877 feat(news): backend ingester service + curated feed API
Adds the services/news-ingester Bun service that pulls 25 public RSS/JSON
feeds into news.curated_articles every 15 min, with Mozilla Readability
fallback for thin RSS bodies and 30-day retention. apps/api /feed is
rewritten to read from the new pool table directly instead of the
sync_changes hack, with topics/lang/since/limit/offset query params.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 15:53:26 +02:00
Till JS
45790ffbb8 refactor(mana): rename inventar → inventory across the codebase
The workbench-registry app id 'inventar' did not match its
@mana/shared-branding MANA_APPS counterpart 'inventory', so the tier-
gating join in apps/web/src/lib/app-registry/registry.ts silently
failed for the inventory module — it fell into the "no MANA_APPS
entry, default visible" fallback and was effectively un-gated. The
codebase had also voted overwhelmingly for 'inventar' (53 files) vs
'inventory' (3 files in shared-branding), so the long-standing
mismatch was just bookkeeping debt waiting to bite.

Pre-release, no live data, so the cleanest fix is to align everything
on the English 'inventory':

- Workbench-registry id, module.config.ts appId, module folder, route
  folder and i18n locale folder all renamed via git mv
- Standalone apps/inventar/ workspace package renamed
- All imports, store identifiers (InventarEvents → InventoryEvents,
  INVENTAR_GUEST_SEED, inventarModuleConfig), i18n keys and href/goto
  paths follow the rename
- The German display label "Inventar" is preserved everywhere it is a
  user-visible string (page titles, i18n values, toast labels)
- Dexie table prefixes (invCollections, invItems, …) are unchanged
- Drive-by fix: ListView.svelte was querying non-existent
  inventarCollections/inventarItems tables — corrected to the actual
  invCollections/invItems names from module.config
- The "inventar ↔ inventory id mismatch" workaround comment in
  registry.ts is removed since the mismatch no longer exists

module-registry.ts also picks up the user's parallel newsModuleConfig
addition because both edits land in the same import block — keeping
them split would have left the build in an inconsistent state.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 15:50:24 +02:00
Till JS
51f408755c fix(api/who): use /v1/chat/completions path for mana-llm
The who module's chat endpoint was returning 502 to the browser
because mana-api called /api/v1/chat/completions on mana-llm and
got 404 — mana-llm exposes the OpenAI-compatible /v1/chat/completions
path with no /api/ prefix.

This is the same bug research had until commit 63a91e36a fixed its
path. The chat module (apps/api/src/modules/chat/routes.ts) still
has the wrong path — flagged as a follow-up.

Diagnostic from inside the mana-api container:
  /v1/chat/completions       → 422 (right path, empty body)
  /api/v1/chat/completions   → 404 (wrong path)

mana-api log line that flagged it:
  who.llm_non_200 status:404

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 15:48:09 +02:00
Till JS
23f13d7139 test(mana/web/nutriphi): cover mealMutations.update
Five new cases against fake-indexeddb covering the new update mutation:

  - patches description and re-encrypts (verified via ENC_PREFIX wire
    format check + absence of original AND new plaintext in the blob)
  - patches numeric nutrition fields (stays plaintext for aggregation)
  - partial update only touches the supplied fields (mealType change
    does not zero out nutrition)
  - bumps updatedAt
  - throws on missing id

Total nutriphi suite is now 16/16 cases, ~50ms.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 15:45:35 +02:00
Till JS
4fd6a5cc77 feat(mana/web/nutriphi): meal detail page + foods breakdown + thumbnail-aware lists
New /nutriphi/[id] route — the missing endpoint of the photo workflow.
Loads the meal via inline useLiveQueryWithDefault(loadMealById, ...) so
the closure captures page.params.id directly (planta DetailView pattern).

Detail page features:
  - Full-resolution photo, click-to-expand lightbox modal
  - All six nutrient cards with the same color tokens as the dashboard
  - "Erkannte Bestandteile" — list of AI-identified foods (name +
    quantity + kcal) so users can see what Gemini actually parsed
  - Inline edit form (mealtype + description + 6 nutrient inputs),
    persists via mealMutations.update
  - "🔄 Erneut analysieren" for photo meals — calls analyze on the
    stored URL and overwrites description + nutrition without
    re-uploading the file
  - Two-stage delete confirm

Add page (add/+page.svelte):
  - Captures upload.thumbnailUrl + analysis.foods after KI analysis
  - Persists both via the extended createFromPhoto signature
  - Shows the foods breakdown card under the confidence badge so users
    see the parse before saving (closes the trust gap on low-confidence
    runs)

List pages (Heute + History):
  - Switch to photoThumbnailUrl ?? photoUrl for the row image — saves
    bandwidth on the most-rendered surface
  - Each meal row is now a link to /nutriphi/[id]
  - History row layout split into <a> + sibling delete button so the
    delete click doesn't bubble through navigation

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 15:45:21 +02:00
Till JS
de4f766b06 feat(mana/web/nutriphi): extend meal schema (foods + thumbnail) + update mutation
Schema additions on LocalMeal:
  - photoThumbnailUrl: pre-generated mana-media thumbnail URL, used in
    list views to save bandwidth (full photoUrl stays for the detail
    view + lightbox)
  - foods: AnalyzedFood[] (name / quantity / calories) — Gemini Vision
    already returns this breakdown but the previous flow threw it away
  - new AnalyzedFood type exported from the barrel

Encryption registry:
  - meals encrypted allowlist now includes 'foods' (food names are
    user content; aes.ts JSON-stringifies arrays before wrap, so an
    array value works the same as a string)
  - registry comment updated to enumerate which photo fields stay
    plaintext and why

New mutation: mealMutations.update(id, dto) for inline meal edits.
Patches only the supplied fields, runs encryptRecord on the partial
update so encrypted columns stay encrypted, then re-decrypts the merged
row to return a plaintext snapshot.

queries.ts: new loadMealById(id) helper used by the detail page's
inline useLiveQueryWithDefault wrapper (matches the planta DetailView
pattern of capturing the route param directly in the closure).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 15:44:55 +02:00
Till JS
e00e6f5a08 refactor(shared-branding): derive APP_URLS from APP_ICONS
The hand-maintained APP_URLS map kept silently drifting from the
AppIconId union — most recently the new 'who' entry was missing,
which crashed getPillAppItems at runtime with "Cannot read properties
of undefined (reading 'prod')". Drift was already flagged by the type
system but the error was lost in the existing svelte-check noise.

APP_URLS is now generated at module load by walking Object.keys of
APP_ICONS (the source of AppIconId), so every id is guaranteed a URL.
A small APP_URL_OVERRIDES map carries the handful of apps that don't
follow the unified mana.how/{id} pattern (root path for the unified
shell, subdomains for standalone apps like arcade).

Adds two integrity tests as defense-in-depth: one asserts every
MANA_APPS id has a matching APP_ICONS icon, the other asserts every
AppIconId resolves to a non-empty dev+prod URL. Both would have caught
the 'who' regression on its own without needing svelte-check.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 15:14:52 +02:00
Till JS
c7fd9369c9 test(mana/web/nutriphi): integration tests for meal mutations + encryption
11 cases against fake-indexeddb covering:

  - mealMutations.create: persistence, encryption allowlist (description
    encrypted, nutrition / mealType / structural fields plaintext),
    decryptRecord round-trip, plaintext snapshot return value,
    default-date and explicit-date paths
  - mealMutations.createFromPhoto: inputType=photo, photoMediaId /
    photoUrl plaintext, snapshot includes photo fields
  - mealMutations.delete: stamps deletedAt + updatedAt without
    physically removing the row (sync needs the tombstone)

Setup mirrors planta/mutations.test.ts: real Web Crypto via
generateMasterKey + MemoryKeyProvider, the same trigger / funnel-tracking
mocks the planta tests use, encryption verified through the ENC_PREFIX
wire-format check rather than mocking aes.ts.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 15:14:24 +02:00
Till JS
189249ba01 feat(mana/web/nutriphi): photo capture + AI meal recognition flow
Wires the new backend endpoints into the unified Mana app and rebuilds
the meal-add page around two modes:

  - Text mode: free-text description + optional " KI-Vorschlag" button
    that runs Gemini on the description and prefills all six nutrient
    fields. The badge auto-clears if the user edits the description so
    stale estimates can't be silently saved.

  - Foto mode: file picker (accept=image/*, capture=environment for
    mobile camera) → preview → upload to mana-media → Gemini Vision on
    the stored URL. Result prefills the same form fields for review.
    Re-analyze without re-upload is supported.

Both modes show a confidence badge (green ≥50 %, yellow with a "prüfen"
warning below). Save is disabled in foto mode until the upload+analysis
has completed, so a meal can never be persisted with a dangling photo
reference.

New module files:
  - api.ts          server-only client (uploadMealPhoto, analyzeMealPhoto, analyzeMealText)
  - mutations.ts    mealMutations.create / .createFromPhoto / .delete + photoMutations
                    keeps the encryption pattern explicit (clone → encrypt → write,
                    return plaintext snapshot)

Touched:
  - queries.ts      propagate photoMediaId/photoUrl through toMealWithNutrition
  - index.ts        export the new mutations + types
  - registry.ts     extend the meals comment to document why nutrition,
                    photoMediaId, photoUrl and confidence stay plaintext
  - +page.svelte / history/+page.svelte    show 64×64 / 48×48 thumbnail
                    + 📷 indicator for photo-mode meals

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 15:14:07 +02:00
Till JS
693d20edd1 refactor(api/nutriphi): split photo flow into /photos/upload + /analysis/photo
Mirror the planta two-step pattern: a FormData upload endpoint that
returns mediaId/publicUrl from mana-media, and a separate Gemini Vision
analysis endpoint that takes a photoUrl. Drops the base64 inline path
and the half-finished parallel-upload kludge in the old combined route.

Why: the old endpoint was wired neither in the frontend nor used
elsewhere, and the combined base64+upload+analyze design made it
impossible to show the photo to the user before AI ran or to re-analyze
without re-uploading.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 15:13:45 +02:00
Till JS
e6564cfc96 fix(mana/web): add standard mobile-web-app-capable meta tag
Chrome deprecates the apple-prefixed meta and now logs a warning
asking for the standardized mobile-web-app-capable equivalent. Adds
the standard tag alongside the apple one so iOS Safari keeps working.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 15:08:12 +02:00
Till JS
07b130ff9e fix(shared-branding): add missing 'who' entry to APP_URLS
The 'who' app was registered in MANA_APPS but never added to APP_URLS,
so getPillAppItems crashed at runtime when mapping over apps with
"Cannot read properties of undefined (reading 'prod')". This was also
flagged by svelte-check as a missing key in the Record<AppIconId, ...>
type but had been ignored.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 15:08:02 +02:00
Till JS
f0faae0fb9 feat(mana/web): same-origin proxy for /api/v1/who/* → mana-api
Replaces the cross-origin call to https://mana-api.mana.how with a
SvelteKit catch-all server route that proxies internally to the
mana-api container over the docker network.

Why
---
The mana-api.mana.how cloudflared route was added as part of the
production deploy of apps/api, but reloading the cloudflared
LaunchDaemon to pick up the new ingress rule needs sudo. The deploy
automation runs unattended (no interactive password prompt), so
the cloudflared route ends up registered with Cloudflare DNS but
not yet served by the local tunnel — every browser request to
mana-api.mana.how gets a 404 from the catch-all rule until someone
manually restarts the daemon.

Same-origin proxy through mana-web sidesteps the whole problem:

  browser → cloudflared → mana-web (mana.how) → mana-api (docker net)

mana.how is already routed, mana-web is already up, mana-api is
already on the same docker network — no new cloudflared work
needed. The deploy is now fully sudo-free and self-contained.

What's in this commit
---------------------
  routes/api/v1/who/[...path]/+server.ts (NEW)
    Catch-all SvelteKit handler. Forwards GET/POST/PUT/DELETE to
    http://mana-api:3060/api/v1/who/<path> with the Authorization
    header from the incoming request. 30s timeout, body streamed
    through, status + content-type passed through 1:1, errors
    surface as 502 so DevTools clearly distinguishes "proxy
    failed" from "handler crashed".

  modules/who/stores/games.svelte.ts
    Drop the getManaApiUrl() import. API_BASE is now the constant
    string '/api/v1/who' — same-origin, no env injection needed.

  modules/who/ListView.svelte
    Same change for the deck-catalogue fetch on mount.

The MANA_API_INTERNAL_URL env var on the proxy lets the upstream
hostname be overridden for local-dev use (default
http://mana-api:3060 matches the docker compose service name).

Trade-off: one extra hop (mana-web in the middle) for every
request. Measured in single-digit ms over the bridge network so
the practical cost is invisible. The big win is the sudo-free
deploy.

Pattern can be reused for the other apps/api modules as their
compute features come online in production — same shape, just
swap [...path] segment to /api/v1/calendar/[...path],
/api/v1/picture/[...path], etc.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 15:06:04 +02:00
Till JS
ab0ca99239 feat(mana/web): app picker — autofocused search + alphabetical order
The "App hinzufügen" picker now sorts available apps alphabetically by
their (i18n-resolved) display name and shows an autofocused search input
above the list to filter quickly. Enter selects the first match.
PickerOverlay gains a `subheader` snippet slot so other pickers can
embed their own controls between header and list without having to
re-implement the shell.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 14:37:04 +02:00
Till JS
41c705a303 feat(mana/web): per-module icons + wire workbench title link
Adds an optional icon field to AppDescriptor and assigns a Phosphor icon
to all 33 registered apps (CheckSquare for todo, Calendar for calendar,
AddressBook for contacts, …). AppPage now passes both the icon and
titleHref={`/${appId}`} to PageShell, so workbench cards show the
module's icon next to the now-clickable title instead of the generic
color dot.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 14:28:01 +02:00
Till JS
a130f8e4c0 feat(mana/web): clickable page titles open route in new tab
PageShell gains an optional titleHref prop — when set, the header title
renders as an <a target="_blank"> with hover underline. Also wires this
into the homepage app gallery (shared-ui/AppsPage): the grid card title
is now an anchor to /{app.id}, while the rest of the card still opens
the existing detail modal. Card converted from <button> to role=button
so the nested anchor is valid HTML.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 14:27:51 +02:00
Till JS
b8bfc4d775 fix(branding): drop who module's required tier from beta to public
The initial requiredTier='beta' was an arbitrary RFC default — when I
first wired it up I was matching the status='beta' badge. But the
beta tier in this app means "early access via founder invite", not
"the feature is in beta". A signed-in standard user landing on /who
hit the AuthGate lock screen with "Standard < Beta required" instead
of being able to play the game.

Drop to 'public', which means "any signed-in user". The module is
still labeled status='beta' in the launcher (so it's flagged as new
+ unfinished), and the LLM calls behind it are credit-gated by the
existing chat-style consume flow — those are the actual gates that
matter for cost control.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 14:27:18 +02:00
Till JS
e3029ef80b fix(api/deploy): use mana-api.mana.how to avoid api.mana.how conflict
api.mana.how is already routed to mana-api-gateway (Go service on
port 3016) — has been since long before the apps/api consolidation.
Hijacking it would have broken whatever existing consumers point at
the gateway.

Switch the new unified Hono/Bun apps/api server to mana-api.mana.how
instead. Cloudflared tunnel route + Cloudflare DNS CNAME registered
on the Mac Mini side; mana-web's PUBLIC_MANA_API_URL_CLIENT updated
to match.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 14:21:06 +02:00
Till JS
2f00d9c5d3 feat(memoro): show title source label below the title input
Mirror the "Voxtral via mana-stt" label that already sits under the
transcript: a small italic line directly below the title input
showing which tier (and roughly which model) generated the title.
This way the user can see at a glance whether the title came from
the local rules engine, from Gemma 4 in their browser, from
gemma3:4b on the Mana server, or from Google Gemini — and can
decide whether to keep it or rewrite manually.

Storage:

  apps/mana/apps/web/src/lib/modules/memoro/llm-watcher.svelte.ts
    - When applying a completed title task, the watcher now also
      stamps memo.metadata.titleSource with the LlmTier string
      ('none' | 'browser' | 'mana-server' | 'cloud') from the queue
      row's `source` field. Stored in the existing plaintext metadata
      object — no encryption needed (the tier name isn't sensitive
      and the encryption registry for memos only covers
      title/intro/transcript). Existing metadata fields are
      spread-preserved so we don't accidentally wipe STT failure
      markers etc.

Manual override clears the marker:

  apps/mana/apps/web/src/lib/modules/memoro/stores/memos.svelte.ts
    - memosStore.update() now detects when `title` is in the diff
      and clears `metadata.titleSource` so the DetailView stops
      showing "via Mana-Server (gemma3:4b)" for a title the user
      typed themselves. Only fires when title is actually present
      in the update payload — non-title updates leave metadata alone
      so we don't blow away other markers.

Display:

  apps/mana/apps/web/src/lib/modules/memoro/views/DetailView.svelte
    - New TITLE_SOURCE_LABELS map gives each tier a human-readable
      label that surfaces the actual model name where known:
        none        → "Lokal (regelbasiert)"
        browser     → "Auf deinem Gerät (Gemma 4)"
        mana-server → "Mana-Server (gemma3:4b)"
        cloud       → "Google Gemini"
      We deliberately don't reuse @mana/shared-llm's tierLabel()
      because the model name is more informative than the abstract
      tier in this UX context.
    - $derived `titleSourceLabel` reads memo.metadata.titleSource
      and validates it via an isLlmTier type guard. Returns null
      (→ no label rendered) when:
        * the entity hasn't loaded yet
        * a title task is currently in flight (titleIsGenerating)
        * the title input is currently focused (user is editing)
        * the metadata field is missing or not a known tier value
    - New `<div class="source-label title-source-label">` slot
      between the title-row and the properties block, with a small
      CSS override (.title-source-label) for a tighter top gap and
      a slight left indent so it visually lines up under the input
      text rather than under the input border.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 14:19:59 +02:00
Till JS
7fa3afcdc7 fix(mana/web/sync): push fresh writes immediately via listener bridge
createUnifiedSync exported onPendingChange but nothing ever called it,
so the Dexie hook in database.ts recorded _pendingChanges rows that
the sync engine never heard about. Live writes only ever drained on
the next page reload (via drainLeftoverPending). Observed live as
fresh calendar/timeblocks writes piling up in _pendingChanges with
zero POST traffic to sync.mana.how.

Add a listener bridge: database.ts exposes setPendingChangeListener,
trackPendingChange invokes it after each successful _pendingChanges
insert, and sync.ts registers schedulePush (gated on a known channel)
inside startAll. stopAll clears the listener so a torn-down sync
engine can't get re-triggered by a stale callback.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 14:13:25 +02:00
Till JS
6cbb1f64d0 fix(api/Dockerfile): switch builder stage to node:20-alpine
oven/bun:1 doesn't ship with npm or pnpm, so the previous
`RUN npm install -g pnpm@9.15.0` failed with `/bin/sh: 1: npm: not
found` on the first Mac Mini build. Bun's own install command
doesn't honor pnpm-workspace.yaml, so we can't use it as a drop-in.

Switch the builder stage to node:20-alpine which has npm built in,
install pnpm there, resolve the workspace graph, then COPY the
finished tree into the bun runtime stage. The runtime stage stays
on oven/bun:1 — bun handles pnpm's node_modules/.pnpm symlink farm
natively, so the workspace layout works the same as it does on a
developer machine.

Tested locally: `docker compose -f docker-compose.macmini.yml build
mana-api` now succeeds through the install stage. The runtime
stage is unchanged.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 14:10:59 +02:00
Till JS
7750c46a12 feat(api): production deploy — Dockerfile + docker-compose service
Adds the missing production deployment artifacts for the unified
apps/api Hono/Bun server. Until now apps/api was code-only — built
during the consolidation sweep but never wired into the Mac Mini
compose stack, so all 17 product modules that depend on it
(calendar, todo, picture, planta, nutriphi, news, traces, presi,
music, contacts, storage, context, guides, research, chat, moodlit,
who) effectively had no backend in production. The frontend modules
shipped, but their compute calls fell through to localhost:3060 in
the browser and just failed.

This commit fixes the gap.

apps/api/Dockerfile (NEW)
-------------------------
Multi-stage Bun build that runs from the monorepo root so the four
workspace dependencies (@mana/shared-hono, @mana/shared-logger,
@mana/shared-storage, @mana/media-client) actually resolve. Builder
stage installs via pnpm with the --filter @mana/api... selector to
keep the install graph minimal; runtime stage copies the resulting
workspace tree (including the pnpm symlink farm) and runs the entry
script with bun directly — no compile step, since bun handles
TypeScript natively.

@mana/media-client lives under services/mana-media/packages/client,
not packages/, so the COPY path is the awkward
services/mana-media/packages/client → ./services/mana-media/packages/
client mirror to keep the workspace layout intact.

Healthcheck hits /health every 30s with a 15s start period — same
shape as the other Bun services in this compose file.

docker-compose.macmini.yml — new mana-api service
-------------------------------------------------
Slotted between glitchtip-worker and the games section. Build
context is the monorepo root (`.`) because the Dockerfile needs the
workspace tree. Container name `mana-api`, image `mana-api:local`,
mem_limit 384m (higher than the smaller Bun services because the
unified server holds 17 modules' route definitions + Drizzle schema
caches in memory).

Environment wires up everything apps/api needs:
  - MANA_AUTH_URL → mana-auth:3001 for JWT validation
  - MANA_LLM_URL → mana-llm:3025 for chat / picture / who LLM calls
  - MANA_SEARCH_URL → mana-search:3012 for guides / research
  - MANA_CREDITS_URL → mana-credits:3002 for credit validation
  - MANA_MEDIA_URL → mana-media:3011 for image uploads
  - DATABASE_URL → mana_platform Postgres for the few server-side
    state stores (research_results, presi share-links, traces guides)
  - MANA_SERVICE_KEY → for the credit/auth service-to-service calls
  - LOGGER_FORMAT=json → structured logs for grafana ingestion
  - CORS_ORIGINS=https://mana.how → only the unified web origin
    needs access, the standalone game frontends don't call this

Port 3060 is exposed on the host so cloudflared can route
api.mana.how → mana-api:3060 (separate Mac Mini side step, not
in this commit).

docker-compose.macmini.yml — mana-web wiring
--------------------------------------------
Two new env vars:
  PUBLIC_MANA_API_URL=http://mana-api:3060
  PUBLIC_MANA_API_URL_CLIENT=https://api.mana.how

The hooks.server.ts injection plumbing for window.__PUBLIC_MANA_API_URL__
already existed (added in an earlier sweep but never had a value to
inject). The CSP connect-src list and the SSR injection script tag
also already include PUBLIC_MANA_API_URL_CLIENT — so once the env
arrives, the existing client-side getManaApiUrl() helper picks it
up automatically.

mana-web also gets a depends_on entry on mana-api with
condition: service_healthy so the web container doesn't start
serving requests against a dead API.

Verification
------------
docker compose -f docker-compose.macmini.yml config validates
cleanly (no YAML errors). Image build is NOT exercised in this
commit — that happens on the Mac Mini via build-app.sh after the
push lands.

Out of scope for this commit (Mac Mini side, manual steps):
  1. ssh mana-server, git pull
  2. ./scripts/mac-mini/build-app.sh mana-api  (first build, ~3-5 min)
  3. ./scripts/mac-mini/build-app.sh mana-web  (rebuild with new env)
  4. cloudflared route: add api.mana.how → mana-api:3060 to
     ~/.cloudflared/config.yml and `systemctl restart cloudflared`
  5. Test https://api.mana.how/health from anywhere
  6. Test https://mana.how/who in a browser

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 14:08:59 +02:00
Till JS
233cf28cf2 fix(shared-llm): switch remote backend to non-streaming, drop credentials
Diagnosis from the user's last test pinpointed the bug: mana-llm
returns totalFrames=0 (no SSE frames at all) when called from the
browser, but works perfectly when called via curl from the same host
with the same payload. Two compounding causes:

  1. credentials: 'include' in our fetch combined with mana-llm's
     CORS headers silently breaks the response body. This is the
     classic "Access-Control-Allow-Origin: * + Allow-Credentials: true"
     mismatch — browsers reject the response per spec but report it
     as a 0-byte success rather than an error.

  2. Streaming over CORS adds a second layer of fragility. Even if
     credentials weren't an issue, the browser fetch API's response
     body for SSE under CORS depends on a specific combination of
     server headers we evidently don't have.

Fix: drop both the streaming AND the credentials.

  - stream: false in the request body. Single JSON response per call,
    much friendlier to the browser fetch API.
  - No `credentials` field at all (default 'same-origin' for cross-
    origin requests = don't send cookies). mana-llm's API key
    middleware accepts anonymous requests, so we don't need to send
    any auth context.
  - Parse the response as `await res.json()` instead of streaming
    SSE chunks. Pull `choice.message.content` (or fall back to
    `choice.text` for legacy completions API responses).
  - Backwards-compatibility shim for `req.onToken`: if a caller
    registered a token callback (legacy chat-style streaming UX),
    fire it ONCE with the full content at the end. The current
    orchestrator + queue model never consumes per-token streams for
    remote tiers, so this is a degraded-but-equivalent path. The
    playground module uses its own client and isn't affected.

Verified manually with curl:

  $ curl -X POST https://llm.mana.how/v1/chat/completions \
      -H 'Content-Type: application/json' \
      -d '{"model":"gemma3:4b","messages":[{"role":"user","content":"Hi"}],"max_tokens":50,"stream":false}'
  → returns clean JSON with `choices[0].message.content` populated.

  Same call with `stream: true` from the same host also works (full
  SSE frames come back). The bug really is browser+credentials
  specific, not a service bug.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 14:07:06 +02:00
Till JS
ad618930b5 chore(planta): remove orphan apps/planta/packages/shared
The package was a leftover from the per-product Planta backend that
got consolidated into apps/api a while back. Repo-wide grep for
@planta/shared returns zero matches — it had no consumers.

- Delete the four files (package.json, src/index.ts, src/types/index.ts,
  tsconfig.json)
- Update apps/planta/CLAUDE.md to reflect the cleanup (the previous
  note pointed at a refactoring audit doc that already tracked it)
- Refresh pnpm-lock.yaml so the workspace member is no longer pinned

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 14:06:11 +02:00
Till JS
b68fcc8fd1 fix(mana/web/planta): /planta routes — layout fix, i18n, nullability, button nesting
- Add /planta/+layout.svelte that provides every live-query context
  the legacy routes already reference via getContext (plants,
  plantPhotos, wateringSchedules, wateringLogs, plantTags, tags).
  Without this layout the legacy routes would crash at runtime with
  "Cannot read properties of undefined (reading 'value')" — they had
  always relied on a provider that did not exist anywhere in the repo.
- Replace every hardcoded German label across +page.svelte,
  [id]/+page.svelte, add/+page.svelte and tags/+page.svelte with
  $_('planta.*') calls so the locale switcher actually changes the
  copy. Health/light/humidity helper maps converted from German maps
  to switch + i18n lookups.
- Fix the 4 type errors in [id]/+page.svelte caused by SvelteKit's
  $page.params.id being string | undefined: coerce to '' so the
  helpers stay strictly typed and "missing id" still resolves to
  "not found".
- Fix the SSR hydration warning on /planta from a <button> nested
  inside another <button> in the plant grid. Replaced the outer
  card with <div role="link" tabindex="0"> + Enter/Space keydown
  handler so the inner "water now" button is structurally legal.
- formatDate calls drop the hardcoded de-DE locale and use the
  browser locale (undefined) instead.
- Toast notifications on every mutation in these routes so failures
  are user-visible (handleWater, handleDelete, savePlant).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 14:05:56 +02:00
Till JS
60fedbb611 feat(mana/web/planta): photo upload, AI identification, tags, watering history, i18n + tests
Brings the planta module to production-ready state:

- Photo upload UI in the workbench DetailView (file picker, primary
  selection, removal, hover overlay) wired to /api/v1/planta/photos/upload
- AI plant identification trigger that calls /analysis/identify on the
  primary photo and shows a result card with apply-to-plant CTA;
  applyIdentification only fills empty fields by default to avoid
  clobbering user edits
- Tag picker (chip UI + dropdown) backed by plantTagOps junction
- Watering history list (last 5 logs) in DetailView
- Full i18n: every locale (de/en/es/fr/it) now has plant/list/photo/
  identify/errors/success keys; ListView and DetailView consume them
  via $_('planta.*') instead of hardcoded German
- Toast notifications on every mutation success/failure path
- mutations.ts refactored: methods now throw on failure instead of
  swallowing errors and returning null, so callers can surface them
- New api.ts client for the two server-only operations (upload, identify)
- New photoMutations + plantMutations.applyIdentification helpers
- quick-input-adapter type fix: stop referencing the non-existent
  parsed.species field; create plants through plantMutations.create
  so encryption + timestamps run, and decrypt names before substring
  search
- 20 new tests:
  - queries.test.ts (13 pure-function tests for getDaysUntilWatering /
    isWateringOverdue / getScheduleForPlant / getLogsForPlant)
  - mutations.test.ts (7 fake-indexeddb integration tests for
    wateringMutations.logWatering — log appended, schedule re-anchored,
    soft-deleted schedules skipped, multi-call uniqueness)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 14:05:13 +02:00
Till JS
b83e8d6d92 fix(mana/web): seed pending-changes badge count on mount
Some checks are pending
CI / Build mana-api-gateway (push) Blocked by required conditions
CI / Build mana-crawler (push) Blocked by required conditions
CI / Build mana-media (push) Blocked by required conditions
CI / Build mana-credits (push) Blocked by required conditions
CI / Build mana-web (push) Blocked by required conditions
CI / Build chat-backend (push) Blocked by required conditions
CI / Build chat-web (push) Blocked by required conditions
CI / Build todo-backend (push) Blocked by required conditions
CI / Build todo-web (push) Blocked by required conditions
CI / Build calendar-backend (push) Blocked by required conditions
CI / Build calendar-web (push) Blocked by required conditions
CI / Build clock-web (push) Blocked by required conditions
CI / Build contacts-backend (push) Blocked by required conditions
CI / Build contacts-web (push) Blocked by required conditions
CI / Build presi-web (push) Blocked by required conditions
CI / Build storage-backend (push) Blocked by required conditions
CI / Build storage-web (push) Blocked by required conditions
CI / Build telegram-stats-bot (push) Blocked by required conditions
CI / Build nutriphi-backend (push) Blocked by required conditions
CI / Build nutriphi-web (push) Blocked by required conditions
CI / Build skilltree-web (push) Blocked by required conditions
Docker Validate / Validate Dockerfiles (push) Waiting to run
Docker Validate / Build calendar-web (push) Blocked by required conditions
Docker Validate / Build todo-backend (push) Blocked by required conditions
Docker Validate / Build todo-web (push) Blocked by required conditions
Docker Validate / Build zitare-web (push) Blocked by required conditions
Docker Validate / Build mana-auth (push) Blocked by required conditions
Docker Validate / Build mana-sync (push) Blocked by required conditions
Docker Validate / Build mana-media (push) Blocked by required conditions
Mirror to Forgejo / Push to Forgejo (push) Waiting to run
The OfflineIndicator badge shows networkStore.pendingCount, which is
only refreshed inside unifiedSync.onStatusChange. That callback fires
on transitions only — so on a fresh tab where sync stays idle, the
badge sticks at the last persisted value (or 0). Observed live as
"13 pending" while _pendingChanges actually held 27 rows.

Extract refreshPendingCount as a local helper and call it once right
after startAll() to seed the badge. The transition-driven refresh
inside onStatusChange now reuses the same helper.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 13:25:06 +02:00
Till JS
be8c0482b7 fix(mana/web/sync): drain leftover pending changes on startup
startAll() registered channels but never kicked a push for changes
that survived across page reloads. schedulePush only fires from the
Dexie hook on fresh writes, so any pending row from a previous session
sat in _pendingChanges until the user happened to mutate the same
table again — observed live as 27 pending across mana/memoro/places
that never reached the server despite a healthy sync route.

Add drainLeftoverPending() called once at the end of startAll(): scan
_pendingChanges for distinct appIds and schedulePush each registered
channel. Fire-and-forget; errors swallowed because the push retry
path already handles failures.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 13:24:51 +02:00
Till JS
0450c86527 fix(shared-llm): SSE shape diagnostics + simpler title prompt + fragment detection
User test on the mana-server tier showed Ollama gemma3:4b returning
LITERALLY empty content for the title task, which is much weirder
than the small browser model misbehaving. Three layered fixes plus
diagnostics that will tell us what's actually happening over the
wire next time.

1. remote.ts: SSE diagnostics + liberal field shape

   The mana-llm /v1/chat/completions endpoint claims OpenAI
   compatibility, but different upstream providers (Ollama, OpenAI,
   Gemini) wrap their token text in different field paths inside
   the SSE delta. Be liberal in what we accept:
     - choice.delta.content   (canonical OpenAI)
     - choice.delta.text      (some Ollama-compat shims)
     - choice.message.content (non-streaming response embedded in stream)
     - choice.text            (legacy completion API)

   Plus: count totalFrames + dataFrames + capture firstFrameRaw +
   firstFrameParsed during the stream. When `collected` is empty at
   the end of the stream, dump all of that to console.warn so the
   next test session shows us exactly what mana-llm is sending. This
   is the only reliable way to debug "empty completion" without a
   network sniffer in the user's browser.

2. generate-title.ts: drop few-shot, use simple system+user prompt

   The previous few-shot prompt with three `Aufnahme: "..."\nTitel: ...`
   examples was apparently too much for Ollama gemma3:4b on the
   mana-server tier — it returned literal "" for reasons we don't
   fully understand (chat-template confusion with the embedded
   quotes? multi-section format? some quirk of how mana-llm formats
   the messages for Ollama?). Either way, the failure mode is clear.

   Replace with a minimal two-message format:
     - system: "Du erzeugst einen kurzen Titel (3-5 Wörter)..."
     - user: <transcript>
   Same instruction, much simpler shape. Bumped maxTokens 24 → 32
   to give the model breathing room.

3. generate-title.ts: rules fallback detects sentence fragments

   Even when the LLM fails and we fall through to runRules, the
   previous heuristic for medium-length transcripts (10-20 words)
   would extract the first 7 words verbatim — which for a typical
   "Eine kleine Testaufnahme um zu sehen ob alles funktioniert" memo
   produces "Eine kleine Testaufnahme, um zu sehen, ob" as the
   "title". That's a sentence fragment ending mid-thought, not a
   title. Worse than "Memo vom 9. April 2026".

   Add a "looks like a sentence fragment" heuristic: if the last
   word of the extracted slice is a German stop-word or article
   (und/oder/wenn/ob/zu/um/der/die/das/ein/...) the result is
   clearly mid-clause. In that case fall through to dateLabel()
   instead of writing the fragment.

   Stop-word list is curated to 30 entries — common conjunctions,
   articles, prepositions, auxiliaries. Not exhaustive but catches
   the typical "first 7 words of a German sentence" failure mode.

After this commit lands, the next test will surface in the console
EITHER:
  - the actual delta shape mana-llm is using (so we know if our
    parser is wrong or if the model is genuinely silent)
  - a real LLM-generated title (if the simpler prompt worked)
  - "Memo vom <date>" via the rules fallback (if the LLM still
    fails but the rules fragment detection caught the bad slice)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 13:12:13 +02:00
Till JS
ef780cf069 chore: remove whopixels — superseded by the who module
Standalone games/whopixels has been replaced by the who module that
landed in the previous four commits. The whopixels Phaser RPG world
wrapper around the chat (~80% of the source) was deliberately
dropped during the port; the chat loop, the 26 historical-figure
personalities, and the [IDENTITY_REVEALED] sentinel trick all live
on inside apps/api/src/modules/who/.

What's gone in this commit:

  games/whopixels/                    — 33 source files, ~3.6k LOC
    Phaser scenes (Boot, MainMenu, Game, RPG)
    Managers (Player, NPC, World, Touch, Sound, Storage, ChatUI)
    Vanilla http server with hand-rolled rate limit + Azure OpenAI
    Static assets, css, jsconfig

  docker-compose.macmini.yml          — `whopixels` service block
    Build context, Azure OpenAI env wiring, healthcheck. Port 5100
    is now free. Comment left in place explaining the migration so
    a future reader doesn't wonder why this gap exists.

What still has to happen outside this PR (Mac Mini side):
  - docker rm -f mana-game-whopixels
  - cloudflared route for whopixels.mana.how needs a redirect or
    archive (sub-domain stops resolving once the container is gone
    unless DNS / tunnel routes are touched separately)

The migration is non-destructive in terms of data: whopixels stored
no per-user state — sessions were in-memory, conversation history
lived only in the browser tab. There's nothing to migrate.

Net delta of the entire who module migration (5 commits combined):
  +1880 LOC (RFC + backend + module + UI + branding)
  -3666 LOC (whopixels)
  ───────
  -1786 LOC

Closes Phase A.6 of docs/WHO_MODULE.md.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 13:11:36 +02:00
Till JS
65c4d935d5 feat(shared-branding): register the who module in mana-apps + new icon
Two changes:

  app-icons.ts
    Add APP_ICONS.who — purple gradient theatre-mask silhouette with
    a question mark, references the "guess who's behind the disguise"
    mechanic. Stays in the same hand-rolled SVG-data-URL style as the
    other module icons (no external assets, no font dependencies).

  mana-apps.ts
    New ManaApp entry: id 'who', name 'Who', purple #a855f7,
    requiredTier 'beta', status 'beta'. Description in DE + EN
    explains the mechanic and lists the four shipping decks.
    Slotted at the end of MANA_APPS so the existing app order is
    preserved.

These are the last pieces needed for the unified Mana app launcher
to surface the new module. With this commit + the previous two, the
module is end-to-end visible: launcher → /(app)/who route → ListView
with deck picker → PlayView chat loop.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 13:10:55 +02:00
Till JS
f24438f778 feat(mana/web): who module — frontend (game store + UI + routes)
Client side of the who module. Standard Mana module pattern: types,
collections (Dexie), queries (live), store (mutations), UI components,
routes. Plus three integration points (data layer registries).

Module files
------------
  types.ts
    Two Dexie record interfaces (LocalWhoGame, LocalWhoMessage) and
    matching view types. Server response shapes (WhoChatResponse,
    WhoRandomResponse, WhoGuessResponse) live here too so the store
    and UI both type-check against the same wire contract.

  collections.ts
    Dexie table accessors. No guest seed — the picker handles empty
    state directly.

  queries.ts
    Three liveQueries (allGames$, gameByIdLive, messagesForGameLive)
    that decrypt the encrypted-at-rest fields before returning view
    types. The messages query uses the [gameId+createdAt] composite
    index for ordering. toWhoGame / toWhoMessage converters bridge
    the BaseRecord-extended local types to the public view types.

  module.config.ts
    Standard ModuleConfig: appId='who', tables=[whoGames as 'games',
    whoMessages as 'messages']. The syncName remap means the unified
    Dexie table whoGames syncs to mana-sync's `games` collection
    under appId 'who' — keeps the wire format clean.

  stores/games.svelte.ts
    The mutation surface. Five public methods:
      - start(deckId)        → POST /who/random + insert LocalWhoGame
      - sendMessage(id, txt) → optimistic insert + POST /who/chat +
                               insert NPC reply + (on win) flip status
      - submitGuess(id, txt) → POST /who/guess + (on match) flip
      - surrender(id)        → status=surrendered + finishedAt
      - setNotes(id, notes)  → encrypted post-game notes
      - deleteGame(id)       → soft-delete game + cascade messages
    All writes go through encryptRecord for encrypted-at-rest fields.

UI components
-------------
  ListView.svelte
    Module landing page. Header + 4 deck cards (loaded from
    GET /api/v1/who/decks on mount) + past-games list. Picking a
    deck calls store.start() and navigates to the play view. Past
    games are clickable (read-only for finished games) and
    deletable.

  views/PlayView.svelte
    The chat-loop screen. Header with deck/difficulty + back button
    + Tippen/Aufgeben actions while playing. Scrollable message
    area with bubbles (user purple-tinted, NPC white-tinted).
    Textarea input with Enter-to-send + sending disabled state.
    On reveal: result banner with "Erraten in N Nachrichten!" and
    the resolved name. Post-game: input area swaps to a notes
    textarea with debounced auto-save. Explicit guess modal as
    fallback when the LLM forgets to emit the sentinel.

Routes
------
  /(app)/who                 → ListView wrapper
  /(app)/who/play/[gameId]   → PlayView wrapper, $page.params.gameId

Registry plumbing
-----------------
  database.ts
    Two new Dexie tables in version(1):
      whoGames: 'id, status, deckId, startedAt, finishedAt, [status+startedAt]'
      whoMessages: 'id, gameId, sender, createdAt, [gameId+createdAt]'

  module-registry.ts
    Imports whoModuleConfig and adds to MODULE_CONFIGS. The sync
    engine picks up the appId/table mapping automatically — no
    edits needed in sync.ts.

  crypto/registry.ts
    Two entries:
      whoGames:    { enabled: true, fields: ['revealedName', 'notes'] }
      whoMessages: { enabled: true, fields: ['content'] }
    All other fields stay plaintext for index/sort/filter.

Closes Phase A.2 / A.3 / A.4 / A.5 of docs/WHO_MODULE.md.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 13:10:34 +02:00
Till JS
74b5808496 feat(api): who module — LLM character-guessing endpoint cluster
Server side of the who module. Three endpoints under /api/v1/who/*:

  POST /chat
    Hot path. Body: { gameId, characterId, message, history[] }.
    Looks up character by id (server-side only — clients never see
    personalities), builds a system prompt instructing the LLM to
    roleplay the figure WITHOUT revealing its name and to append
    [IDENTITY_REVEALED] when the player has guessed correctly,
    forwards to mana-llm. Response: { reply, identityRevealed,
    characterName? } — characterName only present on win.

    Same credit pattern as chat module: validateCredits + consume
    after the LLM call succeeds. Operation 'AI_WHO', cheap (0.1
    credit) for local models, 5 for cloud.

  POST /random
    Picks a random character from a deck and returns just the id +
    category + difficulty. Frontend uses this to start a new game
    without ever knowing the personality pool. Server-side
    randomness so a determined attacker can't predict picks.

  POST /guess
    Explicit "I think it's X" submission. Fallback path for when
    the LLM forgets to emit the sentinel even though the player
    clearly said the right name. Deterministic lowercase substring
    match against the canonical name (with diacritic stripping +
    last-name-only matching for unambiguous figures like "Tesla").

  GET /decks
    Public deck catalogue with counts and category labels. Zero
    sensitive data — never leaks names or personalities. Used by
    the picker UI on mount.

data/characters.ts holds 37 characters: the original 26 from
whopixels verbatim + 11 new for the antiquity / women / inventors
decks. Each entry is in one or more decks via a `decks` array, so
e.g. Marie Curie shows up in both `historical` and `women`. Adding
a new character is one entry.

The system prompt is the carefully-tested German prompt from the
original whopixels server.js — tells the LLM to respond in the
language the user writes, give subtle hints, never directly say
"I am X", and emit the sentinel only on a correct guess.

The explicit-guess matcher catches three patterns:
  1. Exact normalized match ("Marie Curie" === "marie curie")
  2. Last-name-only ("Curie" matches "Marie Curie")
  3. Guess-contains-name ("I think it's Marie Curie" → contains)

Closes Phase A.1 of docs/WHO_MODULE.md.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 13:09:46 +02:00
Till JS
32419a679e docs(who): RFC for the historical-figure guessing module
Pre-implementation design doc for porting the core mechanic of the
standalone games/whopixels Phaser app into a normal Mana module.

The doc covers:
  - The actual mechanic (LLM roleplays a historical figure, user
    guesses the name through conversation, [IDENTITY_REVEALED]
    sentinel triggers the win) — clearing up the misleading
    "pixel-art editor" framing in the legacy README
  - Why personalities have to stay server-side (open DevTools, grep
    bundle, game over)
  - Module architecture: two Dexie tables, one Hono endpoint cluster
    in apps/api, encryption-registry entry, mana-apps registry entry
  - Four shipping decks (historical / women / antiquity / inventors)
  - The fallback explicit-guess endpoint for when the LLM forgets
    its sentinel
  - Build order, scope, risks, and what's deferred to Phase B
    (daily challenge, leaderboard) and Phase C (generative variant)

Default decisions baked in: name `who`, sync-only LLM (no SSE in v1),
free hint button with usage counter, daily challenge deferred,
whopixels deletion in the same PR as the new module.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 13:08:07 +02:00
Till JS
43d19b5900 docs(shared-tailwind/themes): document hsl() wrap rule + token allowlist
Extends the top-of-file comment with the lessons learned from the P5
visual-track migration:

- Why bare var(--color-X) silently fails (browser falls back to inherit;
  the zitare white-on-white regression that triggered the rewrite).
- Concrete / examples for the three rewrap patterns (plain ref, ref
  with fallback, color-mix opacity).
- The brand-literal carve-out — which palettes deliberately stay as
  literal colors and why they should not be migrated.
- The stable token allowlist + the four removed names that future code
  should not reference (--color-info / --color-text / --color-destructive
  / --color-surface / --color-input) and the right replacements.
- A note on the runtime story: createThemeStore writes the same names so
  static defaults handle first paint and hydration takes over after.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 13:05:16 +02:00
Till JS
d8591b320b fix(generate-title): few-shot prompt + rolling cleanup + date label for short transcripts
User test on browser tier (Gemma 4 E2B) showed two compounding bugs:

  1. The LLM produces empty content. The cleanup chain strips it to ""
     and falls through to runRules.
  2. runRules takes the first 7 words of the transcript. For short
     voice memos like "So erneut eine kleine Testaufnahme hier"
     (6 words) that means the entire transcript becomes the title —
     not actually a title, just the recording verbatim.

User log:
  [memoro] enqueued title task ...
  [generateTitle] LLM returned empty after cleanup, falling back to rules
  [memoro-llm-watcher] writing title to memo X: "So erneut eine kleine Testaufnahme hier"

Three changes to fix the actual quality, not just the empty-string
symptom from the previous commit:

1. Rewrite the LLM prompt as few-shot

   Replace the previous "Du erstellst kurze Titel — kein Markdown,
   keine Anführungszeichen, keine Vorrede, kein Punkt am Ende" prompt
   (a wall of negative constraints that small instruct models like
   Gemma 4 E2B handle poorly) with a few-shot user-only message:

     Erstelle einen kurzen Titel (3-5 Wörter) für die folgende Aufnahme.

     Beispiel 1:
     Aufnahme: "Erinnere mich daran, morgen Vormittag den Müll
                rauszubringen, bevor die Müllabfuhr kommt."
     Titel: Erinnerung Müll rausbringen

     Beispiel 2: ... (Idee Präsentation Demo-Start)
     Beispiel 3: ... (Steuererklärung 2025)

     Aufnahme: "<user transcript>"
     Titel:

   Small instruct models complete the pattern much more reliably
   than they obey negative constraints. The expected continuation is
   just the title text, no punctuation, no markdown, no preamble.

2. Rolling cleanup that won't go to empty

   The previous cleanup chain (`.trim().replace(quotes).replace(dots).trim()`)
   could end up with "" if the model emitted only `.` or `**.**` or
   similar. Replace with a four-stage chain that picks the FIRST
   non-empty stage from the bottom up:

     trimmed     = result.content.trim()
     stripFences = first line only (kills any model rambling)
     stripQuotes = strip surrounding quotes/markdown markers
     stripDots   = strip trailing dots
     cleaned     = stripDots || stripQuotes || stripFences || trimmed

   This way "Test." → "Test" but `"."` → `"."` (kept as-is rather
   than stripped to empty). The runRules fallback only fires when
   the model truly emits nothing usable in any stage.

3. runRules is smarter about short transcripts

   For voice memos with ≤8 words in the first sentence, the "title"
   would just be the whole transcript echoed back. That's not useful.
   The new threshold: short transcripts get a date label instead
   ("Memo vom 9. April 2026"), longer ones still get the first-N-words
   snippet. The threshold is empirical — short voice memos benefit
   from a date marker, longer ones can spare a few words for a snippet.

   Extracted dateLabel() to a module-scope function so both rulesImpl
   (for empty/short transcripts) and the watcher's last-resort
   backstop can format dates consistently.

Diagnostic: log the RAW LLM output before cleanup so the next test
session shows exactly what Gemma is producing. If the model is still
emitting only punctuation despite the few-shot prompt, the log will
show `"\n"` or `"."` and we'll know the bug is in the inference path
rather than the cleanup.

After this commit, the user-visible result for a 6-word transcript
on the browser tier should be:
  - LLM produces something real ("Test der Sprachaufnahme") → write it
  - LLM produces nothing → rules → "Memo vom 9. April 2026"
  - both fail somehow → watcher's date backstop → same
  - never the verbatim transcript

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 13:03:16 +02:00
Till JS
ea8ca13d37 fix(mana/web): wrap bare var(--color-X) refs in hsl() across 19 files (P5)
These were latent rendering bugs: --color-X holds raw HSL channels at
runtime (set by createThemeStore), so a bare var(--color-foreground) is
not a valid CSS color value — the browser falls back to inherited and
the affected elements render with the wrong color (often invisible
text on the same-colored background).

Mechanical wrap of every bare reference in the affected files:
  var(--color-X)              → hsl(var(--color-X))
  var(--color-X, #fallback)   → hsl(var(--color-X))   (fallback dropped)
  color-mix(... var(--color-X) N%, transparent)
                              → hsl(var(--color-X) / 0.NN)

Also re-mapped two long-removed token names:
  --color-surface     → --color-muted    (subtle surface intent)
  --color-destructive → --color-error    (semantic alias)

190 refs across 19 files (habits, photos, notes, places, todo, cycles
helpers + their parent route shells). Brand-literal hex/rgba colors
left untouched (cycles pink, sport/category palettes, indigo→violet
gradients, photo placeholder gradients).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 13:02:33 +02:00
Till JS
9760269e9f fix(memoro): generateTitle empty-result fallback + watcher diagnostics
User test surfaced the actual auto-title bug: the entire pipeline
(enqueue → process → watcher) works correctly, but the task result
itself is empty:

  [memoro] enqueued title task { taskId, memoId }
  [memoro-llm-watcher] saw 1 done title task(s)
  [memoro-llm-watcher] writing title to memo XXX: ""
  [memoro-llm-watcher] applied + cleared row YYY

The watcher faithfully wrote "" to memo.title, the input placeholder
showed "Titel..." again, and we looked stuck. Three layered fixes so
this can't bite us in any execution path going forward.

1. generate-title.ts: extract rules logic + use it as runLlm fallback

   Pulled the deterministic first-sentence heuristic into a private
   `rulesImpl()` function so both `runLlm` and `runRules` can call
   it. runLlm now invokes rulesImpl as a fallback when the cleaned
   LLM output is empty. This catches the case where the model emits
   only punctuation, only special tokens, or only whitespace — all
   of which collapse to "" after my cleanup chain (`.trim()` → strip
   surrounding quotes/markdown → strip trailing dots → `.trim()`).

   The most likely real-world trigger: Gemma 4 occasionally emits a
   single `.` for short prompts that hit its over-strict
   "answer with ONLY the title" instruction. The cleanup turns
   "." into "" and we lose the result.

2. llm-watcher.svelte.ts: date-based backstop for any empty result

   Belt-and-suspenders: even if a future task implementation forgets
   the rules fallback, the watcher itself now guarantees a non-empty
   title. When `row.result.trim()` is empty, synthesize a label like
   "Memo vom 9. April 2026" from the memo's createdAt (or the
   current date if createdAt is also broken). The user always sees a
   real title — never an empty placeholder.

   Same write path otherwise (encryptRecord + memoTable.update +
   delete queue row), just with the guaranteed-non-empty value.

3. llm-watcher.svelte.ts: enhanced diagnostic logging

   The "writing title" log now includes `row.source` (which tier
   actually executed) and `row.attempts`, so the next time we see
   weird behavior we can tell at a glance whether it was the
   browser tier, the rules tier, or the server. The empty-result
   path logs `console.warn` (not info) with the raw result via
   JSON.stringify so we see exactly what came back ("", ".", "  ",
   undefined-coerced-to-string, etc.).

After this commit lands:
  - Tier 0 user: runRules returns at minimum "Ohne Titel" (its
    own fallback). The watcher writes that.
  - Browser tier with empty Gemma output: runLlm now falls through
    to rulesImpl which also can't return empty. The watcher writes
    the rules-tier output.
  - Any other freak case where the result is still empty: the
    watcher's date-based backstop kicks in. "Memo vom <date>".

So the user-visible "stuck on empty title" symptom is impossible in
all three layers.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 12:54:06 +02:00
Till JS
0987b08185 style(mana/web): migrate (app) page-level routes to theme tokens (P5)
calendar, contacts, finance, spiral, todo route shells: bare var()
references → wrapped hsl(), broken rgba/hex fallback chains dropped.

DnD overlay (`.mana-drop-target-hover` / `-success`) is duplicated
inline in calendar/contacts/todo since it's a `:global()` rule each
route declares for itself; all three now read --color-primary +
--color-success for the drop animation instead of literal indigo/green.

finance: income=success, expense=error, type-toggle uses
--color-error/--color-success with /0.15 + /0.3 alpha modifiers.

spiral: indigo→violet stat highlight + app-bar gradient stay literal
(spiral's brand mark is the indigo→violet ramp, not the app theme
primary). Danger button now uses --color-error.

Skipped: rsvp/[token] (public landing, deliberate rose palette outside
the auth-gated chrome) and observatory (cosmic-scenes brand palette,
already established as brand-legitimate).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 12:43:24 +02:00
Till JS
4423c03573 fix(docker): drop packages/shared-config (deleted) from sveltekit-base
Fourth stale package COPY in three days. The pattern is unfortunately
predictable: package gets removed in a parallel cleanup commit, the
Dockerfile.sveltekit-base entry stays behind, nobody notices because
nobody runs the base build manually anymore. Then is_base_image_stale
fires the next time something in packages/ changes and the build
falls over.

Long-term: add a pre-flight check to build-app.sh that validates
every COPY-referenced path actually exists before kicking off Docker.
Failing fast is much friendlier than failing 30 seconds into a Docker
layer.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 12:43:17 +02:00
Till JS
526d92f41c fix(memoro): diagnostic logs + loading states + transcription source label
User reported three issues after the Phase 5 + the encryption-decrypt
fix landed:

  1. Auto-title still doesn't appear (placeholder "Titel..." stays empty)
  2. No loading state visible while transcription / title are in flight
  3. Transcript should say which STT engine produced it

This commit ships diagnostics for issue 1 and concrete UX for 2 + 3.

Issue 1 — diagnostics (no fix yet, root cause unknown):

  Add console.info logs at every step of the auto-title pipeline so
  the next test session surfaces exactly where it breaks:

  - memos.svelte.ts after llmTaskQueue.enqueue() succeeds:
      "[memoro] enqueued title task { taskId, memoId }"
  - memos.svelte.ts on enqueue failure:
      "[memoro] failed to enqueue title task: <err>"
  - memoro/llm-watcher.svelte.ts on subscribe:
      "[memoro-llm-watcher] starting subscription"
  - watcher's next handler when rows arrive:
      "[memoro-llm-watcher] saw N done title task(s)"
  - applyRow logs each step: drop / skip / write / consume

  Refactor: extract per-row logic into applyRow() so the next handler
  loop can wrap each row in try/catch — a single bad row won't crash
  the watcher and prevent later rows from being processed.

  Belt-and-suspenders startup sweep: run a one-shot manual sweep of
  done rows immediately after subscribing. Dexie liveQuery sometimes
  misses the first emission when the subscription is set up in the
  same microtask as a recent table update; the sweep catches any
  done rows that already exist from a previous tab session OR that
  were written between layout mount and subscription start.

  Encryption check fix: the previous skip-if-manual-title check
  read `memo.title?.trim()` after Dexie.get(), but Dexie reads
  return the ENCRYPTED row (no decrypt hook) — so memo.title is
  either null/undefined (no manual title) OR an `enc:1:...` blob
  (manual title set). Either way, presence-check is enough; no
  need to decrypt to know whether the user filled it in. The old
  code happened to work because trim() on a non-empty string
  returns truthy regardless. Comment now spells this out.

Issue 2 — visible loading states:

  apps/mana/apps/web/src/lib/modules/memoro/views/DetailView.svelte

  Transcript area now branches on processingStatus:

    - processing → "Wird transkribiert…" with three pulsing dots
                   (CSS @keyframes loadingPulse)
    - failed     → red error message + manual retry hint
    - completed + transcript → the transcript itself + source label
    - completed + no transcript → italic "Kein Transkript vorhanden."

  Title input placeholder swaps to "Titel wird generiert…" while a
  generateTitleTask for this memo is in pending or running state.
  The check uses a Dexie liveQuery against llmQueueDb.tasks via the
  [refType+refId] compound index, returning the most recent task row.
  Reactive — the placeholder switches back to plain "Titel…" the
  moment the watcher writes the title and deletes the queue row.

Issue 3 — transcription source label:

  Below the transcript: a small italic "Voxtral via mana-stt" label.
  Hardcoded to Voxtral because that's services/mana-stt's default
  model (DEFAULT_MODEL = "mistralai/Voxtral-Mini-3B-2507" in
  voxtral_service.py). If we ever route to Whisper or another model
  per-request, the label will need to come from the response payload
  rather than be hardcoded — Phase 5.5 work.

After this commit lands, the test loop is: record a memo, watch the
browser console for the [memoro] / [memoro-llm-watcher] log lines.
Whichever step is missing identifies the broken link.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 12:41:28 +02:00
Till JS
a7fbd29a67 style(mana/web): migrate photos/times/contacts module helpers to theme tokens (P5)
photos/PhotoCard + PhotoDetailModal: bare var() refs → hsl(var()), broken
fallbacks dropped. The lightbox backdrop stays explicit near-black — photo
viewing chrome is intentionally theme-neutral.

times/FocusCard: phase color (focus=red, break=green, idle=muted) reads
theme tokens via wrapped hsl() strings so the SVG ring tracks variants.
The bogus --color-input fallback is gone.

times/EntryItem: was referencing the long-removed shadcn aliases without
the --color- prefix (--border, --card, --foreground, --muted-foreground,
--primary, --input). Re-prefixed; --input → --background since we have
no separate input token. The delete button's text-red-500 / hover bg are
now --color-error so they track theme variants.

contacts/ContactPage: avatar + self-badge color-mix fallback chains
collapse to plain hsl(var(--color-primary) / 0.12).

The cycles pink #ec4899 birthday accent on the contact row stays literal
— it's a deliberate brand color, not theme intent.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 12:37:29 +02:00