diff --git a/CLAUDE.md b/CLAUDE.md index e940398..b6aafbe 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,6 +9,7 @@ MCP server (TypeScript, ESM, Express 5, `@modelcontextprotocol/sdk`) that genera - `npm run typecheck` - `npm test`: unit tests plus fixture-based browser tests. The browser tests skip if Playwright Chromium is missing. When the default cache is read-only, set `PLAYWRIGHT_BROWSERS_PATH`. - `npm run login` (`-- --check`): manual chatgpt.com login with the persistent profile. The server must be stopped first. +- `npm run selfheal` (`SELFHEAL_DRY_RUN=true`): codex repair of the scraper in a throwaway clone; opens a PR (docs/selfheal.md) ## Layout @@ -18,6 +19,7 @@ MCP server (TypeScript, ESM, Express 5, `@modelcontextprotocol/sdk`) that genera - `src/chatgpt/`: `selectors.ts` (the only DOM knowledge), `client.ts` (page operations), `provider.ts` (one image per new chat), `browser.ts` (persistent context), `prompts.ts` - `src/media.ts`, `src/public-media.ts`: disk storage, manifests, HMAC URLs - `src/update.ts`, `scripts/update.sh`: authenticated self-update +- `src/selfheal.ts`, `scripts/selfheal.sh`, `scripts/selfheal/` (prompt, Playwright + playwright-stealth inspector): codex self-heal - `test/fixtures/`: reduced chatgpt.com DOM used by `test/client.test.ts` ## Conventions diff --git a/README.md b/README.md index b83c13d..5c51c74 100644 --- a/README.md +++ b/README.md @@ -43,5 +43,6 @@ npm test - [docs/architecture.md](docs/architecture.md): generation flow and lineage - [docs/deployment.md](docs/deployment.md): install on Debian/Ubuntu with systemd - [docs/update.md](docs/update.md): update script and authenticated update endpoint +- [docs/selfheal.md](docs/selfheal.md): automatic scraper repair with codex, delivered as a pull request > This automates a consumer web UI. It is unofficial, can break whenever chatgpt.com changes, and must comply with OpenAI's terms for the account used. diff --git a/docs/architecture.md b/docs/architecture.md index fc28db4..b8266c4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -22,6 +22,8 @@ MCP client ──POST /mcp──▶ tools.ts ──▶ JobManager (serial queue, Transient failures (`TURN_TIMED_OUT`, `UI_CHANGED`, `NO_IMAGE_RETURNED`, `BROWSER_ERROR`, generic ChatGPT errors) are retried up to `CHATGPT_RETRIES` times, each in a new chat with a growing pause (`CHATGPT_RETRY_DELAY_SECONDS × attempt`); a crashed browser is relaunched first. Usage limits, lost sessions and content-policy refusals fail immediately. The final error message says how many attempts were made. +Failures that survive the retries and look like frontend changes can trigger a codex self-heal run that opens a pull request ([selfheal.md](selfheal.md)). + `image_count > 1` repeats this in a new chat per image. Every job runs alone because the profile can only be used by one browser. ## Lineage diff --git a/docs/deployment.md b/docs/deployment.md index b4717b5..8108f2b 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -5,7 +5,7 @@ Target: Debian or Ubuntu (one of the last three major releases) in an LXC contai ## 1. System packages ```bash -apt update && apt install -y git xvfb curl ca-certificates +apt update && apt install -y git xvfb curl ca-certificates python3 python3-venv # python3 only for self-heal # Node.js >= 20 via NodeSource (see https://github.com/nodesource/distributions) curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && apt install -y nodejs ``` diff --git a/docs/selfheal.md b/docs/selfheal.md new file mode 100644 index 0000000..6ce1a07 --- /dev/null +++ b/docs/selfheal.md @@ -0,0 +1,81 @@ +# Self-heal (codex) + +chatgpt.com changes its frontend without notice. When the scraper breaks, the server can run **codex in yolo mode** to inspect the live site and patch the code. The fix arrives as a **pull request** that a human reviews and merges. Nothing is merged or deployed automatically. + +## Trigger + +1. Transient failures are first retried in the server (`CHATGPT_RETRIES`, see [architecture.md](architecture.md)). +2. Jobs that still fail with `UI_CHANGED` or `TURN_TIMED_OUT` count as consecutive scraper failures. A successful job resets the counter. + - Usage limits, lost sessions, refusals and text-only replies do not count, because no code change fixes them. +3. At `SELFHEAL_FAILURE_THRESHOLD` failures (default 3), and if no run happened in the last `SELFHEAL_COOLDOWN_HOURS` (default 6), the queue takes the next turn to close the browser and copy the logged-in profile to a temporary directory. It then starts `scripts/selfheal.sh` in the background. + +The run's state and the PR URL appear in `get_usage`, `who_am_i` and `/health` (`selfHeal`). The output goes to `SELFHEAL_LOG_FILE`. + +## What the script does + +1. Clones `SELFHEAL_REMOTE/SELFHEAL_BASE_BRANCH` into a throwaway directory and creates the branch `selfheal/chatgpt-scraper-`. +2. Copies the newest diagnostics (HTML and screenshots of the failures) next to it. +3. Ensures a Python venv (`SELFHEAL_VENV`) with `playwright` and `playwright-stealth`, then runs `npm ci` in the clone. +4. Runs `codex exec --dangerously-bypass-approvals-and-sandbox` with the prompt in `scripts/selfheal/prompt.md`. Codex gets: + - the diagnostics; + - the profile copy; + - `scripts/selfheal/browse.py`, an inspector built on Playwright and playwright-stealth. It opens chatgpt.com with the profile copy, can send a test image prompt, and saves HTML, screenshots and a JSON summary of `data-testid`, `aria-label`, roles, inputs and images over time. +5. Discards the attempt if anything outside `src/chatgpt/*.ts`, `test/fixtures/*.html` or `test/client.test.ts` changed. +6. Runs `npm run typecheck` and `npm test` in the clone. +7. Commits, pushes the branch and opens the PR with `tea`. Codex's summary becomes the description. +8. Always deletes the clone and the profile copy. + +Exit codes and the `SELFHEAL_RESULT` log line: + +| Code | Meaning | +|---|---| +| 0 | PR created, or a dry run succeeded | +| 3 | No changes | +| 4 | Forbidden paths changed | +| 5 | Verification failed | +| 6 | Codex failed or timed out | + +## Manual run + +Stop the service first: the profile is copied from `CHATGPT_PROFILE_DIR`. + +```bash +SELFHEAL_DRY_RUN=true npm run selfheal # no push, no PR +npm run selfheal +``` + +## Server setup (once, as user `mcp`) + +- **codex CLI:** install it and run `codex login`. Its config lives in `~/.codex`, which is `/opt/chatgpt-imagegen-mcp/.codex` with the default install. +- **Python:** `python3` and `python3-venv` (apt). The venv and the Python Playwright browser are installed on the first run. +- **git push:** needs a deploy key with **write** access to the repository, or credentials for the remote. +- **tea:** `tea login add` with a token that can open PRs. Set `SELFHEAL_TEA_LOGIN` when there are several logins. +- **Enable it:** set `SELFHEAL_ENABLED=true` in `.env`. + +## Risks (accepted by design) + +Yolo mode means codex runs with the full permissions of the `mcp` user and without a sandbox. It can read files the service can read, `.env` included, and it holds a copy of the ChatGPT session cookies while it runs. The limits in place: + +- codex works on a throwaway clone and a profile copy, never the running checkout; +- the server's secrets are removed from its environment; +- a path allowlist is enforced; +- the full test suite must pass; +- a human reviews every PR before merging. + +The diagnostics and live page content are untrusted: the prompt tells codex to treat them as data. Review PRs with that in mind, and check that fixtures carry no conversation text. + +## Settings + +| Variable | Default | Purpose | +|---|---|---| +| `SELFHEAL_ENABLED` | `false` | Turn automatic runs on | +| `SELFHEAL_FAILURE_THRESHOLD` | `3` | Consecutive scraper failures before a run | +| `SELFHEAL_COOLDOWN_HOURS` | `6` | Minimum time between runs | +| `SELFHEAL_SCRIPT` / `SELFHEAL_LOG_FILE` | `scripts/selfheal.sh` / `logs/selfheal.log` | Script and log paths | +| `SELFHEAL_REMOTE` / `SELFHEAL_BASE_BRANCH` | `origin` / `main` | Where to clone from and target the PR | +| `SELFHEAL_CODEX_BIN` / `SELFHEAL_CODEX_MODEL` | `codex` / unset | codex binary and optional model | +| `SELFHEAL_CODEX_TIMEOUT_SECONDS` | `2700` | Hard limit for the codex run | +| `SELFHEAL_VENV` | `.selfheal-venv` | Python venv with playwright and playwright-stealth | +| `SELFHEAL_PR_ASSIGNEES` / `SELFHEAL_TEA_LOGIN` | unset | PR assignees and tea login | +| `SELFHEAL_GIT_NAME` / `SELFHEAL_GIT_EMAIL` | selfheal identity | Commit author | +| `SELFHEAL_DRY_RUN` | `false` | Stop after verification, no push or PR |