# Modules

A module is a business capability: it owns its domain, data, contracts and lifecycle. It is not a plugin:
plugins are technical extensions; external integrations should run as services that talk to Fellow by API and events.

```ts
import { defineModule } from '@fellowframework/core'

export default defineModule({
  id: 'records',
  version: '1.4.0',
  name: 'Records',
  description: 'Registration and tracking of official documents.',
  fellow: '^1.0.0-alpha.0',                                 // compatible framework versions
  dependencies: { organizations: '^1.0.0' },
  events: { publishes: ['records.document.created'], consumes: ['organizations.unit.renamed'] },
  permissions: { 'records.document.create': 'Create documents' },
  roles: { 'records.clerk': { description: 'Registers documents', permissions: ['records.document.*'] } },
  entitlements: ['records'],                      // what a tenant must have contracted
  navigation: [{ label: 'Records', path: '/records/documents', permission: 'records.document.read' }],
  requires: ['database', 'storage'],                // checked by `fellow doctor`
  updatePolicy: 'auto',                             // or 'manual'
  retention: [{ table: 'records_access_logs', days: 365, description: 'Access logs' }],
})
```

Routes, pages, entities, migrations, events, listeners, policies and tests are discovered by convention;
`fellow intel` shows the full contract of every module. `fellow module:schema` prints the JSON Schema of the manifest.

## Boundaries

- A module imports another module only through `modules/<id>/public.ts`, and only if it declares the dependency.
- A module never references another module's tables. Call a service from its `public.ts`, or react to its events.
- Events a module emits are declared in `events.publishes`; events it listens to, in `events.consumes`, and they
  must come from dependencies.
- Dependency cycles are errors. Core modules may only depend on core modules.

## Lifecycle

| State | Where | How |
|---|---|---|
| Available | Code in `modules/` of the release | `fellow module:add` (package) or source |
| Installed | `fellow_modules` (version) | `fellow migrate` runs its migrations and records the version |
| Updating / upgraded | | `fellow migrate` (policy `auto`) or `fellow module:upgrade <id>` (policy `manual`); downgrades are refused |
| Contracted | `fellow_entitlements` | `fellow entitlement:grant <key> --tenant t [--expires]` |
| Active per tenant | `fellow_tenant_modules` | `fellow module:activate <id> --tenant t` (no rebuild) |
| Suspended per tenant | | `fellow module:suspend <id> --tenant t` (403 `module.suspended`) |
| Disabled | | `fellow module:disable <id>` (all tenants) |
| Uninstalled | | `fellow module:uninstall <id>`: no tenant may use it; needs a human approval; tables are never dropped |

Activation is runtime only: code, migrations and contracts come from a controlled release. Turn it on in `app.ts`:

```ts
export default defineApp({ moduleActivation: true })
```

With activation on, a route or page of a non-core module answers only when the module is installed and enabled,
active for the tenant and every entitlement is valid. Otherwise: 404 (inactive, disabled, not installed),
403 `module.suspended` or `module.not_entitled`, 503 `module.updating`. Events are not delivered to listeners
of modules inactive for the tenant. Pages receive `navigation`: the entries of the modules serving the tenant
that the user may see. Activation requires every dependency to be active; deactivation is refused while active
modules depend on the module. Deactivating never deletes data. Every change is audited in the tenant.

Changes made by the CLI reach running servers within 15 seconds (or at once with a shared Redis cache).

```ts
import { hasEntitlement, isModuleActive } from '@fellowframework/core'

if (await hasEntitlement('records.signature')) { /* premium path */ }
```

## Events

```ts
export const documentCreated = defineEvent({
  name: 'records.document.created',
  version: 1,
  payload: z.object({ id: z.uuid() }),
})

await emitEvent(documentCreated, { id })      // validates the payload
onEvent(documentCreated, async (payload) => { ... })
```

Delivery is in-process and synchronous; the transactional outbox ([`fellow docs operations`](/docs/operations)) replaces the transport without
changing `defineEvent`, `emitEvent` or `onEvent`.

## Packages and integrity

```bash
fellow module:keygen                                           # Ed25519 key pair in .fellow/keys (not committed)
fellow module:pack records --sign .fellow/keys/publisher.key.pem
fellow module:verify dist/modules/records-1.4.0.tgz
fellow module:add dist/modules/records-1.4.0.tgz --upgrade
```

A package is a `.tgz` with the module files and `fellow-package.json`: module metadata, the SHA-256 of every file
and the module's contract surface. `fellow-package.sig` signs that file with Ed25519. Verification rejects links,
absolute or `..` paths, unlisted, missing or altered files, and signatures from keys not in `.fellow/trust/*.pem`
(or `--key`). Unsigned packages need `--allow-unsigned`. The result includes a `sha512-` integrity string for
lockfiles and registries.

`module:pack` compares the contracts with the previous package (the latest older one in `--out`, or `--previous`):
removing a route, page, event, permission or entity needs a major bump; adding or changing one needs a minor bump
(before 1.0.0, minor counts as major and patch as minor). A smaller bump fails with FW-MOD-015.

Packages run inside the application process: install only code you trust. Third-party code that is not trusted
should run as a separate service integrated by API and events.

## Distribution

Pack, sign, publish and install modules through a registry: see [`fellow docs publishing`](/docs/publishing). Compatibility rules for
module versions: [`fellow docs versioning`](/docs/versioning).
