# CloudAudit API, permissions, and AI contract

## API conventions

- Base: `/api/v1` with JSON requests/responses over HTTPS.
- Cookie/session authentication for web/PWA; CSRF token required for state changes.
- Every state-changing request carries an `Idempotency-Key`.
- List endpoints use cursor or page pagination, explicit filter allow-lists, and server-side organisation/branch scope.
- Errors use `{ "error": { "code", "message", "fields?", "request_id" } }` and never expose stack traces.

## Endpoint groups

```text
/auth, /me, /organizations, /branches, /users, /roles
/dashboard, /activities, /notifications
/products, /categories, /warehouses, /stock-movements, /stock-adjustments
/customers, /sales, /invoices, /payments, /returns
/suppliers, /purchase-orders, /goods-receipts, /bills
/accounts, /journal-entries, /expenses, /cash-bank, /reports
/ai/chat, /ai/insights, /ai/action-proposals
```

## Minimum permission catalogue

```text
dashboard.view
products.view, products.create, products.update
inventory.view, inventory.receive, inventory.adjust, inventory.transfer, inventory.approve_adjustment
sales.view, sales.create, sales.approve, sales.void
invoices.view, invoices.create, payments.record, returns.create, returns.approve
purchasing.view, purchase_orders.create, purchase_orders.approve, goods_receipts.create, bills.create
accounting.view, accounting.journal.create, accounting.journal.approve, accounting.period.lock
reports.view, reports.export
ai.use, ai.view_usage, ai.approve_action
users.manage, roles.manage, settings.manage, audit.view
```

Permissions are checked by PHP policies/services, not merely by hiding buttons. Approval permissions should be separated from creation permissions for refunds, material stock adjustments, purchase approval, and manual journals.

## AI provider contract

```text
AIProvider::generate(ConversationContext, ToolDefinition[], ProviderOptions): ProviderResponse
AIManager::respond(AIRequest): AIResponse
```

`AIManager` selects Mistral first. Gemini is attempted only for provider-level failure covered by policy (timeout, transient error, service unavailable, or configured capacity limit). It records the selected provider, fallback reason, model identifier, latency, token/usage estimate, request ID, and tool result IDs.

## AI tool contract and safety

- Tools are registered server-side with JSON-schema inputs and required permission(s).
- The model never receives database credentials or unrestricted SQL capability.
- Tool arguments are validated, tenant/branch scope is injected from the authenticated request, and results are minimised to the user’s permitted data.
- Read tools return typed data plus period and source-record identifiers.
- Write tools are proposal tools only: `propose_invoice`, `propose_purchase_order`, `propose_journal_entry`. They return a draft; a user with approval permission performs the actual posting through normal business APIs.
- Prompt injection contained in uploaded files, transaction descriptions, or AI responses must not override tool, permission, or approval rules.

## AI endpoints

| Endpoint | Purpose | Write effect |
|---|---|---|
| `POST /ai/chat` | Scoped conversation and approved read tools | none |
| `GET /ai/insights` | Saved dashboard insights | none |
| `POST /ai/action-proposals` | Create reviewable business draft | proposal only |
| `POST /ai/action-proposals/{id}/approve` | Convert proposal through normal posting service | consequential, permission-protected |
| `GET /ai/usage` | Admin usage/cost telemetry | none |

## Security and observability

- Secrets are environment variables/secret-store entries, never database UI fields or source control.
- Redact credentials, session data, and unnecessary customer PII from AI logs.
- Log all permission denials, transaction posting, reversals, exports, AI tool calls, approvals, and provider failovers.
- Apply per-user and per-organisation limits to authentication, exports, posting, and AI requests.
- Test object-level authorization for every entity endpoint and tool.

