# AI Content Hub — Plan

Status: **planning** (nothing built yet). Update the checkboxes in "Phases" as work lands.

## Goal

Turn this project (`base-inertia`) into an **AI chat hub** that replaces the content dashboards of other
projects. A user logs in to the hub, picks a site (e.g. **Mega Steel**, `C:\xampp\htdocs\mega steel`),
and edits that site's content by chatting. The hub talks to an LLM through **OpenRouter** with
**tool calling**; the tools call a small, protected API on the target site.

It must work for many sites, not only Mega Steel: adding a site should be "install a package +
config + env + register it in the hub".

## Architecture

```
[User] → base-inertia (Hub: chat UI + auth + OpenRouter)
              │  tool calls over HTTPS (token + HMAC)
     ┌────────┼──────────┐
 mega steel  site B    site C      ← each runs the "AI Connector" package
```

- **Hub (this project):** users, sites, per-site access, chat history, LLM calls, confirmation UI,
  audit view, cost tracking. Holds all AI keys.
- **Site (spoke):** no AI at all. Exposes a manifest of what can be edited and endpoints to read/update
  it, reusing its own Requests/Services for validation and saving.

### Request flow

1. User logs in to the hub, opens the chat for "Mega Steel". Hub checks `site_user` access.
2. Hub fetches `GET /api/ai/manifest` from the site (cached): sections, fields, JSON Schema
   (translatable `{ar,en}`, media, enums…).
3. Hub turns the manifest into tools for OpenRouter: `list_sections`, `get_section`,
   `update_section`, `upload_image`, `list_pages`.
4. Model returns a tool call → read tools run directly; **write tools show a diff and wait for the
   user's approval** → hub sends `PATCH /api/ai/sections/{key}`.
5. Site validates with its existing Form Request, saves through its Service, writes an audit row with
   the old value, returns the new state.

### Hard rules

- The AI never writes to a database directly, never runs SQL, never touches a model that is not in
  the site's registry (`config/ai-connector.php`).
- Every write needs user confirmation (configurable, default on).
- No delete endpoints in v1.
- Fetch section details on demand; don't stuff the whole site into the prompt.

## Stack decision

Keep **Laravel 12 + Inertia + Vue 3** for the hub. Reasons: auth, Spatie permissions, i18n, RTL and
dark mode already exist; the sites are Laravel too, so hub and connector share language and patterns.

Add:

| Need | Choice |
|---|---|
| OpenRouter + tool calling | `prism-php/prism` (supports OpenRouter, tools, streaming) |
| Streaming replies | SSE via `response()->stream()`; Vue side `@laravel/stream-vue` (`useStream`) |
| Long agent loops | Queue job + Laravel Reverb (or polling) |
| Later: MCP | `laravel/mcp` |

**Hosting:** put the hub on a **VPS** (Nginx + PHP-FPM + Supervisor for queues), not cPanel. SSE gets
buffered and long requests time out on shared hosting, and each stream holds a PHP-FPM worker. If load
grows: Octane / FrankenPHP. Sites can stay on cPanel.

Alternatives considered: Next.js + Vercel AI SDK (best chat ecosystem, but rebuilds auth/i18n/RTL in
another language), Python FastAPI + LangGraph (overkill for content edits). Revisit only if the chat
becomes the whole product with a very complex UX.

## Connector package (installed in each site)

Name (placeholder): `yourvendor/ai-connector`. Develop it locally as a path repository, then move to a
private VCS repo.

Contents:

- **ServiceProvider + routes** under `/api/ai/*`:
  - `GET  /api/ai/manifest`
  - `GET  /api/ai/sections/{key}`
  - `PATCH /api/ai/sections/{key}`
  - `POST /api/ai/media` (multipart or remote URL, size/type limits)
  - `GET  /api/ai/pages`
  - `GET  /api/ai/audit` and `POST /api/ai/audit/{id}/revert` (phase 3)
- **Middleware:** token check (Sanctum token with abilities), IP allowlist, HMAC signature over
  `timestamp + body` with a short window to block replays, `X-Acting-User` header logged for audit.
- **Registry** `config/ai-connector.php` — the only per-site part:

  ```php
  'sections' => [
      'hero' => [
          'model'   => \App\Models\Hero::class,
          'label'   => 'Home Hero',
          'fields'  => [
              'title'    => 'translatable',
              'subtitle' => 'translatable',
              'image'    => 'media',
          ],
          'rules'   => \App\Http\Requests\Admin\UpdateHeroRequest::class,
          'service' => \App\Services\Admin\HeroService::class,
      ],
  ],
  ```

- **Audit table** `ai_connector_changes`: section key, acting user, old value, new value, timestamp.
  Used for undo.
- Manifest output should follow the MCP tool shape (`name`, `description`, JSON Schema `input`) so a
  later move to `laravel/mcp` is cheap.

Mega Steel notes: Laravel 12, Sanctum already installed, `spatie/laravel-translatable` (fields are
`{ar,en}`), `spatie/laravel-medialibrary` for images, one model per section (`Hero`, `AboutValues`,
`SiteHeader`, `SiteFooter`, `SeoSetting`, …).

## Hub side (this project)

Follows the normal module structure (Controller / Service / Request / Resource, see `CLAUDE.md`).

Tables:

- `sites` — name, base_url, `token` (encrypted cast), `hmac_secret` (encrypted cast), brand prompt
  (tone, terms, forbidden words), default model, active flag.
- `site_user` — which users can use which site, plus a role (e.g. `editor` = text only, `admin` = all).
- `conversations` / `messages` — chat history per user per site, including tool calls and results.
- `pending_actions` — write tool calls waiting for approval (diff, status, approved_by).
- `ai_usage` — tokens + cost per message, per site, per user.

Pieces:

- `OpenRouterService` (wrapping Prism): builds the system prompt (base + site brand prompt), maps the
  manifest to tools, runs the loop.
- `SiteConnectorClient`: signed HTTP calls to a site, retries, timeouts, manifest cache.
- Chat page (Vue): streaming messages, tool-call cards, diff + Approve / Reject, site switcher.
- Admin pages: Sites (CRUD, "test connection"), access per site, usage.

## Environment

### Hub (`base-inertia`)

```env
OPENROUTER_API_KEY=sk-or-...
OPENROUTER_BASE_URL=https://openrouter.ai/api/v1
OPENROUTER_MODEL=anthropic/claude-sonnet-5.5
OPENROUTER_SITE_URL=https://hub.example.com     # sent as HTTP-Referer
OPENROUTER_APP_NAME="Content Hub"               # sent as X-Title
AI_REQUIRE_CONFIRMATION=true
```

Site tokens live **encrypted in the database**, not in `.env`, so sites can be added without a deploy.
⚠️ This makes the hub's `APP_KEY` critical: rotating it breaks every stored token.

### Each site (e.g. Mega Steel)

```env
AI_CONNECTOR_ENABLED=true
AI_CONNECTOR_HMAC_SECRET=long-random-secret
AI_CONNECTOR_ALLOWED_IPS=1.2.3.4               # hub server IP
```

Token: a Sanctum personal access token for a dedicated `ai-hub` user with abilities such as
`sections.read`, `sections.update`, `media.upload`. Generate it on the site, paste it into the hub's
Sites page.

## Pros / cons

**Pros:** one interface for every site; non-technical clients can edit; AR/EN translation in the same
request; cheap onboarding of new sites; sites stay light, AI keys stay in one place.

**Risks and mitigations:**

| Risk | Mitigation |
|---|---|
| Hub is a single point of compromise | Scoped token abilities, IP allowlist, HMAC, no delete endpoints |
| Model misunderstands and edits the wrong thing | Diff + confirmation, audit + undo |
| Token cost grows with history and manifest | On-demand section fetch, trim history, track cost |
| SSE buffering / timeouts | VPS, queue for long loops |
| Site schema changes, manifest goes stale | Manifest generated from config, cache with short TTL, version field |
| File transfer between servers | Dedicated media endpoint with size/type limits |

Keep each site's normal dashboard as a fallback at first; don't remove it.

## Phases

- [ ] **Phase 1 — Connector PoC (Mega Steel, Hero only):** package skeleton, middleware (token + HMAC +
      IPs), `manifest`, `GET`/`PATCH` for `hero`, reuse existing Request/Service.
- [ ] **Phase 2 — Hub chat:** `sites` + `site_user`, `SiteConnectorClient`, Prism + OpenRouter with
      tools, chat page with streaming, write confirmation with diff.
- [ ] **Phase 3 — Safety:** audit table on the site, undo/revert tool, audit view in the hub.
- [ ] **Phase 4 — Coverage:** all Mega Steel sections in the registry, pages, SEO, media upload.
- [ ] **Phase 5 — Preview:** site returns a signed preview URL with the pending change; hub shows it in
      an iframe before approval (same idea as `AdminClientPreviewFrame`).
- [ ] **Phase 6 — Second site:** install the package in another project to prove it is generic; fix
      anything Mega-Steel-specific.

## Later ideas

- Drafts and scheduled publishing ("publish this on Thursday").
- Per-site roles (client edits text only, admin edits everything).
- Cost tracking and billing per site / per user.
- Per-site brand context (tone, glossary, forbidden words).
- Smart tasks: SEO suggestions, "find sections missing an Arabic/English translation", summarize the
  contact inbox.
- Expose the connector as an MCP server (`laravel/mcp`) so other clients (Claude Desktop, Cursor) can
  use the same tools.
- Octane / FrankenPHP if concurrent streams become a bottleneck.

## Open questions

- Package name / vendor and where it is hosted (private GitHub repo?).
- Default model on OpenRouter and a monthly budget cap.
- Do site clients log in to the hub themselves, or only the agency team?
- Hub domain and VPS provider.
