# Plan: Plugin & Extension Ecosystem

**Status**: Draft
**Author**: Prism Core Team
**Created**: 2026-02-06
**Updated**: 2026-02-06

## Overview

Transform Prism from a standalone code generation tool into an extensible platform with a community-driven plugin ecosystem. Plugins can add new generators, templates, spec extensions, CLI commands, and pre-built model packages — allowing the community to share and reuse solutions for common patterns (e.g., blog, e-commerce cart, audit logging).

## Goals

- Define a plugin API that allows third-party code to hook into every stage of generation
- Support plugin types: **generators**, **templates**, **spec extensions**, **model packs**, **CLI commands**
- Create `prism plugin` CLI commands for discovery, installation, and management
- Build a plugin registry (initially file-based, later hosted at `plugins.prism.dev`)
- Enable "model packs" — pre-built spec fragments for common patterns (blog, comments, audit log, notifications)
- Allow plugins to compose — a plugin can depend on other plugins

## Non-Goals

- Visual plugin builder / GUI (deferred to Visual Spec Builder)
- Revenue sharing or paid plugins
- Plugin sandboxing / security isolation (trust-based, like npm)
- Runtime plugins (all plugins operate at generation time)

## Design

### Plugin Structure

```
prism-plugin-audit-log/
├── plugin.yaml              # Plugin manifest
├── generators/
│   └── audit_log.py         # Custom generator class
├── templates/
│   └── audit_log/
│       ├── model.py.j2
│       └── middleware.py.j2
├── spec/
│   └── audit_config.py      # Pydantic spec extension model
├── models/
│   └── audit_models.py      # Pre-built model definitions
├── commands/
│   └── audit_cli.py         # Custom CLI commands
├── tests/
│   └── test_audit.py
└── README.md
```

### Plugin Manifest (`plugin.yaml`)

```yaml
name: prism-plugin-audit-log
version: 1.0.0
description: "Automatic audit logging for all model changes"
author: community-contributor
license: MIT
prism_version: ">=1.7.0"

provides:
  generators:
    - name: AuditLogGenerator
      phase: post_backend     # pre_backend | post_backend | pre_frontend | post_frontend
      entry: generators.audit_log:AuditLogGenerator

  spec_extensions:
    - name: AuditConfig
      section: audit          # Adds `audit:` section to prism.yaml
      model: spec.audit_config:AuditConfig

  model_packs:
    - name: audit_models
      models: models.audit_models
      auto_include: true      # Automatically add to spec when plugin is active

  commands:
    - name: audit
      group: prism audit
      entry: commands.audit_cli:audit_group

depends_on:
  - prism-plugin-auth        # Optional: depends on auth plugin
```

### Technical Approach

#### 1. Plugin API (Generator Hooks)

Plugins register into Prism's generation pipeline via hooks:

```python
from prisme.plugin import PrismPlugin, hook

class AuditLogPlugin(PrismPlugin):
    @hook("post_backend_generate")
    def generate_audit(self, context: GenerationContext):
        """Called after backend generators finish."""
        for model in context.spec.models:
            if model.config.get("audit", True):
                self.render_template(
                    "audit_log/middleware.py.j2",
                    output=f"backend/app/audit/{model.snake_name}_audit.py",
                    model=model,
                )

    @hook("pre_migration")
    def add_audit_tables(self, context: MigrationContext):
        """Inject audit tables into migration."""
        context.add_model(self.get_model_pack("audit_models"))
```

#### 2. Plugin Discovery & Installation

```bash
# Search the registry
prism plugin search "audit"

# Install from registry
prism plugin install prism-plugin-audit-log

# Install from git
prism plugin install git+https://github.com/user/prism-plugin-audit-log.git

# Install from local path (development)
prism plugin install ./my-plugin

# List installed plugins
prism plugin list

# Remove a plugin
prism plugin remove prism-plugin-audit-log
```

Plugins installed to `.prism/plugins/` in the project directory.

#### 3. Model Packs

Pre-built spec fragments that inject models into the generation:

```python
# models/blog_models.py
from prisme.plugin import ModelPack

blog_pack = ModelPack(
    name="blog",
    models=[
        {
            "name": "Post",
            "fields": [
                {"name": "title", "type": "str", "max_length": 200},
                {"name": "slug", "type": "str", "unique": True},
                {"name": "content", "type": "text"},
                {"name": "published", "type": "bool", "default": False},
                {"name": "published_at", "type": "datetime", "optional": True},
            ],
            "relationships": [
                {"name": "author", "type": "many_to_one", "target": "User"},
                {"name": "tags", "type": "many_to_many", "target": "Tag"},
            ],
        },
        {
            "name": "Tag",
            "fields": [
                {"name": "name", "type": "str", "max_length": 50, "unique": True},
            ],
        },
    ],
)
```

Usage in spec:
```yaml
plugins:
  - prism-plugin-blog:
      prefix: blog        # Table prefix: blog_posts, blog_tags
      author_model: User  # Map to existing user model
```

#### 4. Plugin Registry

**Phase 1**: JSON index file hosted on GitHub (`prism-plugin-registry` repo)
**Phase 2**: Hosted registry at `plugins.prism.dev` with search, ratings, download counts

Registry index format:
```json
{
  "plugins": [
    {
      "name": "prism-plugin-audit-log",
      "version": "1.0.0",
      "description": "Automatic audit logging",
      "repository": "https://github.com/...",
      "downloads": 1250,
      "tags": ["audit", "logging", "security"]
    }
  ]
}
```

### Spec Changes

```yaml
# prism.yaml
plugins:
  - prism-plugin-audit-log:
      track_models: all
      exclude: [GlobalConfig]
  - prism-plugin-blog:
      prefix: blog
  - prism-plugin-notifications:
      channels: [email, in_app]
```

### API Changes

- Plugins can register new API routes via the generator hook system
- No changes to core API structure

### Database Changes

- Model packs inject new tables into migrations
- Plugins can add columns to existing tables via migration hooks

## Implementation Steps

1. **Plugin API** — Define `PrismPlugin` base class, hook system, `GenerationContext`
2. **Plugin loader** — Discover and load plugins from `.prism/plugins/`
3. **CLI commands** — `prism plugin install|remove|list|search|create`
4. **Model packs** — Model injection system with prefix/mapping support
5. **Spec extensions** — Allow plugins to register new spec sections
6. **Plugin template** — `prism plugin create my-plugin` scaffolding
7. **Registry** — GitHub-based plugin index with search
8. **Starter plugins** — Audit log, blog, notifications, soft-delete as reference implementations
9. **Documentation** — Plugin authoring guide, API reference

## Testing Strategy

- **Unit tests**: Plugin loading, hook execution order, model pack injection
- **Integration tests**: Install plugin → generate → verify output includes plugin contributions
- **Compatibility tests**: Plugin version constraints, dependency resolution
- **Starter plugin tests**: Each reference plugin has its own test suite

## Rollout Plan

1. Core plugin API + CLI commands + local plugin loading
2. Model packs + spec extensions
3. Registry (GitHub-based)
4. 3-4 starter plugins as reference implementations
5. Plugin authoring documentation + guide

## Complexity & Effort

**Effort Estimate**: 6-8 weeks (1-2 senior developers)
**Complexity**: HIGH — architectural change to generation pipeline

## Dependencies

- None — this is a foundational capability that other features can build on

## Risk Assessment

**High Risks**:
- Plugin API stability — breaking changes to the API break all plugins (mitigated: version pinning, deprecation warnings)
- Plugin quality — bad plugins create bad user experiences (mitigated: starter plugins as reference, testing requirements)
- Dependency conflicts between plugins (mitigated: explicit dependency declaration, conflict detection)

**Adoption Risk**: MEDIUM — requires community engagement to build the ecosystem.

## Open Questions

- Should plugins be Python-only or support other languages (e.g., Node.js for frontend-only plugins)?
- Should we support "plugin themes" — complete visual overhauls via plugin?
- How should plugin updates be managed when they change generated code?
