# PageAgent cPanel installer

## Purpose and security model

The PageAgent cPanel package bootstraps the accepted Node application without Docker or root access. Only the temporary PHP wizard is placed below the addon domain document root. Application source, `.env.production`, uploads, logs, backups, runtime state, and installer state remain below `/home/mealservice/pageagent-app` or `/home/mealservice/.pageagent-installer-state`.

The installer starts locked. Create a one-time token from cPanel Terminal with the command shown on the lock screen. The token contains 32 random bytes, is stored as `/home/mealservice/.pageagent-install-token` with mode `0600`, is rate limited, is never logged, and is removed after completion. Sessions use HttpOnly and SameSite Strict cookies, rotate after unlock, and every modifying request requires CSRF validation.

## Upload and unlock

1. Upload `PageAgent-cPanel-Installer-v1.0.4.zip` and its SHA256 file to `/home/mealservice/pageagent.mealservice.au`.
2. Verify the checksum, then extract the ZIP. It must contain `install/`, `payload/`, `release-manifest.json`, and `INSTALL-README.txt` directly below the addon domain document root.
3. Browse to `https://pageagent.mealservice.au/install/` and run one of the displayed token commands using cPanel Terminal, SSH, or a root shell where indicated.
4. Paste the token once. The installer never asks for a root or sudo password.

## Requirements and root prerequisites

The requirement page reads the Node range from release metadata, evaluates explicit, NVM, cPanel EA, and system runtimes, and persists the selected absolute toolchain. PostgreSQL connectivity and pg_dump backup tooling are separate checks. Domain health is split into DNS, HTTP virtual host, HTTPS, certificate hostname and expiry, addon-domain document-root isolation, and primary-domain redirect safety.

When a server component is missing, download `pageagent-root-prerequisites.sh`, read it, and run it manually as root. The generated root helper installs PostgreSQL client tools only when missing. It never installs or enables PostgreSQL server, replaces cPanel EA Node packages, or changes Redis. A separate inspectable user helper installs an isolated NVM runtime when Node is missing. It contains no secrets and never changes unrelated sites, mail, DNS, PHP versions, users, firewall rules, or Docker access. Return to the wizard and select **Recheck Requirements**.

## Database and Redis

Use either a cPanel PostgreSQL database or an owner supplied server. The test checks authentication, `SELECT 1`, and transactional schema creation followed by rollback. Create databases and users under **cPanel → PostgreSQL Databases** when API creation is unavailable. Database superuser credentials are neither needed nor accepted.

Redis accepts `redis://` or `rediss://`. Keep Redis bound to `127.0.0.1` or a protected private socket. The test performs PING and a namespaced SET/GET/DELETE probe, then removes its key. It never flushes shared data or changes global state.

## Clean and migration installs

**CLEAN INSTALL** generates a new 32 byte hexadecimal credential encryption key and secure session/webhook values. It creates one owner through PageAgent's bcrypt implementation. The password must contain upper and lower case characters, a number, a symbol, and at least 12 characters. No mock or acceptance data is seeded.

**MIGRATE EXISTING PAGEAGENT** requires the original `CREDENTIAL_ENCRYPTION_KEY`. A replacement key makes existing encrypted Meta tokens and provider credentials unreadable. Restore the database before migrations and preserve the original key separately from database backups.

Meta configuration is optional. The Graph version defaults from the accepted application configuration (`v26.0`). AI configuration is deferred to authenticated PageAgent administration.

## Installation and service model

The wizard verifies the embedded payload checksum, safely extracts a new release, runs `npm ci`, builds Next.js, runs `prisma migrate deploy`, and switches the `current` symlink atomically. It never runs development seeds. Completed stages are persisted so Retry and browser resume skip completed operations.

Passenger is preferred when cPanel exposes it. Register the private application root in Application Manager and use the generated `server.cjs` startup file. The worker uses a user owned PM2 installation. If Passenger is unavailable, PM2 runs both web and worker on `127.0.0.1:3000`; the installer reports **ROOT PROXY CONFIGURATION REQUIRED** and supplies domain scoped instructions. A marked `@reboot` cron entry restores the PM2 process list without starting duplicate workers every minute.

Initial safety is always Real Writes OFF, Content Automation SHADOW, Comment Automation SHADOW, and Incident Mode OFF. The installer never enables Autopilot.

## Failed install and recovery

Status and sanitized logs remain in `/home/mealservice/.pageagent-installer-state`. Reopen the browser with the valid session/token or run `php install/cli.php install`; completed stages are skipped. Fix the named requirement and retry. Build or migration failure stops before service activation and does not mark installation complete.

Before finalization, manually remove only the new release directory named in installer state when abandoning a fresh failed install. Never delete an existing database, `shared/`, another release, unrelated cPanel files, or other cron entries. The installer deliberately has no broad cleanup command.

## Management

`/home/mealservice/pageagent-app/pageagentctl` supports `status`, `doctor`, `restart`, `restart-web`, `restart-worker`, `backup`, `restore <backup>`, `logs`, `migrate`, `health`, `version`, `upgrade <release>`, and `rollback`.

`doctor` reports PASS, WARNING, FAIL, or NOT CONFIGURED for Node, database/web health, Redis, storage, disk, Meta configuration, AI configuration, and backup presence. It never prints environment values.

## Backup and restore

`pageagentctl backup` creates a private mode `0600` custom PostgreSQL dump in `shared/backups`. Keep the original credential encryption key in a separate secrets manager. Schedule backups and copy them to encrypted offsite storage. A nonzero backup confirms dump creation; it does not prove restoration.

For restore, stop PageAgent, place the dump in `shared/backups`, inspect the target, and use the tool's explicit confirmation environment. Restore validation against a temporary database remains an owner operations step when the PostgreSQL account can create one. Never test a destructive restore against production.

## Upgrade and rollback

Upgrades require a trusted release archive and create a backup before activation. The release must pass checksum, dependency, build, migration, and health checks before `current` changes. Rollback changes the release symlink only; it never attempts an unsafe automatic schema downgrade. Review migration compatibility before rollback.

## Uninstall considerations

Stop PM2 processes and remove only the marked PageAgent reboot cron entry. Preserve `.env.production`, database dumps, and encrypted data until retention decisions are complete. Remove the private PageAgent application directory and its dedicated database/user only after verification. Do not delete the addon domain, other document roots, shared Redis data, or unrelated cPanel configuration.

## Finalization

Successful installation creates `/home/mealservice/pageagent-app/shared/.installed`, removes the one-time token and owner password input, and disables public installation. Future `/install/` requests show only **PageAgent is installed.** Use `pageagentctl` or authenticated PageAgent administration for maintenance.

## Installer 1.0.4 PostgreSQL testing

**Test safely** persists and displays separate connection, authentication, SELECT 1, transactional DDL, and pg_dump results. Database readiness requires the first four checks to pass. Missing pg_dump remains a visible warning and root action item without being reported as a database connection failure. Advanced details contain only safe host, port, server, SSL, database, username, and client-tool information.

## Installer 1.0.4 runtime hardening

The official archive extracts directly into the addon-domain document root. If the wizard detects `install/install/`, it reports the exact safe move instead of moving files. Do not extract the archive inside an existing `install` directory.

Node discovery evaluates installer configuration, `PAGEAGENT_NODE_PATH`, user NVM releases, cPanel EA releases, the PHP process PATH, and safe user-local locations. Candidates must resolve to regular executable files in trusted, non-world-writable locations with matching npm and npx. The newest compatible candidate is persisted as `NODE_EXECUTABLE`, `NODE_BIN_DIR`, `NPM_EXECUTABLE`, and `NPX_EXECUTABLE`; build, Prisma, web, worker, PM2, management, upgrade, and reboot paths use those absolute values without loading shell startup files.

Application Manager availability is advisory. Passenger is used only with a compatible cPanel EA runtime. Otherwise PageAgent uses account-scoped PM2 and produces an inspectable domain-scoped reverse-proxy helper for a root or cPanel administrator.

The requirements page offers a redacted diagnostic report containing versions, paths, statuses, domain diagnostics, selected Node details, PostgreSQL client paths, and cPanel capability. It omits tokens, passwords, database URLs, App Secrets, and API keys.

## Installer 1.0.4 database migration consistency

A successful **Test safely** operation stores one canonical database configuration under the private installer state directory. Host, port, database, username, and SSL mode are stored exactly as tested. The password is encrypted with an installer-local mode `0600` key and is never copied into browser state, diagnostics, or logs. The Configuration step displays the tested non-secret values and no longer asks the owner to enter a second database endpoint.

The production `DATABASE_URL` is generated once from that canonical configuration with URI encoding for reserved credential characters. Before Prisma migration, the installer parses the generated URL and compares its host, port, database, username, and SSL mode with the tested configuration. A mismatch stops with `DATABASE_CONFIG_MISMATCH`. The migration stage removes inherited PostgreSQL variables, explicitly loads `shared/.env.production`, verifies the actual selected-Node child process sees the tested host, and then performs `SELECT 1` and `prisma migrate deploy` through the selected Node executable. Web, worker, PM2, `pageagentctl`, health, backup, restore, and upgrades explicitly load the same shared production environment; backup and restore also pass its exact SSL mode to PostgreSQL tooling.

When replacing an older installer with v1.0.4, keep the private installer state and pageagent-app directories unchanged. An existing successful PostgreSQL test and saved production configuration remain valid. Select **Retry failed step** to resume directly at database migration; completed dependency, Prisma generation, and build stages remain complete and are skipped.
## Installer 1.0.4 resume child environment

Browser retry invokes the distinct CLI retry command through a clean env -i launcher, carrying only safe home, document-root, package-root, and explicit runtime path values. The CLI reloads the shared production environment file for every child process. Before Prisma starts, the installer records only database host, port, and database name, then aborts with DATABASE_CHILD_ENV_MISMATCH if the child endpoint differs from the tested canonical configuration.

## Installer 1.0.4 live installation recovery

The installer persists its stage, current safe operation, completed stage IDs, command results, sanitized log tail, timestamps, failure class, and release path under the private installer state directory. The browser polls this state and derives progress only from completed stages. Closing or refreshing the browser does not stop or restart the account-level installer job.

A failed or stale job can resume from its first incomplete idempotent stage. The v1.0.1 stage names are normalized during recovery, so a VPS that already completed dependency installation and the PageAgent build does not repeat them. The known PostgreSQL 11-and-earlier enum migration is split into compatible migrations; a failed `20260920213000_product_infrastructure` attempt is marked rolled back through Prisma before one controlled retry.

Command results contain descriptions rather than secret-bearing command lines. stdout, stderr, browser details, diagnostics, and the downloadable installation report are redacted before persistence or display.
