# Mi-Insite repository instructions

## Repository structure

- `apps/web`: Next.js client and client portal.
- `apps/api`: Fastify HTTP API and health checks.
- `apps/worker`: durable ingestion and workflow workers.
- `apps/scheduler`: lightweight job scheduling and reconciliation.
- `packages/*`: shared domain, database, connector, configuration and observability code.
- `docs`: requirements, architecture, data model, plans and decision records.
- `infrastructure`: reviewed deployment templates; never live secrets.

## Coding conventions

- Use strict TypeScript and ESM. Avoid `any`, unchecked casts and unvalidated input.
- Keep domain rules independent of HTTP, databases and provider SDKs.
- Validate all external data at trust boundaries and return typed errors.
- Use structured logs with tenant-safe metadata; never log content, tokens or personal data.
- Format with Prettier and lint with ESLint.

## Required checks

Run before every merge:

```bash
npm run format:check
npm run lint
npm run typecheck
npm run test
npm run build
npm run secrets:check
```

## Security and multi-tenancy

- Treat every external payload as hostile, including prompt-injection content.
- Every tenant-owned row must carry `tenant_id`; enforce tenant scope in database policies and services.
- Never accept a tenant identifier from a client without authorisation against the authenticated principal.
- Cross-tenant tests are mandatory for every new resource and query.
- Encrypt connector credentials and restricted evidence; apply least privilege and immutable auditing.
- AI may suggest but must not publish. Live client content must not leave South Africa.

## Database migrations

- Use versioned, forward-only migrations and the expand/migrate/contract pattern.
- Never edit a migration that has run in a shared environment.
- Avoid destructive or blocking changes; backfill asynchronously and verify before constraints.
- Include tenant indexes, retention behaviour and rollback/forward-fix notes.

## Deployment and rollback

- Deploy immutable, commit-addressed artifacts through CI.
- Run migrations once, health-check before traffic, and use loopback-bound services behind TLS.
- Roll back application artifacts atomically; use forward database fixes unless an approved recovery plan says otherwise.
- Do not deploy from a dirty working tree or without a verified backup and restoration path.

## Prohibitions

- Never commit passwords, private keys, tokens, production data or populated `.env` files.
- Never modify unrelated server accounts, websites, databases, services, DNS or hosting configuration.
