# Nexus Manual Tester

Interactive testing via nexus-client against a running (or auto-started) backend.

## Arguments

$ARGUMENTS — What to test (e.g. "create a contact, verify it exists, delete it"). If empty, ask the user. If the user says "en la demo" or similar, use demo mode (see below).

## Context detection

Detect the execution context by inspecting the working directory:

| Check | Context | CLI prefix | Notes |
|-------|---------|-----------|-------|
| `packages/backend/package.json` exists with `@gzl10/nexus-backend` | **Monorepo** | see below | Nexus monorepo development |
| Otherwise | **Project** | `pnpm nexus` or `npx nexus` | External project using Nexus |

**Monorepo sub-modes** (detected from $ARGUMENTS):

| Mode | Trigger | CLI prefix | Target |
|------|---------|-----------|--------|
| **Core** (default) | No demo/plugin mention | `pnpm nexus` | `packages/backend` |
| **Demo** | "en la demo", "demo", "demo-backend", or when testing plugins | `pnpm nexus:demo` | `demos/demo-backend` |

**Project context:** Use `pnpm nexus` if `nexus` is in local devDependencies, otherwise `npx nexus`. Backend start command: whatever `scripts.dev` is in `package.json`.

Throughout the steps below, `$CLI` refers to the resolved CLI prefix.

## Plugin testing rule

**In monorepo context:** Plugins MUST be tested in demo mode only (`pnpm nexus:demo` / `demos/demo-backend`). NEVER install or activate plugins in the core backend (`packages/backend`). If the user asks to test a plugin without mentioning "demo", auto-select demo mode and inform them.

**In project context:** Plugins are tested directly (the project IS the app).

Before testing a plugin:

1. **Verify the plugin is installed and enabled:**
   ```bash
   $CLI plugin list
   ```
   If the plugin is not listed or not enabled, install/enable it first:
   ```bash
   $CLI plugin add <plugin-name>
   $CLI plugin enable <plugin-name>
   ```

2. **Run pending migrations:**
   ```bash
   $CLI migrate deploy
   ```

3. Only then proceed with testing.

## Step 0: Discover available endpoints

Read the REST Client files to understand what endpoints and payloads are available:

- **Monorepo core:** `packages/backend/requests/*.http`
- **Monorepo demo:** `demos/demo-backend/requests/*.http` (if exists), plus core requests
- **Monorepo plugins:** `plugins/*/requests/*.http`
- **Project:** `requests/*.http` (if exists)

Use these as reference for endpoint paths, expected payloads, and authentication patterns.

## Step 1: Build (if needed) and ensure backend is running

**Monorepo demo mode only:** Build core packages if dist directories are missing:

```bash
pnpm build --filter @gzl10/nexus-sdk --filter @gzl10/nexus-backend --filter @gzl10/nexus-client --filter @gzl10/nexus-ui
```

Check if the backend is reachable:

```bash
$CLI client health
```

If it fails (connection refused), start the backend in background **forcing JSON logs** so you can parse them reliably (sin códigos ANSI ni multilínea de pino-pretty):

- **Monorepo core:** `cd packages/backend && LOG_FORMAT=json pnpm dev &`
- **Monorepo demo:** `cd demos/demo-backend && LOG_FORMAT=json pnpm dev &`
- **Project:** `LOG_FORMAT=json pnpm dev &` (from project root)

`LOG_FORMAT=json` produce una línea JSON por evento — útil para grep/jq y para que la IA filtre logs sin parsear ANSI. Si el `.env` ya define `LOG_FORMAT`, el override del entorno tiene prioridad solo si no se exporta antes.

Wait until `$CLI client health` succeeds (poll every 2s, max 30s).

Record whether we started the backend (to shut it down at the end).

## Step 2: Login

```bash
$CLI client login [email] [password]
```

- If credentials provided in $ARGUMENTS, use those
- If not, defaults from .env (ADMIN_EMAIL / ADMIN_PASSWORD) are used automatically
- If no defaults, ask the user

Session is persisted via PAT in `~/.nexus/session.json` indexed by project path — no expiration, survives across commands, supports multiple projects.

Confirm login succeeded (check output for user JSON).

## Step 3: Execute operations

Translate the user's instructions into nexus CLI calls:

```bash
$CLI client entity <module/entity> <action> [args]
```

Available commands:

**Entity CRUD:**

- `$CLI client entity <path> list` — list entities
- `$CLI client entity <path> get <id>` — get by ID
- `$CLI client entity <path> create '<json>'` — create
- `$CLI client entity <path> update <id> '<json>'` — update
- `$CLI client entity <path> delete <id>` — delete

**Actions (module/entity/row):**

- `$CLI client action <module> <key> ['<json>']` — module action (POST by default)
- `$CLI client action <module> <key> <id> ['<json>']` — row action
- `$CLI client action <module> <key> -m GET` — read action (e.g. sessions, list-tokens)

**Generic HTTP (any endpoint):**

- `$CLI client fetch <METHOD> <url> ['<json>']` — hit any endpoint
- `$CLI client fetch GET /auth/me` — example read
- `$CLI client fetch POST /mail/send '{"to":"x"}'` — example write
- `$CLI client fetch GET /some/endpoint --pat <token>` — bypass session, use PAT directly

**Storage:**

- `$CLI client storage upload <file...> [--folder X] [--scope X] [--visibility public|internal|private]` — upload one or more files
- `$CLI client storage download <id> [--output path]` — download file to disk (default: original filename in CWD)
- `$CLI client storage list [--mimetype X] [--folder X] [--scope X] [--limit N]` — list storage files
- `$CLI client storage delete <id>` — delete file by ID
- `$CLI client storage stats` — storage statistics (total files, size, by type)

**Other:**

- `$CLI client health` — health check
- `$CLI client login [email] [password]` — authenticate (creates PAT)
- `$CLI client me` — current user info
- `$CLI logs [--lines N] [--file path]` — tail backend log file in real time (requires LOG_FILE in .env)
- `$CLI migrate list` — show migration status (alias for `migrate status`)

**Command selection guide:**
- **entity** — CRUD on entities (list, get, create, update, delete)
- **action** — declared actions in modules/plugins (have a key, may need body or row id)
- **storage** — file upload/download/list/delete/stats
- **fetch** — anything else (custom routes, plugin endpoints, non-standard paths)

Use `--debug` flag on any command for verbose HTTP logging.

For each operation:
1. Execute via `$CLI client`
2. Capture and display the response
3. Interpret whether it succeeded or failed

## Step 4: Verify coherence with database

After each write operation (create, update, delete), verify via db shell:

```bash
$CLI db shell <<< "SELECT * FROM <table> WHERE id = '<id>';"
```

Compare the API response with the raw database state:
- **Create:** record exists in DB with correct values
- **Update:** record reflects new values, updated_at changed
- **Delete:** record no longer exists (or soft-deleted if applicable)

Report discrepancies clearly.

## Step 5: Logout and cleanup

```bash
$CLI client logout
```

This revokes the PAT server-side and removes the entry from `~/.nexus/session.json`.

If we started the backend in Step 1, stop it:

```bash
kill %1  # or the recorded PID
```

## Step 6: Report

Summarize:
- Operations executed and their results
- Database coherence: PASS / FAIL per operation
- Any errors or unexpected behavior

Format as a table:

| # | Operation | API Result | DB Check | Status |
|---|-----------|------------|----------|--------|
| 1 | POST /contacts | 201 Created | Row exists | PASS |
| 2 | PATCH /contacts/:id | 200 Updated | Values match | PASS |
| 3 | DELETE /contacts/:id | 204 | Row gone | PASS |
