# Host-Hook-Points + Plugin-Lifecycle + Tenant-Admin-UI + Crash-Handling **Status:** in_progress (foundation-shipped, settings iframe/CSP/postMessage shipped; marketplace + hot-reload + output-hooks + 13-more-hook-points + global-crash-counter deferred) **Task-ID:** #22 **Phase:** 06 **Estimated Effort:** 4-5 Wochen **Owner:** unassigned > **Historical implementation plan.** Current truth lives in > `docs/features/plugins.md`, `docs/operations/plugin-lifecycle.md`, > `docs/architecture/plugin-hooks.md`, the tenant plugin API at > `apps/web/app/routes/api.tenants.$tenant.plugins.tsx`, the tenant settings UI > under `apps/web/app/routes/app.$tenant/settings/plugins*`, and worker fanout at > `apps/worker/src/jobs/plugin-hook-fanout.ts`. The plan below is retained as > historical design context; do not treat early "Problem" or checklist text as > live status without reconciling it against those canonical docs. Where the > original plan says `plugin.invoke` outbox/job events, the shipped queue path is > `outbox.plugin-hook` fanout into `toolctrl.plugin-invoke`. ## Problem When this plan was written, the runtime existed only as an early foundation and host trigger/lifecycle/UI paths still needed to be built. That is no longer the live state: tenant-scoped lifecycle APIs, settings UI, settings iframe CSP/postMessage contract, hook fanout, invoke queue, crash tracking, and capability review paths now exist behind the production runtime gate. Original gaps listed by the plan: 1. **Hook-Points im Host-Code** — es gibt heute ~15-20 Stellen im Code (Tenant-Signup, User-Create, Entity-CRUD, Workflow-Execution, Webhook-Outbound, Email-Send, Chatbot-Message, Export-Run, Billing-Pre/Post, Auth-Login etc.), an denen Plugins zu Recht etwas tun wollen würden. Diese Stellen rufen keinerlei Plugin-Registry auf. 2. **Plugin-Lifecycle-Management** — kein `installPlugin(file)`, kein `enablePlugin(pluginId, tenantId)`, kein Update-Path, kein Uninstall-Path. Plugins die per Hand auf Disk landen (siehe Staging-Steps von Task #21) sind ein Hack, kein Workflow. 3. **DB-Schema pro Plugin** — Plugins die eigene Tabellen brauchen (`plugin_com_acme_slack_messages`) haben keinen Mechanismus diese anzulegen, zu migrieren oder beim Uninstall zu bereinigen. 4. **Tenant-Admin-UI** — kein UI um Plugins zu sehen, zu installieren, Capabilities zu reviewen, Settings zu konfigurieren oder per-User zu enablen. Tenant-Admin müsste DB-Access haben, was wir nicht erlauben. 5. **Per-User-Enablement** — manche Plugins (z.B. Slack-Notifier mit Per-User-Channel-Config) brauchen Per-User-Einstellungen, nicht nur Per-Tenant. 6. **Crash-Handling** — ein Plugin das in einer Endlosschleife immer wieder crashed füllt die Queue, das Audit-Log und blockiert Worker-Threads ohne dass jemand etwas merkt. Es fehlt Auto-Disable + Notification. Betroffene Codestellen (zu modifizieren): - `apps/web/app/routes/onboarding.tsx` — Tenant-Signup-Pfad - `apps/web/app/utils/db/users.db.server.ts` — User-Create - `apps/web/app/utils/services/entities/entitiesSingleService.ts` — Entity-CRUD - `apps/web/app/modules/workflowEngine/services/WorkflowEngineService.ts` — Workflow-Execute - `apps/web/app/modules/webhooks/services/WebhookService.ts` — Outbound-Webhook - `apps/web/app/utils/services/emailService.ts` — Email-Send - `apps/web/app/modules/chatbot/services/*` — Chatbot-Message (kommt aus Phase 07; Hook-Stub vorbereiten) - `apps/api/src/billing/handlers.ts` — Billing-Pre/Post - `apps/web/app/utils/services/.server/authService.ts` — Auth-Login ## Depends on - `06-plugin-system/wasm-sandbox.md` — die Runtime + SDK + Invoker müssen lauffähig sein, sonst gibt es nichts zu triggern. Hook-Calls landen auf `invokePlugin()` aus Task #21. - `03-scaling-infrastructure/outbox-pattern.md` — Hooks werden niemals synchron aufgerufen, sondern immer als Outbox-Event-Producer (`plugin.hook.`). Aktueller Code: der `worker-general`-Pool konsumiert `outbox.plugin-hook`, fanoutet tenant-scoped Subscriber und enqueued `toolctrl.plugin-invoke`; der `worker-plugin`-Pool führt nur die isolierten WASM-Invocations aus. Synchrone Hook-Calls würden den Web-Request-Pfad blockieren und Tenant-Operationen mit Plugin-Crashes koppeln. - `05-business-features/feature-flags.md` — Capability-Grants pro Tenant werden über das Feature-Flag-System gespeichert/abgefragt (cached in SharedStore), nicht über eigene Lookup-Tabelle. ## Blocks - `06-plugin-system/audit-docs.md` — Audit-Logging pro Plugin-Call hängt am Invoker; Developer-Docs + Beispiel-Plugins brauchen die Hook-API und das Install-Flow um realistisch zu sein. - `11-backlog/marketplace.md` — kein Marketplace ohne funktionierenden Install-Flow. ## Approach **Hook-Registry-Modul + Outbox-Event-Producer + Plugin-DB-Schema mit Tabellen-Prefix + Lifecycle-State-Machine + Tenant-Admin-Routes.** ### 1. Hook-Registry Ein zentrales `packages/plugin-hooks/`-Package definiert alle Hook-Namen + ihre Input/Output-Schemas (Zod) als Single Source of Truth. Hook-Caller im Host-Code rufen niemals direkt Plugin-Code auf — sie produzieren ein Outbox-Event: ```ts import { emitHook } from "@toolctrl/plugin-hooks"; // In Tenant-Signup-Handler: await emitHook("onTenantSignup", { tenantId, tenantSlug, ownerEmail, plan }); ``` `emitHook` macht intern: 1. Validiert Payload gegen das Hook-Schema (Schutz vor falschen Payloads). 2. Lädt aus DB / Cache welche installed/enabled Plugins diesen Hook abonniert haben (für diesen Tenant). 3. Pro Plugin: erzeugt einen `plugin.invoke`-Outbox-Event mit `{ pluginId, version, hookName, tenantId, input }`. 4. Returnt sofort — kein Warten auf Plugin-Output. Die 15-20 Hook-Points (initial-Scope, weitere erlaubt in Folge-Phasen): | Hook-Name | Ausgelöst von | Input-Felder | Output-Verwendung | | ------------------------ | -------------------------- | ---------------------------------------------------------------------- | ----------------------------------------- | | `onTenantSignup` | Tenant-Signup-Flow | tenantId, slug, ownerEmail, plan, createdAt | none (fire-and-forget) | | `onTenantDeleted` | Tenant-Hard-Delete | tenantId, deletedAt | none | | `onUserCreate` | User-Create | userId, tenantId, email, role | none | | `onUserUpdate` | User-Update | userId, tenantId, changedFields[] | none | | `onUserDelete` | User-Delete | userId, tenantId | none | | `onEntityCreate` | Entity-Create (CRM/etc.) | entityType, entityId, tenantId, data | none | | `onEntityUpdate` | Entity-Update | entityType, entityId, tenantId, changedFields[], beforeData, afterData | none | | `onEntityDelete` | Entity-Delete | entityType, entityId, tenantId | none | | `onWorkflowExecute` | Workflow-Run | workflowId, runId, tenantId, status, durationMs | none | | `onWebhookOutbound` | Outbound-Webhook-Pre-Send | webhookId, url, method, tenantId, payloadHash | optional `transform` Output (siehe unten) | | `onEmailSend` | Email-Pre-Send | toEmail, subject, templateId, tenantId | optional `cancel` | | `onChatbotMessage` | Chatbot-Message (Phase 07) | conversationId, tenantId, userMessage, intent | optional `additionalTools[]` | | `onExportRun` | Export-Run-Start | exportId, tenantId, format, rowCountEstimate | none | | `beforeBilling` | Billing-Cycle-Pre | tenantId, periodStart, periodEnd, lineItems[] | optional `additionalLineItems[]` | | `afterBilling` | Billing-Cycle-Post | tenantId, invoiceId, total, currency | none | | `afterAuthLogin` | Successful-Auth | userId, tenantId, method, ipHash | none | | `onApiKeyCreated` | API-Key-Create | apiKeyId, tenantId, scopes[] | none | | `onIntegrationConnected` | OAuth-Integration-Connect | integrationProvider, tenantId, userId | none | **Output-Hooks** (wo Plugin etwas zurückgibt das den Host-Pfad beeinflusst, z.B. `onWebhookOutbound.transform`): nur eine kleine Whitelist. Diese laufen **synchron** gegen die Plugin-Runtime mit striktem Wall-Clock-Limit von 500ms — wenn das Limit überschritten wird, wird der Original-Payload unverändert gesendet (graceful degradation). **Default: fire-and-forget**, Output-Hooks sind die Ausnahme. ### 2. Plugin-Lifecycle-State-Machine ``` ┌─────────────┐ │ pending │ ← Tenant-Admin lädt Plugin hoch, Signature-Verify läuft └──────┬──────┘ │ verify-ok ▼ ┌─────────────┐ │ awaiting- │ ← Capabilities werden Tenant-Admin im Consent-Dialog gezeigt │ consent │ └──────┬──────┘ │ tenant-admin clicks "Approve" ▼ ┌─────────────┐ │ installed │ ← Migrations laufen, Plugin ist installiert aber disabled │ (disabled) │ └──────┬──────┘ │ tenant-admin enables ▼ ┌─────────────┐ ┌─────────────┐ │ enabled │ ◄────► │ disabled │ (per-tenant + per-user) └──────┬──────┘ └─────────────┘ │ │ tenant-admin clicks "Uninstall" ▼ ┌─────────────┐ │ uninstalling│ ← cleanup-Hook ausgelöst, Migrations-Down, Storage-Cleanup └──────┬──────┘ │ ▼ ┌─────────────┐ │ uninstalled│ ← DB-Eintrag gelöscht └─────────────┘ Crash-Path (separater Übergang): enabled ──(>5 crashes in 10 min)──► auto-disabled ──(tenant-admin re-enables)──► enabled ``` ### 3. Plugin-DB-Schema-Migrations Plugins die eigene Tabellen brauchen, deklarieren das im Manifest: ```jsonc { "migrations": [ { "version": 1, "file": "migrations/001_init.sql" }, { "version": 2, "file": "migrations/002_add_column.sql" }, ], } ``` **Tabellen-Prefix-Pflicht:** Jede Tabelle die ein Plugin anlegt MUSS mit `plugin__` beginnen (z.B. `plugin_com_acme_slack_messages`). Der Migration-Runner parsed jede `CREATE TABLE`-Statement und lehnt Migrationen ab, deren Tabellen-Namen den Prefix nicht haben. **Alternative die wir nicht nehmen:** Separate Postgres-Schemas pro Plugin (`plugin_com_acme_slack.messages`). Eleganter, aber: erschwert Multi-Tenant-Queries (jeder Schema-Switch ist eine eigene Connection-Search-Path-Manipulation), bricht den `prismaRead/prismaWrite`-Split, macht Backups komplexer. **Prefix-basiert reicht.** **Tenant-Scoping in Plugin-Tabellen:** Jede Plugin-Tabelle MUSS eine `tenantId TEXT NOT NULL` Spalte haben + Index darauf. Migration-Runner validiert das via Schema-Inspection nach Apply. Plugin-DB-Capabilities (siehe `wasm-sandbox.md`) injizieren `WHERE tenantId = …` automatisch — der Plugin-Autor muss das nicht selber tun, aber das Schema muss es supporten. **Down-Migrations:** Pflicht — beim Uninstall werden alle Down-Migrations in umgekehrter Reihenfolge ausgeführt. Wenn keine Down-Migration existiert: Tabelle wird DROPped (Default-Behavior). **Connection:** Plugin-Migrations laufen via `prismaWrite` (Primary-DB), NIEMALS via Plugin-Sandbox. Migration ist ein Host-Operation, kein Plugin-Operation. ### 4. Tenant-Admin-UI Historical target: neue Route `app/$tenant/plugins` mit folgenden Sub-Routes. Shipped UI lives under tenant settings: `apps/web/app/routes/app.$tenant/settings/plugins.tsx` and `apps/web/app/routes/app.$tenant/settings/plugins.$id.audit.tsx`. | Route | View | Aktion | | ----------------------------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `/app/$tenant/plugins` | Plugin-Liste (installed) | Search/Filter, Status-Badges (enabled/disabled/auto-disabled), Per-Card-Link auf Settings/Uninstall | | `/app/$tenant/plugins/install` | Install-Dialog | File-Upload (.zip), zeigt Manifest-Parse-Preview, Signature-Verify-Status, Capability-Liste mit Beschreibungen + Consent-Checkbox-pro-Capability + „Install"-Button | | `/app/$tenant/plugins/$pluginId` | Plugin-Detail | Status, Version, Author, Capabilities, Last-Invocations-Stats (count, error-rate), Enable/Disable-Toggle, Uninstall-Button | | `/app/$tenant/plugins/$pluginId/settings` | Plugin-Settings-Page | Lazy-loaded UI-Slot — rendert die `ui/settings.html` aus dem Plugin in einem sandboxed iframe (siehe Security Notes) | | `/app/$tenant/plugins/$pluginId/users` | Per-User-Enablement | Liste aller Tenant-User mit Toggle „Plugin für diesen User aktiv?" | | `/app/$tenant/plugins/$pluginId/audit` | Plugin-Audit-Trail | Letzte 100 Invocations mit Outcome, Capability-Used, Duration — Link auf `audit-docs.md`-Full-View | ### 5. Per-User-Enablement Default: ein installed + enabled Plugin gilt für **alle** Tenant-User. Optional kann Tenant-Admin die Per-User-Granularität aktivieren (Toggle in Settings). Wenn aktiv: Plugin wird nur für User getriggert die explizit enabled sind. Stored in `tenant_plugin_user_enablement (tenantId, pluginId, userId, enabled)`. ### 6. Crash-Handling + Auto-Disable - Jeder Plugin-Invocation-Fehler (Trap, Timeout, Capability-Denied, Resource-Exceeded) wird in SharedStore in einem Sliding-Window-Counter pro `(pluginId, tenantId)` gezählt. - Schwellwert: **5 Failures in 10 Minuten** → Plugin wird auto-disabled für diesen Tenant (`status='auto-disabled'`, `autoDisabledReason='repeated_failures'`, `autoDisabledAt=now()`). - Tenant-Admin bekommt eine In-App-Notification + (wenn aktiviert) Email mit Link auf Plugin-Detail-Page. - Tenant-Admin kann manuell wieder enablen — Counter wird gleichzeitig zurückgesetzt. - Counter-Reset-Mechanismus: bei jedem erfolgreichen Call wird der Failure-Counter dekrementiert (nicht auf 0, aber um 1 — verhindert dass Plugins die 4× crashen + 1× klappen permanent im Counter-Fast-Path bleiben). - Operator-Level-Auto-Disable: zusätzlich zum Tenant-Level gibt es einen Global-Counter. Wenn ein Plugin in mehreren Tenants gleichzeitig crashed (Schwellwert: 3 Tenants in 30 Min mit ≥3 Crashes), wird das Plugin **global** deaktiviert und der Operator wird via PagerDuty-Style-Alert benachrichtigt. ## Implementation Steps 1. **Plugin-Hooks-Package scaffolden** — Single Source of Truth für Hook-Namen + Schemas - Files: - `packages/plugin-hooks/package.json`, `tsconfig.json`, `src/index.ts` - `packages/plugin-hooks/src/hooks.ts` — Const-Record `HOOKS` mit Hook-Name als Key und `{ inputSchema: ZodSchema, outputSchema: ZodSchema | null, allowsOutput: boolean }` als Value. 18 Hooks aus Approach-Tabelle. - PNPM-Workspace-Eintrag. - Tests: `packages/plugin-hooks/src/hooks.test.ts` — Exhaustiveness, Schema-Validity. - Commit: `06-plugin-system/hooks-lifecycle: scaffold plugin-hooks package with 18 hook definitions` 2. **`emitHook`-Funktion** — Producer-Side - Files: `packages/plugin-hooks/src/emit.ts` — `emitHook(name, payload, ctx)` validiert Payload, sucht Subscribers per Cache + DB (cached via `tenant-plugin-subscriptions` SharedStore-Key, TTL 60s), produziert pro Subscriber einen `plugin.invoke` Outbox-Event. - Tests: `packages/plugin-hooks/src/emit.test.ts` — Payload-Validation, Subscriber-Lookup, Outbox-Producer-Call (mocked). - Commit: `06-plugin-system/hooks-lifecycle: add emitHook with outbox event production` 3. **Synchron-Output-Hook-Pfad** — für `transform`/`cancel`-Capability - Files: `packages/plugin-hooks/src/emitSync.ts` — `emitHookSync(name, payload, ctx)` ruft Invoker mit Wall-Clock-500ms direkt auf (statt Outbox), aggregiert Outputs der Plugins (chained `transform` order via Manifest-`priority` Feld), graceful fallback bei Timeout. - Tests: `packages/plugin-hooks/src/emitSync.test.ts` — Single-Plugin, Chained-Plugins, Timeout-Fallback, Output-Schema-Violation-Fallback. - Commit: `06-plugin-system/hooks-lifecycle: add emitHookSync for transform/cancel hooks` 4. **DB-Migration: installed_plugins-Schema** — Lifecycle-State + Subscriptions + Secrets + User-Enablement - Files: `prisma/schema.prisma`-Ergänzung + Migration: - `installed_plugins (id, tenantId, pluginId, version, status, manifestJson, signature, publisherKeyId, installedAt, installedByUserId, lastInvocationAt, autoDisabledReason, autoDisabledAt)` — eindeutig per `(tenantId, pluginId)` - `tenant_plugin_capability_grants (id, tenantId, pluginId, capabilityName, scopeJson, grantedAt, grantedByUserId)` - `tenant_plugin_secrets (id, tenantId, pluginId, keyName, valueEncrypted, updatedAt)` — Value via PG-encrypted Field (TC-existing Pattern) - `tenant_plugin_user_enablement (id, tenantId, pluginId, userId, enabled, updatedAt)` - `tenant_plugin_settings (id, tenantId, pluginId, settingsJson, updatedAt)` — Plugin-Settings (key-value-blob) - `plugin_invocations (id, tenantId, pluginId, hookName, durationMs, outcome, errorCode, capabilityUsedCsv, startedAt)` — wird hier vorbereitet, voll-genutzt in `audit-docs.md` - `plugin_migrations_applied (id, tenantId, pluginId, migrationVersion, appliedAt)` - Prisma-Migration `prisma/migrations/_plugin_lifecycle_schema/migration.sql` + Down-SQL. - Tests: Prisma-Migration-Test (apply + rollback gegen ephemeral postgres). - Commit: `06-plugin-system/hooks-lifecycle: add db schema for plugin lifecycle` 5. **Plugin-Migration-Runner** — Prefix-Validation + Apply + Down - Files: - `packages/plugin-runtime/src/migrations.ts` — `applyPluginMigrations(pluginId, manifestMigrations, prismaWrite)`: parsed SQL via `pg-query-emscripten`, validiert dass alle `CREATE TABLE`-Statements den `plugin__`-Prefix haben + dass jede Tabelle `tenantId`-Spalte hat. Apply via `prismaWrite.$executeRawUnsafe`, tracks via `plugin_migrations_applied`. - `rollbackPluginMigrations(pluginId)` — liest down-SQL aus geladenem Manifest oder DROP'ed Tabellen via Information-Schema-Lookup. - Tests: `packages/plugin-runtime/src/migrations.test.ts` — gegen testcontainers-postgres: valid Migration apply, invalid Prefix → Reject, fehlende tenantId-Spalte → Reject, Down-Path round-trip. - Commit: `06-plugin-system/hooks-lifecycle: add plugin db migration runner with prefix validation` 6. **Plugin-Lifecycle-Service** — Install/Enable/Disable/Update/Uninstall - Files: `apps/web/app/modules/plugins/services/PluginLifecycleService.ts` - `install(tenantId, zipBuffer, userId)` → parsed Manifest, Verify-Signature, in `pending` insert, returnt `{ pluginId, capabilities }` für Consent-Dialog. - `grantConsent(tenantId, pluginId, grants[], userId)` → schreibt Grants in `tenant_plugin_capability_grants`, läuft Migrations, transition `installed (disabled)`. - `enable(tenantId, pluginId, userId)`, `disable(tenantId, pluginId, userId)` → Status-Toggle + Cache-Invalidate (`tenant-plugin-subscriptions` Key). - `update(tenantId, pluginId, newVersionZip, userId)` → installiert neue Version side-by-side, läuft up-Migrations vom alten Version-Tail bis neue Version, marked alte Version `superseded` (bleibt für Rollback verfügbar). - `uninstall(tenantId, pluginId, userId)` → triggert `onUninstall`-Hook im Plugin (falls deklariert), läuft Down-Migrations, löscht Storage-Keys via Storage-Capability-Sweep, löscht Secrets, löscht DB-Einträge, löscht Binary von Filesystem. - `autoDisable(tenantId, pluginId, reason)` → wird vom Crash-Counter-Handler aufgerufen, sets `status='auto-disabled'`, emittiert In-App-Notification. - Tests: `apps/web/app/modules/plugins/services/PluginLifecycleService.test.ts` — pro Lifecycle-Transition ein Test, plus negative Paths (Install mit invalider Signatur, Enable von uninstalled Plugin, etc.). - Commit: `06-plugin-system/hooks-lifecycle: add PluginLifecycleService` 7. **Plugin-API-Routes (Backend)** — REST/Action-Routes für Tenant-Admin-UI - Historical note: the shipped tenant plugin API is consolidated in `apps/web/app/routes/api.tenants.$tenant.plugins.tsx`; do not add new `apps/web/app/routes/api/plugins/*` routes from the old sketch below. - Files: - Current API: `apps/web/app/routes/api.tenants.$tenant.plugins.tsx` — GET list, POST install/enable/disable via operation params. - Current audit UI: `apps/web/app/routes/app.$tenant/settings/plugins.$id.audit.tsx`. - Historical permission sketch: mutating routes require `userHasPermission('app.plugins.manage')`; current read-only list/audit access is split to `app.plugins.use` as documented in `docs/architecture/plugin-hooks.md`. - Tests: pro Route ein Vitest mit gemocktem PluginLifecycleService. - Commit: pro Route-Group ein Commit (4-5 Commits). 8. **Tenant-Admin-UI-Routes (Frontend)** — neue React-Router-Routes - Files: - Current list UI: `apps/web/app/routes/app.$tenant/settings/plugins.tsx`. - Current audit UI: `apps/web/app/routes/app.$tenant/settings/plugins.$id.audit.tsx`. - **WICHTIG:** Nach Hinzufügen sofort `pnpm run typecheck` ausführen damit `./+types/` generiert werden. Imports strikt als `import type { Route } from "./+types/"`. - UI-Komponenten: nutzt existierende shadcn-UI-Komponenten (`Card`, `Dialog`, `Table`, `Switch`, `Button`), keine neuen Design-System-Tokens. - Tests: Component-Tests via Vitest + Testing-Library für jede Route. - Commit: pro Route ein Commit (7 Commits). 9. **Settings-Page-Sandboxed-iframe** — Sicheres Rendern von Plugin-UI - Files: `apps/web/app/modules/plugins/components/PluginSettingsFrame.tsx` - Rendert `