Commit graph

3388 commits

Author SHA1 Message Date
Till JS
a480393bfd fix(ai): P1 batch — N+1 queries, vault-locked, debug hardening, timeout
Four P1 fixes from the AI Workbench audit:

#3 N+1 junction queries → batch lookups:
  - TagLinkOps gains getTagIdsForMany(entityIds) — single
    where(field).anyOf(ids).toArray() instead of N calls.
  - filterBySceneScopeBatch() uses a pre-fetched Map<id, tagId[]>.
  - All 4 module queries (notes, todo, contacts, calendar) migrated.
  - 500 notes now = 2 Dexie queries (records + junctions) instead of 501.

#4 Vault-locked detection in readLocalNote:
  - Catches VaultLockedError from decryptRecords.
  - Throws descriptive "Vault ist gesperrt" instead of returning null.
  - Tools surface it as a clear error to the planner ("bitte Vault
    entsperren") instead of "Notiz nicht gefunden".

#5 Debug log hardening:
  - Resolved-input content truncated to 500 chars before storage.
  - Time-based purge: entries older than 7 days auto-deleted.
  - Reduces privacy exposure if device is stolen/profile synced.

#6 Timeout 90s → 180s:
  - 5 LLM calls on slow models (Ollama/GPU) regularly hit 90s.
  - 180s gives comfortable headroom for the reasoning loop.

Audit doc updated with status markers.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 16:25:17 +02:00
Till JS
93358ed002 fix(ai): P0 — tool exception handling + mission run mutex
Two critical fixes from the AI Workbench audit:

1. Tool exceptions in the reasoning loop:
   stage(ps, aiActor) is now wrapped in try-catch. If a tool throws
   (Dexie error, vault locked, network timeout), the step is recorded
   as failed with the error message in the summary, and the loop
   continues with the next step. Previously, one broken tool crashed
   the entire iteration.

2. Concurrent mission scope interleaving:
   runMission() now serializes through a promise-based mutex. Two
   concurrent calls (double-click, cadence overlap) queue instead of
   interleaving — prevents the ambient withAgentScope() from stomping
   a running mission's scope with a different agent's tags.

   scope-context.ts also gains filterByScopeExplicit(records, scopeTagIds,
   getTagIds) — the explicit, race-safe variant that doesn't read
   ambient state. Callers that already have the scope should prefer it.

Also adds docs/optimizable/ai-workbench-audit-2026-04-16.md with the
full audit (P0–P2, 12 items).

Runner tests: 8/8.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 16:17:08 +02:00
Till JS
484761e475 fix(docker): remove deleted subscriptions pkg + add shared-ai to sveltekit-base
packages/subscriptions was deleted in the credits-merge cleanup; the
COPY line in the base Dockerfile broke every subsequent --no-cache
build. Also adds packages/shared-ai which was missing (webapp depends
on it since the Multi-Agent Workbench rollout).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 16:15:01 +02:00
Till JS
9dd2c64de2 fix(credits): replace octal literal placeholders with real toast messages
Three toast.success('\1') calls broke Vite's strict-mode parser on
startup. Replaced with proper German messages: purchase success,
cancel confirmation, reactivation confirmation.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 15:34:00 +02:00
Till JS
57c2bdb2ad feat(workbench): scope TagSelector in SceneHeader + agent auto-infer
The SceneHeader (left side of the workbench homepage) now shows a
TagSelector directly above the template-gallery button. Users can
assign scope tags to the active scene — filtering notes/tasks/contacts/
calendar to only records tagged with those scopes (+ untagged globally
visible).

Auto-inference: when a scene is bound to an agent via viewingAsAgentId
and the scene has no explicit scopeTagIds, the agent's scopeTagIds
are used instead. A small "via Agent" hint appears so the user knows
the scope comes from the binding. Explicitly setting scope tags on the
scene overrides the agent's.

New store methods: setSceneScopeTags + updateScene (both sync the
reactive scene-scope store when the active scene is affected).
patchScene accepts scopeTagIds in its type union.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 15:29:07 +02:00
Till JS
fe141e193e docs: add langfristige Roadmap-Punkte zu AI_AGENTS_IDEAS.md
Update the AI agents backlog with:
- Status update: mark SSE streaming, dynamic tool catalog, MCP server,
  guardrails, OTel tracing, budget enforcement as done (with commit refs)
- New item #9: Agent-to-Agent Delegation (the biggest remaining gap)
- New item #10: A2A Agent Cards (depends on #9)
- New item #11: Graph-based Mission Workflows (low priority)
- New item #12: Agent Long-Term Memory via Embeddings

Each item includes problem statement, industry comparison, implementation
sketch, dependencies, effort estimate, and impact assessment.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 15:27:38 +02:00
Till JS
b7f83cb734 fix: migrate remaining inline toasts + delete dead /subscription route
Fix 2 broken showToast() calls in SyncSection (function was removed
but two call sites survived — runtime error on deactivate/interval).

Migrate inline toasts to central toast store in:
- gifts/+page.svelte (11 refs)
- gifts/redeem/[code]/+page.svelte (9 refs)

Delete routes/(app)/subscription/+page.svelte — dead standalone route
from before the credits merge. Update Stripe redirect URLs in
subscriptions API to use /?app=credits&success/canceled=true.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 15:27:18 +02:00
Till JS
4b41549d20 fix(profile): expand data model + fix interview field mappings
- Add leisure section (media, sports, pets) + social.livingSetup to userContext
- Fix interview questions: each maps to its own field, no more bio overwrites
  (leisure.favoriteMedia → leisure.media, leisure.sports → leisure.sports,
   social.living → social.livingSetup, social.pets → leisure.pets)
- Add merge flag for array fields (goals.learn merges into goals, not replaces)
- Store.setField() supports merge=true for deduped array merging
- All ContextOverview sections now always visible with empty-state hints
- All tag-based sections (languages, goals, allergies) are inline-editable
- Routine/nutrition/social link to interview for editing
- EditProfileModal: restore email change UI (Ändern button + verification flow)
- Update AI resolver with leisure + livingSetup fields
- Add leisure to crypto registry encryption fields

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 15:24:11 +02:00
Till JS
a1bb703086 docs: final report update — 7/10 roadmap items done, all tables consistent
Fix missing strikethroughs in §6 table (#1, #2, #6) and update Fazit
to reflect final state: 7 of 10 items done. Document remaining 3
langfristige Punkte with context on dependencies and priorities.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 15:23:37 +02:00
Till JS
fabf259526 feat(ai-agents): missions lookup + simple policy + agent fingerprint (UX 3-6)
Four UX improvements that make agents more discoverable and their
behavior more transparent. All svelte-check clean (0 errors in
changed files).

=== UX 3: Reverse-Mission-Lookup ===

Agent detail view now shows a "Missions (N)" section listing all
missions owned by this agent with status dots + state labels. Includes
a "+ Neue Mission für [agent]" button that navigates to the template
gallery. Users no longer have to mentally cross-reference between the
agents and missions modules.

=== UX 4: Simple-Mode Policy ===

The Policy section defaults to three radio-card presets:
- Standard (Vorschlag für alles)
- Vorsichtig (alles Vorschlag, keine Auto-Writes)
- Aggressiv (gleichartige Schreibvorgänge automatisch)

The full per-module matrix is now hidden behind "▸ Erweitert
anzeigen". This covers 90% of users who just want a quick
conservative/aggressive toggle. Power-users still get the full
matrix.

=== UX 5: Policy Natural Language Summary ===

Above the preset radios, a preformatted block summarizes the current
policy in plain German: "Gesperrt: X, Y · calendar: automatisch ·
Alles andere: Vorschlag". Generated from the policy object. Updates
live when the user switches presets or changes module overrides.

=== UX 6: Agent Fingerprint on List-Views ===

New <AgentDot record={item} /> component: reads __lastActor from
any Dexie record, resolves the agent's avatar via the live useAgents
query, and renders a tiny inline emoji dot next to the item title.
When no AI actor wrote the record, renders nothing (zero-width).

Wired into:
- /todo — task title row, after the title span
- /notes — note title row, after the title span

Each module import is a single line (`import AgentDot from ...`);
the component is self-contained (owns its own query + styles).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 15:22:55 +02:00
Till JS
26e1c4774f feat(scene-scope): wire filterBySceneScope into notes/todo/contacts/calendar queries
The four modules with tag junctions now filter their main useAll*
queries through filterBySceneScope: when a scene has scopeTagIds set,
only records tagged with at least one matching tag (+ untagged records)
appear in the UI. Modules without tag junctions (drink, food, habits,
journal, dreams, places) are unaffected — their records are always
globally visible.

- useAllNotes → noteTagOps.getTagIds
- useAllTasks → taskTagTable junction lookup
- useAllContacts → contactTagOps.getTagIds
- useAllCalendarItems → eventTagOps.getTagIds (calendar-sourced blocks
  only; task/habit blocks pass through unfiltered)

When no scene scope is active (scopeTagIds undefined), filterBySceneScope
is a no-op identity pass — zero overhead for unscoped scenes.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 15:22:47 +02:00
Till JS
62fc566693 docs: mark OTel tracing (#7) as done in architecture report
7 of 10 roadmap items now complete. Remaining: Agent-to-Agent (#4),
A2A Agent Cards (#8), Graph Workflows (#9), Agent Memory (#10).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 15:21:45 +02:00
Till JS
76577869e1 feat(mana-ai): OpenTelemetry tracing + Grafana Tempo backend
Add distributed tracing to the mana-ai background runner so mission
execution can be visualized end-to-end in Grafana.

Instrumentation (services/mana-ai/):
- tracing.ts: OTel provider setup with OTLP/HTTP exporter, withSpan() helper
- tick.ts: tick.planMission span with mission/agent/user attributes
- client.ts: planner.complete span with LLM model, tokens, latency

Infrastructure:
- docker/tempo/tempo.yaml: Grafana Tempo config (OTLP HTTP on 4318)
- docker-compose: tempo service + tempo_data volume + mana-ai env var
- docker/grafana/provisioning/datasources/tempo.yml: auto-provisioned

Trace flow:
  tick.planMission (root span)
    └── planner.complete (child span)
        ├── llm.model = "gpt-4o-mini"
        ├── llm.tokens.total = 1234
        └── llm.response.length = 567

Enable: set OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
View: Grafana → Explore → Tempo datasource

Also fixes: removed broken @mana/subscriptions workspace ref from arcade.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 15:21:23 +02:00
Till JS
8def989ed9 chore: global ToastContainer, migrate inline toasts, delete SETUP.md
Add ToastContainer.svelte to (app) layout — renders toasts from the
central toast.svelte store (stacked, auto-dismiss, color-coded by
type). Previously the store existed but had no renderer.

Migrate inline toast implementations to the central store:
- SyncSection: showToast() → toast.success/error(), strip DOM + CSS
- Credits ListView: same migration, remove showToast + inline toast
- Profile ListView: same migration, remove showToast + inline toast

Delete apps/mana/apps/web/SETUP.md — completely outdated (references
Supabase, teams, organizations — all removed long ago). Real docs
live in CLAUDE.md and docs/LOCAL_DEVELOPMENT.md.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 15:18:50 +02:00
Till JS
0ddaab53e4 feat(workbench): Scene.scopeTagIds + reactive scene-scope store
WorkbenchScene grows an optional scopeTagIds field so scenes can act
as data-scope lenses: when set, module queries filter records to those
tagged with at least one of the scene's tags (+ untagged = global).

New reactive store scene-scope.svelte.ts:
  - setSceneScopeTagIds(ids) — called by scene store on switch/init
  - getSceneScopeTagIds()    — read by module queries
  - filterBySceneScope()     — reusable filter (same semantics as
                               AI scope-context's filterByScope)

Wired into workbench-scenes.svelte.ts:
  - setActiveScene() syncs scope on manual switch
  - liveQuery subscription syncs scope on init/sync/tab-focus

Module queries can now opt into scene scoping by calling
filterBySceneScope in their useAll* hooks — not wired yet (each
module opts in as needed). The foundation is in place.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 15:15:44 +02:00
Till JS
fad7f4bea3 feat(ai): guardrail layer — pre/post-plan + pre-execute checks
Add a guardrail system that runs alongside the Mission Runner pipeline
to catch obvious issues before they waste tokens or corrupt data.

Architecture (packages/shared-ai/src/guardrails/):
- types.ts: Guardrail, GuardrailResult, 4 phase interfaces
- builtin.ts: 4 built-in guardrails (always active):
  - input-size-limit: blocks >100K chars of resolved input
  - plan-step-limit: blocks plans with >25 steps (runaway planner)
  - duplicate-destructive-tool: warns if undo_drink called 2x
  - empty-required-params: blocks create_task without title
- runner.ts: runPrePlanGuardrails/runPostPlanGuardrails/runPreExecuteGuardrails

Wired into runner.ts at 3 checkpoints:
- Before deps.plan() — pre-plan check
- After plan received — post-plan check
- Before each stage() call — pre-execute check

Guardrails are synchronous, never hit the network, and produce
clear error messages when they block.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 15:11:34 +02:00
Till JS
f5392b8b63 fix(profile): update profile.test.ts for new avatar upload + email change API
- Replace getAvatarUploadUrl test with changeEmail + uploadAvatar tests
- Fix authStore mock: getValidToken instead of getAccessToken
- Add getManaApiUrl mock for avatar upload endpoint

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 15:09:59 +02:00
Till JS
c412508b95 feat(ai-scope): wire filterByScope into list_tasks/contacts/events + note tag UI
All major list-returning auto-tools now filter by the ambient agent
scope: list_notes (already done), list_tasks (via taskTagTable),
get_contacts (via contactTagOps), get_todays_events (via eventTagOps).
Untagged records pass through (globally visible); tagged records are
only returned when at least one tag matches the agent's scopeTagIds.

Notes detail view (/notes/[id]) grows a TagSelector widget between
the content textarea and the color picker, powered by the new
noteTagOps junction. Users can manually tag notes to scope them to
specific agents — complements the AI's add_tag_to_note tool.

Also: todo/stores/tags.svelte.ts created (taskLabelOps wrapper around
the existing taskLabels junction for the scope filter).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 15:06:11 +02:00
Till JS
ed01d24f2d feat(ai): add AI tools for myday, goals, mood, finance, and times
Expand agent tool coverage from 28 to 47 tools across 16 modules:

- myday: get_myday_summary (full daily context in one call)
- goals: list_goals, get_goal_progress, create_goal, pause/resume/complete_goal
- mood: log_mood, get_mood_today, get_mood_insights (trends + correlations)
- finance: extend add_transaction, add get_month_summary + list_transactions
- times: extend start/stop_timer, add get_timer_status, get_time_stats, list_projects

All tools registered in both AI_TOOL_CATALOG (shared-ai) and webapp init.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 15:01:12 +02:00
Till JS
acd7e0d6b0 docs: update architecture comparison — 5/10 roadmap items done
Update report to reflect all completed work:
- Matrix: streaming , tool registration updated to 29 tools + MCP
- §5.2 Streaming: marked done
- §5.3 Tool System: marked done
- §6 Table: items 1-3 + 5 struck through with commit refs
- §8 Fazit: updated gaps and recommendations

5 of 10 roadmap items complete in one session:
1. SSE Streaming, 2. Dynamic Tool Registry, 3. Budget Enforcement,
5. MCP Server Export (27/29 tools with DB ops), plus Tool Drift Fix.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 15:00:09 +02:00
Till JS
ce57e11950 feat(mana-ai): server-side token budget enforcement per agent
Implement rolling 24h token budget enforcement in the mana-ai tick loop.
Agents with maxTokensPerDay set are now rate-limited server-side.

Changes:
- PlannerClient: extract usage.total_tokens from mana-llm response
- planOneMission: return {plan, tokensUsed} tuple
- tick loop: check getAgentTokenUsage24h() before planning; skip with
  'skipped-budget' decision if over limit
- tick loop: record token usage after successful plan via
  recordTokenUsage() INSERT into mana_ai.token_usage
- migrate.ts: new mana_ai.token_usage table with rolling window index
- metrics.ts: mana_ai_tokens_used_total counter (by agent_id)

Budget flow:
  Agent.maxTokensPerDay = 50000
  → tick checks: SELECT SUM(tokens_used) WHERE ts > now()-24h
  → if sum >= 50000: skip mission, emit skipped-budget metric
  → else: plan mission, INSERT token_usage row

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 14:41:31 +02:00
Till JS
e2d540a958 refactor(settings): rewrite GeneralSection inline + delete @mana/subscriptions
GeneralSection: replace the GlobalSettingsSection wrapper (which
rendered its own SettingsSection pill + SettingsCard, requiring
title="" to suppress the inner header) with inline settings rows.
Each setting is a label+control row with scoped CSS — no double-card,
no wrapper hack.

Delete packages/subscriptions/ — the package is dead after merging
its SubscriptionPage into the Credits & Abo workbench app.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 14:33:35 +02:00
Till JS
f203e100c1 chore: final cleanup — dead link, security status, showTitle, drop subscriptions
1. CompleteStep: /apps → / ("Workbench" instead of dead "Alle Apps")
2. pnpm lockfile synced after @mana/subscriptions removal
3. Security header panel: status dots for Passkey/2FA/Sessions count
4. GeneralSection: inline settings rows replace GlobalSettingsSection
   wrapper — no more title="" hack or double-card nesting
5. shared-auth-ui: showTitle prop on PasskeyManager, SessionManager,
   TwoFactorSetup, AuditLog; SecuritySection passes showTitle={false}
6. Drop @mana/subscriptions from sources.css + package.json

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 14:27:46 +02:00
Till JS
04c806fbb2 feat(mcp): implement remaining 19 tool handlers (27/29 total)
Complete tool handler coverage for the MCP server:

Todo: complete_tasks_by_title
Calendar: create_event (with timeBlock)
Notes: update_note, append_to_note, add_tag_to_note
Places: create_place, visit_place, get_places
Drink: log_drink, get_drink_progress, undo_drink
Food: log_meal, nutrition_summary
Journal: create_journal_entry
Habits: create_habit, log_habit (get_habits improved)
News: save_news_article

27 of 29 tools now have real implementations. Remaining 2
(research_news, get_current_location) need external service
calls that aren't available in the API server context.

Also updates architecture comparison report to mark MCP as done.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 14:08:57 +02:00
Till JS
e969324cc8 feat(mcp): Phase 2 — real DB operations for tool execution
Implement actual sync_changes reads and writes for MCP tool calls:

- sync-db.ts: Connection to mana_sync DB, RLS-scoped withUser(),
  readLatestRecords() for replaying sync state, writeRecord() for
  creating sync_changes entries
- executor.ts: 10 tool handlers implemented:
  - Reads: list_tasks, get_task_stats, list_notes, get_todays_events,
    get_contacts, get_habits
  - Writes: create_task, complete_task, create_note, create_contact
  - Remaining tools return helpful "not yet implemented" message
- server.ts: userId from auth context bound into MCP session via closure
- index.ts: typed Hono app with AuthVariables

Write pattern matches mana-ai: INSERT into sync_changes with
actor={kind:'system', source:'mcp-tool'}, client_id='mcp-server'.
Records appear on user devices on next sync cycle.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 13:46:06 +02:00
Till JS
10acabfed6 feat(ai): tag-based agent scoping — agents see only their tagged records
Connects the existing global tag system (@mana/shared-tags, 15+ module
junctions, TagSelector UI) to the AI agent model so different agents
can operate on different slices of the user's data.

Core additions:

1. Agent.scopeTagIds — optional array of global tag IDs. When set,
   the agent sees only records tagged with at least one of those tags
   (plus untagged records, which stay globally visible). Empty/undefined
   = General-Agent, sees everything. Agent-editor grows a <TagSelector>
   under "Bereiche (Tag-Scope)".

2. Per-agent kontext documents — new Dexie table `agentKontextDocs`
   (v22, encrypted, synced). Each agent can have its own markdown
   context doc, replacing the global singleton auto-inject. Runner
   tries agent kontext first, falls back to global singleton when
   the agent has no dedicated doc.

3. Ambient scope context — `withAgentScope(tagIds, fn)` sets a
   module-level scope during the reasoning loop. Auto-tools read it
   via `getAgentScopeTagIds()` and filter their result sets.
   `filterByScope(records, getTagIds)` is the reusable filter
   primitive (keeps untagged records, drops mismatched tagged ones).

4. Notes tag junction — `noteTags` table (v22) + `noteTagOps` via
   `createTagLinkOps`. Notes was the only major module without
   structured tag support. `list_notes` now calls `filterByScope`
   so a scoped agent only sees notes tagged with its scope.

Flow: mission starts → runner resolves owning agent → reads
agent.scopeTagIds → wraps entire reasoning loop in withAgentScope →
list_notes (and future list_tasks etc.) auto-filter → planner sees
only scope-relevant records → proposes scoped edits.

Runner tests: 8/8. shared-ai type-check: clean.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 13:43:33 +02:00
Till JS
3f60f68573 fix(shared-tailwind): export CSS under 'style' condition for Vite build
@tailwindcss/vite's enhanced-resolve looks for the 'style' export
condition when resolving CSS imports. The previous exports field used
plain string values which worked in dev but not in the Docker
production build (Vite build mode). Adding explicit 'style' +
'default' conditions fixes the "'sources.css' is not exported under
the condition 'style'" error.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 13:39:01 +02:00
Till JS
db4dd437bd feat(api): MCP server endpoint — expose AI tools to external clients
Mount an MCP (Model Context Protocol) server at /api/v1/mcp in the
unified Hono API. External clients like Claude Desktop, Cursor, and
VS Code Copilot can discover and call all 29 Mana tools via the
standard MCP protocol.

Architecture:
- WebStandardStreamableHTTPServerTransport for Bun/Hono compatibility
- AI_TOOL_CATALOG → MCP tool definitions with JSON Schema (via Zod)
- Stateful sessions with Mcp-Session-Id header
- Auth via existing authMiddleware (JWT or API key)

Phase 1 scope: tools/list returns all 29 tools with schemas,
tools/call acknowledges with descriptive messages. Phase 2 will add
actual DB reads/writes via sync_changes.

Usage:
  Claude Desktop config:
  {"mcpServers": {"mana": {"url": "http://localhost:3060/api/v1/mcp"}}}

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 13:37:52 +02:00
Till JS
827b252090 feat(settings): inline sync, my-data, and vault — delete all sub-routes
The three Settings sub-routes (/settings/sync, /settings/security,
/settings/my-data) were standalone pages with their own PageHeaders
that felt disconnected from the workbench settings app. Inline them
as section components so everything lives in one scrollable view:

- SyncSection.svelte (from /settings/sync) → embedded in Data tab
- MyDataSection.svelte (from /settings/my-data) → embedded in Data tab
- VaultSection.svelte (from /settings/security) → embedded in Security tab

Each component is the route content minus PageHeader/Breadcrumbs/
svelte:head. Toasts stay self-contained in each section.

- Delete all three route files + empty /settings/ directory tree
- Add 'vault' anchor to searchIndex (search "Verschlüsselung")
- Update external links: sync-status dropdown, sync billing banner,
  EncryptionIntroBanner → /?app=settings#cloud-sync / #vault

The routes/(app)/settings/ directory is now completely gone.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 13:30:33 +02:00
Till JS
56171ff13b fix(ai): resolve tool name + parameter drift between catalog and webapp
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 food-backend (push) Blocked by required conditions
CI / Build food-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 quotes-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 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
8 mismatches fixed between AI_TOOL_CATALOG and webapp module tools:

Tool name renames (webapp → catalog name):
- record_visit → visit_place (places)
- undo_last_drink → undo_drink (drink)
- location_log → get_current_location (places, catalog side)

Catalog parameter fixes (aligned to webapp execute functions):
- create_event: startIso/endIso → startTime/endTime + isAllDay/location/description
- create_note: title required→optional, content optional→required
- complete_tasks_by_title: titleSubstring → titleMatch
- create_place: add latitude/longitude (required) + category enum + address
- create_journal_entry: English mood enum → German mood enum

Webapp parameter additions:
- create_contact: add company + notes params (store already accepts them)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 13:18:51 +02:00
Till JS
299cf9cf72 chore: cleanup dead props, deps, dirs, and stale comments
- Remove empty dirs: modules/mana/, modules/subscription/, and 7
  empty route dirs (spiral, profile, themes, help, apps, mana, credits)
- Remove @mana/subscriptions from web app dependencies (never imported)
- PillNavigation: drop settingsHref, manaHref, allAppsHref/allAppsLabel
  props + their link-builder blocks (none are passed anymore; all system
  pages route via /?app=<id> deep-links now)
- Update layout comment to reflect current architecture

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 13:17:59 +02:00
Till JS
d40a61119e refactor(ai): dynamic tool registry — single-source catalog in shared-ai
Introduce AI_TOOL_CATALOG in @mana/shared-ai as the single source of truth
for all 29 tool schemas (17 propose + 12 auto). Both the webapp policy and
the server-side mana-ai planner now derive their tool lists from the catalog
instead of maintaining independent hardcoded copies.

- New: packages/shared-ai/src/tools/schemas.ts — catalog with ToolSchema type
- Rewrite: proposable-tools.ts — derived from catalog instead of hardcoded array
- Rewrite: services/mana-ai/src/planner/tools.ts — 277→30 lines (imports from catalog)
- Simplify: webapp policy.ts — derives AUTO/PROPOSE from catalog defaultPolicy

Adding a new tool now requires 2 files instead of 3-5:
1. Add schema to AI_TOOL_CATALOG (shared-ai)
2. Add execute function in the module's tools.ts (webapp)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 13:06:07 +02:00
Till JS
b4ce8523b0 feat(credits): merge subscription management into Credits & Abo
The standalone "Abonnement" workbench app (lib/modules/subscription/)
duplicated billing functionality that should live alongside credits.
Users saw two separate apps for the same domain.

Replace the placeholder SubscriptionPage in the Abo tab with the real
subscription management from the subscription module:
- Current plan status with cancel/reactivate
- Plan selection with billing interval toggle (monatlich/jährlich)
- Stripe checkout integration
- Invoice history (collapsed <details>)
- Stripe billing portal link

Delete:
- lib/modules/subscription/ (merged into credits)
- app-registry 'subscription' registration
- CreditCard icon import (no longer used)

The Credits & Abo app now has 5 tabs:
1. Übersicht — balance + recent transactions + quick-buy
2. Abo — current subscription + plan picker + invoices
3. Verlauf — full transaction table
4. Kaufen — one-time credit packages (Stripe)
5. Kosten — per-operation pricing breakdown

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 12:51:31 +02:00
Till JS
3be4612f04 fix(mana-llm): google-genai v1.73 keyword-only Part.from_text()
google-genai >=1.70 changed Part.from_text() from positional to
keyword-only argument. The production container installed v1.73.1
and crashed on startup with "Part.from_text() takes 1 positional
argument but 2 were given".

Fix: Part.from_text(msg.content) → Part.from_text(text=msg.content)

Tested live: curl https://llm.mana.how/v1/chat/completions with
model=google/gemini-2.5-flash returns correct response.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 12:47:23 +02:00
Till JS
3ce8420bc1 fix: drop duplicate manaHref — Credits & Abo is the single billing entry
After merging /mana into the credits workbench app, both manaHref and
creditsHref pointed to /?app=credits, rendering two identical dropdown
entries ("Mana" + "Credits"). Drop manaHref so only the "Credits"
entry remains.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 12:40:51 +02:00
Till JS
659a7d9774 fix(mana-llm): add google-genai to requirements.txt for Docker builds
google-genai was in pyproject.toml but missing from requirements.txt.
The Dockerfile uses pip install -r requirements.txt, so the Google
provider never loaded in production. Now that the key is set and the
cloud tier upgraded to gemini-2.5-flash, the import fires on startup.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 12:40:30 +02:00
Till JS
c6c4d630fe refactor(subscriptions): compact row-based card layout
SubscriptionCard and PackageCard were large centered multi-cell cards
designed for a standalone pricing page. In the workbench context (narrow
card inside a carousel), they wasted too much vertical space for users
to compare plans at a glance.

Redesigned both as horizontal rows:
- Icon | name+mana | price | action — all in one line
- Badges (current/popular) inline next to the plan name
- No more 3-column internal grid with 70px min-height cells
- Clickable row replaces separate SubscriptionButton

SubscriptionPage:
- Drop the big centered header (icon + title + subtitle)
- Move Usage + Costs into a collapsed <details> section
- Section titles as small-caps labels
- Billing toggle at top, plans immediately visible

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 12:38:30 +02:00
Till JS
d83fc370a0 docs: update tool coverage table + server-side research + templates
Catches up all docs with the current state of the AI tool system.

services/mana-ai/CLAUDE.md:
- New v0.6 status section documenting NewsResearchClient,
  pre-planning research injection, config.manaApiUrl, and the full
  28-tool / 11-module inventory (17 propose + 11 auto).

apps/mana/CLAUDE.md:
- New "Tool Coverage" table in the AI Workbench section listing all
  tools per module with their policy (propose vs auto).
- New "Templates" subsection documenting the two-section gallery
  (agent vs workbench templates), the seed-handler registry, and
  the current handlers (meditate, habits, goals).
- Architecture cross-reference updated to include §23.

docs/architecture/COMPANION_BRAIN_ARCHITECTURE.md:
- §23.2 gains a "Server-Side Research (mana-ai, ab v0.6)" subsection
  explaining how NewsResearchClient mirrors the client-side research
  pre-step: same endpoints, same trigger regex, but HTTP-direct from
  the Docker network instead of SvelteKit-internal.

docs/plans/README.md:
- workbench-templates.md added to the roadmap table (T1 shipped).
- Multi-agent description updated to mention 28 tools + server-side
  web-research.
- Architecture cross-reference includes §23.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 12:35:40 +02:00
Till JS
2ead0f36df fix(subscriptions): single-column layout for workbench context
SubscriptionPage had responsive multi-column grids (up to 4 columns
on xl). In the workbench card context this created awkward layouts.
Switch to single-column throughout and narrow max-width to 40rem.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 12:34:36 +02:00
Till JS
be81d11dc3 feat(ai): SSE streaming for foreground Mission Runner
Enable real-time token streaming during the planner "calling-llm" phase
so the user sees live progress ("empfange Plan… 128 tokens") instead of
a static spinner. The parser still receives the full text once complete —
no partial-JSON risk.

Changes:
- Extract shared SSE parser from playground into @mana/shared-llm/sse-parser
- remote.ts: use stream:true when onToken callback is provided
- AiPlanInput: add optional onToken field (shared-ai)
- ai-plan task: pass onToken through to backend.generate()
- runner.ts: throttled (500ms) phaseDetail updates during streaming
- Playground: refactored to use shared SSE parser

Also includes: AI agent architecture comparison report (docs/reports/)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 12:32:43 +02:00
Till JS
8a0bf93699 chore(cloud-tier): upgrade default model gemini-2.0-flash → gemini-2.5-flash
gemini-2.0-flash is deprecated June 1 2026. gemini-2.5-flash has been
stable since Q1 2026 with similar pricing ($0.15/$0.60 per 1M tokens
vs $0.10/$0.40 — pricing table already had the entry).

Three files touched:
- packages/shared-llm/src/backends/cloud.ts — client default
- services/mana-llm/src/config.py — server default
- services/mana-llm/src/providers/google.py — Ollama→Gemini fallback
  map + constructor default + deduplicated model list

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 12:32:03 +02:00
Till JS
95e65bbdcb chore: remove /apps route — not needed
The standalone /apps page (AppsPage from shared-ui) is redundant in the
workbench model — apps are discoverable via the app picker and scene
management directly on the home screen.

- Delete routes/(app)/apps/+page.svelte
- Remove command menu "Alle Apps" entry
- Drop allAppsHref prop from PillNavigation

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 12:30:37 +02:00
Till JS
27ac5fc23e feat(credits): merge Credits + Mana subscription into one workbench app
The former /credits (balance, transactions, Stripe checkout, cost
breakdown) and /mana (subscription plans placeholder) were separate
pages covering the same billing domain. Merge into a single workbench
app "Credits & Abo" with 5 tabs:

1. Übersicht — balance cards + recent transactions + quick-buy
2. Abonnements — SubscriptionPage from @mana/subscriptions
3. Transaktionen — full transaction history table
4. Kaufen — Stripe-integrated package cards
5. Kosten — per-operation cost breakdown with category filter

Stripe redirect handling: Stripe returns to /?app=credits&success=true.
The deep-link handler opens the app and strips ?app; the ListView reads
?success / ?canceled from window.location.search on mount, shows the
appropriate toast, and cleans the URL via history.replaceState.

- Delete /credits/+page.svelte and lib/modules/mana/ (placeholder)
- Register workbench app id='credits' (Crown icon, amber)
- Replace mana app registration (no longer needed)
- Update all links: command menu, PillNavigation (manaHref + creditsHref
  both → /?app=credits), CreditsSection, CreditsWidget,
  TransactionsWidget, CompleteStep, sync-status, sync billing page,
  gift redeem page

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 12:26:27 +02:00
Till JS
23b8cc13fb feat(ai-tools): server-side web-research + contacts for agents
Two major tool expansions — the Recherche-Agent and Today-Agent can
now research the web autonomously (no browser needed), and a future
Meeting-Prep agent can read + create contacts.

=== research_news (server-side execution) ===

The biggest addition: mana-ai can now call mana-api's news-research
endpoints (POST /discover + /search) directly, without a browser.

Infrastructure:
- services/mana-ai/src/planner/news-research-client.ts — full HTTP
  client with discover→search pipeline. 15s/30s timeouts. Graceful
  null on any failure (network, mana-api down, bad response) so the
  tick never crashes from research errors.
- config.manaApiUrl added (default http://localhost:3060); wired in
  docker-compose.macmini.yml as http://mana-api:3060 + depends_on
  mana-api with service_healthy condition.

Pre-planning research step (cron/tick.ts):
- Before the planner prompt is built, the tick checks if the
  mission's objective or conceptMarkdown matches research keywords
  (same RESEARCH_TRIGGER regex the webapp uses). When it matches:
  * NewsResearchClient.research(objective) runs discovery + search
  * Results are injected as a synthetic ResolvedInput with id
    '__web-research__' and a formatted markdown context block
  * The Planner then sees real article URLs/titles/excerpts and can
    reference them in create_note / save_news_article steps
  * Log line: "pre-research: N feeds, M articles"

Tool registration:
- research_news added to AI_PROPOSABLE_TOOL_NAMES + mana-ai tools.ts
  with params (query, language?, limit?). This lets the planner also
  explicitly propose a research step as a PlanStep (in addition to
  the pre-planning auto-injection).

=== create_contact ===

- Added to AI_PROPOSABLE_TOOL_NAMES + mana-ai tools.ts with params
  (firstName required, lastName/email/phone/company/notes optional).
- Contacts are encrypted at rest; server planner can plan the step
  but execution stays on the webapp (same as all propose tools).
  Full server-side contact resolution via Key-Grant is a future
  enhancement.
- get_contacts added to webapp AUTO_TOOLS so agents can inspect
  existing contacts without nagging (read-only, auto-policy).

Module coverage now:
   todo (5)   calendar (2)   notes (5)   places (4)
   drink (3)  food (2)       news (1)    journal (1)
   habits (3)  news-research (1)  contacts (1)

  11 modules, 28 tools total (17 propose, 11 auto).

Tests: mana-ai 41/41 (drift-guard passes), shared-ai type-check
clean, webapp svelte-check 0 errors, 0 warnings.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 12:25:45 +02:00
Till JS
ae53e93b9a feat(mana): migrate subscription page to workbench app
Extract /mana route into lib/modules/mana/ListView.svelte. Register as
workbench app id='mana' with Crown icon (amber). The page shows the
SubscriptionPage component from @mana/subscriptions.

- Delete routes/(app)/mana/+page.svelte
- Update PillNavigation manaHref to /?app=mana

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 12:03:20 +02:00
Till JS
5d46aa19a0 refactor(help): drop standalone /help route, use workbench app
The help workbench module (lib/modules/help/ListView.svelte) already
renders the same HelpPage component with identical props. The
standalone route was redundant.

- Delete routes/(app)/help/+page.svelte
- Update PillNavigation helpHref to /?app=help

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 12:01:35 +02:00
Till JS
1266b583e4 feat(ai-tools): unlock create_note + create_journal_entry + habit tools for agents
Closes the three biggest tool-coverage gaps so the shipped agent
templates can actually do their job end-to-end. Before this, the
Recherche-Agent couldn't create notes (only edit), the Today-Agent
couldn't create journal entries, and no habit-related tool was
server-proposable at all.

shared-ai (proposable-tools.ts):
- create_note (notes) — key unlock: Recherche-Agent now creates
  per-source notes and the summary report.
- create_journal_entry (journal) — key unlock: Today-Agent proposes
  a poem as a journal entry with optional mood.
- create_habit (habits) — agent can suggest new habits.
- log_habit (habits) — agent can log a habit completion for today.

Organized the list with per-module section comments for readability
now that we're at 15 proposable tools.

mana-ai (planner/tools.ts):
- 5 new tool definitions with full parameter schemas:
  * create_note (title, content?)
  * create_journal_entry (content, title?, mood? enum)
  * create_habit (title, icon, color)
  * log_habit (habitId, note?)
- Drift-guard contract test passes (41/41) — confirms the mana-ai
  tool list is in sync with the shared-ai canonical set.

Webapp (policy.ts):
- get_habits added to AUTO_TOOLS (read-only; agent can inspect
  which habits exist without nagging the user for approval).
- list_notes added to AUTO_TOOLS (was already used in the reasoning
  loop but missing from the explicit auto-list; the planner default
  fell through to 'propose' which was wasteful for a read op).

Module coverage after this change:
   todo (5 tools)   calendar (2)   notes (5 incl. create)
   places (4)       drink (3)      food (2)
   news (1)         journal (1)    habits (3)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 12:00:17 +02:00
Till JS
bc5c15096c feat(spiral): migrate to workbench app, delete standalone route
Extract the /spiral route into lib/modules/spiral/ListView.svelte
(same content minus the standalone PageHeader — the workbench card
provides its own chrome). Register as workbench app id='spiral' with
the Phosphor Spiral icon.

- Delete routes/(app)/spiral/+page.svelte
- Update command menu + PillNavigation spiralHref to /?app=spiral
- deep-link scheme works out of the box (/?app=spiral)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 11:58:25 +02:00
Till JS
0af1dd7ec6 feat(workbench): section deep-links + migrate profile & themes to workbench
Section deep-links: /?app=settings#ai-options now switches the Settings
ListView to the KI tab and scrolls to the ai-options anchor. ListView
reads the URL hash on mount and maps it to a category via the existing
searchIndex anchors. The AI-tier dropdown "KI-Einstellungen" link now
targets /?app=settings#ai-options instead of just /?app=settings.

Profile & Themes workbench consolidation — same pattern as Settings:
- Delete standalone /profile and /themes routes (redundant with the
  workbench apps registered in app-registry)
- Migrate all links: PillNavigation profileHref/themesHref, dashboard
  QuickActionsWidget, +layout theme-switcher "Alle Themes", and the
  scene context-menu "Hintergrund ändern"

Credits stays as a standalone route — no workbench app registered for it.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 11:52:25 +02:00
Till JS
334c36a68e docs: document reasoning loop, research pre-step, debug log, new tools
Updates apps/mana/CLAUDE.md AI Workbench section with:
- Reasoning loop (5-round auto→propose chain)
- Cross-module proposal inbox in mission detail
- Kontext auto-inject
- Web-research pre-step (RSS via news-research)
- Debug log (local-only _aiDebugLog + AiDebugBlock panel)
- New proposable tools: save_news_article, list_notes, update_note,
  append_to_note, add_tag_to_note

Adds §23 to COMPANION_BRAIN_ARCHITECTURE.md covering the full
architecture: loop algorithm pseudocode, research pre-step rationale
(RSS over deep-research), kontext auto-inject privacy boundary,
debug log schema + UI + toggle mechanics, and new tool inventory.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 11:50:21 +02:00