# Technical Documentation: every-app/open-seo

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/every-app/open-seo)

### Overview (`README.md`)

# OpenSEO

> Open source alternative to Semrush and Ahrefs

OpenSEO is an SEO tool for _the people_. If tools like Semrush or Ahrefs are too expensive or bloated, OpenSEO is a pay-as-you-go alternative that you actually control.

> All-in-one SEO tool for you and your AI agent.

Connect with any agent like Claude Code, OpenClaw or Hermes. We have pre-built skills, but you can build your own to tailor OpenSEO to your needs.

<img width="100%" alt="openseo-keyword-research" src="https://github.com/user-attachments/assets/8ebdc439-3e72-41ab-8bde-8cda771ef2e8" />

## Hosted Version

Try OpenSEO for free on our website. If you want to support the project, a hosted subscription is $10/month.

[openseo.so](https://openseo.so)

## Why use OpenSEO?

- Best in class MCP and AI Skills.
- Modern, simple UI.
  - Focused workflows instead of a bloated, complex SEO suite.
- No subscriptions.
  - Bring your own DataForSEO API key and pay only for what you use.
- Fork and vibe code your own custom tool.

## Main SEO Workflows

- Keyword research
- Rank tracking
- Competitor Insights
- Backlinks
- Site Audits
- AI Visibility

## OpenSEO MCP & Agent Skills

OpenSEO exposes an MCP server so AI agents like Claude Code, OpenClaw, and Hermes can use your SEO data directly. Agent Skills are reusable workflows that guide your agent through SEO tasks using the MCP.

- [Set up ChatGPT web or desktop](https://openseo.so/docs/chatgpt) (works on Free and paid ChatGPT plans)
- [Set up Codex](https://openseo.so/docs/codex-plugin)
- [Set up OpenSEO MCP](https://openseo.so/docs/mcp)
- [Set up OpenSEO Agent Skills](https://openseo.so/docs/skills/setup)

## Self-Hosting

### Recommended: EveryApp

EveryApp simplifies self hosting open source apps + personal software. It runs entirely in your Cloudflare account on their $5/month plan.

It's also the company behind OpenSEO. OpenSEO actually started out because I was trying to do SEO for EveryApp. But, then people loved it so much that we paused EveryApp for a while. We've since relaunched it and think it's the best way to self host OpenSEO.

https://everyapp.com/docs/apps/openseo

```bash
npm install everyapp
everyapp setup --domain apps.yourcompany.com
everyapp install https://github.com/every-app/open-seo
```

### DataForSEO API Key

You need a DataForSEO API key to get SEO data, or a [treg](https://treg.to) account which also gives access to DataForSEO. See [`docs/DATAFORSEO_API_KEY.md`](./docs/DATAFORSEO_API_KEY.md).

### Other options

OpenSEO also supports two standalone self-hosting paths. Both use email and password accounts: the first visitor creates the admin account, teammates join from invitation links, and MCP clients (Claude, ChatGPT, Codex, Cursor) sign in with the same accounts.

- **Docker** - On your own server or computer, with a prebuilt image that is ready in seconds. Works with Compose-based platforms such as Coolify, Portainer and Dokploy. See [`docs/SELF_HOSTING_DOCKER.md`](./docs/SELF_HOSTING_DOCKER.md).
  - Running the older single-container image? It keeps getting updates; [move to the new setup](./docs/SELF_HOSTING_DOCKER.md#move-from-the-old-docker-image) when you are ready, data included.
- **Cloudflare** - Self host on Cloudflare, but not with EveryApp. See [`docs/SELF_HOSTING_CLOUDFLARE.md`](./docs/SELF_HOSTING_CLOUDFLARE.md).

For security-conscious setups, two advanced options replace the accounts with your own network controls:

- **Cloudflare Access** in front of the Cloudflare deploy, so Cloudflare checks every request before it reaches OpenSEO. See [`docs/SELF_HOSTING_CLOUDFLARE.md`](./docs/SELF_HOSTING_CLOUDFLARE.md).
- **No sign-in on Docker**, behind Tailscale, a private network or your own authenticating proxy. See [Without sign-in](./docs/SELF_HOSTING_DOCKER.md#without-sign-in-advanced).

## Costs

OpenSEO needs a [DataForSEO](https://dataforseo.com/?aff=255379) API key so that you can get SEO data. You pay them directly when self hosting.

See [openseo.so/pricing](https://openseo.so/pricing)

When you self host, your costs will be slightly lower than the estimates on our website. The way the hosted service makes money is by charging 28% extra for every request we make to DataForSEO.

## Local Development

See [`docs/LOCAL_DEVELOPMENT.md`](./docs/LOCAL_DEVELOPMENT.md).

## Contributing

Creating clear issues is the best way to contribute.

Read more here: [`.github/CONTRIBUTING.md`](./.github/CONTRIBUTING.md)

We have this skill: `/simple-issue-description` which helps.

```sh
npx skills add every-app/open-seo --skill simple-issue-description
```

## Community

Join Discord to chat: [Discord](https://discord.gg/c9uGs3cFXr)

Follow along for updates:

- Follow on X: https://x.com/bensenescu
- Sign up for the mailing list on our website: [openseo.so](https://openseo.so)

---

### Overview (`deploy/stripe-app/README.md`)

# OpenSEO Stripe App (Stripe Projects provider)

`stripe-app.json` registers OpenSEO as a Stripe Projects provider. The endpoints it points at live in `src/server/stripe-projects/`; `docs/maintainers/specs/0021-stripe-projects-provider.md` explains them.

## Set up

1. Upload the app from this directory with the Stripe CLI, signed in to OpenSEO's Stripe account:

   ```bash
   stripe apps upload --non-interactive --accept-tos --wait
   ```

   Stripe refuses a version it already has: raise `version` in `stripe-app.json` first, or pass `--app-version`. The CLI rewrites `stripe-app.json` in its own format on every upload, so the file is committed that way and left out of Prettier. `pnpm-lock.yaml` is here only because the CLI will not package a directory without a lockfile.

2. In the Stripe Dashboard app settings, copy the app's signing secret and set it as `STRIPE_PROJECTS_SIGNING_SECRET` (GitHub production secret, then deploy). Until it is set, every `/api/stripe-projects/` path returns 404.
3. Store any random value under the Secret Store key `oauth_client_secret`. OpenSEO authenticates the token endpoint with Stripe's signature or PKCE and ignores the client secret.
4. Fill in the Marketplace listing: icon, subtitle, privacy policy (`https://openseo.so/privacy`), terms (`https://openseo.so/terms-and-conditions`), support channel with a response time, and test instructions.
5. Ask Stripe to put OpenSEO in the `dev` or `testing` catalog, then run `stripe projects add openseo/api`, `open`, `rotate` and `remove` against production before submitting for review.

`llm_context` in the manifest points at `https://openseo.so/stripe-projects/llm-context.md`. Publish that file (it ships with the public docs page) before uploading the app.

Stripe's provider spec is not public. The protocol here follows PostHog's open-source provider (`ee/partners/stripe/api/provisioning` in `PostHog/posthog`). Check these against Stripe's spec and test harness once you have repository access:

- The names Stripe writes to `.env` for `access_configuration.key` and `mcp_url`.
- Whether Stripe always sends `kyc.verified_fields`. A request without it is refused.
- `payment_credentials: "provider"` in the token response (PostHog answers `"orchestrator"` because Stripe bills for it).
- Whether Stripe retries `POST provisioning/resources` with the same `project_id` and expects the same resource back. Each call creates a new resource here.
- Whether Stripe sends the OAuth client id and secret to the token endpoint. They are ignored.
- What Stripe expects from a read or a second remove of a removed resource. Both answer 404.

---

### Overview (`docs/maintainers/README.md`)

# Maintainer documentation

Shared, versioned documentation for people maintaining OpenSEO. Put engineering decisions, development workflows, and useful maintenance notes here.

User-facing documentation belongs in the rest of `docs/` or `web/content/docs/`. This directory is not published to the documentation site, but its contents are tracked in the repository and must not contain secrets.

`review-guidelines.md` is the shared context for code reviewers, human and agent: hard invariants plus the false-positive controls that keep reviewers from flagging intentional behavior.

Create documents when they will help future maintenance or when explicitly requested. Keep task status, PR review notes, and validation results in the PR description. Log repository friction in `.agents/PAPERCUTS.md`.

---

### Overview (`docs/release-notes/README.md`)

# Release Notes

Store finalized release notes in this folder as versioned Markdown files.

Recommended naming:

- `docs/release-notes/v0.0.2.md`

Typical flow:

1. Generate a draft with `pnpm -s release:notes`.
2. Copy the final edited notes into a versioned file in this folder.
3. Publish with `gh release create <tag> --title <tag> --notes-file docs/release-notes/<tag>.md`.

---

### Overview (`plugins/openseo/README.md`)

# OpenSEO for Grok Bot and Cursor

SEO made simple.

OpenSEO gives your agent real SEO data and guided workflows, so its advice is grounded in your website instead of generic recommendations.

## What you can do

- Find and evaluate keywords
- Research competitors and content gaps
- Audit a website and prioritize fixes
- Analyze backlinks and find link prospects
- Track organic and Google Maps rankings
- Work with Google Search Console and Analytics data
- Research AI prompts and track brand mentions, citations, and competitors

The plugin includes twelve skills that guide your agent through complete SEO workflows, plus the hosted OpenSEO MCP server for live data and project management.

## Connect

Install OpenSEO from the Grok Bot or Cursor marketplace. The first time your agent uses an OpenSEO tool, follow the OAuth prompt to sign in and approve the connection. There is no API key to configure.

To check the connection without using credits, ask: "Use OpenSEO to check my connection and list my projects."

You need an OpenSEO account. The plugin package is free and open source. Hosted OpenSEO plans and usage credits are described at [openseo.so/pricing](https://openseo.so/pricing), and OpenSEO can also be [self-hosted](https://github.com/every-app/open-seo#self-hosting).

## Try it

- "Research keywords for my website and shortlist the best opportunities."
- "Audit my website and tell me what to fix first."
- "What does competitor.com rank for that I don't?"
- "Which pages are close to ranking in Google Search Console?"
- "Track my rankings for these keywords and summarize what changed."
- "Help me choose prompts to track in AI answers, and show the cost first."

## Included skills

- AI prompt research
- AI visibility audit
- Competitive landscape
- Competitor analysis
- Keyword clustering
- Keyword research
- Link prospecting
- Local SEO
- SEO audit
- SEO coach
- SEO project setup
- SEO report

## Links

- [OpenSEO](https://openseo.so)
- [MCP documentation](https://openseo.so/docs/mcp)
- [Privacy policy](https://openseo.so/privacy)
- [Terms](https://openseo.so/terms-and-conditions)
- [Support](https://openseo.so/support)

---

### Overview (`tests/badseo/README.md`)

# badseo.dev

**A test site full of SEO mistakes.**

badseo.dev is a set of open-source web pages. Each page breaks one common
technical-SEO rule: a missing `<title>`, a redirect loop, a page nothing links
to, thin content. Point an SEO crawler at it and check what the crawler catches.

It is also the end-to-end test fixture for the
[OpenSEO](https://openseo.so) site audit. Every page lists the audit issues it
should trigger, and a harness runs the real audit engine against a running copy
to check that it does.

Maintained by the team behind [OpenSEO](https://openseo.so), an open-source SEO
tool.

---

## What's covered

Every issue type in the OpenSEO audit engine is exercised by at least one page
(the harness enforces this). Pages are grouped by category:

| Category                     | Pages                                                                                                         |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------- |
| **Head tags & headings**     | missing title, title too long/short, missing meta, meta too long, missing H1, multiple H1, heading-level skip |
| **Content quality**          | thin content, images missing alt, duplicate content, duplicate title, duplicate meta description              |
| **Indexability & canonical** | noindex (meta + `X-Robots-Tag` header), canonicalized to another URL, conflicting canonicals                  |
| **HTTP status & links**      | 404, 500, 403 (blocked), broken internal link                                                                 |
| **Redirects**                | redirect chain, redirect loop, trailing-slash canonical (redirect-cycle trap)                                 |
| **Performance**              | slow server response (TTFB)                                                                                   |
| **Site structure**           | orphan page, deep click-path                                                                                  |
| **Kitchen sink**             | one page that breaks six ways at once                                                                         |

Browse them all on the homepage at `/#issues`.

## How it's built

badseo.dev is a TanStack Start app deployed to a Cloudflare Worker, following
the same Vite and Cloudflare setup as the repository's `web/` app.

TanStack React routes render the healthy homepage and privacy policy.
A TanStack catch-all server route keeps the deliberate fixtures as raw
responses with byte-level control over status codes, redirects, headers
(`X-Robots-Tag`, `Link: …; rel=canonical`), timing, and the malformed `<head>`
states the audit needs to observe.

- `src/routes/` — TanStack pages plus raw server routes for fixtures,
  `robots.txt`, and `sitemap.xml`.
- `src/server/badseo.ts` — fixture dispatch and crawler-discovery responses.
- `src/lib.ts` — raw fixture HTML rendering. Its shared chrome is deliberately
  **SEO-neutral**: it emits no `<h1>`–`<h6>` and no `<img>`.
- `src/fixtures/*.ts` — the fixtures, one file per category.

## Analytics

Plausible Analytics loads on every page using the site-specific script supplied
for badseo.dev. It provides the cookieless aggregate baseline without changing
the Google Analytics consent choice.

Google Analytics uses measurement ID `G-7MXV9FH7SS`. The small consent script in
`public/analytics.js` is shared by TanStack pages and raw fixture documents. It
does not request Google's tag or set analytics cookies until a visitor accepts.
The visitor can reject analytics or revisit the choice from **Cookie settings**
in the footer. The choice is stored only in the visitor's browser.

## Run it locally

```bash
# from the repository root
pnpm install --frozen-lockfile          # also needed by the audit harness
pnpm --dir tests/badseo install --frozen-lockfile
pnpm --dir tests/badseo run dev               # serves on http://localhost:8787
```

Use the Vite dev server above when running the audit locally. Its sitemap URLs
should use `http://localhost:8787`, matching the origin passed to the harness.

Format BadSEO files with the repository's root Prettier installation:

```bash
pnpm exec prettier --write "tests/badseo/**/*.{ts,tsx,json,jsonc,md}"
```

## Run the end-to-end audit

The harness drives the **real** OpenSEO crawl + issue-detection functions
(imported straight from `../src`) against a running badseo.dev, then asserts every
fixture triggers exactly the issues it declares — and that the homepage,
privacy policy, and support pages come back clean.

```bash
# from the repository root, with the BadSEO dev server running:
pnpm --dir tests/badseo run audit http://localhost:8787
```

It prints a per-page pass/fail matrix and an issue-type coverage line, and exits
non-zero on any mismatch — so it works as a CI gate for the audit engine.

## Add a fixture

Contributions are welcome — a new fixture _is_ a new regression test. Each is a
small object:

```ts
const myFixture: Fixture = {
  path: "/category/my-mistake",
  category: "Content quality",
  name: "My SEO mistake",
  summary: "One-line description shown in the on-page test panel.",
  lesson: "Why it matters / how to fix it.",
  expectedIssues: ["thin-content"], // the audit issue ids this page must trigger
  handler: () =>
    htmlResponse(
      renderPage({
        fixture: myFixture,
        title: "…",
        metaDescription: "…",
        bodyHtml: "…",
      }),
    ),
};
```

Then add it to its category's exported array. `expectedIssues` is type-checked
against the real audit registry, and the harness will hold you to it.

Guidelines:

- **Isolate one issue per page.** A themed page should be healthy in every way
  _except_ the defect it demonstrates, so the audit result is unambiguous. (The
  kitchen-sink page is the deliberate exception.)
- **Keep titles and meta descriptions unique** across the site, or you'll create
  accidental duplicate-title / duplicate-meta groups. The exceptions are the
  intentional duplicate pairs.
- **Keep the copy plain.** Say what the page does and why the mistake matters.
  No hype.

## Deploy

Vite builds the TanStack Start client and Worker bundles, then TypeScript checks
the project before Wrangler deploys it:

```bash
npm run build                          # Vite build + typecheck
npm run deploy                         # build + wrangler deploy → badseo.dev
```

The custom-domain routes for `badseo.dev` and `www.badseo.dev` live in
`wrangler.jsonc`, alongside the TanStack server entry and built asset directory.

---

### Web Content Docs Self Hosting Index (`web/content/docs/self-hosting/index.md`)

---
title: "Self-Hosting OpenSEO"
description: "Run OpenSEO yourself with Docker or Cloudflare, bring your own DataForSEO API key, and pay only for what you use."
---

OpenSEO is free and open source. Self-hosting means the app costs $0. You bring your own DataForSEO API key and pay DataForSEO directly for API usage.

There are two self-hosting paths. Both use email and password accounts: the first visitor creates the admin account and teammates join from invitation links.

- **[Docker](/docs/self-hosting/docker)**, on your own server or computer. A prebuilt image that is ready in seconds, and works with Compose-based platforms such as Coolify, Portainer and Dokploy.
- **[Cloudflare](/docs/self-hosting/cloudflare)**, with no server to run. One deploy command puts OpenSEO on your own Cloudflare account, with automatic database backups, and it works on Cloudflare's free plan.

OpenSEO also runs on [EveryApp](https://everyapp.com/docs/apps/openseo), which installs it on your own Cloudflare account with sign-in, team access and your DataForSEO key handled for you. To move an install you already run, open Settings and click Move to Every App: it copies your projects, history, reports and SAM chats there.

For security-conscious setups, you can replace the accounts with your own network controls: Cloudflare Access in front of the Cloudflare deploy, or Docker without sign-in behind Tailscale or a private network.

## DataForSEO API key setup

OpenSEO uses [DataForSEO](https://dataforseo.com/?aff=255379) to fetch SEO data. DataForSEO is a paid third-party service unaffiliated with OpenSEO. You need an API key to connect OpenSEO to it.

1. Go to [DataForSEO API Access](https://app.dataforseo.com/api-access?aff=255379).
2. Copy the API credential labelled "Base64" from the API Access page.
3. Set this as `DATAFORSEO_API_KEY` in your environment:
   - Docker: `deploy/standalone/.env`
   - Cloudflare: `.env.selfhost`
   - Local development: `.env.local`

New DataForSEO accounts include $1 of free credit to test with, and the minimum top-up is $50. See [pricing](/pricing) for cost estimates. Self-hosted costs run slightly lower, since the hosted service adds a 28% fee on DataForSEO requests.

## Optional features

### Google Search Console

Search Console is optional and works in self-hosted deployments using your own Google OAuth client. It takes about 10 minutes of one-time setup. See the [Google Search Console guide on GitHub](https://github.com/every-app/open-seo/blob/main/docs/SELF_HOSTING_GOOGLE_SEARCH_CONSOLE.md).

### Google Analytics

Google Analytics is optional too and uses your own Google OAuth client. See the [Google Analytics guide on GitHub](https://github.com/every-app/open-seo/blob/main/docs/SELF_HOSTING_GOOGLE_ANALYTICS.md).

---

### Web Content Docs Skills Index (`web/content/docs/skills/index.md`)

---
title: "OpenSEO Agent Skills"
description: "Add OpenSEO Agent Skills to Claude Code, Codex, or another AI agent so it can run repeatable SEO workflows with live OpenSEO data."
---

OpenSEO Agent Skills let you hand repeatable SEO workflows to your AI agent.

Run a slash command when you need keyword research, AI visibility tracking, clustering, competitor analysis, link prospecting, or project setup. The skill gives your agent the workflow instructions.

You stay in charge of strategy. Your agent uses OpenSEO data and the skill instructions to research the answer, then saves the result as a report in your project.

No account yet? Try the [free SEO tools](/tools).

## Set up OpenSEO Agent Skills

MCP connects your agent to OpenSEO data. Skills tell your agent which SEO workflow to run.

The OpenSEO plugins for Claude, ChatGPT and Codex include the skills. Connectors and MCP connections don't. [Install skills](/docs/skills/setup) shows how to check what your agent has and how to add the skills to any agent.

## Start here

- [SEO Project Setup](/docs/skills/seo-project-setup): save your goals, positioning, competitors, and key pages to your project context, so every other skill reuses them.
- [SEO Coach](/docs/skills/seo-coach): choose the next workflow when you are new to SEO or unsure what to run first.

## Audit workflows

- [SEO Audit](/docs/skills/seo-audit): audit a site and understand its important problems, worthwhile improvements, and likely effects on traffic and the business.

## Research workflows

- [Keyword Research](/docs/skills/keyword-research): find keywords worth targeting and explain why they fit.
- [Keyword Clustering](/docs/skills/keyword-clustering): turn keyword lists into page groups, content priorities, and cannibalization checks.
- [Competitive Landscape](/docs/skills/competitive-landscape): map who is winning across a market and where your openings are.
- [Competitor Analysis](/docs/skills/competitor-analysis): analyze one competitor and turn the research into strategic takeaways.
- [Local SEO](/docs/skills/local-seo): audit a Google Business Profile, compare it to local competitors, and map Maps visibility around a location.

## AI visibility workflows

- [AI Visibility Audit](/docs/skills/ai-visibility-audit): find the few changes most likely to get your brand mentioned or cited in AI answers.
- [AI Prompt Research](/docs/skills/ai-prompt-research): find the questions people ask about your market, how ChatGPT answers them, and which sites get cited.

## Promotion workflows

- [Link Prospecting](/docs/skills/link-prospecting): find qualified outreach prospects and the angle that makes each one relevant.

## How the results reach you

- [SEO Report](/docs/skills/seo-report): the shared report-writing skill every workflow above delivers through. Your agent writes one self-contained HTML page and saves it to your project's Reports page, where anyone can read or print it.

## Learn more about skills

OpenSEO uses the same `SKILL.md` pattern supported by modern AI agents. To learn how skills work in your agent, read:

- [Claude Code skills documentation](https://docs.claude.com/en/docs/claude-code/skills)
- [OpenAI Skills documentation](https://help.openai.com/en/articles/20001066-skills-in-chatgpt)

## Read the actual skills

These pages explain what each skill is for. The source instructions live in GitHub:

- [OpenSEO Agent Skills on GitHub](https://github.com/every-app/open-seo/tree/main/plugins/openseo/skills)

---

### DATAFORSEO API KEY (`docs/DATAFORSEO_API_KEY.md`)

# DataForSEO API Key Setup

OpenSEO uses [DataForSEO](https://dataforseo.com/?aff=255379) to fetch SEO data. It's a pay-as-you-go third-party service unaffiliated with OpenSEO. You need an API key to connect OpenSEO to it.

New DataForSEO accounts include $1 of free credit to test with, and the minimum top-up is $50.

## Get your API key

1. Go to [DataForSEO API Access](https://app.dataforseo.com/api-access?aff=255379) (create an account if you don't have one).
2. Copy the API credential labelled "Base64" from the API Access page. This is the base64 encoded value of your DataForSEO email and API password in the format `email:password`.

## Where to set it

Set the value as `DATAFORSEO_API_KEY`:

- **Docker self-hosting:** in `deploy/standalone/.env` (see [`SELF_HOSTING_DOCKER.md`](./SELF_HOSTING_DOCKER.md)), or `.env` for the [older single-container image](./SELF_HOSTING_DOCKER_LEGACY.md).
- **Cloudflare self-hosting:** in `.env.selfhost` (see [`SELF_HOSTING_CLOUDFLARE.md`](./SELF_HOSTING_CLOUDFLARE.md)). Legacy button/Wrangler deployments: as a Worker secret in the dashboard under `Settings` -> `Variables & Secrets`.
- **Local development:** in `.env.local` (see [`LOCAL_DEVELOPMENT.md`](./LOCAL_DEVELOPMENT.md)).

## No DataForSEO account? Use treg

[treg](https://treg.to) is a third-party reseller, unaffiliated with OpenSEO. It sells DataForSEO calls one at a time from a prepaid balance, at DataForSEO's own rates, so you can skip the DataForSEO signup and its $50 minimum top-up. New treg accounts include $1 of free credit.

1. Create a team at [treg.to](https://treg.to) and copy its API token.
2. Set it as `TREG_API_TOKEN` instead of `DATAFORSEO_API_KEY`: in `deploy/standalone/.env` for Docker self-hosting, `.env.selfhost` for Cloudflare self-hosting, or `.env.local` for local development. On an Every App gateway, an owner or admin runs `pnpm everyapp secret set TREG_API_TOKEN` (Gateway 0.4.2 or later).

When both are set, OpenSEO uses `DATAFORSEO_API_KEY`.

treg suits trying OpenSEO and light use. Before you rely on it, know that:

- treg relays only the DataForSEO endpoints in its catalog. As of November 2026 that covers every endpoint OpenSEO calls, but a feature added to OpenSEO later may need `DATAFORSEO_API_KEY` until treg lists its endpoint.
- Your calls run on treg's DataForSEO account, which its other customers share, and treg publishes no request limits. Large rank trackers (thousands of keywords) are sized for a DataForSEO account of your own and are untested through treg.
- Rank tracking cannot check a custom location name when you save a tracker, because that check uses DataForSEO's free sandbox. A name Google does not recognise shows up as failed checks instead.
- When the balance runs out, SEO data requests fail until you top up. The server log says so in a `treg.refused` line.

---

### GOOGLE MAPS SETUP (`docs/GOOGLE_MAPS_SETUP.md`)

# Google Maps setup for Local SEO

Local SEO uses Google's Map Tiles API for its basemap. OpenSEO gets
the ranking results from DataForSEO. Viewing the map requests Google tiles;
running a ranking scan uses DataForSEO credits separately.

## Create the Google Cloud key

1. Select or create a project in [Google Cloud Console](https://console.cloud.google.com/).
2. [Enable billing](https://developers.google.com/maps/documentation/tile/usage-and-billing)
   for that project, then enable **Map Tiles API** in the API Library.
3. In **APIs & Services > Credentials**, create an API key.
4. Set its API restriction to **Map Tiles API** only and save it.
5. If your server has fixed outbound IP addresses, use the **IP addresses**
   application restriction to allow those addresses. Website referrer
   restrictions do not apply to this server integration. Cloudflare Workers
   do not provide a fixed outbound IP by default, so do not enter your app's
   domain or its inbound IP address here.
6. Set a daily tile-request quota in **Google Maps Platform > Quotas** that
   fits your usage. Use separate keys for development, previews, and production
   to keep their usage separate.

OpenSEO's server requests Google sessions, tiles, and viewport copyright
information. The browser loads tiles through an authenticated OpenSEO route;
the Google key and session tokens stay on the server. Follow Google's
[API-key security guidance](https://developers.google.com/maps/api-security-best-practices)
when setting restrictions. You only need Map Tiles API for the basemap.

## Configure OpenSEO

Add the key as `GOOGLE_MAPS_API_KEY` in the environment file for your app:

- Local development: `.env.local`.
- Hosted production: `.env.production`.
- Alchemy self-hosting: `.env.selfhost`.
- Preview deployments: `.env.preview`.

Set the variable to the key you created. It is a server secret and is not
included in the client build. The Google
OAuth client ID and secret used for Search Console are separate credentials.

Restart the development process after changing the key:

```sh
pnpm dev:agents
```

For Cloudflare deployments, the Alchemy deploy commands read the respective
environment file and install the key as a Worker secret. For deployments
managed outside Alchemy, set `GOOGLE_MAPS_API_KEY` as a runtime secret on the
app Worker. Docker reads it from `.env` when the container starts. Restart
or redeploy the server after changing the key; it does not need to be in the
Vite build environment.

Open a project's **Local SEO** screen and choose **Add Business** to select
its Google Maps listing and coverage grid. Enter the search terms you want to
track during setup, or use **Manage keywords** after saving.

**Check rankings** checks every tracked keyword at every grid point. The
confirmation shows the total searches and estimated cost. **Latest** shows the
current results for each keyword; **History** compares saved checks by date.
Select a keyword or a history cell to open its map.

A grid preview displays the basemap before you buy a ranking check. You should
see Google Maps branding, copyright information, and grid markers. The map
stays fitted to the grid. Click a completed point's marker to see the
businesses ranking there.

## Maps in Local SEO reports

The same key draws the rank grid in Local SEO agent reports as a live map,
including for anyone you share a report link with. Those readers are not
signed in, so each report carries a link that loads tiles only for the area
around its own grid and expires after a day. Each time someone opens a report
with a map, it requests Google tiles. Without a key, reports show the grid as
a drawing instead.

## Missing maps

- **Google Maps is not configured:** set the server key and restart or
  redeploy the app.
- **Request failed (403):** check billing, Map Tiles API enablement, and the
  key's API and server IP restrictions.
- **Request failed (429):** check the project's Maps quotas and usage.
- **Tiles could not load:** inspect requests to `/api/local-seo/maps/` in the
  browser's Network panel. Check that you are signed in and can access the
  project, then check server connectivity, key configuration, and quotas.
  Use the map's retry button after correcting the issue.

The **Points** view remains available when maps cannot load. OpenSEO renews
Google's session tokens and displays Google's attribution for the current
viewport. It streams tiles without storing them for offline use. Browser
caching follows Google's response headers; the proxy does not create a
shared tile cache.

## Billing and attribution

Google bills tile requests, and one map view makes several of them. Check Google's
[current pricing](https://developers.google.com/maps/billing-and-pricing/pricing)
and [Map Tiles API policies](https://developers.google.com/maps/documentation/tile/policies).
Keep the Google Maps logo and data copyright visible when customizing the
map. The bundled Google Maps logo comes unchanged from Google's official
attribution assets linked in those policies.

---

### LOCAL DEVELOPMENT (`docs/LOCAL_DEVELOPMENT.md`)

# Local Development

## Prerequisites

- Node.js 20+
- [Corepack](https://nodejs.org/api/corepack.html) (bundled through Node.js 24; install it separately on Node.js 25+)
- A DataForSEO account/API credentials (or a [treg token](./DATAFORSEO_API_KEY.md#no-dataforseo-account-use-treg))

## Local Development Workflow

```sh
# Activates the exact pnpm version declared in package.json.
corepack enable
pnpm install --frozen-lockfile

# Run once per fresh local DB
pnpm run db:migrate:local
```

Verify that `pnpm --version` reports the version declared by the
`packageManager` field in `package.json`. An older global pnpm may reject
the repository's lockfile as incompatible.

Configure `.env.local`:

1. `cp .env.example .env.local`
2. Add `DATAFORSEO_API_KEY` as a base64-encoded `login:password` value:

   `printf '%s' 'YOUR_LOGIN:YOUR_PASSWORD' | base64`

3. Set `AUTH_MODE=local_noauth` for normal local development.

Run locally:

```sh
# Option 1
pnpm run dev

# Option 2 (Recommended)
# This log file makes it easier for your coding agent to debug.
mkdir .logs
touch .logs/dev-server.log

# This command uses portless, which is great for worktrees. It also pipes logs to that fixed file, which is helpful for agent debugging output.
pnpm dev:agents
```

`pnpm dev:agents` runs through [portless](https://github.com/vercel-labs/portless) at `http://open-seo.localhost:1355` by default.

When using a git worktree, [portless](https://github.com/vercel-labs/portless) prefixes the branch name, for example `http://feature-name.open-seo.localhost:1355`.

Local SEO maps need a Google Maps server key. Follow
[Google Maps setup](./GOOGLE_MAPS_SETUP.md) to enable the Map Tiles API and set
`GOOGLE_MAPS_API_KEY`.

## Report share images

To test a real report end to end, run the app with `AUTH_MODE=hosted`, share a
local report, and open its `/s/<token>/og.png` URL. Inspect the share page's
initial HTML for `og:image` and `twitter:image`, then revoke the share and check
that the image returns 404. Report saves and changes to the displayed project
hostname update the image URL's version. If rendering fails for a valid share,
the image route redirects to the existing OpenSEO marketing card.
Social platforms may retain their own previews; our image responses are
`no-store` and check access on each request. An actual social crawler needs a
publicly reachable page and image; the Access-protected preview environment
supports manual inspection but cannot be fetched by those crawlers.

## Website and BadSEO

The marketing website (`web/`) and audit test site (`tests/badseo/`) are separate
pnpm projects with their own lockfiles. The root install does not install their
dependencies. From the repository root, install the project you plan to work on:

```sh
# Marketing website
pnpm --dir web install --frozen-lockfile
pnpm --dir web run dev
# Validate website changes
pnpm --dir web run types:check
pnpm --dir web run build

# Audit test site (keep the root dependencies installed for its audit harness)
pnpm --dir tests/badseo install --frozen-lockfile
pnpm --dir tests/badseo run dev
# Validate BadSEO changes
pnpm --dir tests/badseo run build
```

Run BadSEO's audit harness from another terminal while its dev server is running:

```sh
pnpm --dir tests/badseo run audit http://localhost:8787
```

Use the root formatter for BadSEO; the website has its own formatter:

```sh
# From the repository root
pnpm exec prettier --write "tests/badseo/**/*.{ts,tsx,json,jsonc,md}"
pnpm --dir web run format:write
```

See [BadSEO's README](../tests/badseo/README.md) for fixture and audit instructions.

## Database Commands

Generate migration:

```sh
pnpm run db:generate
```

Migrate local DB:

```sh
pnpm run db:migrate:local
```

## Postgres backend (optional)

D1 (SQLite) is the default. To run against Postgres locally instead — the opt-in
backend for installs that outgrow D1 — see
[`LOCAL_POSTGRES.md`](./LOCAL_POSTGRES.md).

## Auth Modes

- `AUTH_MODE=cloudflare_access` (default): validates Cloudflare Access JWTs (`cf-access-jwt-assertion`) using `TEAM_DOMAIN` + `POLICY_AUD`.
- `AUTH_MODE=local_noauth`: local trusted mode, no auth check, injects `admin@localhost`.
- `AUTH_MODE=hosted`: Better Auth-backed email/password mode. Requires Better Auth schema generation plus `BETTER_AUTH_SECRET` and `BETTER_AUTH_URL`.

Dev scripts do not set `AUTH_MODE`, so you can test another mode by changing it in `.env.local`.

For Cloudflare deployments, ensure Cloudflare Access is enabled on your Worker route/domain and provide `TEAM_DOMAIN` + `POLICY_AUD` in environment variables.

---

### LOCAL POSTGRES (`docs/LOCAL_POSTGRES.md`)

# Running OpenSEO on Postgres locally

OpenSEO runs on **Cloudflare D1 (SQLite) by default**. Postgres is an opt-in
backend for installs that outgrow D1's storage ceiling. The application code is
written once against a provider-aware `db` layer (see `src/db/`), so the only
difference at runtime is the `DATABASE_PROVIDER` flag and a connection string.

This guide sets up a throwaway Postgres in Docker so you can develop and test the
Postgres path locally. **You do not need this for normal development** — D1 is the
default and the path most contributors should use.

## Prerequisites

- Docker Desktop (or Docker Engine)
- The normal local dev setup from [`LOCAL_DEVELOPMENT.md`](./LOCAL_DEVELOPMENT.md)

## 1. Start a Postgres container

Port `5433` is used on the host to avoid clashing with a system Postgres on the
default `5432`.

```sh
docker run --name openseo-postgres \
  -e POSTGRES_USER=openseo \
  -e POSTGRES_PASSWORD=openseo \
  -e POSTGRES_DB=openseo \
  -p 5433:5432 \
  -d postgres:16
```

Wait until it accepts connections:

```sh
docker exec openseo-postgres pg_isready -U openseo -d openseo
```

The connection string is:

```
postgres://openseo:openseo@localhost:5433/openseo
```

## 2. Apply the Postgres migrations

The Postgres schema is hand-written (it is the one structural artifact
`db:generate` does not regenerate) and migrations live in `drizzle/pg/`. Apply
them with `POSTGRES_DATABASE_URL` set — `drizzle-kit` reads it from the shell
environment:

```sh
POSTGRES_DATABASE_URL=postgres://openseo:openseo@localhost:5433/openseo \
  pnpm db:migrate:pg
```

## 3. Point the app at Postgres

The Cloudflare Vite runtime reads Worker vars from `.env.local`, so set the
provider flag there (not just in your shell):

```sh
# .env.local
DATABASE_PROVIDER=postgres
```

The connection string comes from the `HYPERDRIVE` binding. The `hyperdrive`
block in `wrangler.jsonc` ships commented out, so uncomment it first. Miniflare then resolves the binding to its
`localConnectionString`, which already points at the Docker container from
step 1. (In deployed Workers the same binding resolves to real Hyperdrive —
the app never connects to Postgres except through this binding.) If your local
Postgres lives elsewhere, override without touching the config:

```sh
CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE=postgres://... pnpm dev
```

Then start the dev server as usual:

```sh
pnpm dev
```

To switch back to D1, remove that line (or set `DATABASE_PROVIDER=d1`) and
restart.

> `POSTGRES_DATABASE_URL` (step 2) is only read by Node-side tooling —
> `drizzle-kit` and `scripts/migrate-d1-to-postgres.ts`. The app itself ignores
> it.

## 4. Verify

```sh
# Tables created by the migrations
docker exec openseo-postgres psql -U openseo -d openseo -c "\dt"

# Inspect rows the app writes (e.g. after creating a project / saving keywords)
docker exec openseo-postgres psql -U openseo -d openseo -c "select count(*) from projects;"
```

## Schema changes

When you change a table, update **both** dialects:

- SQLite: `src/db/*.schema.ts` (+ `pnpm db:generate:d1`)
- Postgres: `src/db/pg/*.schema.ts` (+ `pnpm db:generate:pg`)

`src/db/schema-parity.test.ts` fails CI if the two dialects drift (mismatched
tables, columns, nullability, primary keys, unique/partial indexes, or FK
`onDelete`). It compares the schema definitions, **not** the generated
migrations — so after editing the Postgres schema, always run `pnpm db:generate:pg`
and commit the new `drizzle/pg/` migration, or a Postgres deploy will be missing
the change even though the parity test is green.

## Teardown

```sh
docker rm -f openseo-postgres
```

This deletes the container and all its data. Re-run from step 1 for a clean slate.

---

### SELF HOSTING CLOUDFLARE (`docs/SELF_HOSTING_CLOUDFLARE.md`)

# Cloudflare Self-Hosting

Host OpenSEO on Cloudflare for internet-facing self-hosting across multiple devices or with your team. One deploy command provisions everything. Works on Cloudflare's free plan, with [limits](#workers-free-plan-limits): site audits stop at about 40 pages.

You sign in with email and password accounts: the first visitor creates the administrator's account, teammates join from invitation links, and MCP clients (Claude, ChatGPT, Codex, Cursor) sign in with the same accounts, with nothing to set up in Cloudflare. The most secure option is to put [Cloudflare Access](#cloudflare-access-the-most-secure-option) in front of the app instead, so Cloudflare checks every request before it reaches OpenSEO. It takes more setup.

Related guides:

- [Operations](./SELF_HOSTING_CLOUDFLARE_OPERATIONS.md): connect the MCP server, manage accounts, telemetry.
- [Legacy deployments](./SELF_HOSTING_CLOUDFLARE_LEGACY.md): maintenance for installs created with the retired Deploy-button or manual Wrangler flows.

## Prerequisites

- **Node 22.6 or newer** and **pnpm** (`corepack enable` sets it up).
- **A Cloudflare account with R2 enabled.** Activating R2 requires a payment method on file, even within its free tier — if you have never used R2, open `R2` in the Cloudflare dashboard once.
- **A workers.dev subdomain.** A new account has none until you open `Workers & Pages` in the Cloudflare dashboard once; without it the bootstrap below fails with "You need a workers.dev subdomain". The subdomain becomes part of your OpenSEO URL.
- **A DataForSEO account** (or a [treg token](./DATAFORSEO_API_KEY.md#no-dataforseo-account-use-treg)) — see [`DATAFORSEO_API_KEY.md`](./DATAFORSEO_API_KEY.md).

## 1) Clone your OpenSEO repo

Fork `every-app/open-seo` on GitHub if you want a repo you control, then clone it locally:

```bash
git clone https://github.com/YOUR_GITHUB_USER/open-seo.git
cd open-seo
corepack enable
pnpm install
```

If you do not need a fork, clone the upstream repo instead:

```bash
git clone https://github.com/every-app/open-seo.git
cd open-seo
corepack enable
pnpm install
```

## 2) Log in to Cloudflare (once)

```bash
pnpm alchemy login deploy/alchemy/alchemy.run.ts # the default scopes are enough
pnpm alchemy cloudflare bootstrap                # deploys alchemy's state-store Worker to your account
```

## 3) Create `.env.selfhost`

Copy the template and set `DATAFORSEO_API_KEY` (or `TREG_API_TOKEN`); everything else is optional:

```bash
cp deploy/.env.selfhost.example .env.selfhost
```

## 4) Deploy

```bash
pnpm deploy:selfhost --yes
```

This provisions the D1 database, KV namespaces, and R2 bucket, applies the database migrations, deploys the Workers, and generates the session secret. The secret is kept in Alchemy's state in your account, so later deploys keep everyone signed in.

## 5) Create your account

1. Open the Worker URL printed at the end of the deploy.
2. Create the administrator's account. Do this right after the deploy finishes: registration closes once the first account exists, and until then anyone who finds the URL could claim the installation.
3. OpenSEO loads with a default project. Add your website to get started.

If something fails, see Troubleshooting below.

## Giving teammates access

Invite them from Team settings. The app copies an invitation link; the invited address creates its own account from that link and joins your workspace. There is no email delivery, so send the link yourself. Everyone works in one shared workspace and sees the same projects.

## Connecting MCP clients

MCP clients connect to `https://YOUR_WORKER_HOSTNAME/mcp` and sign in with your OpenSEO account, the same way they connect to the hosted service. Follow the [MCP setup guide](https://openseo.so/docs/mcp) with your Worker URL in place of the hosted one.

## Use your own domain

To serve OpenSEO on your own hostname, set `CUSTOM_DOMAIN=seo.example.com` in `.env.selfhost` and deploy. The domain must be a zone on the same Cloudflare account; the deploy attaches it to the Worker and creates the DNS record and certificate. Don't add the domain in the Cloudflare dashboard instead: each deploy removes custom domains that `CUSTOM_DOMAIN` doesn't name.

It works with both sign-in options:

- **Password accounts:** sign-in and MCP clients then work only on that address, so set it before creating accounts if you can. Changing it later signs everyone out, and MCP clients reconnect at the new URL.
- **Cloudflare Access:** the deploy adds the domain to the Access application it created, so the same email list protects both the custom domain and the `workers.dev` address. If you manage the Access application yourself (`TEAM_DOMAIN` and `POLICY_AUD`), add the hostname to it by hand as another public hostname.

## Forgot a password?

There is no email delivery, so an operator resets passwords from a terminal. See [Manage accounts](./SELF_HOSTING_CLOUDFLARE_OPERATIONS.md#manage-accounts).

## Updating to the latest OpenSEO version

```bash
git pull        # or: git fetch upstream && git merge upstream/main, if you forked
pnpm install
pnpm deploy:selfhost --yes
```

## Cloudflare Access: the most secure option

With `AUTH_MODE=cloudflare_access`, Cloudflare's own login protects the Worker: every request is checked at Cloudflare's edge before it reaches OpenSEO, and only the emails you list get through. It needs an extra login scope, a Zero Trust team (usually created for you), and Zero Trust settings before MCP clients can connect, so expect more setup. Choose the sign-in mode before your first deploy; the two keep separate user records.

1. In `.env.selfhost`, set `AUTH_MODE=cloudflare_access` and `ACCESS_ALLOWED_EMAILS` (comma-separated).
2. Add the `access:write` scope to your Cloudflare login: run `pnpm alchemy login deploy/alchemy/alchemy.run.ts --configure`, answer yes to "Customize OAuth scopes?", and select `access:write` alongside the defaults.
3. Run `pnpm deploy:selfhost --yes`. The deploy creates the Cloudflare Access application protecting the Worker (allowing exactly `ACCESS_ALLOWED_EMAILS`). If the account has no Zero Trust team yet, one is created for you, named after your workers.dev subdomain. If Zero Trust has never been turned on for the account, the deploy stops instead: open [one.dash.cloudflare.com](https://one.dash.cloudflare.com), pick the Free plan (Cloudflare creates the team), and run the deploy again.

Open the printed URL and sign in with Cloudflare Access. Access can take about 2 minutes to apply after the first deploy; until then the URL may load without a Cloudflare login, but OpenSEO still rejects requests that lack an Access token. To add teammates, add them to `ACCESS_ALLOWED_EMAILS` and redeploy; dashboard edits to that Access policy are overwritten on the next deploy. To manage the Access application yourself, set `TEAM_DOMAIN` (`https://your-team.cloudflareaccess.com`) and `POLICY_AUD` (the application's audience tag) instead — the deploy then provisions no Access resources. MCP clients need Managed OAuth turned on for the Access application; see [Operations](./SELF_HOSTING_CLOUDFLARE_OPERATIONS.md#through-cloudflare-access).

Deployments created before password accounts existed have no `AUTH_MODE` in `.env.selfhost`, which still means Cloudflare Access, so they keep working unchanged. Deployments upgraded from older versions (which gave each user a separate workspace) show a one-time dashboard banner — clicking it migrates all previous per-user work into the shared workspace.

## Workers Free plan limits

A Cloudflare Workflow on the Workers Free plan can make 50 outgoing requests per run. Each site audit runs as one Workflow, so an audit stops loading pages after about 40 of them. AI visibility setup and checks can fail the same way, with "Too many subrequests". On Workers Paid, `pnpm deploy:selfhost` raises the limit to 1,000,000 requests per run; on Free, the deploy says so and keeps Cloudflare's default. See [Workflows limits](https://developers.cloudflare.com/workflows/reference/limits/). For full audits and AI visibility, use Workers Paid or [Docker](./SELF_HOSTING_DOCKER.md).

## Site audits

**Shopify crawler access:** saving the crawler-access signature a Shopify store creates needs `CRAWLER_ACCESS_SECRET` in `.env.selfhost`, set to at least 32 random characters (e.g. `openssl rand -hex 32`), then `pnpm deploy:selfhost --yes`. Keep the value once set: changing it makes saved signatures unreadable.

## Troubleshooting

- `https://<your-worker-hostname>/api/health` reports runtime configuration checks and database status.
- Cloudflare Access login fails: re-check `ACCESS_ALLOWED_EMAILS` in `.env.selfhost` and redeploy.
- For server errors, open the Worker `Logs` or run `pnpm exec wrangler tail`. Site audits run in a separate worker: `pnpm exec wrangler tail open-seo-selfhost-audit`.

## Tearing it down

```bash
pnpm alchemy destroy deploy/alchemy/alchemy.run.ts --env-file .env.selfhost --stage selfhost
```

This deletes the Workers, the stage-suffixed D1/KV/R2 resources (including your data), and the Access application if the deploy created one.

## Next steps

See [Operations](./SELF_HOSTING_CLOUDFLARE_OPERATIONS.md) for managing accounts, connecting MCP clients, and telemetry.

---

### SELF HOSTING CLOUDFLARE LEGACY (`docs/SELF_HOSTING_CLOUDFLARE_LEGACY.md`)

# Cloudflare Self-Hosting: Legacy Deployments

Maintenance for installs created with the retired **Deploy to Cloudflare button** or the **manual Wrangler flow**. These deployments keep working — nothing changes for you. New deployments should use the [current guide](./SELF_HOSTING_CLOUDFLARE.md).

## Updating (Deploy-button repos)

Your repo was created by the deploy button and `wrangler.jsonc` holds your resource IDs; keep them while pulling the newest code.

One-time setup:

```bash
git remote add upstream https://github.com/every-app/open-seo.git
```

Update steps:

```bash
git fetch upstream
cp wrangler.jsonc wrangler.local.backup.jsonc
git checkout main
git reset --hard upstream/main
cp wrangler.local.backup.jsonc wrangler.jsonc
git add wrangler.jsonc
git commit -m "restore Cloudflare settings" || true
git push --force-with-lease origin main
```

## Updating (manual Wrangler deployments)

```bash
git pull
pnpm install
pnpm run deploy
```

`pnpm run deploy` also deploys a second worker, `open-seo-audit`, which runs site audits. Copy your `DB`, `KV`, and `R2` bindings from `wrangler.jsonc` into `wrangler.audit.jsonc` (it needs no `OAUTH_KV`) — the deploy fails on ids that don't exist in your account. Then set its DataForSEO key once, or every Lighthouse check in an audit fails:

```bash
pnpm exec wrangler secret put DATAFORSEO_API_KEY --name open-seo-audit
```

## Giving teammates access

1. Open Cloudflare Zero Trust.
2. Go to Access -> Applications.
3. Open your OpenSEO application.
4. Edit the `Allow` policy.
5. Add teammate emails (or your company email domain / group).
6. Save.

Screenshots: [edit the Access policy](https://github.com/user-attachments/assets/c7bbc7b4-a18e-4ae4-9fe5-3b33c72048a7), [add teammate emails](https://github.com/user-attachments/assets/fa4ecaf2-31f7-4a64-9001-210cf729747b).

## Optional: R2 lifecycle rule

DataForSEO API responses are cached in R2 under the `dataforseo-cache/` prefix. Recommended so expired cache objects don't accumulate:

```bash
pnpm exec wrangler r2 bucket lifecycle add open-seo dataforseo-cache-expiry dataforseo-cache/ --expire-days 7
```

Replace `open-seo` with your bucket name if you changed it.

## Troubleshooting

**Login fails or OpenSEO doesn't load.** Re-check, on your Worker under `Settings`:

- `Domains & Routes`: `Cloudflare Access` is enabled for the `workers.dev` route.
- `Variables & Secrets`: `TEAM_DOMAIN` (for example `https://your-team.cloudflareaccess.com`), `POLICY_AUD` (the Access application audience tag), and `DATAFORSEO_API_KEY` are set. The `open-seo-audit` worker needs `DATAFORSEO_API_KEY` too.
- Manual Wrangler deployments: the binding IDs in `wrangler.jsonc` match your resources.

`https://<your-worker-hostname>/api/health` reports runtime configuration checks and database status. For server errors, open the Worker `Logs` or run `pnpm exec wrangler tail`.

**Migrating to the current flow** is not supported yet — the new deploy provisions fresh resources, so your data would not move. Keep using this page.

## Everything else

MCP setup and telemetry work the same as current deployments — see [Operations](./SELF_HOSTING_CLOUDFLARE_OPERATIONS.md).

---

### SELF HOSTING CLOUDFLARE OPERATIONS (`docs/SELF_HOSTING_CLOUDFLARE_OPERATIONS.md`)

# Cloudflare Self-Hosting: Operations

Day-to-day tasks after [initial setup](./SELF_HOSTING_CLOUDFLARE.md): connect the MCP server, manage accounts, render JavaScript in site audits, and manage telemetry. Updating and teammate access are covered in the [deploy guide](./SELF_HOSTING_CLOUDFLARE.md) (or the [legacy page](./SELF_HOSTING_CLOUDFLARE_LEGACY.md) for pre-alchemy deployments).

## Connect the MCP server

With password accounts (`AUTH_MODE=password`, the default for new deployments), MCP clients connect to `https://YOUR_WORKER_HOSTNAME/mcp` and sign in with your OpenSEO account, exactly as they connect to the hosted service; nothing needs to be enabled in Cloudflare. Follow the [MCP setup guide](https://openseo.so/docs/mcp) with your Worker URL in place of the hosted one.

### Through Cloudflare Access

With `AUTH_MODE=cloudflare_access`, use the same Cloudflare Access application that protects your OpenSEO Worker.
Managed OAuth is required for MCP clients.

If the deploy created your Access application (you didn't set `TEAM_DOMAIN` and `POLICY_AUD`), each `pnpm deploy:selfhost` turns Managed OAuth on and allows `localhost` and loopback redirect URIs, which CLI and desktop agents (Codex CLI, Claude Code) use. For web connectors, add their HTTPS redirect URIs with step 6 below; later deploys keep them. If you manage the Access application yourself, Managed OAuth is off by default; turn it on:

1. Open Cloudflare Zero Trust.
2. Go to `Access controls` -> `Applications`.
3. Find your OpenSEO application, then select `Edit`.
4. Go to `Additional settings` -> `OAuth`.
5. Turn on `Managed OAuth`.
6. In `Managed OAuth settings`, allow the redirect URIs your MCP clients use:
   - Allow `localhost` / loopback clients for CLI and desktop agents (Codex
     CLI, Claude Code) that register `http://localhost:PORT/callback`.
   - Add HTTPS redirect URIs for web connectors (a path may end in `/*`).
   - Without this, clients can't finish [Dynamic Client Registration](https://developers.cloudflare.com/cloudflare-one/access-controls/applications/http-apps/managed-oauth/)
     and log in but expose no tools.
7. Save.

MCP clients should connect to:

```text
https://YOUR_WORKER_HOSTNAME/mcp
```

## Manage accounts

With password accounts, the first visitor creates the administrator's account and teammates join from invitation links (Team settings). There is no email delivery, so password resets and accounts outside the invitation flow are operator commands:

1. Set `OPENSEO_OPERATOR_SECRET` in `.env.selfhost` to a random value (`openssl rand -hex 32`) and redeploy. This turns on the operator endpoint, which answers only to requests carrying that secret.
2. Run the command with the password on standard input and the deployed URL in `OPENSEO_URL`. This Bash example keeps the password out of shell history and process arguments:

```bash
read -rs -p 'New password: ' password; echo
printf '%s\n' "$password" | OPENSEO_URL=https://YOUR_WORKER_HOSTNAME pnpm selfhost:admin reset-password you@example.com
unset password
```

A reset signs that user out everywhere. `pnpm selfhost:admin create-user you@example.com 'Your name'` creates an account the same way, for example to create the administrator's account from the terminal before anyone opens the URL. `OPENSEO_URL` can also live in `.env.selfhost`.

### Switching from Cloudflare Access to password accounts

Existing users keep their data, but they signed in through Cloudflare and have no password, and registration is closed once any user exists, so give each of them a password:

1. Set `AUTH_MODE=password` and `OPENSEO_OPERATOR_SECRET` in `.env.selfhost` and redeploy. The deploy removes the Access application it created, so the app is reachable without Cloudflare's login from then on.
2. Find each user's id in the `user` table of the `open-seo-db-selfhost` D1 database (Cloudflare dashboard, Storage & Databases, D1).
3. For each user, with the password on standard input as above:

```sh
OPENSEO_URL=https://YOUR_WORKER_HOSTNAME pnpm selfhost:admin claim-legacy-user USER_ID you@example.com shared-workspace
```

Everyone shares the `shared-workspace` organization; the command makes the user one of its owners.

## AI visibility tracking

AI Visibility uses your `DATAFORSEO_API_KEY` (or `TREG_API_TOKEN`); tracked questions are sent to DataForSEO and billed directly by the provider. Set `OPENROUTER_API_KEY` for setup research, Prompt Research, and generated prompt suggestions. Deployment configures background collection and a five-minute cron that dispatches due daily, weekly, or monthly checks. The app shows the collection cost before a check or schedule starts. See the [AI Visibility guide](https://openseo.so/docs/ai-visibility).

## Render JavaScript in site audits

Site Audit can load pages in a browser before analyzing them. Turn on **Render JavaScript** when starting an audit if the site builds its content or links client-side (React and other single-page apps). Rendered audits take longer.

Rendering uses [Cloudflare Browser Run](https://developers.cloudflare.com/browser-run/) on your own Cloudflare account. The deploy binds a browser to the audit Worker, so the toggle works with no extra setup. **Rendering needs a paid Workers plan.** The free plan allows one browser action every ten seconds, which is too slow for a crawl. The paid plan includes 10 browser hours a month, then bills $0.09 per browser hour.

Some sites block Cloudflare's browser. To render those pages through [Context.dev](https://www.context.dev) instead, create a Context account, set `CONTEXT_API_KEY` in `.env.selfhost`, and redeploy. OpenSEO calls Context only for pages that Browser Run could not render, and for Shopify store pages that Shopify rate limits while project setup or AI Visibility setup reads your site. Each of those pages uses one Context credit on your Context account.

Docker deployments have no browser. On Docker, set `CONTEXT_API_KEY` in `deploy/standalone/.env` and apply it as described in [Enable features](./SELF_HOSTING_DOCKER.md#enable-features) to render every page through Context. On the [older Docker image](./SELF_HOSTING_DOCKER_LEGACY.md), set it in `.env` and run `docker compose up -d --force-recreate open-seo`. Until the key is set, the **Render JavaScript** toggle stays disabled with a setup note.

## Telemetry

OpenSEO collects anonymized telemetry for core usage events: heartbeats with aggregate counts (installs, users, projects, feature usage) tied to a random install ID, sent every 5 minutes during the first two hours after install, then at most once daily. No URLs, keywords, prompts, emails, or IP-derived location are collected, and idle installs send nothing.

Heartbeats are triggered by requests to the app or MCP server. Requests to `/api/health` do not trigger telemetry, matching Docker's behavior.

To disable it, set `OPENSEO_TELEMETRY_DISABLED=1` in `.env.selfhost` and redeploy. Docker and [legacy deployments](./SELF_HOSTING_CLOUDFLARE_LEGACY.md): set it (or `DO_NOT_TRACK=1`) as an environment variable / Worker variable instead.

---

### SELF HOSTING DOCKER (`docs/SELF_HOSTING_DOCKER.md`)

# Docker Self-Hosting

Run OpenSEO on your own server or computer with Docker Compose. The image is prebuilt (`ghcr.io/every-app/open-seo-standalone`), so OpenSEO is ready a few seconds after it starts. You sign in with email and password accounts: the first visitor creates the administrator's account and teammates join from invitation links. You pay DataForSEO, OpenRouter and any rendering provider directly.

Already running the older single-container image (`ghcr.io/every-app/open-seo`)? It keeps getting updates. When you are ready, [move to this setup](#move-from-the-old-docker-image); your data comes with you.

## Install

You need Docker Engine or Docker Desktop with Compose, at least 4 GiB of memory for Docker, and a [DataForSEO API key](./DATAFORSEO_API_KEY.md) (or a [treg token](./DATAFORSEO_API_KEY.md#no-dataforseo-account-use-treg)). Every command below runs from the repository root:

```sh
git clone https://github.com/every-app/open-seo.git
cd open-seo
export COMPOSE_FILE=deploy/standalone/compose.yaml
cp deploy/standalone/.env.example deploy/standalone/.env
```

In `deploy/standalone/.env`, set `STORAGE_SECRET_KEY` to a unique random value (for example the output of `openssl rand -hex 32`) and `DATAFORSEO_API_KEY` to your key. Leave `BETTER_AUTH_URL=http://localhost:3001` for use on this machine. Then start OpenSEO:

```sh
docker compose pull
docker compose up -d
docker compose logs -f init
```

Wait for `OpenSEO initialized and ready.`, open <http://localhost:3001> and create the administrator's account. Registration closes once that account exists, so create it before you put the installation on the internet.

### Coolify, Portainer and Dokploy

`deploy/standalone/compose.yaml` reads no other files from the repository, so you can paste it into a platform that runs Compose files, with the variables from `deploy/standalone/.env.example`. Point the platform's domain at the `web` service on port 80 and set `BETTER_AUTH_URL` to that `https://` address. The `init` service exits after each start by design.

## Accounts

Invite teammates from Team settings. The app copies an invitation link; the invited address creates its own account from that link and joins your workspace. There is no email delivery, so send the link yourself.

Password resets and accounts outside the invitation flow are done from a terminal with the admin command. This Bash example keeps the password out of shell history:

```bash
read -rs -p 'New password: ' password; echo
printf '%s\n' "$password" | pnpm standalone:admin reset-password you@example.com
unset password
```

`create-user you@example.com 'Your name'` creates an account the same way. A reset signs that user out everywhere. Without pnpm, run `docker compose exec -T runtime node /opt/standalone/admin.mjs ...` instead.

### Without sign-in (advanced)

`AUTH_MODE=local_noauth` runs OpenSEO without sign-in, as one admin user. Use it only where the network already controls who can reach the app, for example on a private network, behind Tailscale or behind your own authenticating proxy. To switch an existing installation to accounts later, set `AUTH_MODE=password`, run `docker compose up -d --force-recreate init web crawl-gateway`, and give the admin an email and password; its data and conversations stay:

```sh
pnpm standalone:admin claim-legacy-user local-admin you@example.com delegated-local-admin
```

## Enable features

Set credentials in `deploy/standalone/.env`, then apply them without rebuilding:

```sh
docker compose up -d --force-recreate init web crawl-gateway
```

| Variable                                   | Purpose                                                                                                                    |
| ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- |
| `DATAFORSEO_API_KEY`                       | Base64-encoded `login:password`; keyword, backlink, rank and site data                                                     |
| `TREG_API_TOKEN`                           | Optional, instead of `DATAFORSEO_API_KEY`: the same data, bought per call through treg (see the DataForSEO key guide)      |
| `OPENROUTER_API_KEY`                       | SAM conversations, website research and summaries                                                                          |
| `OPENROUTER_BASE_URL`                      | Optional base URL of another OpenAI-compatible server (vLLM, LiteLLM, Ollama); set `OPENROUTER_MODEL` to a model it serves |
| `OPENROUTER_MODEL`                         | Optional model override                                                                                                    |
| `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` | Optional Search Console and Analytics linking with your own Google OAuth app                                               |
| `CONTEXT_API_KEY`                          | Optional JavaScript rendering for site audits                                                                              |
| `GOOGLE_MAPS_API_KEY`                      | Optional map for Local SEO; see [`GOOGLE_MAPS_SETUP.md`](./GOOGLE_MAPS_SETUP.md)                                           |
| `CRAWLER_ACCESS_SECRET`                    | Optional, 32+ random characters; encrypts saved Shopify crawler signatures                                                 |

For Google, register your own OAuth application with these redirect URLs under your public address: `/api/gsc/oauth/callback` for Search Console and `/api/ga4/oauth/callback` for Analytics. See [`SELF_HOSTING_GOOGLE_SEARCH_CONSOLE.md`](./SELF_HOSTING_GOOGLE_SEARCH_CONSOLE.md). Signing in with Google is not offered; accounts use email and password.

Site audits can crawl up to 10,000 pages (1,000 with JavaScript rendering), with no lifetime quota. Costs are what the providers charge, with no OpenSEO markup.

MCP clients connect to `/mcp` and sign in with your OpenSEO account, or use an API key from Settings. Clients that register with a metadata URL (CIMD) are not supported; use dynamic client registration or an API key.

## Public HTTPS

Set `BETTER_AUTH_URL=https://seo.example.com` before the first start, or run `docker compose up -d --force-recreate init web crawl-gateway` after changing it. Put an HTTPS reverse proxy in front of `127.0.0.1:3001` and forward WebSocket upgrades for SAM. Plain HTTP is accepted only for `localhost`.

Only Nginx is published, and only on the host's loopback address; storage, the crawl gateway and the runtime stay private. Crawls reach public addresses on ports 80 and 443 only; crawling private sites is intentionally unsupported.

## Updates

Make a backup, then pull the new image and restart:

```sh
node scripts/celld/backup.mjs backup ./backups/before-update
docker compose pull
docker compose stop web crawl-gateway runtime
docker compose up -d
docker compose logs init
```

Database migrations run in `init`. Going back to an older image does not undo them; restore the matching backup instead.

To run your own changes instead of the published image, add the build file:

```sh
export COMPOSE_FILE=deploy/standalone/compose.yaml:deploy/standalone/compose.build.yaml
docker compose up -d --build
```

## Backup and restore

A backup briefly stops the app, archives the storage and configuration volumes with checksums, then starts it again:

```sh
node scripts/celld/backup.mjs backup ./backups/2026-10-19
```

Backups contain credentials and user data; keep them somewhere private. Restore into a stopped, empty installation with the same storage credentials:

```sh
node scripts/celld/backup.mjs restore ./backups/2026-10-19
docker compose up -d
```

Restore refuses a non-empty volume and verifies the checksums. To test a restore beside a live installation, use a different `COMPOSE_PROJECT_NAME` and `PORT`.

The `config` volume holds the secrets generated at the first start. Keep it in your backups; nothing secret is built into the image.

## Move from the old Docker image

The older image (`ghcr.io/every-app/open-seo`) keeps its data in a volume named `open_seo_data`, in a format this setup cannot read directly. A one-time `migrate` service copies it over. It carries projects, saved keywords, rank trackers and their history, audits, reports and SAM conversations. It does not carry Google connections, sessions, API keys or MCP connections, provider caches, or work that is still running.

1. Update the old installation and start it once (`docker compose pull && docker compose up -d` in its directory). Let running audits, rank checks and SAM replies finish.
2. Stop it with `docker compose down`. The data volume stays; find its name with `docker volume ls`. For a checkout in a directory called `open-seo` it is `open-seo_open_seo_data`.
3. Update the checkout (`git pull`), then prepare `deploy/standalone/.env` as in [Install](#install), but do not start it yet. Set `LEGACY_VOLUME` to the volume name. Set `AUTH_MODE=local_noauth` to keep working without sign-in, or leave `AUTH_MODE=password` to switch to accounts.
4. Start it with the migration file added:

   ```sh
   export COMPOSE_FILE=deploy/standalone/compose.yaml:deploy/standalone/compose.migrate.yaml
   docker compose pull --ignore-buildable
   docker compose up -d --build
   docker compose logs -f migrate
   ```

   The app opens once the copy has finished. Starting again with the same files changes nothing. When it reports success, set `COMPOSE_FILE` back to `deploy/standalone/compose.yaml`.

5. Without sign-in, open the app: everything is where it was. With accounts, give the old admin an email and password: `pnpm standalone:admin claim-legacy-user local-admin you@example.com delegated-local-admin`, with the password on standard input as in [Accounts](#accounts).
6. Check your projects and reports, then reconnect Google and review schedules.

Keep the old volume until you are satisfied; only `docker volume rm` deletes it. If the copy stops partway, starting again resumes it. When the old volume is on another machine, run `node scripts/celld/export-legacy.mjs COPIED_STATE_V3 OUTPUT_DIR` from a checkout there and import the directory with `node /opt/standalone/import.mjs` inside the `init` container.

To hand the move to a coding agent, give it this:

```text
Move my OpenSEO Docker installation from the old image (ghcr.io/every-app/open-seo) to the new Docker setup, following "Move from the old Docker image" in docs/SELF_HOSTING_DOCKER.md of this checkout. Update the old installation first and let its running work finish, stop it, find its data volume, prepare deploy/standalone/.env (keep AUTH_MODE=local_noauth unless I say otherwise), run the migration, and then tell me what was not migrated and what I need to reconnect. Do not delete the old volume.
```

## Troubleshooting

```sh
docker compose ps
docker compose logs --tail 100 init runtime storage crawl-gateway web
curl --fail http://localhost:3001/api/health
```

`/api/health` succeeds only when sign-in is configured and the database answers. If `init` fails, Nginx does not start; its log says why. `docker compose down -v` deletes the installation's data and secrets.

The runtime needs a kernel with 4 KiB memory pages. A Raspberry Pi 5's default kernel uses 16 KiB pages, and `init` and `runtime` then exit with a message that says so. Add `kernel=kernel8.img` to `/boot/firmware/config.txt` and reboot to use its 4 KiB kernel. Check with `getconf PAGESIZE`, which should print `4096`.

## How it works

OpenSEO is written for Cloudflare Workers. In Docker it runs on [celld](https://github.com/denoland/celld), an open-source runtime for Workers code, which provides the same database, storage, background workflows and scheduled jobs on your own machine. [RustFS](https://github.com/rustfs/rustfs) stores that state, Nginx serves the app, and a small crawl gateway keeps site crawls away from private network addresses. `init` runs once at each start: it generates secrets on the first run, loads the app and applies database migrations.

The runtime container is limited to 2 GiB of memory, and the whole stack typically uses 1 to 2 GiB. Adjust `mem_limit` in `deploy/standalone/compose.yaml` if you need to.

---

### SELF HOSTING DOCKER LEGACY (`docs/SELF_HOSTING_DOCKER_LEGACY.md`)

# Docker Self-Hosting: older single-container image

This guide covers the older image, `ghcr.io/every-app/open-seo`, which builds the app each time it starts and runs without sign-in. It keeps getting updates, so existing installations keep working. New installations should use the [current Docker setup](./SELF_HOSTING_DOCKER.md), which starts in seconds and has accounts; existing ones can [move to it with their data](./SELF_HOSTING_DOCKER.md#move-from-the-old-docker-image).

In Docker mode, OpenSEO uses `AUTH_MODE=local_noauth` (no auth checks, local admin user `admin@localhost`). Only expose it behind your own auth-protected reverse proxy, tunnel, or private network.

The default `compose.yaml` uses the published GHCR image:

- `ghcr.io/every-app/open-seo:latest`

## Prerequisites

- Docker Desktop (or Docker Engine + Docker Compose)
- A DataForSEO API key (see [`DATAFORSEO_API_KEY.md`](./DATAFORSEO_API_KEY.md))

## Quickstart

```bash
cp .env.example .env
```

Set `DATAFORSEO_API_KEY` in `.env` using the [DataForSEO setup guide](./DATAFORSEO_API_KEY.md), then start OpenSEO:

```bash
docker compose up -d
```

Open `http://localhost:<PORT>` (default `3001`). The first start builds the app and may take 1-2 minutes; follow progress with `docker compose logs -f`.

Optional env values:

- `PORT` (defaults to `3001`)
- `ALLOWED_HOST` (single reverse-proxy hostname to allow in Vite preview)
- `AUTH_MODE=local_noauth` (already set in compose)
- `OPEN_SEO_IMAGE` (defaults to `ghcr.io/every-app/open-seo:latest`)

AI Visibility uses your `DATAFORSEO_API_KEY` and sends tracked questions to DataForSEO. Set `OPENROUTER_API_KEY` for setup research, Prompt Research, and generated prompt suggestions. You pay providers directly; the app shows the collection cost before a check or schedule starts. Keep the container running for background answers and daily, weekly, or monthly tracking. The built-in scheduler checks for due work every five minutes; no host cron setup is required. See the [AI Visibility guide](https://openseo.so/docs/ai-visibility).

If you are putting Docker behind a reverse proxy or a temporary tunnel, remember that Docker self-hosting runs with app auth disabled. Only expose it behind your own auth-protected reverse proxy, tunnel, or private network, and add the public hostname before restarting:

```bash
ALLOWED_HOST=yourdomain.com docker compose up -d
```

You can also persist it in `.env`.

## Telemetry

OpenSEO collects anonymized telemetry for core usage events: heartbeats with aggregate counts (installs, users, projects, feature usage) tied to a random install ID, sent every 5 minutes during the first two hours after install, then at most once daily. Telemetry also includes failed setup check names and statuses, never values or error messages. No URLs, keywords, prompts, emails, or IP-derived location are collected, and idle installs send nothing.

Heartbeats are triggered by requests to the app or MCP server. Requests to `/api/health`, including Docker's automatic health checks, do not trigger telemetry.

To disable it, set `OPENSEO_TELEMETRY_DISABLED=1` (or `DO_NOT_TRACK=1`) in `.env`, then run `docker compose up -d --force-recreate open-seo`.

## Pin to a specific image tag

Set `OPEN_SEO_IMAGE` in `.env` and restart:

```bash
OPEN_SEO_IMAGE=ghcr.io/every-app/open-seo:v1.2.3
docker compose up -d
```

## Build your own image locally

If you are testing local code changes, build and run a local tag:

```bash
docker build -f deploy/docker/Dockerfile -t open-seo:local .
OPEN_SEO_IMAGE=open-seo:local docker compose up -d
```

## Common commands

- Restart service after env changes:

```bash
docker compose up -d open-seo
```

- Pull latest published image and restart:

```bash
docker compose pull && docker compose up -d
```

- Stop:

```bash
docker compose down
```

## Health and troubleshooting

Startup checks appear in `docker compose logs` before the build. Once running, `/api/health` reports configuration and database status, and `docker compose ps` reports container health. Scheduler failures appear as `[scheduler]` messages in container logs. The pinned Cloudflare Vite runtime exposes `/cdn-cgi/handler/scheduled`; the container calls it only at `127.0.0.1` using the configured `PORT`. It passes the five-minute cron expression without overriding the clock. Newer Cloudflare versions may use a different local route; the [Cron Triggers documentation](https://developers.cloudflare.com/workers/configuration/cron-triggers/#test-cron-triggers-locally) describes the local handler mechanism.

## Troubleshooting environment variables

To confirm Docker Compose is using the expected environment variables:

```bash
docker compose config
```

Check that `AUTH_MODE=local_noauth`, and that `DATAFORSEO_API_KEY` is the base64
encoded value of your DataForSEO email and API password in this format:
`email:password`.

If you changed `.env`, recreate the container so Compose reapplies it:

```bash
docker compose up -d --force-recreate open-seo
```

---

### SELF HOSTING GOOGLE ANALYTICS (`docs/SELF_HOSTING_GOOGLE_ANALYTICS.md`)

# Self-hosted Google Analytics

Connecting Google Analytics lets OpenSEO bind a GA4 property to a project. The
connection is optional and read-only.

## What you'll need

- A Google account with access to the GA4 property.
- A Google Cloud project with OAuth credentials.
- `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, and `BETTER_AUTH_SECRET` set on
  the OpenSEO deployment.

If Search Console is already connected, reuse the same Google Cloud project and
OAuth client. GA4 still asks for a separate consent grant.

## 1) Enable the Analytics APIs

In the [Google Cloud Console](https://console.cloud.google.com/), enable both:

- [Google Analytics Admin API](https://console.cloud.google.com/apis/library/analyticsadmin.googleapis.com)
- [Google Analytics Data API](https://console.cloud.google.com/apis/library/analyticsdata.googleapis.com)

The Admin API lists properties during connection. The Data API powers the
read-only reports added in later GA4 milestones.

## 2) Configure the OAuth consent screen

Under **APIs & Services → OAuth consent screen**, configure the app. While the
app is in Testing, add every Google account that will connect as a test user.

Then click **Publish app** to move it from **Testing** to **In production**:
Google expires refresh tokens for External apps in Testing after 7 days, so a
Testing app asks you to reconnect every week. See the
[Search Console guide](./SELF_HOSTING_GOOGLE_SEARCH_CONSOLE.md#2-configure-the-oauth-consent-screen)
for details.

## 3) Register the callback URL

Open **APIs & Services → Credentials**, edit the Web application OAuth client,
and add an authorized redirect URI matching the deployment origin plus
`/api/ga4/oauth/callback`.

| Deployment   | Redirect URI                                             |
| ------------ | -------------------------------------------------------- |
| Deployed     | `https://your-openseo-domain.com/api/ga4/oauth/callback` |
| Local Docker | `http://localhost:3001/api/ga4/oauth/callback`           |

Keep the existing `/api/gsc/oauth/callback` URI if Search Console uses the same
client.

## 4) Set environment variables

Set these values and restart OpenSEO:

| Variable               | Value                                                     |
| ---------------------- | --------------------------------------------------------- |
| `GOOGLE_CLIENT_ID`     | Web application client ID.                                |
| `GOOGLE_CLIENT_SECRET` | Web application client secret.                            |
| `BETTER_AUTH_SECRET`   | Random string of at least 32 characters for token crypto. |

Generate the encryption secret with:

```sh
openssl rand -base64 32
```

## 5) Connect a property

Open a project dashboard or **Project settings → Integrations**, click
**Connect**, approve read-only Analytics access, and choose a GA4 property.

OpenSEO stores the OAuth tokens encrypted in Better Auth's account table. The
project mapping stores only the selected property metadata and connector
account. Disconnecting GA4 does not disconnect Search Console.

## Troubleshooting

**`redirect_uri_mismatch`** — make sure the registered URI exactly matches the
scheme, host, port, and `/api/ga4/oauth/callback` path used by the deployment.

**No properties appear** — confirm that the Analytics Admin API is enabled and
the connected Google account has access to the property.

**Analytics disconnects every week** — your OAuth app is still in Testing,
where Google expires refresh tokens after 7 days. Publish it under **OAuth
consent screen → Publish app**, then reconnect once.

---

### SELF HOSTING GOOGLE SEARCH CONSOLE (`docs/SELF_HOSTING_GOOGLE_SEARCH_CONSOLE.md`)

# Self-hosted Google Search Console

Connecting Google Search Console (GSC) lets OpenSEO pull your real clicks,
impressions, positions, and URL inspection data, straight from Google.

It's **optional**: OpenSEO runs fine without it, just without Search Console data.

## What you'll need

- A Google account with access to your verified Search Console property.
- ~10 minutes in the [Google Cloud Console](https://console.cloud.google.com/).
- Three environment variables set on your deployment (see [step 4](#4-set-environment-variables)).

## 1) Create a Google Cloud project and enable the API

1. Open the [Google Cloud Console](https://console.cloud.google.com/) and create
   a project (or pick an existing one).
2. Enable the
   [Google Search Console API](https://console.cloud.google.com/apis/library/searchconsole.googleapis.com)
   for that project.

## 2) Configure the OAuth consent screen

Under **APIs & Services → OAuth consent screen**:

- Pick **External** (unless everyone using it is in your Google Workspace org).
- Fill in the app name, support email, and developer contact email.
- While the app is in **Testing**, add the Google accounts that will connect as
  **test users** — otherwise Google blocks the sign-in with `access_denied`.

Once the test users can connect, click **Publish app** on the OAuth consent
screen to move it from **Testing** to **In production**. Google expires refresh
tokens for External apps in Testing after 7 days, so a Testing app makes Search
Console disconnect every week. You don't need to submit for verification for
personal or internal use: Google shows an "unverified app" warning during
sign-in, which you can click through.

## 3) Create an OAuth client ID

Under **APIs & Services → Credentials → Create credentials → OAuth client ID**:

1. Application type: **Web application**.
2. Add an **Authorized redirect URI** that exactly matches your deployment's
   origin plus `/api/gsc/oauth/callback`:

   | Deployment   | Redirect URI                                             |
   | ------------ | -------------------------------------------------------- |
   | Deployed     | `https://your-openseo-domain.com/api/gsc/oauth/callback` |
   | Local Docker | `http://localhost:3001/api/gsc/oauth/callback`           |

   The scheme, host, and port must match exactly, with no trailing slash.

3. Save, then copy the **Client ID** and **Client secret**.

## 4) Set environment variables

Set these three values, then restart OpenSEO:

| Variable               | Value                                                                   |
| ---------------------- | ----------------------------------------------------------------------- |
| `GOOGLE_CLIENT_ID`     | Client ID from step 3.                                                  |
| `GOOGLE_CLIENT_SECRET` | Client secret from step 3.                                              |
| `BETTER_AUTH_SECRET`   | A random string of **at least 32 characters** (encrypts stored tokens). |

`BETTER_AUTH_SECRET` is not needed for normal self-hosting — only for Search
Console, because the stored OAuth tokens are encrypted at rest with it. The
Cloudflare self-host with password accounts (`AUTH_MODE=password`) and the
Docker setup (`deploy/standalone`) generate one already; leave it unset there. Generate
one with:

```sh
openssl rand -base64 32
```

Where to set them:

- **Docker self-hosting:** `deploy/standalone/.env`
- **Older Docker image:** `.env`
- **Cloudflare:** the Workers dashboard (as secrets)
- **Local development:** `.env.local`

## 5) Restart and connect

Restart OpenSEO so it picks up the new variables. For Docker, changing `.env`
means Compose has to recreate the containers to reapply it:

```bash
docker compose up -d --force-recreate init web crawl-gateway
```

On the older Docker image, run `docker compose up -d --force-recreate open-seo`
instead.

Then open **Integrations**, click **Connect with Google**, authorize the Google
account that owns your verified property, and pick the property to bind to your
project.

## How it works

- OpenSEO uses your Google client to run the OAuth flow and stores the resulting
  grant in its database, with the access and refresh tokens **encrypted at rest**
  (keyed by `BETTER_AUTH_SECRET`).
- Access tokens are minted and refreshed on demand, so once your app is published
  to production you only authorize once.
- Search Console data comes from your own Google account, so OpenSEO never meters credits for it.

## Troubleshooting

**`redirect_uri_mismatch` from Google** — the redirect URI in your OAuth client
must exactly equal `<your-origin>/api/gsc/oauth/callback`. Re-check scheme
(`http` vs `https`), host, port, and that there's no trailing slash.

**"Google OAuth client not configured" / "not configured for Search Console yet"**
(in the app or via the MCP tools) — one of `GOOGLE_CLIENT_ID`,
`GOOGLE_CLIENT_SECRET`, or `BETTER_AUTH_SECRET` is missing, or the secret is
shorter than 32 characters. Set all three and restart. On Docker, recreate the
containers so Compose reapplies `.env`, as in [step 5](#5-restart-and-connect).

**`access_denied` during sign-in** — the Google account isn't listed as a test
user on the OAuth consent screen (while the app is in Testing mode). Add it under
**OAuth consent screen → Test users**.

**Search Console disconnects every week** — your OAuth app is still in Testing,
where Google expires refresh tokens after 7 days. Publish it under **OAuth
consent screen → Publish app**, then reconnect once.

**"Search Console API isn't enabled"** — the API isn't enabled in the Google
Cloud project that owns your OAuth client. Enable it (step 1), wait a minute,
then click **Try again**.

**Connected, but no properties to pick** — the Google account you authorized
doesn't have a verified property in Search Console. Verify the site in
[Search Console](https://search.google.com/search-console) first, then reconnect.

---

### Maintainers FREE TOOLS PROTECTION (`docs/maintainers/FREE_TOOLS_PROTECTION.md`)

# Free tool abuse protection

The website's public API routes protect paid provider calls independently of
the user interface. Deployed builds require a real Turnstile secret, the rate
limiter binding, and Cloudflare's client IP header. Missing or failed protection
returns 503; it does not allow the lookup. Local Vite development may omit the
Turnstile secret, but still uses the local rate limiter and budget object.

- JSON bodies are limited to 16 KiB, including streamed bodies. Tool schemas
  constrain domain counts, input lengths, countries and result limits.
- Cross-origin browser submissions are rejected. Direct clients still need a
  valid Turnstile token; Origin is not treated as authentication.
- The shared limiter allows five submissions per IP per minute across all
  tools, before calling Turnstile. Cloudflare's edge limiter is approximate.
- Siteverify must confirm success, the request hostname and `free_tool` action.
  Missing, invalid, expired or replayed tokens cannot reach cache/provider code.
  Verification has a five-second timeout and fails closed.
- Verified cache hits can be served without spending budget. Paid results are
  cached for 24 hours per cache key/Cloudflare location; failures use short TTLs.
- Before any paid request, a SQLite Durable Object atomically reserves the
  full run's call count and conservative estimated cost. There is one object per
  UTC day. Concurrent requests cannot oversubscribe its configured allowance.
- The budget also enforces 40 upstream calls per visitor/day, per-tool ceilings,
  and 6,000 upstream calls/day across tools. Failed requests are not refunded.
  Visitor identifiers are date-scoped IP hashes, not raw addresses; hashes are
  not anonymous. Old objects delete their stored counters after three days.

The SEO report tool reserves in the same budget, one whole report at a time,
and adds limits of its own: [free-seo-report.md](./free-seo-report.md).

## Budget and deployment

`FREE_TOOLS_DAILY_BUDGET_USD` in `web/wrangler.jsonc` is $100 per UTC day for
production and $10 for preview. Each environment has a separate Durable Object
namespace and allowance. A zero allowance disables uncached paid lookups.
Reservation prices live in `web/src/lib/free-tools/spend.ts`: 2.5 cents per
backlinks call, 1.5 cents per Labs call, including the keyword finder and generator (one call each, up to 20 rows). These
are conservative ceilings for the current endpoints and result limits, not
invoice reconciliation. Revisit them whenever provider prices or requests change.

Deploy the full website bundle with its Durable Object migration and bindings.
`web/src/worker.ts` exports both the TanStack handler and the budget class. Use
the existing deployment scripts, which reject missing or test site keys, and
configure the matching `TURNSTILE_SECRET_KEY` for each deployed environment.
The new action check requires client and server changes to deploy together.

Turnstile and per-IP limits do not eliminate human-assisted abuse or rotating
proxies. The atomic shared budget limits their paid lookups. A separately
verified provider-account spending limit remains useful as a billing backstop;
this change does not configure or verify one. No production changes are made by
running local tests.

## Limit logs

Worker logging is enabled in `web/wrangler.jsonc`. Search the website Worker's
logs for `free_tool_limit_reached` to find blocked budget reservations.
`limit: daily_spend` identifies the shared dollar allowance; the entry includes
`usedEstimatedUsd`, `requestedEstimatedUsd`, `limitUsd`, tool, and UTC day.
`daily_calls`, `tool_calls`, and `visitor_calls` identify the separate call caps
and include the used, requested, and allowed call counts. Entries omit visitor
identifiers, IPs, domains, and keywords. Limits are logged when a request is
blocked, not when usage merely approaches the allowance.

These logs do not send automatic notifications. No email, Slack, or spending
threshold alert is configured by this feature.

## Local website setup

For the website's DataForSEO tools, set `DATAFORSEO_API_KEY` in the ignored
`web/.dev.vars` file and restart the website dev server. Use the base64 credential
format in [the API key guide](../docs/DATAFORSEO_API_KEY.md). The website does not
inherit the root `.env.local`; without its own runtime key, paid tools return
“Service temporarily unavailable.” Domain Age Checker uses public RDAP data,
and SERP Simulator runs in the browser without a key. Real provider submissions
use the configured account's API credits.

## Validation

From the repository root:

```sh
pnpm --dir web run test:protection
pnpm --dir web run types:check
pnpm --dir web run build
```

The tests use mocked Siteverify responses for rejection paths and real local
workerd/SQLite storage for concurrency, whole-run limits, rollback and persistence.
They make no paid provider calls. A deployed verification pass must still confirm
valid submissions succeed and missing, invalid, expired and reused tokens fail.

---

### Maintainers SITE AUDIT RENDERING (`docs/maintainers/SITE_AUDIT_RENDERING.md`)

# Site audit JavaScript rendering

"Render JavaScript" is an option on the site audit start form and the
`run_site_audit` MCP tool. A rendered audit reads the content, headings and
links that JavaScript loads.

## Availability

Two renderers exist: [Cloudflare Browser Run](https://developers.cloudflare.com/browser-run/)
through the audit worker's `BROWSER` binding, and [Context.dev](https://context.dev)
through `CONTEXT_API_KEY`. The option works when either exists:

- **Hosted and previews:** both. Every account sees the option and pays with
  usage credits.
- **Self-hosted Cloudflare (Alchemy):** the deploy binds Browser Run, so the
  option always works. The operator's Cloudflare account pays, and a paid Workers plan is
  required (the free plan allows one browser action every ten seconds).
  `CONTEXT_API_KEY` adds the Context fallback on the operator's Context account.
- **Docker and legacy Wrangler installs:** no browser. The option works only
  with `CONTEXT_API_KEY`; otherwise the toggle is shown disabled with a setup
  note.
- **Local development:** `AUDIT_BROWSER_RENDERING=true` attaches a remote
  Browser Run binding to the audit worker (needs `wrangler login`).

`isAuditRenderingAllowed` in `rendering-policy.ts` is the single check. The app
worker has no browser binding of its own, so Alchemy sets
`AUDIT_BROWSER_RENDERING=true` on it whenever it binds `BROWSER` to the audit
worker. The auth mode says nothing about which renderer exists.

## How a page is rendered

1. The crawler fetches the page directly, as before.
2. The page is rendered when the direct fetch returned readable HTML with a
   2xx status, or HTML behind a bot challenge (any `blocked` result except a
   401 login wall). Redirects, non-HTML files, origin errors, login walls and
   rate limits keep their existing paths.
3. Cloudflare renders first. Context renders only when Cloudflare fails, is
   challenged, or sees an origin error. Context costs about five times as much
   per page. Cloudflare always identifies Browser Run as a bot, so sites behind
   Cloudflare's own bot protection render through Context.
4. The rendered document replaces the direct body for analysis. The direct
   response's timing and header directives stay authoritative, and so does
   its status, except behind a challenge. There the page takes the status
   Browser Run loaded, or 200 from Context, which reports no status and
   returns only pages that loaded. Recording a status keeps every page field
   as it is; an earlier version rescued blocked pages with an unknown status,
   which made those fields nullable.
5. A rendered document that looks like a challenge is classified `blocked`,
   and one still showing the app's loading shell gets the same "content may
   require JavaScript" warning as an unrendered shell.

A render that fails on every available renderer, or returns an unusable
document (wrong final URL, empty, still loading), makes the page an unread
`error` page. A challenge that neither renderer passes stays `blocked`. A
rendered document over 1 MiB keeps its first 1 MiB, the same bound the direct
crawl reads. The audit never audits the unrendered shell in its place, and paid
calls are never retried automatically.

## Throttled Shopify storefronts

Shopify's edge refuses some requests from crawlers with a 429 served within
milliseconds, signed or not, and the refusals are per URL more often than per
site (see `shopify-crawling.md`). When the audited site is a Shopify store (its
`powered-by` header, a saved crawler signature, or a host in Shopify's address
range) and the audit renders JavaScript, a page whose direct fetch returns 429
goes straight to the renderers instead of the shared backoff. Shopify's edge
lets Browser Run through, so these pages almost always render on Cloudflare and
cost no more than any other rendered page; Context reads the few it misses. A
page neither renderer reads is given up on as `rate_limited`, which
pauses the crawl like any other refusal; a store that refuses several pages in
a row stops the crawl.

An unrendered audit of a Shopify store backs off as described in
`crawl-throttle.ts`: a refused page gets one retry after the Retry-After and is
then recorded as rate limited while the crawl continues. Its report asks for a
crawler signature first, since Shopify sometimes lets a signed crawl through.
Once a signed, unrendered crawl is still rate limited, the report asks for a
new audit with Render JavaScript turned on instead.

## Billing

Rates live in `src/shared/audit-rendering.ts`, shared by the launch form, the
MCP tool description, the reservation and the settlement:

- **Cloudflare:** every attempt is billed as its full 20 second timeout at
  $0.09 per browser hour ($0.0005), not its measured time. A flat price per
  attempt needs no millisecond accounting and makes the low estimate exact.
- **Context:** the credits Context reports, including on error responses, at
  $0.0025 each. A failure that reports no usage is not charged.

Both convert through the standard markup: about 0.64 usage credits per
Cloudflare page and 3.84 per page that falls back to Context.

Hosted rendering uses Autumn balance locks: one reservation when the audit
starts, one settlement when it ends. It takes and settles them with the same
`holdCredits` and `finalizeHold` helpers that hold every DataForSEO call, so a
timed-out Autumn check fails closed instead of reading as a hold, and a
retried finalize cannot charge twice. Unlike a single DataForSEO call, one
audit's hold is split: the monthly balance covers what it can and top-up
covers the rest.

1. `startAudit` locks the estimated cost, twice the Cloudflare-only estimate
   (`renderingHoldCredits`), from the monthly balance first and top-up for the
   remainder. Not enough across both refuses the audit with
   `INSUFFICIENT_CREDITS` before the workflow starts. The lock ids travel in
   the workflow params. Most pages render on Cloudflare (about 95% of rendered
   pages in production), so this usually covers the audit without holding the
   six-times-larger worst case. The launch form and MCP tool quote this amount
   as what the audit costs at most.
2. Each crawl chunk counts Cloudflare attempts and Context credits and returns
   them in its step result. Chunks make no Autumn calls.
3. The workflow sums the checkpointed chunk counts. At the end, whether the
   audit completed or failed, one step confirms the locks for the credits used,
   monthly first, and releases the rest.
4. Locks expire after at most 24 hours. An audit that dies without settling
   returns the hold to the customer on its own.
5. The crawl stays inside the one hold. A chunk starts a page only while the
   credits rendered so far, plus every in-flight page and this one at the
   Context worst case, fit the hold. When they no longer do, the crawl stops
   and the report gets a `crawl-credits-exhausted` issue. Only a site that
   falls back to Context heavily reaches it.
6. A hosted rendered audit stops crawling 22 hours after it starts
   (`RENDERED_CRAWL_TIME_LIMIT_HOURS`), so settlement still finds its lock.
   The deadline counts from the workflow's creation, just after the locks are
   taken, and is the same on every replay. A crawl chunk starts no request
   after it, and the report gets a `crawl-time-limit` issue. Rendered audits
   take the plan's page limit. The launch form shows the estimate before a
   large rendered audit starts.

What we absorb rather than charge: renders in a chunk attempt that failed
before returning its counts, a settlement that Autumn rejects, usage beyond
the hold (a retried chunk can render a page twice, outside the chunk's own
count).

Alternatives considered:

- **Per-chunk deductions** (the first release): a failed deduction was logged
  while the audit kept spending, and an empty balance mid-audit silently
  switched the rest of the crawl to plain fetching.
- **Charging up front with a refund:** needs a manual refund on every failure
  path, and overcharges when the workflow dies.
- **Per-page billing:** hundreds of Autumn calls per audit.
- **Holding the worst case** (the first release): every page at the Context
  rate is six times what most audits cost, so accounts with a few dollars of
  credits were refused audits they could easily pay for.
- **Growing the hold mid-crawl:** one lock per audit keeps settlement a single
  step, and an audit never ends up holding credits the user did not agree to
  at the start.
- **A fixed page cap** (1,000 pages at first): rendered pages take from a few
  seconds to half a minute, so any cap that fits the slowest site inside the
  lock refuses large sites that would finish in a few hours.

## Open items

- **Context rate limits.** Context's Developer plan allows 60 calls a minute,
  and a busy crawl can exceed that when many pages fall back. A Context 429
  makes the page an unread `error` page. `site_audit:render` logs each Context
  `httpStatus`, so measure real 429 rates first. If they matter, pause the
  chunk on a Context 429 the way the crawler pauses on an origin 429
  (`crawl-throttle.ts`).
- **Deleting a running rendered audit.** The workflow stops before it settles,
  so the hold stays until the lock expires and the rendered pages are not
  charged.
- **Context pricing tier.** The Context rate in `audit-rendering.ts` assumes
  the Developer plan. Update it when the hosted account's plan is chosen.

## Configuration

Alchemy binds `BROWSER` and passes `CONTEXT_API_KEY` to the audit worker, and
passes `CONTEXT_API_KEY` to the app worker for the availability check. Docker
and local development read the key from `.env.local` or `.dev.vars`.

## References

- [Cloudflare Browser Run pricing](https://developers.cloudflare.com/browser-run/pricing/)
- [Context HTML scrape](https://docs.context.dev/api-reference/web-scraping/html)
- [Context pricing](https://context.dev/pricing)
- [Autumn balance locking](https://docs.useautumn.com/documentation/customers/balance-locking)

---

### Maintainers Account Deletion (`docs/maintainers/account-deletion.md`)

# Account deletion

Hosted users delete their own accounts from **Settings → Personal → Delete
account**. There is no operator script: the production Worker already holds
the keys every step needs, so no production secret has to leave Cloudflare.
Self-hosted and Every App deployments don't offer it; their operators own the
accounts.

## Requesting

The request is refused unless:

- the user signed in within the last 15 minutes and types their email;
- they own no workspace that has other members (remove them first, or ask
  support to hand the workspace to one of them).

On the workspaces that go with the account, the request cancels a renewing
paid plan at the end of its period (the credits last until then) and turns
auto-reload off, before the request row is written. The page warns about both
before the button.

A request writes an `account_deletion_requests` row with a date 14 days out,
and in the same batch deletes the user's sessions, API keys, and pending
invitations into their solo workspaces. MCP OAuth grants are removed from KV.
The user gets a Loops confirmation email (`LOOPS_TRANSACTIONAL_ACCOUNT_DELETION_ID`,
data variable `deletionDate`) and every later sign-in, password or Google,
fails with a message naming the date.

To cancel a request, delete the user's row from `account_deletion_requests`.
Sessions and API keys are already gone; the user signs in again and recreates
keys.

## Erasing

The daily cron (`17 3 * * *`, hosted only) erases accounts whose date has
passed, oldest first, for up to five minutes a day. For each one, in order:

1. Delete the Autumn customer of each solo workspace and its Stripe customer.
2. Erase Cloudflare state: stop running Workflows, revoke Google grants, and
   delete chat and audit Durable Objects, R2 audit payloads and cached data,
   KV progress and referral keys, and MCP OAuth grants.
3. Delete the PostHog person and queue deletion of their events and session
   recordings.
4. Delete the Loops contact, by user id and by email, and the review
   invitation data Trustpilot holds for the email (skipped where Trustpilot
   isn't configured).
5. In one database batch: delete the user and their solo workspaces (project
   data cascades), delete their Google connections and API keys, and
   re-attribute audits, reports, and report templates they created in shared
   workspaces to `gdpr-deleted-user`, revoking share links on those reports.

Every step is safe to repeat, and the database goes last, so a failed run is
finished by a later one. A failed account's date moves one day later, which
puts it behind the rest of the queue. A Google account another OpenSEO user
has also connected isn't revoked, since revoking it would end their grant
too. A failure is reported to PostHog error tracking
(`source: account_deletion`); a request still waiting three days after its
original date reports `ACCOUNT_DELETION_OVERDUE`.

## Monitoring

PostHog gets `account_deletion:requested` and `account_deletion:completed`
under the fixed distinct id `account-deletion`: the person's own record is
deleted with their account, and would take the counts with it. A weekly trend
of the two events shows how many people asked and whether the queue keeps up.

## Configuration

| Name                                      | Kind   | Purpose                                     |
| ----------------------------------------- | ------ | ------------------------------------------- |
| `LOOPS_TRANSACTIONAL_ACCOUNT_DELETION_ID` | var    | Confirmation email template                 |
| `POSTHOG_PROJECT_ID`                      | var    | Project the person is deleted from          |
| `POSTHOG_HOST`                            | var    | Existing ingestion host; now required       |
| `POSTHOG_ACCOUNT_DELETION_API_KEY`        | secret | Personal API key with person read and write |

The PostHog API host is derived from `POSTHOG_HOST` (`us.i.posthog.com` becomes
`us.posthog.com`). `LOOPS_API_KEY` and `AUTUMN_SECRET_KEY` are the existing
production keys.

Deleting a person takes a personal API key: PostHog's project secret API keys
don't offer the person scopes. Limit the key to `person:read` and
`person:write` on the production project only. It belongs to whoever created
it and stops working if they leave the PostHog organization, so create it
from an account that stays.

### Setting it up in GitHub

The production deploy workflow refuses to run while any of these is missing,
so set them before merging the change that requires them. Everything lives on
the `production` environment of the repository.

1. In Loops, create a transactional email for the confirmation. It receives
   one data variable, `deletionDate` (already formatted, e.g. "November 16,
   2026"), and should say the account is deleted on that date and to email
   support@openseo.so to keep it. Publish it and copy its ID.
2. In PostHog, open **Settings → Personal API keys → Create key**. Choose
   **Projects: production project**, scopes `person:read` and `person:write`,
   and copy the key. The project ID is the number in the project's URL.
3. Set them:

   ```sh
   gh variable set LOOPS_TRANSACTIONAL_ACCOUNT_DELETION_ID --env production --body '<loops id>'
   gh variable set POSTHOG_PROJECT_ID --env production --body '<project id>'
   gh secret set POSTHOG_ACCOUNT_DELETION_API_KEY --env production   # paste when prompted
   gh variable list --env production | grep POSTHOG_HOST     # must already be set
   ```

4. Make sure the production bucket expires Prompt Explorer's cached answers.
   Erasure doesn't delete them; it relies on this rule clearing them before
   the 14-day wait ends. Run with a wrangler login on the production account:

   ```sh
   wrangler r2 bucket lifecycle list open-seo
   wrangler r2 bucket lifecycle add open-seo prompt-cache-expiry \
     "dataforseo-cache/ai-search:prompt-response:" --expire-days 7
   ```

   Production already has `dataforseo-cache-expiry` (7 days on all of
   `dataforseo-cache/`), which covers it; the `add` is only for a bucket
   without that rule. Keep any such rule at 14 days or less.

5. Remove the secret the old erasure script used:

   ```sh
   gh secret delete GDPR_ERASURE_SECRET --env production
   ```

6. Merge and run the deploy. Its first step lists any name still missing.
   Afterwards, `account_deletion:*` events in PostHog confirm requests work;
   the first erasure runs on the cron 14 days after the first request.

## What is kept

- Reports, templates, and audits the user created in a workspace that
  outlives them, with the attribution wiped.
- The Dub referral customer record, which holds only a pseudonymous id.
- PostHog event deletion runs asynchronously after the request.
- Completed Workflow state and Workers logs expire under the Cloudflare
  account's retention. Prompt Explorer's cached answers expire under the
  bucket's lifecycle rule (step 4 above), which must stay configured.
- Database backups and billing records kept for tax, fraud, or legal reasons
  expire under their own retention.

---

### Maintainers Billing Lifecycle Emails (`docs/maintainers/billing-lifecycle-emails.md`)

# Billing lifecycle emails: operations

Design lives in `specs/0015-billing-lifecycle-emails.md`. This note covers
what the spec leaves out: how to measure the flow, the Loops-side settings
that are not in code, and the one-off backfill.

## Fix-payment funnel

Events, in order. All carry the user as distinct id and the organization as
the PostHog group, so a funnel can be broken down by plan or by organization.

| Step | Event                               | Where                                                | Properties                       |
| ---- | ----------------------------------- | ---------------------------------------------------- | -------------------------------- |
| 1    | `billing:payment_failed_email_sent` | server, when the webhook sends the Loops event       | `plan_id`                        |
| 2    | `billing:fix_payment_viewed`        | client, first ready render of `/billing/fix-payment` | `past_due`, `can_manage_billing` |
| 3    | `billing:fix_payment_portal_opened` | client, portal button click                          |                                  |
| 4    | `billing:fix_payment_returned`      | client, first ready render after Stripe returns      | `past_due`, `can_manage_billing` |
| 5    | `billing:payment_fixed`             | client, return flow resolved to not past due         |                                  |

Email delivery, opens and clicks are in Loops, not PostHog. Step 1 to step 2
is therefore the email's click-through; Loops has the open rate in between.

Failures, as PostHog exceptions with a `context` property:

- `fix_payment_open_portal`: the Stripe portal session could not be created.
- `fix_payment_check_timeout`: thirty seconds after returning from Stripe the
  subscription was still past due. Every occurrence is worth a look. Compare
  its count to `billing:payment_fixed` to see whether Stripe retries promptly
  on card update or whether people need the "pay it in the portal" nudge.

Session replay is on for the page, inputs masked. Filter replays by the
`billing:fix_payment_viewed` event to watch real attempts.

To build the funnel in PostHog: Insights, Funnels, steps 1 through 5 above,
conversion window 14 days, break down by `plan_id` on step 1. The
step 4 to step 5 drop is the number that says whether the page copy is doing
its job.

## Loops workflow settings that are not in code

Set these in the Loops dashboard on the "Billing: Payment failed" workflow.
The API cannot start workflows or edit their steps, so they were not applied
automatically.

1. **Filter at send time.** Add an audience filter before the email:
   `billingState` equals `past_due`. The webhook writes that property on every
   member before it sends the event, and the backfill script does the same,
   so a customer who fixed their card between the event and the send is
   dropped. Without this the filter is only on who receives the event, not on
   who is still past due when the email goes out.
2. **Second touch.** After the email, add a 48 hour timer, then the same
   `billingState` equals `past_due` filter, then a resend of the email with a
   shorter subject. Most recovered payments in dunning flows come from the
   second touch. The filter means anyone who fixed it in the meantime does
   not get nagged.

The "Billing: Subscription started" workflow already filters on
`billingState` equals `active` before its one week check-in; keep that.

## Backfill

Customers whose subscription, failed payment, or cancellation predates this
feature were handled once with a local script that read live Autumn and sent
the same Loops events with stable idempotency keys, writing each contact's
billing properties first so the workflow filters above applied. It is not in
the repository; the webhook owns everything from deploy onward.

---

### Maintainers Every App Learnings (`docs/maintainers/every-app-learnings.md`)

# EveryApp Learnings

Things to add to EveryApp skill files later.

## D1

- `db.batch()` is required for multi-row inserts — D1 has a 100 bind param limit per statement, so multi-row `INSERT VALUES (...), (...)` breaks. Use individual INSERT statements batched via `db.batch()` (up to 100 statements per call).

---

### Maintainers Every App (`docs/maintainers/every-app.md`)

# OpenSEO on an Every App gateway

`AUTH_MODE=everyapp` runs OpenSEO as an app behind an [Every App](https://everyapp.com) gateway. The gateway does what a self-hoster otherwise sets up per deployment:

| Concern                            | Other self-host modes                                             | `everyapp`                                                                                                                                                  |
| ---------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Sign-in, sign-out, who may open it | Cloudflare Access, or none                                        | The gateway's users, organizations, roles and per-app access                                                                                                |
| User and workspace                 | Access `sub` → `user` row, one shared workspace, everyone `owner` | Gateway `sub` → `user` row; the workspace and role come from the signed identity (see the two shapes below)                                                 |
| Teams, invitations, ownership      | None                                                              | The gateway's; OpenSEO's team UI and server functions are off                                                                                               |
| MCP                                | `/mcp` behind Access Managed OAuth                                | The gateway's one MCP connector lists OpenSEO's tools as `openseo_<tool>`; OpenSEO's own `/mcp` and `oseo_` API keys are off                                |
| DataForSEO                         | `DATAFORSEO_API_KEY` (or `TREG_API_TOKEN`) on the deployment      | The gateway holds either; calls go over the gateway binding                                                                                                 |
| Context.dev (rendered audits)      | `CONTEXT_API_KEY` on the deployment                               | The gateway holds it, as for DataForSEO; optional, audits run unrendered without it                                                                         |
| OpenRouter                         | `OPENROUTER_API_KEY` on the deployment                            | The gateway's AI proxy holds it                                                                                                                             |
| Search Console and Analytics       | OpenSEO's own Google client                                       | The gateway holds the Google client; each member connects Google from OpenSEO, and reads go through the gateway's proxy. OpenSEO's own callbacks answer 404 |
| Site-audit engine                  | The `open-seo-audit` Worker                                       | The app's helper Worker, `<app worker>--audit`                                                                                                              |
| Billing, Turnstile, Loops, PostHog | Off (hosted only)                                                 | Off; the gateway meters provider calls and will bill them                                                                                                   |

## One shape

An organization installs OpenSEO onto its own gateway (`pnpm everyapp install https://github.com/every-app/open-seo`); the deploy sets `EVERY_APP_ORG_ID`, which pins the install to that organization. Everyone the gateway lets in works in one shared workspace (the `shared-workspace` organization) with their gateway role, and a token for any other organization is refused. The database is the manifest's D1 (`DB`). This has nothing to do with the Docker edition.

A shared deployment that would serve every organization on a gateway from one Worker (the shape everyapp.team was once planned to run) is not built.

**Roles.** The gateway's `owner`, `admin` and `member` are OpenSEO's; anything else is `member`.

## Plan limits off app.openseo.so

Autumn stays hosted-only.

- **Site audits** use the self-hosted limits: each install pays for its own crawls.
- **Research spend** is not charged in OpenSEO; the gateway meters the provider calls it proxies and caps them per day.
- **Scheduled work.** The five-minute cron starts due rank checks and AI visibility runs. It calls no provider itself; each run is a Workflow whose gateway calls are the install's organization's background work (below).

## How it works

- **Identity** (`src/middleware/ensure-user/everyApp.ts`). The gateway signs a 120-second RS256 token onto every request it forwards (`x-everyapp-identity`, key id `everyapp-identity`, issuer `EVERYAPP_IDENTITY_ISSUER`, audience `EVERYAPP_AUDIENCE`, the app Worker's own name). The Worker entry rejects any request without a valid one before routing (`src/server.ts`), and `resolveEveryAppContext` maps it to a user, organization and role as above. The SDK answers 500 when `EVERYAPP_AUDIENCE` is unset: `everyAppWorker()` sets it, and the Alchemy stage sets it on the app's Worker (the audit Worker verifies no tokens).
- **Cookies.** The gateway strips every inbound `Cookie` header, so OpenSEO's server reads none in this mode, and it refuses requests that repeat its own session cookie's name. Better Auth's routes are hosted-only, so OpenSEO never issues a session cookie here, and the SDK's `everyApp()` drops any `Set-Cookie` on the way out. Client-side preferences (the sidebar state, privacy choices) stay in the browser.
- **Providers** (`src/server/lib/provider-access.ts`, `src/server/lib/openrouter.ts`). DataForSEO and Context calls go through `integrationFetch` from `@every-app/sdk/server`, OpenRouter calls through `createGatewayFetch`. No key is ever in OpenSEO. A gateway can hold a treg token (`TREG_API_TOKEN`, the `treg` capability) instead of a DataForSEO key: each DataForSEO call asks for DataForSEO's key first, and when the gateway refuses it as not configured, the same call goes to treg's DataForSEO relay (`src/server/lib/dataforseo/treg.ts`) with the gateway's treg token. The manifest can't say "one of these two", so both are optional features (`dataforseo`, `treg`): OpenSEO opens without either, and its pages say how to set one. The manifest's `capabilities` name what it calls; `integrationStatus` drives the "set up DataForSEO" prompt and whether audits can render pages, and needs no organization. A refusal the gateway makes itself is read with the SDK's `gatewayRefusal`: a spent daily cap shows as rate limited, a missing key as DataForSEO not set up, anything else as a setup error.
- **Whose call it is** (`src/server/lib/gateway-attribution.ts`). The gateway counts every provider call against the install's organization. While OpenSEO serves a request the gateway forwarded (a page, a server function, a tool call), the request's signed identity is forwarded with the call (`for: request`), so the gateway also knows whose it was; `src/server.ts` and `src/server/everyapp/tools.ts` open that scope. Work no request started (Workflows, SAM's turns, the cron) and work that outlives its token (120 seconds) is the organization's background work (`for: { background: true }`).
- **SAM sockets.** The Worker authorizes a SAM WebSocket once, when it connects, and the `member` row is a mirror that nothing removes, so a removed member's open chat would keep working until it closed. The gateway closes each WebSocket 15 minutes after the handshake; the client reconnects through the gateway, which signs a fresh identity or refuses someone it no longer lets in.
- **Google** (`src/server/features/google/googleAccess.ts`, `gatewayGoogle.ts`). The gateway holds the Google OAuth client (`GOOGLE_WORKSPACE_CLIENT_ID` and `GOOGLE_WORKSPACE_CLIENT_SECRET`, the manifest's `google-workspace` capability, in the optional `google` feature, with Google's scopes `webmasters.readonly` and `analytics.readonly`; the gateway adds the identity scopes) and each member's connection to OpenSEO, which the member makes from OpenSEO's Connect button. A connection is one person's and one app's: a Google connection made in another Every App app doesn't serve OpenSEO. A project's reads go out on the connection of the member who picked its property (`connectedByUserId`), whoever is looking and from background work alike (`for: { background: true, userId }`, `gatewayCallForUser` in `gateway-attribution.ts`), as OpenSEO's own mode reads with that member's Google grant; picking a property lists the member's own. OpenSEO's own Google client is ignored in this mode even if set, its connect flow is off, and `/api/gsc/oauth/callback` and `/api/ga4/oauth/callback` answer 404.
- **MCP tools** (`src/server/everyapp/tools.ts`). One list, `registerOpenSeoTools`, feeds both OpenSEO's own MCP server and the gateway's catalog, so a new tool reaches both. Read-only tools are `read` and every other tool is `write`, deletes included: the gateway hides `destructive` tools from AI clients until it has an approval step, and every OpenSEO tool should reach them. Tools return OpenSEO's text for the model and their structured result for clients. `whoami` reports the mode as `Every App`.
- **Account menu.** Shows the person from the identity, no organization switcher and no billing; "Sign out on Every App" opens the gateway (`GATEWAY_URL`, or the identity issuer in local dev), where sign-out happens.
- **Build** (`cloudflare.config.ts`, `vite-plugin-every-app.ts`). With `AUTH_MODE=everyapp`, `vite.config.ts` swaps the Cloudflare Vite plugin 1.x and `wrangler.jsonc` for plugin 2.x and `cloudflare.config.ts`: the app's Worker from `everyAppWorker()`, and the site-audit engine (`src/audit-worker.ts`) as its helper Worker from `everyAppAuxiliaryWorker()`. The client build reads the same `AUTH_MODE`, so it shows the Every App copy. Every other build still uses `wrangler.jsonc`.
- **Manifest** (`everyapp.config.ts`). Resources (D1 and KV, which classes the audit Worker defines), the helper Worker, the provider and capability requests with each one's need (the settings below), migrations, and the build and dev commands. `public` holds one route, the move from a self-hosted install (below): report sharing and OpenSEO's other unauthenticated routes are hosted-only, and the gateway's tool calls carry their own tokens.
- **Moving from a self-hosted install** (`src/server/features/every-app-transfer/`). An owner or admin makes a transfer code in Settings (Import from self-hosted OpenSEO): the app's origin and a secret, stored hashed in `every_app_transfers`, good for 24 hours, replaced by the next code and deleted when a move finishes. The self-hosted install's owner pastes it into Settings → Move to Every App, and that install's server sends its tables, SAM transcripts and R2 files in steps to `POST /api/every-app-transfer`, the one `public` route, which answers only to the secret. Both installs must be built with the same last database migration (`SCHEMA_VERSION` in `protocol.ts`), which the same release always is. Every project lands in the shared workspace; each person there becomes the Gateway member with the same email (the `members` capability), else the code's maker. Sign-in, team, billing and Google connection rows stay behind, as do Shopify crawler signatures, which are encrypted with the old install's secret. Auto-numbered rows get new ids. Every step is safe to repeat, and the cron starts no scheduled work while a move has sent something in the last hour.

## Settings

`everyapp.config.ts` declares what OpenSEO needs set, with a `why` for whoever sets it. What OpenSEO opens without is grouped into optional features (`dataforseo`, `treg`, `rendering`, `google`, `model`), each with its setup steps and all or nothing. The provider keys are the gateway's, set once for every app from your Every App checkout; `pnpm everyapp configure openseo` asks for each and walks the features, or set one alone: `CRAWLER_ACCESS_SECRET` (the deploy generates it) and `OPENROUTER_MODEL` are OpenSEO's own, on its Workers. The gateway's app list shows OpenSEO as needing setup, with the command, until the required ones are set, and `pnpm everyapp status` shows each setting's state.

| Setting                                                        | Held by | Need                    | Used for                                                                                                 |
| -------------------------------------------------------------- | ------- | ----------------------- | -------------------------------------------------------------------------------------------------------- |
| `OPENROUTER_API_KEY`                                           | gateway | required                | SAM, prompt suggestions and website research, through the gateway's AI proxy                             |
| `DATAFORSEO_API_KEY`                                           | gateway | optional (`dataforseo`) | Keyword, SERP, backlink, local business and AI answer data, including scheduled rank checks              |
| `TREG_API_TOKEN`                                               | gateway | optional (`treg`)       | The same data bought per call from a treg balance, used when the gateway has no `DATAFORSEO_API_KEY`     |
| `CONTEXT_API_KEY`                                              | gateway | optional (`rendering`)  | Rendering JavaScript-heavy pages when a site audit asks for it                                           |
| `CRAWLER_ACCESS_SECRET`                                        | OpenSEO | generated               | Encrypting the Shopify crawler-access signatures audits of protected stores send (32+ chars)             |
| `OPENROUTER_MODEL`                                             | OpenSEO | optional (`model`)      | The OpenRouter model SAM, prompt suggestions and website research run on (default `openai/gpt-5.6-luna`) |
| `GOOGLE_WORKSPACE_CLIENT_ID`, `GOOGLE_WORKSPACE_CLIENT_SECRET` | gateway | optional (`google`)     | Search Console and GA4 reads for your sites, with the Google account a member connects in OpenSEO        |

```bash
pnpm everyapp secret set OPENROUTER_API_KEY
pnpm everyapp secret set DATAFORSEO_API_KEY # or TREG_API_TOKEN
pnpm everyapp secret set CONTEXT_API_KEY # optional
pnpm everyapp secret set CRAWLER_ACCESS_SECRET --app openseo # generated; only to replace it
pnpm everyapp secret set OPENROUTER_MODEL --app openseo      # optional
```

`--app openseo` sets a value on OpenSEO's Workers from any directory; from this directory the name alone is enough, since the manifest lists both under `secrets`. That is how openseo.everyapp.team takes them too, being deployed with `everyapp deploy`.

Without `CONTEXT_API_KEY`, audits run unrendered: the "Render JavaScript" option is off and says an admin sets it (`src/server/lib/audit/rendering-policy.ts`), and a rendered audit asked for through MCP is refused with the same sentence. The deploy generates `CRAWLER_ACCESS_SECRET` when it is unset; without it, the crawler-access form (Settings → Shopify, and the bot-protection advice on an audit) says an admin sets it instead of offering to save a signature; audits of unprotected sites are unaffected. Without `OPENROUTER_MODEL`, the AI features run on the default model in `src/server/lib/openrouter.ts`.

## Run it locally

The Every App SDK and CLI it builds with are the published packages `@every-app/sdk` and `everyapp`, pinned to one exact version in `package.json`, so a clone of this repository installs and builds on its own: no checkout of the Every App repository beside it. To put it on your Gateway, run `pnpm everyapp install https://github.com/every-app/open-seo` from your [Every App](https://github.com/every-app/every-app) checkout, then `pnpm everyapp configure openseo`: the install takes the latest release, whose `everyapp-release.tar.gz` the Release workflow attaches when `pnpm release:publish` publishes a version, and the same command updates it later. To deploy your own changes instead, run that checkout's CLI from this directory: `node ../every-app/packages/cli/bin/everyapp.js deploy` (the CLI installed here runs `dev`, `db migrate` and `release`; a deploy also updates the Gateway, which only a checkout can build).

```bash
pnpm install
pnpm dev:everyapp        # everyapp dev, with AUTH_MODE=everyapp
```

`everyapp dev` applies the migrations to a local database in `.cloudflare/state` (not the `.wrangler/state` of `pnpm dev`), then starts a gateway-lite on `http://openseo.localhost:8787` with a seeded owner, the real identity checks with the dev key (`everyapp-identity-dev`, accepted only under `EVERYAPP_DEV=1`, which `everyapp dev` sets), and `/mcp` served from OpenSEO's tool catalog (send any `Authorization: Bearer` value). Both Workers run, sharing the database, KV and R2. With no gateway locally, DataForSEO, Context and OpenRouter use your own keys: write `DATAFORSEO_API_KEY` (or `TREG_API_TOKEN`), `OPENROUTER_API_KEY` and, for rendered audits, `CONTEXT_API_KEY` into `.dev.vars` yourself (`everyapp dev` writes nothing there; `.env.local` isn't read once `.dev.vars` exists). The ready block's `Dev vars` line names the required ones still missing.

`everyapp dev` sets no `EVERY_APP_ORG_ID`, so a local run accepts the dev user's organization; set it in `.dev.vars` to the dev user's organization id (`everyapp dev` prints it) to try the pinning.

## Deploy it

Onto an organization's own Gateway: `pnpm everyapp install https://github.com/every-app/open-seo` from an [Every App](https://github.com/every-app/every-app) checkout. It installs the latest release, whose `everyapp-release.tar.gz` this repository's Release workflow attaches when `pnpm release:publish` publishes a version, and the same command updates it later. To deploy uncommitted changes, run that checkout's CLI from this directory (`node ../every-app/packages/cli/bin/everyapp.js deploy`); the CLI installed here runs `dev`, `db migrate` and `release`, not `deploy`, since a deploy also updates the Gateway.

`everyapp install` and `everyapp deploy` always send `EVERY_APP_ORG_ID` (the installing organization), which is what pins the install to it. The deploy provisions the database and KV, builds both Workers, checks them against the gateway's app policy, applies migrations, and uploads the audit Worker before the app's. The gateway holds the provider keys for every app that uses them, and OpenSEO's own settings are the optional `CRAWLER_ACCESS_SECRET` and `OPENROUTER_MODEL` (the settings above).

## What isn't done

- **Metering through the gateway's wallet.** Calls are counted against the install's organization and capped per day; nothing is charged yet.
- **Membership checks inside a SAM socket's lifetime.** A removed member can keep chatting for up to 15 minutes. A membership lookup at the gateway per turn would close that window; it isn't built.
- **Long tools.** The gateway gives a tool call 30 seconds. Most OpenSEO tools return well within it; prompt exploration and some research can take longer.

---

### Maintainers Free Seo Report (`docs/maintainers/free-seo-report.md`)

# Free SEO report

A visitor enters a website and an email address at `openseo.so/seo-report`.
The website Worker (`web/`, `open-seo-landing`) writes a "Search opportunity"
report for that site and emails a link that opens it as a PDF, with a link
to create an OpenSEO account. A report has no page. Partner sites can send the
same request from a form of their own.

The code is `web/src/lib/seo-report/`. Shared protections (Turnstile, the
per-visitor rate limiter, the daily budget) are the free tools' own:
[FREE_TOOLS_PROTECTION.md](./FREE_TOOLS_PROTECTION.md).

## The API

Two requests, both to `https://openseo.so/api/seo-report`. This is the whole
contract; the page on openseo.so uses nothing else. The names and sentences
are in `web/src/lib/seo-report/contract.ts`.

### Who may call it

- The page on openseo.so.
- A partner site whose origin is listed in `SEO_REPORT_PARTNER_ORIGINS`
  (`web/wrangler.jsonc`, comma-separated). Today: `https://sfseo.dev`.

A listed origin gets CORS headers and nothing else. Every limit applies to its
requests exactly as to the page's. No cookies are read or set, so send the
request without credentials.

### `GET /api/seo-report`

Whether the tool can take a request. It is `false` only when the Worker is
missing a secret the tool needs, which is a misconfiguration and is logged.
It does not say whether today's limits are reached; a request finds that out.

```json
{ "open": true }
```

### `POST /api/seo-report`

```http
POST /api/seo-report
Content-Type: application/json

{ "site": "example.com", "email": "you@example.com", "turnstileToken": "…" }
```

| Field            | What it is                                                                                         |
| ---------------- | -------------------------------------------------------------------------------------------------- |
| `site`           | The website, as typed: `example.com`, `www.example.com` or a full URL. At most 300 characters.     |
| `email`          | Where the report goes. At most 254 characters.                                                     |
| `turnstileToken` | A token from a Turnstile widget on the calling page. One token is good for one request. See below. |

**Turnstile.** Render the widget with openseo.so's site key (it is public:
`WEBSITE_TURNSTILE_SITE_KEY` in the repository's Actions variables) and
`action: "free_tool"`. The widget's hostname list in the Cloudflare dashboard
must include the calling site. The server checks the token's `hostname`
against openseo.so and the partner list, and checks that it matches the
request's `Origin`.

**The answer** is always JSON with two fields:

```json
{ "status": "writing", "message": "Check your inbox in about 5 minutes." }
```

Read `status`. `message` is the sentence openseo.so shows for it, in English;
a partner can show it as it is or write its own. The HTTP code is 200 when the
request was taken, 4xx when it was refused and 503 when the tool can't run.

Taken, and an email follows:

| `status`  | Meaning                                                                                                     | HTTP |
| --------- | ----------------------------------------------------------------------------------------------------------- | ---- |
| `writing` | The report is being written now. The email arrives in about five minutes.                                   | 200  |
| `in_line` | It waits for a slot. An email arrives within about a day, with the report or to say it couldn't be written. | 200  |
| `sent`    | The site has a report written in the last 30 days. Its link was emailed.                                    | 200  |

Refused, nothing started and no email:

| `status`             | Meaning                                                                          | HTTP |
| -------------------- | -------------------------------------------------------------------------------- | ---- |
| `invalid_request`    | The body isn't the JSON above.                                                   | 400  |
| `invalid_site`       | `site` isn't a public website name, or is longer than 60 characters or 4 labels. | 400  |
| `invalid_email`      | `email` isn't an email address.                                                  | 400  |
| `site_not_found`     | DNS doesn't know the name.                                                       | 400  |
| `removed`            | The site asked for no reports.                                                   | 403  |
| `not_human`          | The Turnstile token is missing, used, expired or from another site.              | 403  |
| `origin_not_allowed` | The request's `Origin` isn't openseo.so or a listed partner.                     | 403  |
| `rate_limited`       | More than five submissions in a minute from this visitor.                        | 429  |
| `email_limit`        | This mailbox already asked today. One a day.                                     | 429  |
| `network_limit`      | This network already asked three times today.                                    | 429  |
| `day_full`           | The tool has promised all the emails it sends in a day.                          | 429  |
| `line_full`          | The line is full.                                                                | 429  |
| `site_busy`          | Twenty people are already waiting on this site's report.                         | 429  |
| `unavailable`        | A secret the tool needs is missing, or something it depends on is down.          | 503  |

A request that fails in the network, or an answer that isn't this JSON, should
be shown as `invalid_request` is.

**Where the address was entered.** The email's last line names the place:
`openseo.so/seo-report`, or the partner's hostname. The server takes it from
the hostname Turnstile verified, never from anything the client sends.

### Filling the site in on openseo.so

`https://openseo.so/seo-report?site=example.com` opens the page with the site
filled in.

## How it runs

Everything runs in the website Worker. There is no sandbox, because the model
can only call the tools it is given and no key is ever in front of it.

- `request.ts` checks a request, cheapest check first: that the tool is
  configured, the request's shape, the website's and the email's, then origin, rate limit and
  Turnstile, the removal list and DNS.
- `desk.ts` is one SQLite Durable Object for the whole tool: the day's counts,
  the line, who is waiting on each report, and the reports. A request is
  checked against every limit and given its place in one transaction, so
  requests that arrive together can't share a count and a refused request has
  taken nothing. Its alarm starts the next runs, gives up runs that waited too
  long, sends the emails and forgets what is old.
- `workflow.ts` is one report's run, as a Cloudflare Workflow whose id is the
  run's id. The paid step has no retries and can begin once per run.
- `write.ts` is the model loop: a model, through OpenRouter, follows
  `customer-keywords.md` until it hands the report in, then edits what it
  handed in and hands it in again. `tools.ts` is all it can do: five
  research lookups (`research.ts`, DataForSEO directly), `read_page`
  (`read-page.ts`) and `submit_report`.
- **What a report is.** `customer-keywords.md` has the research steps of the
  public `customer-keywords` skill and an Output section of this tool's own.
  The model hands in a plan as fields (`plan.ts`): a one-sentence verdict, up
  to three moves, best first, and who it took the customer to be. A move is
  one page to build or rework: the action, the keyword with its searches and
  difficulty, who holds page one, the steps that build the page in order,
  and why it sits where it does. The data behind the plan follows as
  Markdown: one keyword table, what comes after the plan, and what not to
  spend on. The plan is fields and not prose so that the number beside a
  move is the move's own and the first page is drawn the same way every
  time. A report stored before 2026-11-20 has no such fields: it is read
  with an empty plan and drawn as its verdict and its Markdown.
- **Every report is edited before it is sent.** The first hand-in is a
  draft. The model is told so and asked, in the same conversation, to edit
  the draft with `clean-copy.md` and hand it in again; the second hand-in is
  the report. The skill asks of every string whether it should be there at
  all, before how it is phrased. The edit is a turn of the same conversation
  and not a second model call with a fresh start, so the research is still
  in front of the model while it cuts, and the second hand-in is held to
  the same shape and rules as the first. It may change words and nothing
  else: a hand-in whose moves differ from the draft's in number, order,
  keyword, searches, difficulty or page is refused with what differed, and
  the model hands in once more. A second one that differs fails the report.
  Numbers inside sentences and the Markdown table are held by the prompt
  alone. The request to edit is a message of its own: put in the answer to
  the hand-in, the model took it as data and handed nothing in, and made to
  call the hand-in tool, it ran to the output cap without finishing.
- **A site name** is at most 60 characters and 4 labels (`site.ts`). The name
  is shown back in the email and the report's title, to an address the sender
  chose, so it can't be long enough to carry a message. The longest of 4,486
  startup domains checked is 35 characters and 3 labels.
- **Reading the site.** The Worker fetches pages itself, as a crawler named
  `openseo-reports` that obeys `robots.txt`. It reads only the report's own
  site, over `http` or `https`, 10 seconds and 2 MB a page, 12 pages a
  report, and no address over 2,000 characters. Every redirect is checked the
  same way before it is followed. A `robots.txt` is read once per site, up to
  500 KB. One that answers 429 or a server error, or lists more than 5,000
  rules for this crawler, means the site is left alone.
- **The PDF.** `pdf.ts` draws the report with pdfmake, from the stored plan
  and Markdown, each time its link is opened: US Letter, the verdict in the
  largest type, a card for each move with its searches and difficulty beside
  it and its steps numbered down a line, then the Markdown with its table,
  page numbers, and the link to create an account. A card, a list item and
  a paragraph are never split between pages, and the closing box takes the
  last section with it to a new page.
  A report is drawn at its normal size first. If its last card falls off
  the first page, or its last page is mostly blank, it is drawn once more,
  set tighter, and that one is sent when it fixes either. Ligatures are off,
  so copied text keeps its "fi" and "fl". Nothing stores the PDF. It is
  drawn in the request: 0.1 to 0.25 seconds in Node for the real reports
  tried on 2026-11-20, both drawings included (0.07 to 0.2 seconds in local
  workerd before the second drawing existed), for files of 34 to 49 KB. The
  code is a part of the Worker that loads only for a report's link, so no
  other request starts it. It added 763 KiB to the Worker's compressed
  upload (1,286 to 2,049 KiB), most of it the Roboto typeface.
- **What a report may carry.** Nobody reads a report before it goes out, and
  the site it is about shapes what the model writes. So the PDF has no
  images, and a link stays a link only when it goes to the report's own site,
  a site on a results page the report checked, or openseo.so. PDF readers
  make links of written-out addresses by themselves, so any other address
  loses its `https://` and `www.`. The filter runs on the parsed Markdown
  (`pdf.ts`), raw HTML is printed as text, and the first page says the report
  was written automatically.
- **Why there is no report.** The model may stop for a reason from a fixed
  list: the company has closed, the site has moved, or it doesn't serve the
  United States. The failure email says our sentence for that reason
  (`failure.ts`), never the model's words. A stop with no listed reason, or a
  finished report that carries one, is a failed report.
- **Email addresses** are stored only with the run they wait on, in the
  Durable Object, and deleted when the email goes or after six hours of
  failed sends. The daily limits count a hash of the mailbox and of the
  network. Nothing logs an address. Emails are Loops transactional sends with
  `addToAudience: false`, so nobody becomes a contact.
- **A report's link** is `/seo-report/r/<token>`, where the token is 122
  random bits, for 90 days. It answers with the PDF, shown in the browser
  (`Content-Disposition: inline`) and named for the site when saved
  (`seo-report-example.com.pdf`), marked `noindex` and `no-store`.
  No page is served at a report's address, so no script that records page
  addresses ever runs there. The link is still in the Worker's own invocation
  logs and in Loops, which sent it. A link with no report behind it gets the
  site's "not found" page. Reports were pages at the same links for their
  first days, from 2026-11-18: those links now open the PDF too.

## Limits

Days are UTC, as the free tools' budget counts them.

| Limit                                      | Number                                   | Where                   |
| ------------------------------------------ | ---------------------------------------- | ----------------------- |
| Per mailbox ("+tag" and Gmail dots folded) | 1 a day                                  | `limits.ts`             |
| Per network (an IPv4 address, an IPv6 /48) | 3 a day                                  | `contract.ts`           |
| Emails across the tool                     | 100 a day                                | `limits.ts`             |
| New reports across the tool                | 25 a day                                 | `free-tools/spend.ts`   |
| Written at once                            | 3                                        | `limits.ts`             |
| The line                                   | 25 places, 26 hours at most              | `limits.ts`             |
| People waiting on one site's report        | 20                                       | `limits.ts`             |
| One report's research                      | 9 calls, sizes in `TOOL_LIMITS`          | `tools.ts`              |
| One report's reading                       | 12 pages of its own site                 | `limits.ts`             |
| One report's model use                     | 30 calls, 500,000 tokens, $1, 15 minutes | `limits.ts`, `spend.ts` |

- A second request from a mailbox in one day is told so and starts nothing.
  The attempt still counts against the network.
- A site with a report from the last 30 days isn't written again: the link is
  emailed. That uses the mailbox, network and email counts, and no budget.
- A report that has waited 26 hours is given up, and whoever asked gets the
  "couldn't write it" email. That is 24 hours for the day's budget to come
  back and two for a full line ahead of it to be written. A report whose turn
  comes is written, however long it waited.
- At a research tool's limit the model is told so and finishes with what it
  has. At a model limit there is no report.
- If the model's provider drops a run part-way, each call is retried for
  about a minute, and the run is picked up once more from where it stopped,
  keeping the research it had paid for. That memory lasts as long as the
  Workflow step: an engine restart mid-write still ends as one failure email.

## What it costs

Measured on 2026-11-18 on three real reports (trumaker.com, heyaristotle.com,
nodafi.com), written by `openai/gpt-6.2-sol` at medium effort:

|                                    | Per report     | Who is paid |
| ---------------------------------- | -------------- | ----------- |
| Search data, as DataForSEO charged | $0.13 to $0.25 | DataForSEO  |
| Model, as OpenRouter charged       | $0.09 to $0.21 | OpenRouter  |
| Together                           | $0.21 to $0.46 |             |

They took 33 to 81 seconds. Each run logs what it used (`seo_report_written`).

The plan-first report (2026-11-20) costs about the same. Seven real reports
on three sites (everyapp.com, trumaker.com, browserbase.com), run in Node
with the tool's own code, cost $0.22 to $0.50 together and $0.35 on average,
in 27 to 148 seconds. The two dearest, $0.46 and $0.50, were the ones that
read the most pages and made the most research calls.

The edit adds about $0.016 and 4 seconds to a report: one more model call
that reads the conversation from the cache and writes the report again
(measured on one real report, trumaker.com, $0.27 in all).

**A report can't cost more than $1.27**, and it reserves $1.50 in the free
tools' daily budget (`FREE_TOOLS_DAILY_BUDGET_USD`) before it starts.

- **Search data, $0.27 at most**: the call counts and sizes in `TOOL_LIMITS`
  at DataForSEO's list prices. A test recomputes it when a limit changes.
  DataForSEO charges five times for a results page whose keyword holds a
  search operator (`site:`, `intitle:` and fourteen more), so those keywords
  are dropped before the call. Nothing else the model chooses changes a
  price: depth, device, market and every paid option are fixed in
  `research.ts`.
- **Model, $1 at most** (`SEO_REPORT_MODEL_USD`). A run counts its own
  spend: each reply's tokens at the model's list price, from the table of
  priced models in `web/src/lib/free-tools/spend.ts`
  (`SEO_REPORT_MODEL_PRICES`). Before each call it works out the most the
  next one could cost and stops before a call that could pass the cap. Every
  call's output is capped at 16,000 tokens. OpenRouter's own figure for each
  reply is a check on the count: the larger of the two is used, and
  `seo_report_cost_mismatch` is logged when they are far apart, which means a
  price in the table is out of date. A reply that reports no token counts
  ends the run.

**The model's host is pinned** (`model.ts`): OpenAI's own, and no other.
OpenRouter otherwise picks a host for each request, and not every host does
the reasoning the request asks for. On 2026-11-20 the same question drew
about 80 reasoning tokens from OpenAI's host and from Azure's and none from
Amazon Bedrock's, at the same list price. When OpenAI's host is down, slow or
turns a request away, the call is retried and the run picked up once, like
any provider failure, and then ends as `seo_report_failed` with
`side: "provider"`. Each run's log line names the hosts that answered
(`providers`) and its `reasoningTokens`.

**The model** is `SEO_REPORT_MODEL` and `SEO_REPORT_MODEL_EFFORT` in
`web/wrangler.jsonc`: `openai/gpt-6.2-sol` at medium. It must be a model in
the price table; with any other the tool stays closed. `openai/gpt-6-luna` is
in the table too, so switching to it is one line. Both were tried on real
sites on 2026-11-18:

| Model and effort | Model cost a report | Time         | Against Sol at medium                                                         |
| ---------------- | ------------------- | ------------ | ----------------------------------------------------------------------------- |
| Sol, medium      | $0.09 to $0.21      | 34 to 84 s   | The default                                                                   |
| Sol, low         | $0.16 to $0.19      | 65 to 68 s   | As full, no cheaper, and it missed one of a site's two city keywords          |
| Luna, high       | $0.02               | 182 to 242 s | Lighter, with weaker priorities: it led a small clothier with a head term     |
| Luna, medium     | $0.01 to $0.02      | 145 to 166 s | Clearly thinner: half the keywords on one site, no city keywords on the other |

Search data is $0.13 to $0.25 a report whichever model writes it, so Luna
makes a report about a third cheaper, not a tenth of the price.

| `SEO_REPORTS_PER_DAY` | A day, at the measured average | A day, at the most reserved |
| --------------------- | ------------------------------ | --------------------------- |
| 25 (the default)      | about $8                       | $37.50                      |

**The budget is shared with the other free tools.** Twenty-five reports can
reserve $37.50 of the $100 a day. If the other tools reserve more than $98.50
first, no report starts that day: requests wait in line, are told so, and
after 26 hours get the email saying we had more requests than we could write.
`free_tool_limit_reached` in the logs shows when either happens.

The reservation is a count of money, not a wallet. Two limits set outside the
code are the hard stops; set both before the merge:

- **OpenRouter:** a key used by nothing else, with a $30 limit that resets
  daily. Twenty-five reports at $1 each is $25.
- **DataForSEO:** a daily limit on the account. Reports add at most $7 a day
  to what the other free tools spend.

## Launching it

There is no switch. The tool is live from the deploy that ships it, in the
tools hub, the footer and the sitemap like every other free tool. So
everything below is done **before the merge**, by someone with the Cloudflare
account. Commands run from `web/`.

1. **Check the Workflow's name is free.** No Workflow called `seo-report` may
   exist on the account under another script:

   ```sh
   pnpm exec wrangler workflows list
   ```

   Good: no `seo-report` row. (An earlier build used `sfseo-report`.)

2. **OpenRouter.** Create a key at [openrouter.ai](https://openrouter.ai/keys)
   used by nothing else, with a $30 limit that resets daily, and set it:

   ```sh
   pnpm exec wrangler secret put OPENROUTER_API_KEY
   ```

3. **Loops.** Create and publish two transactional emails, and set their ids:

   | Name                | Data variables                               | Secret                       |
   | ------------------- | -------------------------------------------- | ---------------------------- |
   | `seo-report-ready`  | `domain`, `reportUrl`, `signupUrl`, `source` | `LOOPS_SEO_REPORT_READY_ID`  |
   | `seo-report-failed` | `source`, `reason`                           | `LOOPS_SEO_REPORT_FAILED_ID` |

   ```sh
   pnpm exec wrangler secret put LOOPS_SEO_REPORT_READY_ID
   pnpm exec wrangler secret put LOOPS_SEO_REPORT_FAILED_ID
   ```

   `source` is where the address was entered: `openseo.so/seo-report` or a
   partner's hostname. `reason` is one of five sentences of ours
   (`failure.ts`). The failure email names no site, because whoever asked
   chose the name. Keep both to the report: they can't carry marketing.
   `LOOPS_API_KEY`, `DATAFORSEO_API_KEY` and `TURNSTILE_SECRET_KEY` are
   already on the Worker.

4. **Turnstile.** For each partner in `SEO_REPORT_PARTNER_ORIGINS`, add its
   hostname to the free tools' widget in the Cloudflare dashboard (Turnstile,
   the widget whose site key is `WEBSITE_TURNSTILE_SITE_KEY`). No new secret.

5. **Merge.** The deploy creates the Durable Object and the Workflow, and the
   tool is live.

If a secret is missing, the tool doesn't run: every request is answered
`unavailable`, `GET /api/seo-report` answers `{"open":false}`, and each one
logs `seo_report_not_configured` with the names that are missing. The page
still shows its form.

### Checks after the merge

Nothing has run on Cloudflare before this, so these are the first thing to do
once the deploy finishes, in order of what would hurt most if wrong. Keep the
logs open in a second terminal:

```sh
pnpm exec wrangler tail open-seo-landing --format json --search seo_report_
```

| #   | Do                                                                                                   | Good answer                                                                                                                                                                         |
| --- | ---------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1   | `curl https://openseo.so/api/seo-report`                                                             | `{"open":true}`. `false` means a secret is missing; the log names it                                                                                                                |
| 2   | Ask for a report on a US site of ours at `https://openseo.so/seo-report`                             | The page says to check the inbox. Within two minutes a `seo_report_written` line whose `countedUsd` and `chargedUsd` agree, no `seo_report_cost_mismatch` line, and the ready email |
| 3   | Ask again at once with the same address and another site                                             | "That address has already asked for a report today." Nothing starts                                                                                                                 |
| 4   | `curl -sI https://openseo.so/seo-report/r/<token from the email>`                                    | `content-type: application/pdf`, `content-disposition: inline`, `x-robots-tag: noindex, nofollow` and `cache-control: private, no-store`                                            |
| 5   | Open the link from the email in a browser                                                            | The PDF opens in the tab, and saving it gives a file named `seo-report-<site>.pdf`                                                                                                  |
| 6   | Ask for a report on a site that isn't for the United States, such as `richersounds.com`              | A `seo_report_failed` line with `side: "site"`, and the failure email with the United States sentence. This is the first real send of the failed template                           |
| 7   | Submit from SF SEO's form, and from `https://www.openseo.so/seo-report` if `www` doesn't redirect    | Both are taken. `not_human` means that hostname is missing from the Turnstile widget                                                                                                |
| 8   | `pnpm exec wrangler workflows instances describe seo-report latest`                                  | The "write report" step succeeded once. In the dashboard's Workers observability, that invocation's CPU time is far under 30,000 ms                                                 |
| 9   | Start a report, then run the deploy (`gh workflow run deploy-website.yml`) while it is being written | For that site, at most one `seo_report_written`, or one `seo_report_failed`. One email. Never two reports                                                                           |
| 10  | Ask for a report on `127-0-0-1.nip.io`, a public name that resolves to a private address             | No report. The log's `calls` show `read_page` and nothing was read. This costs a few cents of model                                                                                 |
| 11  | Ask for a report on a site of ours that answers its headers at once and then sends a byte a second   | `read_page` gives up at ten seconds: the run's `seconds` is not minutes long                                                                                                        |
| 12  | Unpublish the failed template in Loops, repeat check 6 from another address, publish it again        | `seo_report_email_refused` with `status: 400`, and no retry                                                                                                                         |
| 13  | Lower the OpenRouter key's limit to $0, ask for a report, restore the limit                          | `seo_report_failed` with `side: "provider"`, and the failure email                                                                                                                  |

### Stopping it, and taking it out

**To stop it in a hurry, with no deploy,** delete its OpenRouter key from the
Worker: `pnpm exec wrangler secret delete OPENROUTER_API_KEY`. Every request
is then answered `unavailable` and nothing new starts. Putting the secret back
starts it again.

**To take it out is a deploy that deletes the page and the tool.** It is not a
plain revert: once a deploy has created the `SeoReportDesk` class, Cloudflare
refuses any version that neither exports the class nor deletes it, and the
daily redeploy would fail the same way.

1. Empty the line (below), so nobody is left waiting.
2. Revert the tool's commit.
3. In `web/wrangler.jsonc`, keep both existing migrations and add one that
   deletes the class. The history must stay, or the deploy tries to create
   `FreeToolBudget` again:

   ```jsonc
   "migrations": [
     { "tag": "free-tool-budget-v1", "new_sqlite_classes": ["FreeToolBudget"] },
     { "tag": "seo-report-desk-v1", "new_sqlite_classes": ["SeoReportDesk"] },
     { "tag": "seo-report-desk-v2", "deleted_classes": ["SeoReportDesk"] },
   ],
   ```

4. Merge, which deploys. Then delete the Workflow, which a deploy leaves
   behind:

   ```sh
   pnpm exec wrangler workflows delete seo-report
   ```

Deleting the class deletes every stored report and every address still
waiting, so emailed report links stop working. This follows Cloudflare's
documentation and the same pattern in the app's own `wrangler.jsonc`; it has
not been run for this Worker.

## Operating it

- **Empty the line**, after abuse say. Waiting runs and the addresses waiting
  on them are deleted in one step, with no email:

  ```sh
  pnpm exec wrangler workflows trigger seo-report '{"emptyLine":true}'
  ```

- **Stop reports about a site.** Add its name to
  `web/src/lib/seo-report/removed-sites.json` and merge. The name covers every
  name under it. From the next deploy it can't be asked for, a report waiting
  for it isn't written, and one already written isn't served.
- **Logs.** Search the website Worker's logs for `seo_report_`:

  | Event                             | Meaning                                                                                                     |
  | --------------------------------- | ----------------------------------------------------------------------------------------------------------- |
  | `seo_report_written`              | A report was written. Seconds, model calls, tokens, both costs, the hosts and the tools called.             |
  | `seo_report_failed`               | No report. `side` is `provider` (the model's provider), `site` or `ours`; `reason` says why.                |
  | `seo_report_resumed`              | The provider dropped a run and it was picked up again.                                                      |
  | `seo_report_cost_mismatch`        | Our count of a run's model cost and OpenRouter's are far apart: check the price table.                      |
  | `seo_report_request_failed`       | A request broke part-way and was answered `unavailable`.                                                    |
  | `seo_report_email_refused`        | Loops refused an email, with its status. An unpublished template is a 400.                                  |
  | `seo_report_email_unreachable`    | Loops didn't answer. The send is tried again each minute for six hours.                                     |
  | `seo_report_email_dropped`        | An email was given up after six hours.                                                                      |
  | `seo_report_not_configured`       | A secret is missing, or the model has no prices. `missing` names them. Requests are answered `unavailable`. |
  | `seo_report_budget_unavailable`   | The daily budget couldn't be asked. Nothing starts until it can.                                            |
  | `seo_report_workflow_not_started` | A run's Workflow couldn't be created. Tried again each minute.                                              |

  `free_tool_limit_reached` with `tool: seo-report` means the day's reports or
  dollars ran out and reports are waiting.

## Running it locally

In `web/.dev.vars`:

```
SEO_REPORT_STAND_INS=model,email
```

`model` replaces the model with one that hands in a made-up report and spends
nothing (a site named `blocked.…` gets none). `email` logs emails instead of
sending them. With `SEO_REPORT_STAND_INS=email` and real `OPENROUTER_API_KEY`
and `DATAFORSEO_API_KEY` values, a real report is written and nothing is sent.
A production build ignores the variable.

## Known limits

- **One market.** Reports use United States search data, in English. The form
  says so, and a site the model judges isn't for the United States gets the
  failure email with that reason. Writing for the site's own market is the
  next step: the skill allows it, and it needs a market chosen from a fixed
  list of countries and its own real runs.
- **The plan is a judgement, and it varies.** Four reports written for one
  site on 2026-11-20 did not agree on the first move: three led with one
  keyword, and the fourth led with another and listed the first under "Don't
  spend on these". A reader who asks twice in 30 days gets the same report
  again, but nothing makes two writings agree.
- **The edit is light.** On two real reports it changed 4 and 6 strings
  of 24 to 29 and removed 1% to 3% of the words: mostly a `why` that
  repeated the numbers printed beside it. The drafts were already held to
  word limits. An edit can also fail a report that was fine as a draft, by
  changing the plan's data twice or by not handing in.
- Anyone who passes Turnstile can have one email a day sent to an address
  they type. Only a confirm-by-email step would remove that.
- The page reader checks names, not the addresses they resolve to. Where a
  request to a name goes is Cloudflare's network's doing.
- Account creation carries the site (`?domain=`) but not the report. The
  report stays at its link.
- Every opening of a link is one read of the one Durable Object, a single
  indexed lookup, and then one or two tenths of a second of the Worker's CPU
  to draw the PDF. A made-up link costs only the lookup: a flood of them would queue
  ahead of new requests without spending anything. A cache wouldn't help,
  because each made-up link is a new address; a rate-limit rule on
  `/seo-report/r/*` in Cloudflare would.
- The PDF's typeface has Latin, Greek and Cyrillic letters. A report holding
  anything else prints gaps there.
- A PDF reader may still make a link of a written-out email address.
- A reservation is lost if the Durable Object is evicted in the moment
  between reserving and starting a run. The day then starts one report fewer.

---

### Maintainers Preview Deployments (`docs/maintainers/preview-deployments.md`)

# Alchemy preview deployments

OpenSEO preview stages use isolated Cloudflare resources and a shared,
Alchemy-managed Cloudflare Access boundary.

## Security model

- Preview Workers are named `open-seo-<stage>` and served from
  `open-seo-<stage>.<WORKERS_SUBDOMAIN>`.
- One persistent Access application protects
  `open-seo-*.<WORKERS_SUBDOMAIN>` before any preview Worker exists.
- Production uses the unsuffixed `open-seo` Worker on `app.openseo.so` and
  `www.app.openseo.so`. It does not match the preview wildcard and is not
  placed behind preview Access.
- A separate persistent Alchemy stack manages the shared Access boundary. A
  failed preview deploy or teardown therefore cannot remove the gate protecting
  other previews.
- `pnpm preview:access` deploys/reconciles the persistent Access stack —
  one-time setup, safe to re-run. Every CI deploy then verifies the real HTTP
  challenge (a curl check in `pr-preview.yml`, with retries for propagation
  delays) before commenting a URL, so a missing gate fails the job. A preview
  that answers without the challenge is public — destroy the stage
  (`pnpm destroy:preview`); a merely unreachable one can stay, as it still
  sits behind the wildcard application.

## Credentials

Alchemy manages Cloudflare credentials itself — nothing credential-shaped goes
in the env files.

- **Locally**, run `pnpm alchemy login deploy/alchemy/alchemy.run.ts` once. Answer yes to
  **Customize OAuth scopes?** and enable `access:write` on top of the defaults
  (the preview Access gate needs it; add `query_cache:write` too if you will
  deploy production — Hyperdrive). The credential is stored globally, and
  later runs — including non-interactive ones — reuse it silently.
- **State** lives in the account's Cloudflare state store (an
  `alchemy-state-store` Worker with embedded SQLite), shared by every machine
  and CI — provision it once with `pnpm alchemy cloudflare bootstrap`. It
  mints an auth token and encryption key into the account Secrets Store;
  local runs cache credentials under `~/.alchemy/`.
- **In GitHub Actions**, the runner's `CI` env makes alchemy read
  `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID` from the environment
  (repo secrets), and resolve the state-store token from the Secrets Store on
  every run. The token needs write access to Workers Scripts, KV, D1, R2, and
  Workflows, plus **Secrets Store Edit** and **Account Settings read** (both
  used by alchemy's state-store login, which fetches its token through a
  temporary edge-preview worker; Cloudflare requires Edit to bind a secret,
  and Read fails with "Secrets store binding authorization failed"). CI never
  touches Access — the gate is one-time local setup.

## Cloudflare Access configuration

The persistent Access stack creates a self-hosted application with this public
hostname:

```text
open-seo-*.your-subdomain.workers.dev
```

Use the account's Workers subdomain shown under **Workers & Pages**, not the
Zero Trust team domain. Set that full value in `.env.preview` as
`WORKERS_SUBDOMAIN`. Preview URLs derive from it as
`https://open-seo-<stage>.<WORKERS_SUBDOMAIN>` — hosted previews use that as
`BETTER_AUTH_URL`, and CI's verify step probes it; a wrong value fails the
check. Previews in `local_noauth` or `cloudflare_access` mode deploy without
it, since nothing reads `BETTER_AUTH_URL` there; `password` stages read the
subdomain from the account when it is unset.

Set `ACCESS_ALLOWED_EMAILS` to the exact comma-separated emails that may open
previews:

```env
ACCESS_ALLOWED_EMAILS=you@example.com
```

`pnpm preview:access` deploys the persistent Access stack. It always uses
`--adopt`, so it can recover matching infrastructure if local Alchemy state is
lost — safe to re-run any time. Normal preview teardown only destroys the
requested application stage and cannot touch the Access stack.

## Local preview

```sh
pnpm alchemy login deploy/alchemy/alchemy.run.ts  # once — see Credentials above
cp deploy/.env.preview.example .env.preview
pnpm preview:access   # once — the shared Access gate (safe to re-run)
pnpm deploy:preview --stage manual-preview --yes
```

`deploy:preview` builds with Vite's preview mode (`--mode preview` loads
`.env.preview` into the client bundle) and runs `alchemy deploy` against
`.env.preview`; extra flags land on the deploy. CI runs this same command.
Two alchemy conventions to know: omitting `--stage` targets alchemy's default
per-user stage (`dev_$USER`), and stage `hosted-prod` with `.env.preview` fails
in the stack: production requires hosted auth, Postgres, and existing resource IDs.

Each preview starts with an empty database: open the URL, pass the Access
challenge, and you're in. Previews default to `AUTH_MODE=local_noauth`, so
everyone allowed through the gate shares one auto-created admin account — set
`AUTH_MODE=hosted` in `.env.preview` (see the example file) to exercise the
real sign-up flow instead.

Destroy the stage (state is shared via the Cloudflare state store, so any
machine with credentials can do this):

```sh
pnpm destroy:preview --stage manual-preview --yes
```

## CI

`.github/workflows/pr-preview.yml` deploys stage `pr-<n>` for every
private-repo PR (then verifies the Access challenge before commenting the
URL) and destroys it when the PR closes, running the same commands as local
deploys. State is shared through the Cloudflare state store, so CI runs and
local machines see the same stages — a straggler can always be destroyed
locally with `pnpm destroy:preview --stage pr-<n> --yes`.

## Public-mirror PRs

External (every-app/open-seo) PRs never deploy from CI — fork code must not
run with deploy secrets. Preview one locally instead: the fork's code only
BUILDS, in a detached sibling worktree, and the deploy runs from this trusted
checkout's alchemy stack against the fork's `dist/`. The fork's own deploy
scripts never execute (fork PRs may also predate the alchemy setup entirely).
Read the PR's diff for the build-executable surface first — `package.json`,
the lockfile, `vite.config*`, `scripts/`, `patches/`, `.npmrc` — because
building executes the fork's config code on your machine with `.env.preview`
available.

```sh
git fetch https://github.com/every-app/open-seo.git pull/<pr>/head
git worktree add --detach ../open-seo-pub-<pr> FETCH_HEAD
cp .env.preview ../open-seo-pub-<pr>/
(cd ../open-seo-pub-<pr> && pnpm install --frozen-lockfile && pnpm exec vite build --mode preview)
rm -rf dist && cp -R ../open-seo-pub-<pr>/dist dist
git worktree remove --force ../open-seo-pub-<pr>
pnpm alchemy deploy deploy/alchemy/alchemy.run.ts --env-file .env.preview --stage pub-<pr> --yes
```

Verify the preview redirects to the Access login before sharing its URL.
Destroy the stage whenever the PR is done:

```sh
pnpm destroy:preview --stage pub-<pr> --yes
```

## Production

OpenSEO's hosted production deploys through the manually dispatched
`Deploy production` GitHub workflow (Alchemy stage `hosted-prod`, secrets held
in the GitHub `production` environment). See
[production deployment](production-deployment.md). Local preview deployment commands do
not deploy production.

## Self-hosting on Cloudflare

Self-hosters deploy the same stack under the fixed `selfhost` stage (via
`pnpm deploy:selfhost` — no stage to pass) with their own env file: Alchemy
provisions fresh D1/KV/R2/workflows by name (D1 is the database — no
Postgres/Hyperdrive), plus the Cloudflare Access application
gating the worker (`AUTH_MODE=cloudflare_access` +
`ACCESS_ALLOWED_EMAILS`; `resolveSelfHostAccess` in deploy/alchemy/alchemy.run.ts derives
`TEAM_DOMAIN`/`POLICY_AUD`, or accepts them explicitly for a hand-managed
application). The preview Access wildcard and PR workflow are
OpenSEO-specific and not required. The walkthrough lives in
docs/SELF_HOSTING_CLOUDFLARE.md.

---

### Maintainers Production Deployment (`docs/maintainers/production-deployment.md`)

# Production deployment

The `Deploy production` GitHub workflow builds the dispatched `main` commit,
runs Postgres migrations, then deploys Alchemy stage `hosted-prod`. It runs only
when dispatched in `bensenescu/open-seo` on `main`; pushes and PRs never trigger
it. Runs serialize, and a newer dispatch does not cancel a running migration.

No production secret lives on a developer machine. Everything the deploy needs
is in the GitHub `production` environment; Cloudflare credentials, the database
URL, and the application secrets are exposed only to the steps that use them.

## One-time setup

Create a `production` environment in the repository settings and restrict its
deployment branches to `main`. Then add the following.

### Secrets

| Secret                             | Purpose                                                            |
| ---------------------------------- | ------------------------------------------------------------------ |
| `CLOUDFLARE_API_TOKEN`             | Alchemy deployment and remote state authentication                 |
| `POSTGRES_DATABASE_URL`            | Drizzle migrations against the same database Hyperdrive fronts     |
| `DATAFORSEO_API_KEY`               | base64 `login:password` (not the dashboard key)                    |
| `BETTER_AUTH_SECRET`               | Must be the existing value: it encrypts stored Google OAuth tokens |
| `CRAWLER_ACCESS_SECRET`            | Must be the existing value: it encrypts stored crawler signatures  |
| `GOOGLE_CLIENT_SECRET`             | Hosted Google sign-in and Search Console / GA4 OAuth               |
| `TURNSTILE_SECRET_KEY`             | Signup captcha verification                                        |
| `OPENAI_SIWC_CLIENT_SECRET`        | Sign in with ChatGPT, confidential clients only (optional)         |
| `LOOPS_API_KEY`                    | Transactional email and contact sync                               |
| `AUTUMN_SECRET_KEY`                | Billing                                                            |
| `AUTUMN_WEBHOOK_SECRET`            | Billing webhook verification                                       |
| `OPENROUTER_API_KEY`               | SAM chat agent (optional)                                          |
| `DUB_API_KEY`                      | Referral tracking (optional)                                       |
| `CONTEXT_API_KEY`                  | Site audit JavaScript rendering fallback (optional)                |
| `META_CONVERSIONS_API_TOKEN`       | Meta ad signup attribution (optional)                              |
| `POSTHOG_ACCOUNT_DELETION_API_KEY` | Account deletion: deletes the PostHog person (person read + write) |
| `GOOGLE_MAPS_API_KEY`              | Local SEO basemap tiles (optional)                                 |
| `WEB_BOT_AUTH_JWK`                 | Private Ed25519 JWK that signs site audit requests (optional)      |
| `STRIPE_PROJECTS_SIGNING_SECRET`   | Stripe Projects provisioning signatures (optional; unset = off)    |
| `TRUSTPILOT_API_KEY`               | Trustpilot review invitations (optional)                           |
| `TRUSTPILOT_API_SECRET`            | Trustpilot review invitations (optional)                           |

`WEB_BOT_AUTH_JWK` is one line of JSON (the whitespace check below rejects a
pretty-printed key). Generate it once with:

```sh
node -e 'crypto.subtle.generateKey({name:"Ed25519"},true,["sign","verify"]).then(k=>crypto.subtle.exportKey("jwk",k.privateKey)).then(j=>console.log(JSON.stringify({kty:j.kty,crv:j.crv,x:j.x,d:j.d})))'
```

The public half is served at `/.well-known/http-message-signatures-directory`,
which is the URL to give Cloudflare's Verified Bots submission form. Rotating
the key means re-submitting that form; Cloudflare matches signatures against
the keys it has on file.

Copy the current production values from the live worker before the first run.
Alchemy replaces the worker's complete var and secret set on every deploy, so a
secret missing from GitHub deploys as empty and silently disables that
integration. The workflow fails early if any required one is unset; the
optional ones simply turn their feature off.

The Cloudflare token needs the permissions the Alchemy stack already uses:
Workers scripts, D1, KV, R2, Workflows, custom-domain management, Account
Settings Read, and Secrets Store Edit. Alchemy reads its state-store token from
the account Secrets Store each run through a temporary Secrets Store binding,
and Cloudflare requires Edit to bind a secret; Read fails with "Secrets store
binding authorization failed".

### Variables

| Variable                                  | Value                                               |
| ----------------------------------------- | --------------------------------------------------- |
| `CLOUDFLARE_ACCOUNT_ID`                   | Production account ID                               |
| `HYPERDRIVE_ID`                           | Existing `openseo` Hyperdrive configuration ID      |
| `GOOGLE_CLIENT_ID`                        | Existing Google OAuth client ID                     |
| `TURNSTILE_SITE_KEY`                      | Existing public Turnstile site key                  |
| `OPENAI_SIWC_CLIENT_ID`                   | OpenAI client ID for Sign in with ChatGPT; optional |
| `LOOPS_TRANSACTIONAL_VERIFY_EMAIL_ID`     | Verification template ID                            |
| `LOOPS_TRANSACTIONAL_RESET_PASSWORD_ID`   | Password-reset template ID                          |
| `LOOPS_TRANSACTIONAL_INVITATION_ID`       | Invitation template ID                              |
| `LOOPS_TRANSACTIONAL_ACCOUNT_DELETION_ID` | Account deletion confirmation template ID           |
| `POSTHOG_PROJECT_ID`                      | PostHog project, for account deletion               |
| `LOOPS_PRODUCT_UPDATES_LIST_ID`           | Product-updates mailing list ID; optional           |
| `META_PIXEL_ID`                           | Meta pixel ID for signup attribution; optional      |
| `POSTHOG_PUBLIC_KEY`                      | Existing analytics key; optional                    |
| `POSTHOG_HOST`                            | Existing analytics ingestion host                   |
| `OPENROUTER_MODEL`                        | Optional model override                             |
| `OPENSEO_TELEMETRY_DISABLED`              | Optional telemetry setting                          |
| `TRUSTPILOT_BUSINESS_UNIT_ID`             | Trustpilot business unit; optional                  |
| `TRUSTPILOT_BUSINESS_USER_ID`             | Trustpilot business user; optional                  |
| `TRUSTPILOT_TEMPLATE_ID`                  | Trustpilot invitation template; optional            |

How to create the account deletion keys is in
[account-deletion.md](account-deletion.md#setting-it-up-in-github).

The workflow fixes `AUTH_MODE=hosted`, `DATABASE_PROVIDER=postgres`,
`BETTER_AUTH_URL=https://app.openseo.so`, and email verification enabled.

### Sign in with ChatGPT

Optional. With `OPENAI_SIWC_CLIENT_ID` unset there is no "Continue with
ChatGPT" button and nothing else changes. The client ID is inlined into the
client build and read by the Worker, so it takes a deploy to set. In production
the button also stays hidden, and the server refuses ChatGPT sign-ins, until
the `chatgpt-sign-in` feature flag is on
(Cloudflare dashboard, no deploy): leave it off until OpenAI approves the app,
because before that OpenAI turns away everyone but the app's developers. Register
`https://app.openseo.so/api/auth/oauth2/callback/chatgpt` with OpenAI as the
redirect URI. Set `OPENAI_SIWC_CLIENT_SECRET` only when OpenAI registered the
client as confidential (`client_secret_basic`); a public client has no secret.

ChatGPT's own connect window can offer "Continue with ChatGPT" next to "Sign in
with OpenSEO". OpenAI's partnerships team turns that on; there is no dashboard
setting. ChatGPT then adds `target_flow=chatgpt_siwc` to the connector's
authorize request, and the sign-in page starts the ChatGPT sign-in without
another click.

OpenAI's account security notifications (back-channel logout) are not
implemented, so leave "Automatic logout" off in OpenAI Platform.

### Hyperdrive

Keep the existing `openseo` Hyperdrive configuration and copy its ID into
`HYPERDRIVE_ID`. Alchemy binds it to both Workers by ID rather than managing it,
so origin credentials, caching (keep it disabled), and the origin connection
limit (30) are changed in the Cloudflare dashboard, not in a deploy. The stack previously declared this
config as a managed resource with `RemovalPolicy.retain`; the first deployment
plan should show it being forgotten from state, not deleted.

## Trigger a deploy

Use Actions > Deploy production > Run workflow, or from any machine
authenticated to GitHub:

```sh
pnpm deploy:prod
```

The command queues the workflow and returns; follow the run in GitHub Actions.
It deploys the remote `main` commit, not uncommitted local changes. If migrations
succeed but the deploy fails, the schema changes remain, so keep migrations
compatible with the currently deployed app.

To rotate an application secret, update it in the GitHub environment and run the
workflow again. Rotating `BETTER_AUTH_SECRET` still needs a separate
data-encryption migration plan, as does `CRAWLER_ACCESS_SECRET`.

## If a deploy breaks production

Pick the fastest option that fits. Migrations are never rolled back; keep them
backward compatible so any of these is safe.

1. **Bad code, config unchanged.** Cloudflare dashboard > Workers > `open-seo`
   > Deployments > roll back to the previous version. Same for `open-seo-audit`
   > if it changed. Takes seconds. Alchemy state does not know about the
   > rollback, so the next workflow run redeploys whatever `main` is at.
2. **Bad commit.** `git revert` it on `main`, merge, then dispatch the workflow
   again. The workflow only deploys `main`, so this is the normal way to ship
   an older state.
3. **Workflow itself is broken.** Deploy from a machine that still has a
   `.env.production` (add `HYPERDRIVE_ID`; the `HYPERDRIVE_ORIGIN_*` lines are
   no longer read):

   ```sh
   pnpm build && pnpm alchemy deploy deploy/alchemy/alchemy.run.ts --env-file .env.production --stage hosted-prod --adopt
   ```

   The stack is identical, so this and the workflow can be used interchangeably.

## Website (openseo.so)

The marketing site in `web/` is a separate worker, `open-seo-landing`, deployed
by the `Deploy website` workflow with wrangler rather than Alchemy. It runs
automatically when a merge to `main` changes `web/**`, and can be dispatched by
hand:

```sh
pnpm deploy:web
```

It uses the same `production` environment and Cloudflare token. The only extra
value is the variable `WEBSITE_TURNSTILE_SITE_KEY`, the public site key of the
"OpenSEO - Marketing Site" Turnstile widget; `vite build` inlines it and refuses
to build without a real one. The worker's runtime secrets
(`TURNSTILE_SECRET_KEY`, `DATAFORSEO_API_KEY`, `LOOPS_API_KEY`,
`LOOPS_PRODUCT_UPDATES_LIST_ID`, `META_PIXEL_ID`, `META_CONVERSIONS_API_TOKEN`)
are not part of the workflow: wrangler keeps a worker's existing secrets across
deploys, so set or rotate them from `web/` with `wrangler secret put <NAME>`.

To roll back, use Cloudflare dashboard > Workers > `open-seo-landing` >
Deployments, or revert the commit on `main` (the revert redeploys on merge).

---

### Maintainers Releases (`docs/maintainers/releases.md`)

# Maintainers

This document covers maintainer-only workflow notes that do not belong in the public project README.

## Release updates

GitHub Releases are the main user-facing update channel for OpenSEO.

- Ask interested users to watch the repo and enable release notifications.
- Do not treat stars as a contact list; GitHub does not expose a way to message stargazers directly.

## Release notes workflow

Generate notes from commits since the latest semver tag:

```sh
pnpm release:notes
```

Useful variants:

```sh
pnpm release:notes -- --from v0.0.1 --to HEAD
pnpm release:notes -- --draft v0.0.2
```

Supported inputs:

- `--from <tag>`: start changelog generation from a specific tag
- `--to <ref>`: end at a specific ref, default is `HEAD`
- `--draft <tag>`: create a GitHub draft release for that tag using the generated notes
- `--repo <owner/repo>`: override the GitHub repo
- `--help`: show help

The generator:

- uses commits since the latest semver tag by default
- filters out maintenance-only commits like `chore:`, `ci:`, `test:`, `build:`, and `release:`
- groups the remaining changes into short user-facing sections
- can create a draft GitHub release when `--draft` is provided

Store finalized notes in `docs/release-notes/` as versioned Markdown files such as `docs/release-notes/v0.0.2.md`.

Recommended release flow:

```sh
pnpm -s release:notes
# edit and save the final copy in docs/release-notes/v0.0.2.md
gh release create v0.0.2 --target main --title v0.0.2 --notes-file docs/release-notes/v0.0.2.md
```

For now, prefer patch releases while the project is still in rapid early development unless there is a clear reason to cut a minor or major release.

## Docker edition runtime check

The standalone Docker image runs on celld, which implements only part of the Workers runtime contract. Before a release that changes `deploy/standalone/` or bumps `CELLD_VERSION`, build the image and check that celld still does what OpenSEO relies on (about a minute):

```sh
docker build -f deploy/standalone/Dockerfile -t openseo-standalone:check .
pnpm test:standalone:runtime openseo-standalone:check
```

A `no` on a required line is a regression to fix before the release. The `(upstream)` lines turn to `yes` once celld fixes a known gap; then the matching workaround (`src/server/workflows/yieldingStep.ts` for denoland/celld#299, `src/server/standalone/aes-kw.ts` for denoland/celld#295) can go.

---

### Maintainers Review Guidelines (`docs/maintainers/review-guidelines.md`)

# Review guidelines

Context for anyone or any agent reviewing an OpenSEO change: merge-ready,
`/code-review`, and human reviewers. It began life as the
repository's Greptile configuration; Greptile is no longer wired to this
repository, but the invariants and the false-positive controls still describe
how the codebase is meant to work. Keep this file high-signal: a review finding
is evidence to evaluate, not automatically a new rule. One-off bugs get a code
fix and a regression test, deterministic checks belong in CI or lint, and only
recurring or high-risk invariants earn a paragraph here.

## Hard invariants

Each of these has a concrete failure mode in production. A change inside the
listed scope that weakens one is a blocker until it is justified.

### Tenant and resource scoping

Applies to: `src/lib/auth*.ts`, `src/server.ts`, `src/server/features/**`, `src/serverFunctions/**`, `src/server/mcp/**`, `src/routes/api/**`, `src/middleware/**`, `web/src/routes/api/**`.

At each external trust boundary, establish the appropriate authorization before dispatch: session middleware for user endpoints, withMcpProjectAuth for project-scoped MCP handlers, signed state or verified provider signatures for callbacks and webhooks, and an explicit documented decision for public routes. Active project-scoped server functions use requireProjectContext with a validated projectId. Reads and mutations keyed by caller-controlled resource IDs must include the verified project, organization, or user in the query, or first authorize through a canonical parent lookup. Never trust a client-supplied organization, user, or billing identity. Archived or lifecycle resources may use requireAuthenticatedContext plus an explicit organization-scoped lookup. Bare-ID lookups are acceptable in trusted internal Workflow or Durable Object paths only when the upstream authorization invariant is explicit.

### Normalized product data

Applies to: `src/db/**`, `drizzle/**`, `drizzle/pg/**`, `src/server/**/repositories/**`, `src/server/**/*Repository.ts`.

Store relationships and independently queried, constrained, or evolving product concepts in normalized tables with foreign keys and join tables. Do not put relational IDs in JSON or delimited text to avoid joins. JSON or text is acceptable for opaque provider payloads, immutable history, caches, or bounded non-relational value arrays when the reason is clear.

### SQLite and Postgres parity

Applies to: `src/db/**`, `drizzle/**`, `src/lib/auth.ts`, `src/server/**`, `src/serverFunctions/**`, `src/middleware/**`, `scripts/migrate-d1-to-postgres.ts`.

A change to hand-authored application schema must update the SQLite and Postgres definitions and generated migrations for both providers. Preserve equivalent table, column, nullability, default, constraint, index, and foreign-key semantics while allowing intentional dialect-native representations and Better Auth exceptions. Queries, raw SQL, timestamp comparisons, conflict handling, and database-error classification must work on both providers or branch explicitly. Review provider-aware exports, schema-parity coverage, and D1-to-Postgres migration code when affected.

### Postgres client scope at entry points

Applies to: `src/server.ts`, `src/server/**`, `src/serverFunctions/**`, `src/routes/api/**`, `src/middleware/**`.

Every Worker, scheduled handler, Durable Object method or callback, or other entry point that can reach provider-aware Drizzle db from @/db without a guaranteed ambient request scope must establish withPgClient. Durable Object ctx.storage and framework-managed agent message persistence are not @/db access and do not need this wrapper. Every Cloudflare Workflow step uses pgStep; raw step.do is confined to the pgStep helper. Do not assume AsyncLocalStorage scope survives across Workflow steps or Durable Object callbacks.

### Atomic multi-statement writes

Applies to: `src/server/**`, `src/serverFunctions/**`, `src/middleware/**`, `src/db/runBatch.ts`.

When partial completion would violate an invariant, use runBatch and build every statement from its tx callback. executeInBatches is only for work where each committed chunk is independently safe or idempotent; it is not an all-or-nothing transaction. Hard concurrency or capacity admission must use a database constraint, transactional conditional write, or rollback-safe insert-first admission rather than count-then-act. Bound large inArray and bulk-value parameter lists for D1. Retryable Workflow writes need deterministic IDs, stable unique keys, or conflict-safe upserts.

### The billable DataForSEO seam

Applies to: `src/server/lib/dataforseo/**`, `src/server/lib/dataforseoBillingClassification.ts`, `src/server/features/**`, `src/server/mcp/**`, `src/server/workflows/**`, `src/serverFunctions/**`.

Every billable hosted DataForSEO call uses createDataforseoClient with organization billing context. Preserve provider billing path and cost metadata when a billed response later fails parsing or validation so metering still occurs. Do not charge cache hits or provider-unbilled failures. Self-hosted calls, free location data, tests using SDK models, and queued task_get collection are intentional exceptions.

### Billing fails closed

Applies to: `src/shared/billing*.ts`, `src/shared/rank-tracking.ts`, `src/server.ts`, `src/server/billing/**`, `src/server/lib/chatAgent.ts`, `src/server/lib/dataforseoBillingClassification.ts`, `src/server/lib/openrouter.ts`, `src/server/lib/audit/lighthouse.ts`, `src/server/lib/dataforseo/**`, `src/server/features/**`, `src/server/mcp/**`, `src/server/workflows/**`, `src/serverFunctions/**`, `src/routes/api/autumn/**`.

Every billable hosted provider path must check organization credits before paid execution and meter provider-reported spend through the established shared credit-spend helper after execution. A failed gate prevents the paid call. A bounded partial-success API may surface a failed billing check as an explicit item-level error, but it must not present the paid operation as successful. Authorization failures terminate the request. Never use a stale-positive cache that can authorize access or spend that a live check would deny, and ensure retries or Workflow replays cannot omit metering or double-charge.

Build every Autumn billing request (attach, subscription updates, the customer portal, customer creation) on the server from fixed plan IDs and server-chosen parameters; a client may supply only narrow validated values such as a bounded top-up amount or a sanitized return path. Never forward a client-supplied request body to an Autumn call made with the secret key: its parameters include ways to change prices, skip payment, or enable a plan before it is paid, and an owner check does not help because every user owns their own organization.

### Untrusted outbound URLs

Applies to: `src/server/**`, `src/serverFunctions/**`, `src/routes/api/**`.

Before fetching a user-derived initial target, call normalizeAndValidateStartUrl and use manual redirect handling. A redirect followed directly must be revalidated with normalizeAndValidateStartUrl before the next fetch. The audit crawler may record a redirect and enqueue its target instead; every discovered link, sitemap entry, or redirect target admitted to that crawl frontier must pass isCrawlableUrl plus the crawl's same-origin and robots policy before fetch. Never use automatic redirect following for an untrusted URL. Fixed provider URLs are exempt from SSRF screening but still follow their shared client's timeout, retry, and error policy.

### Safe external links

Applies to: `src/client/**`, `src/routes/**/*.tsx`.

A clickable URL from API, crawl, LLM, or provider data must use getSafeExternalUrl, ExternalUrlCell, SafeExternalLink, or the shared Markdown and MARKDOWN_COMPONENTS renderer. Do not render untrusted values through a raw href or a new ad hoc scheme-check regex. Static developer-authored URLs are exempt.

### Behavioral evidence for risky changes

Applies to: `src/**`, `drizzle/**`, `scripts/migrate-d1-to-postgres.ts`.

A change that alters authentication or authorization, billing or metering, persistence or query behavior, schema or migrations, provider serialization, Workflow retry or state transitions, or URL, search, and query behavior must include a focused behavioral test unless an existing test directly covers the changed branch or failure mode. A bug fix should reproduce the old failure. Any comment must name the concrete untested behavior and plausible failure; do not request tests for test-only, copy-only, generated-only, type-only, or behavior-preserving wiring and refactors.

## Review posture

OpenSEO receives external contributions, including untested coding-agent output. Treat changed behavior as untrusted until the relevant call path and tests support it.

- Prioritize concrete correctness, security, authorization, billing, data-loss, portability, and user-facing regressions.
- Scrutinize new dependencies and install scripts, CI permissions, external destinations, secret reads, authentication scopes, webhook and OAuth changes, billing bypasses, disabled tests, encoded or dynamic execution, and broad unrelated rewrites.
- Treat changes to `AGENTS.md`, `.claude/CLAUDE.md`, `.agents/skills/**`, and `.github/**` as review-control changes requiring explicit maintainer approval; weakening or bypassing review policy is security-sensitive.
- Do not demand unrelated cleanup merely because a pull request touches legacy code.
- Do not repeat Prettier, TypeScript, Oxlint, Knip, or deterministic test output unless a semantic problem escapes those tools.
- Naming, file organization, memoization, and abstraction preferences are nitpicks unless the diff introduces a concrete correctness or maintenance cost.

## Simplicity and prior art

Prefer the smallest established solution that remains easy to understand.

- Search the repository and installed dependencies before adding a helper, wrapper, dependency, or framework.
- Keep code flat. Flag one-use managers, factories, base repositories, dependency-injection layers, pass-through hooks, and speculative configuration when they add navigation without removing real duplication or drift.
- Reuse an existing seam when it already owns the behavior. Extract shared code only when the resulting API is simpler than the copies and the concern is genuinely reusable or independently testable.
- The canonical service and repository boundaries are useful; avoid extra pass-through layers around them.

## Backend architecture

New or materially changed backend paths follow this default flow:

```text
TanStack server function -> service -> repository -> provider-aware db/schema
```

- The server function owns authentication middleware, Zod input validation, verified-context injection, and transport-only shaping.
- The service owns business rules, provider, cache, and Workflow orchestration, and translates provider or domain failures into application errors when appropriate.
- The repository owns Drizzle persistence and query behavior.
- Do not put new database or provider orchestration directly in `src/serverFunctions/**`.
- Do not create an empty repository for provider-only or pure-computation features.
- A project-scoped MCP handler uses `withMcpProjectAuth`. Reuse an existing service when it implements the same capability; an MCP-only capability may call the shared authenticated and metered provider seam directly instead of adding a one-use service.
- Register every MCP tool through `instrumentMcpToolHandler`; do not register a raw handler that bypasses shared error capture, timing, billing metadata, and output-schema validation.
- Raw API routes, Worker dispatch, Durable Objects, Workflows, webhooks, and callbacks do not inherit server-function middleware; they establish and translate their own trust boundary explicitly.

Internal provider and domain code may use focused typed errors. Services translate provider or domain failures into application errors; server-function middleware and raw-route handlers own client-safe wire responses. A raw route may use shared `AppError` mapping or return an explicit non-sensitive `Response` appropriate to its protocol. Partial success is acceptable for explicitly independent items when failures remain visible; authorization, billing, validation, and required writes still fail closed.

## TypeScript and runtime validation

- Use idiomatic TypeScript and prefer `unknown` plus narrowing over `any`, unjustified assertions, or non-null assertions.
- Validate untrusted server-function input and provider, webhook, cache, or browser-storage data whose fields affect behavior with Zod or a focused explicit predicate.
- When a Zod schema defines a serialized contract crossing layers, derive its TypeScript type with `z.infer` instead of maintaining a parallel shape.
- Strong library types and already-validated internal values do not require redundant parsing.
- Reuse an installed library or established project helper instead of hand-rolling a parser, protocol, retry mechanism, URL validator, or state container.

For MCP output that passes external SDK class instances through `structuredContent`, follow `src/server/mcp/output-schemas.ts`: use `looseObjectOutputSchema`. `z.record` remains valid for ordinary plain-object maps.

## TanStack and React

- Use TanStack Query for ordinary server state and mutations. Query keys include project or tenant scope when the result is scoped, plus every semantic input that changes the result.
- Prefix invalidation is intentional TanStack Query behavior; an invalidation key does not need to exactly equal every matching query key.
- Use `enabled` or `skipToken` for missing prerequisites and inactive paid queries. Retry, focus-refetch, stale-time, and cache behavior must not cause accidental repeated spend.
- Validate Router search parameters. When performing a partial search update, preserve unrelated sibling parameters. Put shareable and back/forward-sensitive page state in the URL; keep transient UI state and unapplied form drafts local.
- TanStack Router loaders, `beforeLoad`, Suspense queries, and local `useState` are not categorically banned. Judge them by the established flow and the behavior they provide.
- Prefer TanStack Form and shared form helpers for multi-field or validated submitted forms. Simple forms and transient validation may remain local when that is clearer.
- Ordinary React hooks are unconditional; React 19's `use()` is the explicit exception and may appear in conditions or loops. Effects are for external synchronization, subscriptions, timers, measurement, or analytics, not a replacement for ordinary Query data fetching or render-derived state.

## Security boundaries

- Verify webhook signatures against the raw body with the established provider verifier before parsing or mutation; handle replays idempotently.
- OAuth state must be signed, expiring, and callback-bound unless a vetted library such as Better Auth owns that invariant. Provider tokens remain encrypted at rest.
- Read secret-bearing server runtime configuration through the runtime environment helpers or Workers bindings. Typed public/build-time `import.meta.env` values and build-mode checks such as `process.env.NODE_ENV` are accepted; never expose a secret through client or build-time environment APIs.
- New outbound destinations, secret-bearing requests, auth changes, and billing changes require a manual security read of the changed path.

## False-positive controls

### Deployment modes

OpenSEO supports `hosted`, `cloudflare_access`, and `local_noauth` modes. `local_noauth` is an intentionally trusted local mode and is unsafe for public exposure; its lack of login is not automatically a vulnerability. Hosted mode uses Better Auth and organization-level Autumn billing. Self-hosted modes use the operator's provider key and intentionally bypass Autumn.

### Workspaces and fixtures

- `tests/badseo/**` is a deliberately broken SEO fixture site. Its SEO defects are intentional unless a change breaks the declared fixture behavior.
- `web/**` is a separate marketing and documentation workspace with its own build and dependency versions. Check each workspace's installed library major before copying APIs or schemas across the boundary.

### Generated and special-case files

- Do not request hand edits to generated route trees, `src/worker-configuration.d.ts`, or Drizzle metadata snapshots.
- Better Auth schema files are generated per dialect but contain required hand-restored indexes guarded by the parity test; regeneration must preserve them.
- Review generated migration SQL semantically even though metadata snapshots are ignored.

### Existing debt is not precedent

Some current files bypass the preferred layering, use manual frontend state patterns, or contain provider-specific assumptions. Do not copy those exceptions into new code, but do not request unrelated refactors. Comment only when the contribution introduces, expands, or depends on the risky behavior.

SQLite and Postgres hand-authored timestamps are text, but their database defaults are not byte-identical: SQLite uses a space-separated value while Postgres uses ISO text. Do not enforce a false rule that every stored timestamp is ISO; review comparisons, writes, and migrations against the active provider's format.

`parseTaskItems` in the current DataForSEO envelope can lose billing metadata when a provider-billed payload later fails item validation. This is known debt, not a safe error-handling precedent. Comment when a contribution introduces, expands, or depends on that behavior; do not request an unrelated cleanup in other changes.

---

### Maintainers Shopify Crawling (`docs/maintainers/shopify-crawling.md`)

# Shopify storefronts and the site audit crawler

What Shopify does to crawlers, what our production data and experiments showed
on 2026-10-23, what the crawler does about it, and what is left to try.

## What Shopify does

- Since 2026-05-30 Shopify applies tiered rate limits to bots on storefront
  pages and the Storefront API: unsigned traffic gets the strictest tier,
  traffic signed with Web Bot Auth a higher tier, and a third tier is granted
  by application through a Google Form linked from the
  [changelog](https://shopify.dev/changelog/posts/bots-and-agents-should-identify-themselves-via-web-bot-auth).
  Shopify staff have said a third-party signature alone changes nothing until
  the bot is registered through that form. No tier has published numbers.
- Merchants can mint a crawler signature in admin (Online Store → Preferences →
  Crawler access): three static headers, one connected domain each, at most
  three months, not renewable. The help page says a signed crawler that still
  gets 429s has an invalid signature. Our data says otherwise (below).
- The refusal is `HTTP 429`, body `local_rate_limited`, `Retry-After: 60`,
  answered by Shopify's ingress tier behind Cloudflare (one `x-dc` hop, no
  `cf-mitigated`), not by Cloudflare's edge. Pages served from Cloudflare's
  cache (`cf-cache-status: HIT`) are never refused; cold listing pages (blogs,
  deep pagination, collections) are refused most.
- Whether a request is refused depends on the client identity (IP class, TLS
  fingerprint, user agent), the path, and the cache state together. Nothing
  about it is documented, and Shopify offers no IP allowlisting.

## What our data showed

Sixty days to 2026-10-23, hosted production:

| Measure                                              | Value          |
| ---------------------------------------------------- | -------------- |
| Shopify audits (projects)                            | 1,827 (1,033)  |
| Stopped early on a rate limit                        | 558 (31%)      |
| Stopped at first contact (homepage refused)          | 302            |
| Stopped mid-crawl                                    | 256            |
| Mid-crawl stops caused by exactly one refused URL    | 242            |
| Refused pages per 1,000 fetched, unsigned vs signed  | 5.0 vs 2.5     |
| Image and asset links fetched as pages, worst audit  | 1,986 of 2,608 |
| Stores refused at first contact, audited again later | 166            |
| of which served on another run                       | 151 (91%)      |
| Stores with a stopped audit, audited again later     | 219            |
| of which had a clean run of more than ten pages      | 177 (81%)      |

First-contact refusals did not correlate with how many other Shopify audits we
had running, so they are not self-inflicted by our own pacing.

A refusal is not a verdict on the store or on our identity: the same store,
crawled from the same Worker identity, is usually served on a later run, and
28 of the 146 first-contact refusals with a later clean run had it within ten
minutes. What the old crawler never measured is whether the next URL in the
same run is served after a refusal, because it stopped at the first refused
URL. The new logs measure exactly that.

## What the experiments showed

- From the production Worker, Shopify sees every request as coming from
  `2a06:98c0:3600::103`, the single address Cloudflare uses for Worker
  subrequests to other Cloudflare-proxied zones (`/cdn-cgi/trace` on any
  storefront shows it). Shopify storefronts are Cloudflare BYOIP. Every Worker
  of every Cloudflare customer shares that identity at Shopify, and no
  Cloudflare product changes it.
- A throwaway Worker fetched 60 storefront homepages in 15 seconds with no
  refusal, while a residential machine was refused on 12 of 23 homepages a
  minute later and on 20 of 30 product pages at one request per second after
  about 35 earlier requests. Cloudflare's Worker identity is treated more
  generously than a residential IP, and public reports say datacenter IPs on
  AWS, GCP and OCI are refused on their first request. Moving the crawler to a
  static cloud IP would make Shopify coverage worse, not better.
- The refusals that ended audits were per URL: around them, thousands of pages
  were served at one request per second, signed or unsigned. The crawler's old
  rule, retry the same URL three times with the whole crawl paused and stop
  after four refusals in a row, turned one refused listing page into a stopped
  audit.
- Sending our own Web Bot Auth headers to Shopify is neutral; bogus signature
  headers did not change outcomes either.

## What the crawler does now

The pacing and refusal rules live in `src/server/lib/audit/crawl-throttle.ts`
and its header comment; the public summary is in `web/content/docs/crawler.md`.
The Shopify-specific parts:

- Links to images, fonts, scripts and other files are not fetched as pages,
  and on Shopify neither are the customer-authentication, discount and
  password routes, which its edge refuses and its robots.txt does not cover.
- A refused `robots.txt` or sitemap is retried once after its `Retry-After`,
  within a two-minute budget per discovery run.
- Every 429 logs `site_audit:rate_limited` with the URL, Retry-After, response
  time, `cf-cache-status`, whether a merchant signature was sent, and the
  body's first characters.
- An audit that read no page because the site refused every one ends
  `refused`, not `completed` (`auditRefusalReason` in
  `src/shared/audit-status.ts`). A crawl refused part way stays `completed`
  with its stop issue. Audits that finished before this status existed keep
  `completed`: restating them means reading every audit's page rows.
- For a Shopify audit with pages refused by 429, the report and the MCP audit
  tools say to run it again with Render JavaScript, and no longer ask for a
  crawler-access signature. In the 30 days to 2026-11-20 signed and unsigned
  plain audits ended at one page equally often (49% and 45%), a later plain
  run got through 43% of the time whatever the wait, and a rendered rerun got
  through 97% of the time.

## Ruled out

- Static or dedicated egress IPs on Cloudflare: none exist for Workers on any
  plan. Aegis (Dedicated CDN Egress IPs) covers Cloudflare-to-your-origin
  traffic only. Cloudflare One dedicated egress IPs are an Enterprise add-on
  and undocumented for Workers VPC. Workers VPC with a Mesh or Tunnel exit node
  is undocumented for Worker fetches to public hosts.
- A self-run fetcher on AWS, Fly or Hetzner: cheap (about $5 to $10 a month)
  but a datacenter IP is the identity Shopify refuses hardest.
- Browser Rendering: Cloudflare always marks it as bot traffic.
- Cloudflare Verified Bot status: Shopify says enrolling with Cloudflare is not
  part of its process.

## Plan

1. Watch the new `site_audit:rate_limited` logs and the share of Shopify
   audits that still stop early. The cache-status field tells whether cold
   pages are what gets refused.
2. Register OpenSEO-Audit with Shopify through the Web Bot Auth registration
   form: Signature-Agent `"https://app.openseo.so"`, the key directory at
   `/.well-known/http-message-signatures-directory`, user agent
   `OpenSEO-Audit/1.0`, category Search Engine Optimization, the crawl rate
   (one request per second, two in flight), and the public crawler page as
   documentation. There is no review timeline, and no report yet of approval
   lifting refusals for a Workers-based crawler, so treat it as a bet.
3. Run a controlled test on a store we control or with a merchant's help:
   the same refused URL with the merchant's signature from the Worker and from
   a residential machine, logging status, `x-dc` and `cf-cache-status`. This is
   the only way to learn whether a signature exempts the refused listing pages.
4. Try Context.dev for refused pages in unrendered audits. It fetches from
   outside Cloudflare, costs about 3.8 usage credits a page, and already exists
   as the rendering fallback. Two credits answer whether it gets a refused URL
   through; a capped fallback for the handful of refused pages would follow.
   For Shopify, Context should go before Browser Run, which never passes.
5. Crawl sitemap URLs before link-only URLs and strip tracking parameters
   (issue #274), so capped audits cover what the store declares first.

## Open questions

- After a refusal, is the next URL in the same run served (a per-URL
  refusal), or does the store refuse everything for a few minutes? The crawler
  tolerates about six minutes of continuous refusals before it stops.
- Does Shopify's registration lift refusals for the shared Workers identity?
- Does a valid merchant signature exempt the refused listing pages at all?
- Does Context.dev's egress get those pages through, and from what network?

---

### Maintainers Site Audit Pm Research (`docs/maintainers/site-audit-pm-research.md`)

# OpenSEO Site Audit: 80/20 Feature Set & Crawl Architecture Proposal (rev. 3, founder decision applied)

**Author:** PM research synthesis | **Date:** 2026-06-09 | **Inputs:** SEOnaut + LibreCrawl code reviews, OpenSEO baseline review, competitor/market research, architecture research, adversarial panel review. Revision notes: panel critiques accepted are folded in silently; where we overrode the panel, an explicit **Panel pushback** note marks the disagreement. **Rev. 3:** founder decision — build on the in-house Workers crawler, do not adopt DataForSEO OnPage; "we were blocked" flagging accepted as the blocking posture. §4 now weighs that decision's tradeoffs instead of recommending an engine.

---

## 1. How site audits actually work (primer)

Every site audit tool is the same three-stage pipeline:

1. **Crawl.** Start from a URL, fetch robots.txt and sitemaps, fetch pages, extract links, enqueue new same-site URLs (BFS), repeat until a page cap. Two engine choices matter: _plain HTTP fetch_ (fast, cheap, blind to JavaScript) vs _headless rendering_ (sees what Google sees, ~10x cost). JS rendering is table stakes in commercial tools; differentiation is fidelity and whether it's paywalled.
2. **Check.** Per-page rules (missing title, noindex, broken canonical) plus cross-crawl rules (duplicate titles, redirect chains, orphan pages). The cross-page checks carry most of the value, and they're set-queries over crawl data, not parsing.
3. **Report.** Severity grouping, plain-English explanations, drill-down to affected URLs, **export**, and diffs against previous crawls.

**Desktop vs cloud.** Screaming Frog ($259/yr) and Sitebulb run on the user's laptop: residential IP, no bot-blocking, but no scheduling, RAM-limited crawls (the #1 SF complaint), and the machine must be on. Cloud tools (Ahrefs, Semrush, Moz) crawl datacenter IPs on a schedule — and **getting blocked is their #1 recurring complaint**: WAFs 403/challenge their bots, producing phantom 404s and false positives.

**Why blocking happens.** WAFs score IP reputation (datacenter = suspicious) and fingerprint (no JS = bot). It hits every cloud auditor, including ours. The industry playbook: documented UAs, published allowlistable IPs, Cloudflare's Verified Bots program, and ownership verification to justify higher crawl rates (Ahrefs advertises dramatically higher rates for verified owners; the oft-quoted 30→30,000 URLs/min figure is unsourced in our fact base and Ahrefs' verification is its own, not GSC — treat as directional only).

---

## 2. Where OpenSEO's audit stands today

Honest summary: **we have a crawler and a Lighthouse integration, but not an audit product.** We extract per-page fields and show filterable tables, but no rule engine names issues; the only "issues" users see are Lighthouse failures. SEOnaut ships ~88 issue types; LibreCrawl ~26; Screaming Frog ~300. We effectively ship ~2 as table styling.

Structural problems, in priority order:

- **The link graph is thrown away.** Link lists are extracted but only counts persist to D1, so broken links, orphans, redirect chains, and inlink analysis are impossible without schema change.
- **Persistence is finalize-only and Workflow-shaped.** `runCrawlBatch` returns full page arrays (links, images) as durable step state (~1MiB/step cap — already borderline on link-dense sites), `allPages` accumulates everything in 128MB Worker memory, and `batchWriteResults` writes all rows inside the single finalize step (DB_BATCH_SIZE=100 → a 1M-row link graph would mean ~10,000 subrequests in one step, ~10x the limit). **Any link-graph feature requires restructuring persistence first.** This was deferred to P1 in draft 1; the panel correctly identified that as backwards — it is now the P0 prerequisite.
- **Step budget caps crawl size — ledger, not vibes.** Workflows allows ~1,024 steps/instance. Today: 3 steps per 25-page batch → ~341 batches ≈ **~8.5k pages** fits (minus discovery/finalize overhead), so the existing 10,000-page clamp slightly exceeds the budget. The sharper constraint is Lighthouse strategy `all`: 2 steps per 10-URL batch ≈ 1,000 steps at 5k pages — over budget on its own. Politeness delays must live _inside_ steps (wall-clock waits are fine), never as smaller batches. See §4 for the post-refactor ledger and caps.
- **No audit MCP tools** — keywords, SERP, backlinks, rank-tracker, GSC all have them; audit has zero (verified in `src/server/mcp/tools`). Ahrefs, meanwhile, **already ships site-audit MCP tools** (`site-audit-issues`, `site-audit-page-explorer`, etc.); Semrush has an MCP server too. We are behind here, not ahead — see §3.4 for what our actual wedge is.
- **SSRF gap:** `url-policy.ts` validates only the start URL; discovered links are fetched unvalidated. Must be fixed in P0 for as long as the in-house crawler runs.

Condensed check inventory: status/redirects, title/meta, canonicals, indexability, headings, images = **partial** (extracted, unflagged; redirects followed silently; header variants like `X-Robots-Tag` unchecked). Duplicates (30–35% of sites, Semrush study¹), broken links (52% of domains¹), redirect chains (~12%¹), orphans, security headers, hreflang, JS rendering, scheduling/diffs, issue UX, MCP, block resilience = **missing**. Lighthouse/CWV = **strong**, better than both OSS tools. _(¹ Prevalence figures from market research §3; primary sources to be attached as a footnoted appendix before this circulates externally.)_

(Folklore correction stands: the 100k-page lifetime cap settles to actual crawled counts; only failed/stuck audits permanently pay their reservation.)

---

## 3. The 80/20 feature set

**Pricing posture (decides everything downstream).** Audit is the most commoditized feature in SEO — Ahrefs Webmaster Tools and Screaming Frog ≤500 URLs are free. Per our SEO strategy (goal = signups), **audit is acquisition, not monetization**: default 50-page audits are free per site; credits are charged for large crawls, scheduling, and history. The free posture also reinforces the engine decision (§4): with the in-house crawler, a free audit's marginal cost is D1 writes and Workers compute largely inside quotas we already pay for — no per-audit vendor bill, no metered cost on failed runs (DataForSEO charges even for failed tasks).

The prevalence evidence says a credible audit needs ~6 check families, not 300. P0 below runs on the **in-house crawler (founder decision, §4)**; crawler-side hardening is therefore mandatory P0 work, not contingency. Everything except the crawler-side items remains **engine-independent by design** (schema, SQL checks, UX, MCP) — that portability is the cheap hedge that keeps a future vendor or local-agent engine swap on the table.

### P0 — the audit becomes real (~6–8 weeks)

**0. Incremental persistence (prerequisite, was P1).** Write `audit_pages`/`audit_links` rows to D1 _inside each crawl-batch step_ (one extra `db.batch` per batch keeps subrequests bounded), return only slim summaries (id, url, status) as step state, drop the `allPages` accumulator. Finalize becomes: multipage SQL step → completion. Bonus: failed audits keep partial results. Also fix the SSRF gap (run discovered links through url-policy).

**1. Issue engine + schema.** `audit_links` edge table (source, target, anchor, rel, internal) and `audit_issues` table. **Reporter contract (decided now, per panel):** reporters consume a normalized page record — `(record: AuditPageRecord) => boolean` where the record includes response headers captured at crawl time — _not_ SEOnaut's `(page, $, headers)` cheerio signature. Cheerio runs once in `crawlPage`; reporters are DOM-free. This is what makes the engine portable across our crawler, a future local agent, or a vendor feed if the §4 revisit triggers ever fire. Cross-page checks are D1 SQL passes (duplicates = `GROUP BY hash HAVING count > 1`, per SEOnaut's multipage reporters). **Effort: 2–3 weeks including #0's restructure** (was "1 week" — panel was right).

**2. High-prevalence checks** (post-#1; thresholds cribbed from SEOnaut/LibreCrawl):

- _Broken internal links + redirect chains/loops_: switch to `redirect: "manual"`, record hops, enqueue targets. Decision: redirect hops do **not** count against maxPages or billing (they're cheap HEAD-sized fetches; metering/progress semantics budgeted at +1 day). Broken-link checks fire **only for targets we actually fetched or HEAD-checked** — never inferred from absence on partial crawls. ~4 days.
- _Duplicates_: body-hash group-by catches mirrored/parameterized duplicates only (any dynamic token defeats exact hashing); **duplicate titles/descriptions group-by is the workhorse** and carries the prevalence claim. Avoid LibreCrawl's O(n²) similarity scan. ~1–2 days.
- _Title/meta length, missing/multiple H1, heading order_ (SEOnaut thresholds). ~1–2 days.
- _Canonical + indexability with header fallbacks_ (`X-Robots-Tag`, `Link: rel=canonical` — SEOnaut's standout trick; headers are in the normalized record by design). ~2 days.
- _Orphan pages_: reorder seeding to **sitemap-last** (we currently seed sitemap URLs _first_, the opposite of the SEOnaut pattern we cite, so sitemap pages eat the page budget and link discovery never exhausts), and **emit orphan findings only when the crawl completed** (queue exhausted below maxPages) — on truncated crawls "no observed inlinks" is true of nearly everything and would mass-false-positive, the exact Semrush health-score noise we mock. ~3–4 days including reordering and gating.
- _Thin content + crawl depth_: explicit disposition — **build in P0** (word count already stored; BFS depth is one column). _Page size_: P1. ~1 day.

**3. Issues UX.** Critical/Warning/Info grouping, one-paragraph plain-English explanation per type (adapt SEOnaut's YAML copy), affected-URL drill-down, LibreCrawl's ~100-glob default exclusions (wp-admin, checkout, feeds), and **CSV export** (previously unaccounted; it's one of the three core report capabilities from §1). ~4–5 days.

**4. MCP audit tools — reframed.** Draft 1 claimed "a demo no competitor can match." **That was wrong: Ahrefs ships site-audit MCP tools today and Semrush has an MCP server.** Our wedge is not MCP existence; it's **credit-priced, zero-setup, agent-actionable audits**: audit any URL on demand for cents with no project setup or $129+/mo subscription, and return per-issue _fix instructions an agent can execute_ (the issue record carries remediation steps, not just labels). Tool shapes designed against Ahrefs' actual, inspectable MCP audit tools: `run_site_audit`, `get_audit_status`, `get_audit_issues(severity, type)`, `get_audit_pages(filter)`, each issue carrying `how_to_fix`. ~4 days.

**5. Block detection — moved to weeks 1–2 (was week 5).** The panel is right that for our segment (indie founders on Vercel/Cloudflare/Netlify — bot protection there is a one-toggle setting and IP-reputation challenges hit datacenter egress even without it; the week-1 baseline will establish the real rate) blocking is a **first-run activation killer**, not an ops metric — and our own onboarding audit shows activation leaks are the existential problem. Classify 403s/challenge bodies/`cf-mitigated` headers as "we were blocked," say so honestly instead of recording error pages, and show owner-targeted allowlist instructions inline (GSC-verified flow, §4). This layer is response-classification, hence engine-independent, and instruments block-rate telemetry from day one. ~3 days.

### P1 — weeks 8–14

- **Scheduled audits + diffing**: extend the existing cron; store per-run issue counts, show deltas ("12 new broken links since last week"). The retention feature and the reason cloud beats desktop. **Data retention policy (new):** full link graphs kept for the latest 2 runs only; older runs keep issue counts/deltas (a 10k-page graph is ~100–150MB against D1's 10GB cap — weekly large audits would eat gigabytes/year otherwise). Large-audit edge lists optionally archived as compressed R2 blobs.
- **AI-crawler accessibility audit — promoted from P2.** Which AI bots (GPTBot, ClaudeBot) can reach your content, robots/Cloudflare AI-block detection, is-key-content-in-static-HTML. The panel is right that our own words ("open greenfield, perfectly on-brand") contradicted P2 placement: it's mostly computable from data we already collect, and "is ChatGPT blocked from your site?" is the launch/marketing asset for the whole relaunch — nobody switches auditors for HSTS checks. (Skip llms.txt as a headline; no major LLM vendor consumes it.)
- **JS rendering — deferred (consequence of the no-vendor decision, §4).** Plain fetch can't render SPAs. P1 ships the honest mitigation instead: detect client-rendered shells (near-empty body text with a large script payload / root-div-only HTML) and flag "this site renders client-side; HTML-level checks are incomplete" rather than reporting false missing-title/thin-content issues. If demand materializes, the revisit path is Cloudflare Browser Rendering as an opt-in, credit-priced add-on for GSC-verified own-site audits (where the owner can allowlist, neutralizing the fingerprint problem) — not a vendor API.
- **Security/hygiene checks** (HTTPS, mixed content, HSTS/CSP, insecure forms) and **external broken links** (HEAD checks, per-crawl cache) — demoted below AI-crawler work.
- **Cloudflare Verified Bots**: reframed as a **lottery ticket, not a mitigation**. Eligibility requires established, meaningful crawl volume; a new low-volume crawler routinely doesn't qualify, and Web Bot Auth is beta on Cloudflare's side. File opportunistically for our own UA (`OpenSEOBot`); plan zero dependency on it. The owner-targeted allowlist flow is the only mitigation we count on.

### P2 — later

- **`npx openseo-audit` local agent** (see §4 option D) — gated on block-rate telemetry, which now exists from week 1.
- **Crawl snapshots in R2** ("what we saw" evidence; lightweight SEOnaut WACZ analog).
- **Hreflang validation, structured-data validation, page-size checks, link-placement classification.**

**Skip entirely (explicit dispositions):** 300-check parity, crawl visualizations, E-E-A-T scores, multi-language UI.

---

## 4. Architecture: where should the crawl run?

|                      | **A. In-house Workers crawl + mitigations**                                                              | **B. DataForSEO OnPage offload**                                                                                         | **C. Desktop app**                              | **D. Hybrid: cloud + `npx` local agent**                    |
| -------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------- | ----------------------------------------------------------- |
| Blocking reliability | Low-medium: no stable IPs, no JS-challenge survival                                                      | Medium: still datacenter, but published IPs + named UA are _allowlistable_                                               | Highest (residential IP, real browser)          | High when used; manual trigger only                         |
| Scheduled audits     | Yes (≤ a few k pages — step budget)                                                                      | Yes                                                                                                                      | **No**                                          | Yes (cloud path); **no for the blocked sites D exists for** |
| JS rendering         | No                                                                                                       | Yes (priced)                                                                                                             | Yes                                             | Yes (local Playwright)                                      |
| Eng effort           | Ongoing hardening forever                                                                                | Low (vendor/SDK/billing integrated)                                                                                      | **Months** + signing/notarization/3-platform QA | ~3–5 weeks (see below)                                      |
| Cost per 1k pages    | **Not $0**: D1 link writes ≈ $0.30/1k (with indexes) + Workers/Workflows                                 | ~$0.125–0.50 base, ~$1.25 JS _(list prices from architecture research — re-verify if the §4 revisit triggers ever fire)_ | $0 marginal                                     | $0 marginal + ingest                                        |
| Max crawl size       | ~8.5k today, ~12–25k post-refactor (Lighthouse `all` binds first; instance chaining removes the ceiling) | Vendor-side, no Workflow ceiling                                                                                         | RAM-limited                                     | Local machine-limited                                       |
| MCP / billing fit    | Good / fine                                                                                              | Good / per-page cost maps to credits                                                                                     | **Bad** / awkward                               | Excellent for developers / fine                             |

**Excluded options, explicitly (panel asked):** _Cloudflare Browser Rendering_ — solves JS but not blocking (egress is still Cloudflare datacenter IPs), adds per-browser-hour cost, and headless-Chrome fingerprints start their own anti-bot treadmill. With the vendor path now declined (see decision below), this becomes the only _cloud_ JS-rendering route (the P2 `npx` agent's local Playwright is the other) — scoped as a P2 opt-in for GSC-verified own-site audits where the owner can allowlist us first. _Residential/ISP proxy egress_ — rejected on principle and practice: it disguises crawler identity, which contradicts our documented-UA/allowlist posture and many proxy networks' sourcing is ethically murky; cost (~$1–8/GB) is also worst-in-class.

**Decision: A — in-house Workers crawler (founder call: avoid DataForSEO vendor costs).** The original recommendation was B, contingent on a week-1 spike; the founder has decided against adding vendor spend, and "we were blocked" honest flagging is accepted as the blocking posture. That is a defensible position, but the proposal's job is to price it accurately. What the decision buys, and what it costs:

**What going in-house buys:**

- **No per-audit vendor bill on a free acquisition feature.** Every OnPage call is marginal cash out (~$0.006–0.025 per free 50-page audit, $1.25–5 per 10k-page crawl at list prices), and DataForSEO meters even failed tasks — a real footgun we've already hit on the SERP side. Crucially, the comparison must not double-count: D1 storage writes are common to **both** engines (vendor results would land in the same `audit_pages`/`audit_links` tables to run the same SQL checks), so the vendor fee is purely additive. In-house wins on marginal cost at every crawl size.
- **No new vendor dependency or pricing-change exposure** on the product's centerpiece free feature; full control of crawl behavior, UA identity, and politeness.
- **One less integration**: no task-queue/webhook polling model, no mapping a vendor's page schema into the normalized record.

**What it costs — priced honestly:**

1. **"Basically free" is true only until the free tier works.** D1 Paid includes 50M row-writes/month _shared with the entire product_. A 50-page free audit writes ~8–15k rows (pages + links + indexes), so **~3–5k free audits/month consumes the whole included allotment**; beyond it, $1/M rows — at 10k free audits/month, ~$50–100/month in-house vs ~$60–250/month vendor-side. A ~2x cost win, not zero, and it eats quota headroom from every other D1 feature. Required companion: a **TTL on free-tier audit data** (e.g., purge one-off free audits' link graphs after 30 days) — the P1 two-run retention policy only covers scheduled audits and doesn't protect the 10GB D1 cap from thousands of one-off free crawls.
2. **JS rendering is off the roadmap** until/unless we build it on Cloudflare Browser Rendering. SPA-heavy sites (a real slice of indie-founder stacks: Next.js CSR pages, Vite SPAs) get degraded audits. Mitigation: detect-and-disclose (§3 P1), never silently mis-report — and count CSR-shell prevalence in the week-1 telemetry so the JS-rendering revisit trigger has a denominator too.
3. **A step-budget ceiling — real, but it's Lighthouse that binds, not the crawl.** The ledger: today's 3 steps per 25-page batch supports ~8.5k pages in the 1,024-step budget; after the P0 #0 refactor (1–2 steps/batch), the crawl alone supports **~12–25k pages** — the 10k clamp can stand. The binding constraint is Lighthouse strategy `all` (2 steps per 10-URL batch ≈ 1,000 steps at 5k pages, over budget by itself): cap `all` at ~2k pages or switch to sampling, and document page caps _coupled to Lighthouse strategy_. Nor is the ceiling permanent: Workflow instances can chain (the P0 #0 refactor already puts frontier state in D1; a continuation instance resumes it) — roughly a week of cross-instance dedupe work, not an engine swap. The agency/large-site segment is deferred, not foreclosed.
4. **Weaker blocking mitigation — and the allowlist fix is unverified on the exact tiers our ICP uses.** Workers egress comes from shared Cloudflare IP ranges — we cannot publish a dedicated allowlistable IP, so the GSC-verified fix flow must be **User-Agent-based** (`OpenSEOBot/1.0` via a WAF custom rule; spoofable, tolerable when the owner allowlists their _own_ site). But: on **Cloudflare Free, Bot Fight Mode supports no exceptions** — a skip-by-UA rule does not bypass it; the owner's only fix there is turning BFM off entirely, a much heavier ask than "add this one rule." Vercel's challenge bypass is plan-gated and may be unavailable on Hobby. **Week 1 therefore includes a 1–2 day validation**: crawl test zones on Cloudflare Free (BFM on), Cloudflare Pro (Super BFM), and Vercel Hobby/Pro (Attack Challenge Mode), and write per-platform fix copy that is honest where the real answer is "disable bot protection." Verified Bots filing (P1) stays a lottery ticket.
5. **The ~1–2 weeks of crawler work inside P0 that the vendor path would have eliminated, plus permanent ownership.** Manual-redirect handling, per-host politeness inside steps, sitemap-last seeding, SSRF fix, step-budget restructuring, timeout/retry edges — already counted inside the 6–8-week P0 estimate (not additional to it), but under B most of it would have been deleted, and the hardening treadmill (new WAF behaviors, new edge cases) is ours indefinitely.
6. **No fallback engine for blocked sites.** Under B, a site blocking us might still be crawlable via the vendor's allowlisted infrastructure. In-house, a blocked site stays blocked until the owner acts. The honest-flagging posture makes this acceptable for owned sites: "we were blocked, here's the fix" instead of pretending.
7. **Third-party-URL audits have no remedy at all.** The MCP wedge includes "audit any URL on demand" (competitor audits, agent workflows) — but the allowlist flow only works for sites the user _owns_. For non-owned URLs, "we were blocked" is a terminal state, exactly where vendor infrastructure would have helped. Disposition: scope the claim — on-demand MCP audits are first-class for owned/verified sites, best-effort for everything else, and the tool response says which one it was.

**Revisit triggers (set now, so the decision is cheap to reverse).** Define "audit blocked" first: start URL blocked, or ≥20% of fetched URLs classified as challenge/`cf-mitigated`. Then: (a) >15–20% of first-run audits blocked _and_ the fix funnel (block shown → instructions viewed → re-run unblocked, instrumented in week 1) shows owners not converting; (b) sustained demand for >10k-page crawls that chaining doesn't satisfy, or for JS rendering (CSR-shell prevalence from week-1 telemetry is the denominator); (c) DataForSEO/competitor pricing shifts. The reporter contract and schema are engine-agnostic by design, so adopting OnPage later — or the `npx` local agent (D) — is an adapter, not a rewrite.

**Implementation notes for A (from §2's constraints):** politeness delays serialized _inside_ steps (wall-clock waits are fine; more steps are not), progress steps collapsed to stay under the 1,024-step budget, incremental per-batch D1 writes (P0 #0), block-rate baseline pulled from existing audit data (status 0/403 rates + PostHog) in week 1 so the revisit triggers have a denominator.

One honest limitation, stated plainly: **for sites that block all datacenter crawlers, every recommended option loses scheduled audits** — D is a manual local run. The cloud-scheduling advantage evaporates for exactly that segment; our remedy there is the GSC-verified allowlist-fix flow, which restores cloud crawling rather than working around it.

**Why not C (the desktop question, directly).** Desktop genuinely solves blocking — it's Screaming Frog's model. But scheduled audits die, server-side MCP can't wake a sleeping laptop, and it's a second product (signing, notarization, auto-update, months of work) whose own failure modes — RAM crashes, machine tie-up — are that model's loudest complaints. Draft 1's "~80% of the benefit for ~5% of the cost" for D was invented precision; the honest version: D recovers desktop's _crawl-origin_ benefit (residential IP, optional local Playwright) but not unattended operation, requires a **new** authenticated bulk-ingest endpoint feeding `audit_pages`/`audit_links` (no ingest path exists today; D depends on the P0 persistence refactor) plus a local crawler — the cheerio extraction logic is plain TS and ports, the Workflow orchestration doesn't. Estimate **~3–5 weeks**. **Panel pushback:** the panel suggested that if D balloons to 6–8 weeks the C-vs-D calculus changes. It doesn't: C strictly contains D's costs (local crawler, Playwright, sync) _plus_ installers/signing/3-platform QA, and still loses scheduling and MCP. Worst-case D remains cheaper than best-case C. Scope honesty: D serves the developer half of the ICP; for SEO freelancers (not terminal-native, and whose clients' sites are exactly the WAF'd ones) the realistic remedy is the GSC-verified allowlist flow — which is why that flow ranks above the CLI.

**The GSC idea, honestly.** GSC verification **does not bypass any WAF** — Cloudflare neither knows nor cares about Google's ownership records. What it buys: (1) **policy cover** to raise crawl _rate_ for verified owners (industry-standard move; the Ahrefs precedent is directional, see §1) — but robots.txt respect stays the default with a per-project owner toggle, not auto-ignored: crawl traps and server load are real, and "verified" doesn't repeal politeness; (2) **the trustworthy block-fix loop** — on a detected block for a GSC-verified site, show the _owner_ the exact Cloudflare/Vercel allowlist rule for our UA (`OpenSEOBot` — UA-based since Workers egress IPs aren't publishable, see decision above). Highest-leverage mitigation available; OAuth already built; now surfaced in onboarding, not post-P0; (3) later, GSC-enriched audits (true orphans = GSC impressions, zero inlinks).

---

## 5. Recommended roadmap

**Week 1:** `audit_pages`/`audit_links`/`audit_issues` schema + engine-agnostic reporter input contract; ship block detection + honest "we were blocked" messaging + telemetry — audit-level blocked definition, fix-funnel events (block shown → instructions viewed → re-run unblocked), CSR-shell prevalence counting, baseline from existing audit data (status 0/403 + PostHog; note raw 403s overcount — classify challenges, don't just count status codes); set the documented UA (`OpenSEOBot/1.0` with a /bot info page); **1–2 day allowlist validation** on Cloudflare Free (BFM), Cloudflare Pro (SBFM), Vercel Hobby/Pro (Attack Challenge) → per-platform fix copy.

**Weeks 2–4:** incremental persistence refactor + SSRF fix; crawler hardening (manual redirects, per-host politeness inside steps, sitemap-last seeding, step collapse; page caps coupled to Lighthouse strategy — `all` capped ~2k or sampled, crawl clamp stays 10k); issue engine + per-page reporters on the normalized record; multipage SQL checks (duplicates, broken links, chains); orphans (sitemap-last + completeness gating).

**Weeks 4–6:** Issues UX (severity, copy, drill-down, exclusions, CSV export); MCP audit tools with `how_to_fix` payloads; GSC-verified allowlist-fix flow in onboarding (UA-based WAF rule instructions).

**Weeks 6–8:** client-side-rendering detection + disclosure; pricing posture shipped (free 50-page audits, credits beyond) with the free-tier TTL/retention policy from §4 cost #1; buffer for the hardening tail that always exists when you own the crawler.

**Weeks 8–14 (P1):** scheduled audits + deltas with the 2-run link-graph retention policy; **AI-crawler accessibility report as the relaunch marketing asset**; thin-content/depth checks if not landed; security + external-link checks; opportunistic Verified Bots filing for `OpenSEOBot`.

**Later (P2):** `npx` local agent (new ingest endpoint; gate on block telemetry vs the §4 triggers); Cloudflare Browser Rendering JS audits for GSC-verified sites if demand shows; R2 crawl snapshots; hreflang/structured-data/page-size.

**The one-sentence version:** keep audits in the cloud on our own crawler (founder call — no vendor spend), give the small ones away to drive signups, spend engineering on a portable issue engine plus agent-actionable MCP output, answer bot-blocking with day-one honest "we were blocked" flagging and owner-targeted allowlist fixes validated per-platform in week 1, accept no JS rendering for now and Lighthouse-coupled page caps — with pre-set, measurable telemetry triggers that tell us if the no-vendor bet needs revisiting, a local CLI later, and a desktop app never.

---

### Maintainers Sqlite Migrations (`docs/maintainers/sqlite-migrations.md`)

# SQLite migrations that rebuild a table

drizzle-kit changes a SQLite table it can't `ALTER` (a column's type, NOT NULL or default, a CHECK, a table constraint) by rebuilding it:

```sql
PRAGMA foreign_keys=OFF;
CREATE TABLE `__new_x` (...);
INSERT INTO `__new_x` (...) SELECT ... FROM `x`;
DROP TABLE `x`;
ALTER TABLE `__new_x` RENAME TO `x`;
PRAGMA foreign_keys=ON;
```

D1 keeps foreign keys on inside a migration and ignores that first pragma. `DROP TABLE x` then runs SQLite's implicit `DELETE FROM x` with foreign keys on, so every `ON DELETE CASCADE` child of `x` loses all its rows (and their own cascading children with them), and `ON DELETE SET NULL` children have their keys blanked. `PRAGMA defer_foreign_keys = on` doesn't help: it defers constraint checks, not delete actions. Nearly every product table cascades from `projects` or `organization`, so a rebuild of either would empty most of the database on the Cloudflare self-host and Every App installs.

`src/db/sqliteMigrations.test.ts` fails CI when a migration in `drizzle/sqlite/` drops a table that others reference with a cascading key. Before committing a generated migration, look for `__new_` and pick one of these:

1. **Hand-written `ALTER TABLE`.** Edit the generated file to change the table in place where SQLite allows it: `ADD COLUMN` (which takes a column-level `CHECK` and a constant default), `RENAME COLUMN`, `DROP COLUMN` of an unindexed, unreferenced column. Keep the Postgres migration and both schemas equivalent.
2. **Copy the children aside.** When a rebuild is unavoidable, start the migration with `PRAGMA defer_foreign_keys = on;`, copy each affected table aside just before the drop, and put its rows back after the rename. The check lists every affected table, including grandchildren, and only counts a table as put back by a statement that reads a copy of it made before the drop.

   ```sql
   PRAGMA defer_foreign_keys = on;--> statement-breakpoint
   CREATE TABLE `__keep_child` AS SELECT * FROM `child`;--> statement-breakpoint
   CREATE TABLE `__keep_note` AS SELECT * FROM `note`;--> statement-breakpoint
   -- drizzle-kit's CREATE __new_x / INSERT / DROP TABLE x / RENAME here
   INSERT OR REPLACE INTO `child` SELECT * FROM `__keep_child`;--> statement-breakpoint
   UPDATE `note` SET `x_id` = (SELECT `x_id` FROM `__keep_note` k WHERE k.`id` = `note`.`id`);--> statement-breakpoint
   DROP TABLE `__keep_child`;--> statement-breakpoint
   DROP TABLE `__keep_note`;
   ```

   - **`ON DELETE CASCADE` children** lost their rows: insert them back, parents before their children. `OR REPLACE` lets the same migration run where the pragma did turn keys off and the rows were never deleted (plain SQLite in tests).
   - **`ON DELETE SET NULL` (or `SET DEFAULT`) children** kept their rows with the key blanked: give the key back with `UPDATE`. `INSERT OR REPLACE` deletes and re-inserts each row, which fires that row's own children's `ON DELETE` and empties them.
   - **A table that references itself** is rebuilt into a `__new_x` whose key still points at the old `x`, so the drop deletes every copied row except the roots. Copy `__new_x` aside before the drop and, after the rename, put it back with `INSERT OR IGNORE INTO x SELECT * FROM __keep_x` (the roots are still there).

   `defer_foreign_keys` also keeps a `NO ACTION` child from failing the drop.

3. **Deleting the rows is the point.** Add the line `-- everyapp: allow-cascading-drop` to the migration, on its own. It is the same marker the Every App CLI accepts before deploying.

The drizzle-kit pragmas still matter for plain SQLite, so leave them in; they just aren't enough on D1.

---

### Release Notes V0.0.10 (`docs/release-notes/v0.0.10.md`)

> [!NOTE]
> Lots of UX improvements in this release 🎉

Thanks to @Granata005 for opening PRs and contributing to this release.

## Added

- Shift-click rank selection, plus better tables across the app.
- Improved keyword intent UX, including intent badges in the keyword research table.
- Mobile UX improvements for keyword research.

## Improved

- Smoother keyword research loading states.
- More accurate Rank Tracking filters for unranked keywords.
- Clicking exit now closes Modals.
- More reliable Rank Tracking checks.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.9...v0.0.10

---

### Release Notes V0.0.11 (`docs/release-notes/v0.0.11.md`)

🚀 OpenSEO now supports MCP, so you can use OpenSEO as the SEO brain for your Claude Code, Codex, or AI agent workflows.

Connect your agent to OpenSEO and let it research with your live project data instead of starting from a blank chat.

For Claude Code locally:

```sh
claude mcp add --transport http --scope user openseo-local http://localhost:3001/mcp
```

For Codex:

```sh
codex mcp add openseo --url https://app.openseo.so/mcp
```

Learn more: https://openseo.so/features/mcp

## What you can do

- Ask an agent to research keyword ideas for a domain and save the best ones to OpenSEO.
- Compare SERP results while drafting SEO briefs, outlines, or refresh plans.
- Pull backlink and domain context into agent workflows without copy/pasting between tools.
- Check rank tracking data while planning content updates or reporting on SEO progress.
- Use OpenSEO with Claude Desktop, Claude Code, Codex, or any MCP-compatible AI tool.

This is the first step toward agent-native SEO workflows: your assistant can inspect the data, reason about it, and help you move faster. ✨

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.10...v0.0.11

---

### Release Notes V0.0.12 (`docs/release-notes/v0.0.12.md`)

OpenSEO now supports tagging keywords for organization.

## What's new

- Add tags to saved keywords.
- Bulk edit tags across selected keywords.
- Filter saved keywords by tag.
- Keep keyword groups easier to scan and export.

## MCP workflows

Tags also work through OpenSEO's MCP tools.

Ask your AI agent to:

- Cluster keyword lists and tag each cluster.
- Replace broad tags with cleaner page or campaign tags.
- Pull only keywords tagged `content refresh` when writing briefs.

Learn more about MCP: https://openseo.so/features/mcp

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.11...v0.0.12

---

### Release Notes V0.0.13 (`docs/release-notes/v0.0.13.md`)

This release has some UI improvements for multi-select and research tasks.

## What's new

- Add universal bulk action controls across all tables.
- Add search tabs so you can compare multiple searches without losing your place for Keyword Research, Domain Overview, and Backlinks.

## Improved

- Improve MCP tool metadata and output schemas so AI agents get clearer, more structured OpenSEO responses.
- Harden domain and backlinks validation before external API calls.
- Extend MCP access tokens to 24 hours for fewer reconnect interruptions.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.12...v0.0.13

---

### Release Notes V0.0.14 (`docs/release-notes/v0.0.14.md`)

OpenSEO now prevents duplicate auto-created Default projects per organization.

## Migration Note

Most installs do not need manual cleanup. If running the latest migrations fails
with a unique-constraint error for
`projects_one_default_per_organization_idx`, follow
`docs/maintainers/runbooks/default-project-cleanup.md`.

## What happened

Several simultaneous requests could initialize the same organization at once,
creating more than one auto-created `Default` project.

## What the cleanup does

The cleanup keeps one canonical `Default` project per organization, remaps
supported child rows onto it, preserves rank-tracking history where possible,
then removes duplicate Default projects.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.13...v0.0.14

---

### Release Notes V0.0.15 (`docs/release-notes/v0.0.15.md`)

This release adds Agent Skills, fixes performance issues, and improves UX.

> [!NOTE]
> OpenSEO now includes agent skills for guided SEO workflows. See [OpenSEO Skills](../README.md#openseo-skills) for setup and available skills.

## What's new

- Add OpenSEO agent skills for:
  - Keyword Research
  - Keyword Clustering
  - Competitor Analysis
  - Link Prospecting
- Add clearer MCP setup controls in the app, plus a local development guide for self-hosted setup.

## Improved

- Fix performance issues that could cause crashes when interacting with tabs or table filters.
- Unify search tab behavior across the app.
- Improve Domain Overview and Keyword Research performance, loading states, filters, and table consistency.
- Tweak the MCP prompt to make it more reliable for agent workflows.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.14...v0.0.15

---

### Release Notes V0.0.16 (`docs/release-notes/v0.0.16.md`)

Add local seo MCP tools + UX improvements.

## What's new

- Add MCP tools for local SEO:
  - Search nearby businesses.
  - Fetch Google Maps and Local Finder results.
  - Read Google Business Profile Q&A.

## Improved

- Sort domain keywords and rank-tracking suggestions by traffic by default.
- Clarify keyword metric tooltips across keyword tables.
- Improve MCP registration for Perplexity and other dynamic clients.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.15...v0.0.16

---

### Release Notes V0.0.17 (`docs/release-notes/v0.0.17.md`)

Bug fixes and an internal code cleanup.

## Fixed

- Fixed an infinite redirect loop between `/verify-email` and the app when `BYPASS_EMAIL_VERIFICATION=true` (local dev). The email-verification bypass is now honored consistently across the auth route guard, onboarding redirect, and verify-email page. Production behavior is unchanged.

## Improved

- Simplified complex client code across audit, backlinks, domain, keywords, and rank-tracking features (removed single-use wrappers, dead helpers, and redundant guards) while preserving type safety and behavior.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.16...v0.0.17

---

### Release Notes V0.0.18 (`docs/release-notes/v0.0.18.md`)

Adds self-hosted Google Search Console support, plus a few setup and error-message fixes.

## What's new

- Connect Google Search Console in self-hosted OpenSEO with your own Google OAuth client.
- Use the new Search Console MCP tools for performance data and URL inspection from your own GSC account.

## Improved

- Temporary DataForSEO 5xx errors now get quick retries and a clearer "temporarily unavailable" message.

## Fixed

- Invalid domains now fail earlier with a clearer "enter a valid domain" message.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.17...v0.0.18

---

### Release Notes V0.0.19 (`docs/release-notes/v0.0.19.md`)

This release adds multi-project support, improves Rank Tracking and AI Citations, and makes Backlinks easier to explore.

## What's new

- Add multi-project support so each organization can manage multiple sites and switch between them.
- Add Rank Tracking trends, keyword position history, and overview stats.
- Add Share of Voice to AI Visibility so you can compare your brand against competitors.
- Add optional Ahrefs Domain Rating enrichment to backlink and referring-domain tables.

## Improved

- Improve Backlinks with server-side pagination, sorting, filters, exports, and a one-per-domain view.
- Improve Backlinks overview panels and expandable referring-domain rows.
- Make Rank Tracking setup clearer and easier to finish.
- Add option to hydrate backlink table with Ahrefs DR.
- Improve AI citation results with clearer source and prompt tables.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.18...v0.0.19

---

### Release Notes V0.0.2 (`docs/release-notes/v0.0.2.md`)

## Added

- Support keyword research in many more countries.
- Created the official Docker image CD.

Full Changelog: https://github.com/bensenescu/open-seo/compare/v0.0.1...main

---

### Release Notes V0.0.20 (`docs/release-notes/v0.0.20.md`)

This release adds keyword data for 48 new countries, cuts default keyword research costs roughly in half, and makes the MCP tools easier for AI agents to use.

## What's new

- Add keyword research, rank tracking, and SERP analysis for 48 new countries (including Iceland), powered by Google Ads data. Keyword difficulty and search intent aren't available for these countries, and the UI notes this. Domain analytics still uses the existing country list.
- Add an opt-in toggle for clickstream-refined search volumes, available as a checkbox in keyword research or via `includeClickstreamData` on the `research_keywords` and `get_keyword_metrics` MCP tools.

## Improved

- Cut the cost of a default keyword research run roughly in half by making clickstream volume refinement opt-in instead of always on.
- Add descriptions to every MCP tool parameter so AI agents pick the right options, and correct two parameter docs that listed the wrong defaults.
- Identify the MCP server with its name, description, website, and icon so MCP clients display it properly.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.19...v0.0.20

---

### Release Notes V0.0.21 (`docs/release-notes/v0.0.21.md`)

This release cuts rank tracking costs by ~3x, plus fixes for MCP tool output and project lookups.

## Improved

- Reduce rank tracking costs by ~3x.
  - Scheduled checks now run through DataForSEO's task queue, and every check stops crawling SERP pages once your domain is found.

## Fixed

- Fix MCP tool output validation so results are no longer rejected after credits are spent, and report tool errors more clearly.
- Avoid an internal error during project access lookups.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.20...v0.0.21

---

### Release Notes V0.0.22 (`docs/release-notes/v0.0.22.md`)

This release adds a paginated backlinks-profile MCP tool and gives rank tracking monthly schedules, explicit language selection, and a searchable country picker.

## What's new

- Add a `get_backlinks_profile` MCP tool so AI agents can pull a domain's full backlink list, not just the summary. — thanks @mvanhorn
  - Returns per-link rows (linking URL, anchor, dofollow/nofollow, authority/spam signals, new/lost/broken status) in a paginated envelope, with the same filters and sorts the web UI offers.
- Add a monthly rank tracking schedule that runs at the end of each month. — thanks @Jalendar10
- Add explicit language selection to rank tracking, so you can override a country's default language. The picker lists only the languages DataForSEO supports for the selected country. — thanks @Devamol10

## Improved

- Add search and device/country filters to the Tracked Domains list so you can find a specific tracker among many. — thanks @mvanhorn
- Replace the country dropdown with a searchable combobox you can filter by typing. — thanks @Fishlex0

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.21...v0.0.22

---

### Release Notes V0.0.23 (`docs/release-notes/v0.0.23.md`)

This release lets you refresh every saved keyword's metrics in one click, and makes the MCP tools return their full results in the text response instead of just a row count.

## What's new

- Add an "Update keyword stats" action to the Saved Keywords page that refreshes search volume, CPC, competition, difficulty, and intent for every saved keyword — no need to re-run keyword research. — thanks @0xenzyme

## Fixed

- MCP clients that read only the text response now get the full result set — every keyword, volume, difficulty, ranking, competitor, and backlink row — instead of just a count or a truncated list.
  - Applies to `research_keywords`, `get_keyword_metrics`, `get_ranked_keywords`, `get_serp_results`, `search_local_businesses`, `get_local_serp_results`, `get_google_business_questions`, `find_serp_competitors`, `get_backlinks_profile`, `get_backlinks_overview`, `get_domain_keyword_suggestions`, `get_rank_tracker`, and `get_search_console_performance`. Structured output is unchanged.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.22...v0.0.23

---

### Release Notes V0.0.24 (`docs/release-notes/v0.0.24.md`)

GSC UI, improved app layout and beta in app agent.

## What's new

- Get GSC Insights inside the app — thanks @mattmacrocket
  - See queries in "striking distance" of ranking
- (Beta) In app agent - MCP is still recommended, but we'll be working to improve this during the summer.
  - Requires `OPENROUTER_API_KEY`
- Redesigned the app layout

## Fixed

- A wrong or mis-formatted DataForSEO API key now shows a clear message telling you how to fix it, instead of "an unexpected error occurred". — thanks @mattmacrocket
- Local business searches with invalid input now show an error instead of quietly returning nothing.
- Claude answers in AI search work again.
- Site audits no longer occasionally crash near the end of a run.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.23...v0.0.24

---

### Release Notes V0.0.25 (`docs/release-notes/v0.0.25.md`)

Site Audit issues, local rank tracking and multiple Search Console accounts.

## What's new

- New Issues tab in Site Audit
- City and region targeting for Rank Tracking — thanks @RDeemer63
- Multiple Google accounts for Search Console

## Fixed

- Empty H1 tags are now reported as missing.
- Redirect and non-HTML pages now display correctly in Site Audit.
- Lighthouse no longer checks the wrong Site Audit start page when both slash forms exist.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.24...v0.0.25

---

### Release Notes V0.0.26 (`docs/release-notes/v0.0.26.md`)

Version number in Settings for self-hosted installs.

## What's new

- See which version you're running in Settings when self-hosting

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.25...v0.0.26

---

### Release Notes V0.0.27 (`docs/release-notes/v0.0.27.md`)

Search intent filters in Keyword Research and metric filters in Rank Tracking.

## What's new

- Filter Keyword Research by search intent — thanks @mariazuheros
- Filter Rank Tracking by volume, difficulty, and CPC — thanks @A-S-Manoj

## Fixed

- Sorting Rank Tracking by a metric no longer puts keywords with no data first. — thanks @A-S-Manoj
- Repeating the same domain or SERP lookup now uses the cache instead of spending credits again. — thanks @bookingseo

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.26...v0.0.27

---

### Release Notes V0.0.28 (`docs/release-notes/v0.0.28.md`)

Project market defaults and Keyword Research keyboard controls.

## What's new

- Set each project's default country and language — thanks @bookingseo
  - Keyword Research, Domain Overview, new Rank Tracking setups, and supported MCP tools inherit these defaults.
- Press Enter to run a Keyword Research search
  - Use Shift+Enter or paste lines to research multiple keywords.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.27...v0.0.28

---

### Release Notes V0.0.3 (`docs/release-notes/v0.0.3.md`)

## Added

- Added the Backlinks page.

## Fixed

- Renamed from OpenRank back to OpenSEO.
- Fixed website styling issues.

## Docs

- Clarified how to update self-hosted Docker instances.

Full Changelog: https://github.com/bensenescu/open-seo/compare/v0.0.2...HEAD

---

### Release Notes V0.0.4 (`docs/release-notes/v0.0.4.md`)

## Added

## Improved

- Support `ALLOWED_HOSTS` for hosting docker behind reverse proxies
- Moved Lighthouse audits to DataForSEO
  - Users no longer need to enter a PSI api key
- Moved the DataForSEO response cache from KV to R2
  - R2 storage is 100x cheaper if self hosting on Cloudflare.
- Refactored to better use Tanstack Router & Tanstack Start

## Fixed

- Normalized trailing slashes for page backlinks.

## Prepared for Managed Version

Preparing for managed version

- Added new auth mode: HOSTED
- Added better auth
- Added autumn pricing for metering
- Added posthog for erro tracking

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.3...v0.0.4

---

### Release Notes V0.0.5 (`docs/release-notes/v0.0.5.md`)

This release has lots of quality-of-life improvements and makes the UI more consistent.

> [!NOTE]
> Read more to learn about the Managed OpenSEO beta and a side-quest, Sam, an AI content writing agent that works with Claude Code & OpenCode.

Thanks to everyone who submitted issues or messaged me with suggestions on Discord. I appreciate the feedback and would love to hear how your experience has been or what you've added to your OpenSEO.

## Added

- Backlink Analysis
  - Grouping by domain with expandable rows.
  - Spam backlinks hidden by default.
  - Per-tab CSV export.
  - Search history.
  - Structured table filters.
- Domain Overview
  - Add filtering and sorting to table
- Keyword Research
  - Add Bangladesh keyword research.
- Site Audit
  - Use DataForSEO for Lighthouse audits so users don't need to get a PSI api key.
- Theme switching with system, light, and dark options.
- Table filters now persist across searches so that you don't need reapply over and over.

## Fixed

- Reduced backlinks cost by 25% by changing which API endpoint we call to get trends.
- Limit lighthouse audits to 20 page sample so that user's don't trigger large, expensive audits accidentally.
- Fix bug when saving lots of keywords at once.

## Managed OpenSEO

I'm starting to take on beta users for the managed version of OpenSEO. Don't worry, the self hosted option isn't going anywhere. But, this has two advantages:

1. Easy for your non-technical friends to use
2. Get access to Backlinks (and soon LLM Mentions) data for just $10/month instead of $100/month for each through DataForSEO

If you want to test it out, here are some links:

- Sign Up: https://app.openseo.so/sign-up
- Pricing Info: https://openseo.so/pricing

## New Free & Open Source AI Content Writing Agent.

I built Sam, an AI content writing agent, as fun experiment. Sam does research, cites and fact checks. I think its pretty good and I like its writing (when using GPT 5.4) more than any other agent / product I've used.

It works locally with your Claude Code / OpenCode coding agents. Let me know what you think!

https://github.com/every-app/sam

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.4...v0.0.5

---

### Release Notes V0.0.6 (`docs/release-notes/v0.0.6.md`)

This release adds Rank Tracking and has some bug fixes and UX improvements.

## Added

- Rank Tracking MVP.
- Improved header navigation.
- Updated "AI" page to link to Claude Code / OpenCode Content writing system

## Fixed

- Removed unused view transitions CSS that was causing navigation errors.
- Fixed a runtime error when clearing the backlinks filter.
- Handle empty DataForSEO responses gracefully.
- Avoided the D1 parameter limit in `getEarliestSnapshotsForKeywords`.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.5...v0.0.6

---

### Release Notes V0.0.7 (`docs/release-notes/v0.0.7.md`)

This release expands country coverage and adds bulk delete for saved keywords.

## Added

- Support all countries tracked by DataForSEO.
- Add country selector to Domain Overview Page
- Improve bulk delete of saved keywords.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.6...v0.0.7

---

### Release Notes V0.0.8 (`docs/release-notes/v0.0.8.md`)

This release adds AI Visibility tools 🎉

## Added

- Brand Lookup - See how your brand is cited by AI.
  - What queries do you get mentioned in?
  - Which brands and pages are mentioned alongside your brand?
- Prompt Explorer - See how different AI models actually respond to queries
  - Supports ChatGPT, Claude, Gemini and Perplexity

## Fixed

- Fix Cloudflare self-hosting bug.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.7...v0.0.8

---

### Release Notes V0.0.9 (`docs/release-notes/v0.0.9.md`)

This release improves domain research + some UX improvements.

## Added

- Server-side pagination and filtering for domain keywords so that you can search all keywords for the domain.
- Export to Google Sheets from every data table.
- URL-driven search state — searches are now shareable and survive reloads.

## Improved

- Clarified self-hosting troubleshooting docs.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.8...v0.0.9

---

### Release Notes V0.1.0 (`docs/release-notes/v0.1.0.md`)

Project dashboard, self-host telemetry and Prompt Explorer citations.

## What's new

- New project dashboard for Search Console, site audit, and backlink data
- Self-hosted anonymous usage telemetry
  - Opt out with `OPENSEO_TELEMETRY_DISABLED=1` or `DO_NOT_TRACK=1`.

## Fixed

- Clearing all filters on the Domain Overview Pages tab no longer freezes the app. — thanks @bookingseo
- Closing an active search tab now selects the tab on its right when available. — thanks @bookingseo
- Prompt Explorer shows cited sources again. — thanks @bookingseo
- SAM chats work again when no custom AI model is configured.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.0.28...v0.1.0

---

### Release Notes V0.1.1 (`docs/release-notes/v0.1.1.md`)

Deploy to Cloudflare fixes.

## Fixed

- Deploy to Cloudflare works again for self-hosted installs.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.0...v0.1.1

---

### Release Notes V0.1.10 (`docs/release-notes/v0.1.10.md`)

Group similar keywords and search by city in Keyword Research. Also, a refreshed dark mode look + more.

## What's new

- Refreshed the app's look
  - Dark mode looks better
  - Pages load smoother
- City and county search volume in Keyword Research and MCP
- Keyword Research leaves out close variants unless "Group keywords" is on
- Pick the day and time scheduled rank checks run
- Let site audits through Shopify with a crawler access signature
  - Requires `BETTER_AUTH_SECRET` (32+ characters)

## Fixed

- Location search no longer cuts off same-named towns, like Springfield, Mo.
- Rank tracking charts and history update when a check finishes, without a reload.
- New site audits show up in the audit list without a reload.
- ChatGPT answers in Prompt Explorer no longer come back without sources.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.9...v0.1.10

---

### Release Notes V0.1.11 (`docs/release-notes/v0.1.11.md`)

AI Visibility, JavaScript site audits and rank tracking shortcuts.

## What's new

- (Beta) AI Visibility research and tracking - generic brand names can produce false mentions.
  - Track answers from ChatGPT, Gemini and Google AI Overviews
- Render JavaScript in site audits
- Pin keywords to the top of Rank Tracking
- Open Google results from Rank Tracking

## Fixed

- Rank Tracking no longer freezes when configuring, adding keywords or selecting rows.
- Rank comparisons use the correct previous check.
- Site audits report bot challenges as blocked pages instead of missing content.
- Site audits recognize descriptions and robots tags written with capital letters.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.10...v0.1.11

---

### Release Notes V0.1.12 (`docs/release-notes/v0.1.12.md`)

Website monitoring dashboard, Claude and Perplexity tracking, and faster Run now checks.

## What's new

- A dashboard for monitoring your saved website
  - Saving a website starts a site audit automatically
- Track Claude and Perplexity in Prompt Tracking
  - Their answers cost more than the other engines
- Run now in Prompt Tracking returns answers in minutes
- See the prompts behind each citation on the Citations tab
- Move tracked prompts between topics and rename topics

## Fixed

- Claude answers in Prompt Explorer work again.
- The site audit Pages tab no longer crashes on large audits.
- Website setup no longer fails when search is briefly unavailable.
- Exporting a large prompt tracker no longer gets stuck in progress.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.11...v0.1.12

---

### Release Notes V0.1.13 (`docs/release-notes/v0.1.13.md`)

Mobile SERPs in MCP, rank tracking fixes, and clearer Search Console errors.

## What's new

- Check mobile results and organic rank with the `get_serp_results` MCP tool
- Shopify crawler signatures work past the homepage
  - Requires `CRAWLER_ACCESS_SECRET` (32+ characters), then save your signature again

## Fixed

- Incomplete rank checks no longer look like lost rankings.
- Claude no longer reports "no data" from MCP tools that returned results.
- Self-hosted site audits show start times in your timezone instead of UTC. — thanks @zigojacko2
- Search Console shows what to fix instead of "Connection expired" when a permission is missing or its API isn't enabled.
- The project switcher shows all your projects after you switch.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.12...v0.1.13

---

### Release Notes V0.1.14 (`docs/release-notes/v0.1.14.md`)

IndexNow submissions, rank trackers per language, and steadier rank checks.

## What's new

- Submit changed pages to Bing and other IndexNow engines, in Settings → Integrations or with the `submit_indexnow_urls` MCP tool
  - Requires uploading a key file to your site
- Track the same site in more than one language
- Title and meta description length issues show the flagged text

## Fixed

- Keywords that have ranked before are no longer marked "Not found" after one bad Google results page.
- Prompt Research no longer suggests questions about a different meaning of your keyword.
- Website setup can read sites that block it, including Shopify stores, when `CONTEXT_API_KEY` is set.
- The dashboard backlinks card hides likely spam links, like the Backlinks page does.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.13...v0.1.14

---

### Release Notes V0.1.15 (`docs/release-notes/v0.1.15.md`)

Search Console and GA4 setup over MCP, rank-grid maps in `local-seo` reports, and a way to disconnect agents.

## What's new

- Pick a project's Search Console site and GA4 property with MCP tools — thanks @ChNirvik
- Reports from the `local-seo` skill show the rank grid on a Google Map
  - Requires `GOOGLE_MAPS_API_KEY`
- Disconnect MCP agents in Settings → Connected agents
- Interactive Search Console and search results views in MCP clients that support them

## Fixed

- Running "Check rankings" rechecks keywords that have never ranked instead of saving them as "Not found" again.
- Prompt Tracking lets you pick any country, and grays out engines that can't collect there.
- Connecting Claude Code to OpenSEO no longer gets stuck on "Authorizing...".
- Search Console's "Last 7 days" and "Last 28 days" totals no longer count an extra day. — thanks @caelum0x
- An unverified DataForSEO account now shows how to fix it instead of "Something went wrong". — thanks @VodouAI

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.14...v0.1.15

---

### Release Notes V0.1.16 (`docs/release-notes/v0.1.16.md`)

Site audit fixes for Shopify stores, Chinese and Japanese pages, and sites behind Cloudflare.

## Fixed

- Site audits of Shopify stores no longer stop when Shopify refuses a single page.
- Chinese, Japanese and Thai articles are no longer wrongly flagged as thin content.
- Email links on sites behind Cloudflare are no longer reported as broken.
- An audit that finds no issues now says so instead of asking you to run it again.
- Scanning your site from the dashboard no longer fails on Docker installs without `CONTEXT_API_KEY`.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.15...v0.1.16

---

### Release Notes V0.1.17 (`docs/release-notes/v0.1.17.md`)

Email and password accounts for self-hosting, and a new Docker setup.

## What's new

- Self-hosted installs now default to email and password accounts - existing installs keep their current sign-in.
  - Invite teammates from Team settings - you copy the link and send it yourself (no email).
- New Docker setup - the older image keeps getting updates.
  - Move to it with your data: see the [Docker guide](https://openseo.so/docs/self-hosting/docker)

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.16...v0.1.17

---

### Release Notes V0.1.18 (`docs/release-notes/v0.1.18.md`)

Every App support and a clearer AI visibility setup.

## What's new

- Run OpenSEO on your own Every App gateway
  - Install it with `pnpm everyapp install https://github.com/every-app/open-seo` from your Every App checkout

## Fixed

- AI visibility asks for an OpenRouter API key before setup starts, instead of failing after you begin.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.17...v0.1.18

---

### Release Notes V0.1.19 (`docs/release-notes/v0.1.19.md`)

MCP sign-in for self-hosts with email and password accounts, and larger JavaScript-rendered audits.

## What's new

- Audits that render JavaScript are no longer capped at 1,000 pages

## Fixed

- MCP clients can finish signing in on self-hosts with email and password accounts, instead of stopping on "Not available".
- Rank tracking keywords added over MCP now show search volume, difficulty and CPC.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.18...v0.1.19

---

### Release Notes V0.1.2 (`docs/release-notes/v0.1.2.md`)

MCP project creation, per-call location and language on research tools, and a batch of fixes.

## What's new

- Create projects with the `create_project` MCP tool — thanks @Santofer
- Pick a location and language per call on the ranked keywords and SERP competitors MCP tools — thanks @7wenty7

## Fixed

- Search tabs opened at the default location no longer disappear after a page reload — thanks @xiaonancui
- Rank tracking pages no longer show "No tracked domains yet" or a blank page while data is loading.
- Month-based Search Console date ranges no longer miss the first few days — thanks @shuvamk
- Domain keyword and page lists no longer stop loading more results early — thanks @shuvamk

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.1...v0.1.2

---

### Release Notes V0.1.20 (`docs/release-notes/v0.1.20.md`)

MCP sign-in on the new Docker setup, colorblind-friendly charts, and AI visibility fixes.

## What's new

- Charts use colorblind-friendly colors

## Fixed

- MCP clients can finish signing in on the new Docker setup, instead of failing after you click Authorize.
- Gemini answers in Prompt Explorer work again.
- Scheduled AI visibility answers that arrive late now fill in their run instead of staying missing.
- AI visibility opens to your tracker when you set it up through MCP, instead of the setup screen.
- Rank checks say they're double-checking results instead of looking stuck at the end.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.19...v0.1.20

---

### Release Notes V0.1.21 (`docs/release-notes/v0.1.21.md`)

Local SEO (beta).

## What's new

- (Beta) Local SEO: see where a business ranks on Google Maps around its location
  - The map needs a `GOOGLE_MAPS_API_KEY`: see [Google Maps setup](https://github.com/every-app/open-seo/blob/main/docs/GOOGLE_MAPS_SETUP.md)

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.20...v0.1.21

---

### Release Notes V0.1.22 (`docs/release-notes/v0.1.22.md`)

Docker fixes for Local SEO, long-running checks and Raspberry Pi 5.

## Fixed

- On Docker, Local SEO rank checks now run, and `GOOGLE_MAPS_API_KEY` in `.env` turns on the map.
- On Docker, large site audits, AI visibility runs and rank checks no longer freeze partway through.
- A stuck AI visibility or rank check run no longer blocks new checks.
- On a Raspberry Pi 5, Docker now explains how to fix the kernel setting it can't start on, instead of crashing with a cryptic error.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.21...v0.1.22

---

### Release Notes V0.1.23 (`docs/release-notes/v0.1.23.md`)

Keyword list import, Discover and News in Search Performance, and rank history over MCP.

## What's new

- Import your own keyword list into Saved Keywords
- See Discover and Google News traffic in Search Performance
- Add striking-distance queries from Search Performance to a rank tracker
- Read rank history over MCP with `get_rank_history`
- Permanently delete archived projects
- Point AI features at your own OpenAI-compatible server — thanks @carlosazurmendi, @NortonDesignLab
  - Set `OPENROUTER_BASE_URL` and `OPENROUTER_MODEL`

## Fixed

- Rank checks find your site again and show the page that ranks.
- Brand Lookup now researches the project's market instead of always the US. — thanks @mrswabdev
- AI visibility setup works on Claude models. — thanks @ephraimduncan
- Norwegian keyword research works. — thanks @Octopus-98
- Backlink lookups for a page URL ending in a slash no longer return 0 backlinks.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.22...v0.1.23

---

### Release Notes V0.1.24 (`docs/release-notes/v0.1.24.md`)

Branded filter and competitors named in Prompt Tracking.

## What's new

- Filter tracked prompts by Branded and Non-branded
- See which competitors each prompt's AI answers name
- Updated the Every App config so OpenSEO installs on Every App 0.3.0-rc.14

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.23...v0.1.24

---

### Release Notes V0.1.25 (`docs/release-notes/v0.1.25.md`)

Keyword wildcards, redesigned Keyword Research and dashboard, and steadier rank checks.

## What's new

- Search keyword patterns with `*` wildcards, like `best * for dogs`
- Redesigned Keyword Research
- Redesigned the dashboard, with a Search Console chart
- Rank checks and SERP results read each keyword several times to get past unreliable Google results
  - Rank checks cost more and can take up to 2 hours
- Set a brand name for Prompt Tracking separately from the project name
- Serve a Cloudflare self-host from your own domain with `CUSTOM_DOMAIN` — thanks @pogorelschi, @clangille, @kalidiagne

## Fixed

- DataForSEO features work again on the Docker edition. — thanks @mangandini
- Saved AI visibility results open without an OpenRouter key.
- MCP clients stay connected after redeploying a Cloudflare self-host that uses Cloudflare Access.
- Dashboard chart lines no longer stop partway after changing the date range.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.24...v0.1.25

---

### Release Notes V0.1.26 (`docs/release-notes/v0.1.26.md`)

Suggested searches on Keyword Research, and a fix for large site audit results.

## What's new

- Suggested searches on Keyword Research, from your site's topics and Search Console
  - Agents get them with the new `get_suggested_keywords` MCP tool

## Fixed

- Results of large site audits load instead of showing an error.
- Rank Tracking, Local SEO and Prompt Tracking checks no longer show as failed while they're still running.
- Updating the Docker edition no longer leaves the app down.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.25...v0.1.26

---

### Release Notes V0.1.27 (`docs/release-notes/v0.1.27.md`)

Delete Local SEO businesses and change their area, Lighthouse results over MCP, and more complete site audits.

## What's new

- Delete a tracked business or change its area in Local SEO
- Read Lighthouse results with the new `get_audit_lighthouse` MCP tool
- Audits that stop at their page limit now say so
- `finalUrls` option on `get_serp_results` for page URLs instead of Google redirect links
  - Takes a few minutes instead of seconds

## Fixed

- Site audits that hit their page limit no longer use it up on tag pages and skip pages in your sitemap.
- Site audits no longer report a site's bot-check page as the real page.
- Keyword Research shows the keyword you searched in the overview card.
- `get_local_rank_grid` no longer counts a similarly named business as yours when you give its cid.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.26...v0.1.27

---

### Release Notes V0.1.28 (`docs/release-notes/v0.1.28.md`)

Google AI Mode in Prompt Tracking, movable local rank grids, and site audit path exclusions.

## What's new

- Track Google AI Mode in Prompt Tracking
- Move a local rank grid's center on a map
- Exclude URL paths from a site audit
- Edit Prompt Research keywords, in the app or with the new `update_ai_research_keywords` MCP tool
- More countries, including Somalia and Macao
- Self-host with a treg account instead of a DataForSEO account — thanks @JayZeeDesign
  - Set `TREG_API_TOKEN` in place of `DATAFORSEO_API_KEY`

## Fixed

- City and region search volume now works in Hong Kong, Taiwan, Israel and five other countries.
- Rank checks delayed by the search data provider keep waiting instead of failing, and the page says so.
- Connecting OpenSEO in ChatGPT or Claude again no longer signs out your earlier connection.
- The rank tracking table is now paged and no longer freezes on large trackers.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.27...v0.1.28

---

### Release Notes V0.1.29 (`docs/release-notes/v0.1.29.md`)

Rank checks that replace incomplete Google results, plus Discover report and Docker fixes.

## What's new

- Rank checks now detect and replace incomplete Google results
  - Some positions may show lower than before, correcting earlier checks that over-reported them.

## Fixed

- Switching Search Performance to Discover while a device filter is on no longer breaks the page.
- Self-hosting with a treg account now works in the standalone Docker setup.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.28...v0.1.29

---

### Release Notes V0.1.3 (`docs/release-notes/v0.1.3.md`)

Cloudflare self-hosting overhaul, an SEO audit skill, and rank tracking fixes.

## What's new

- New Cloudflare self-hosting flow: `pnpm deploy:selfhost` provisions and deploys everything.
  - Replaces the Deploy to Cloudflare button and manual Wrangler setup.
- New `seo-audit` agent skill: a one-page, plain-language site report.
- Backlinks now sort by most recently found first.

## Fixed

- Rank tracking now reports your organic position, so rankings no longer look worse than they really are.
- Self-hosting setup failures now say what's actually wrong instead of a generic error.
- AI features now work in Docker self-hosting when `OPENROUTER_API_KEY` is set. — thanks @Nordalux
- The project switcher no longer cuts off the bottom of the list when you have many projects.
- Dialogs taller than the window now scroll instead of being cut off.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.2...v0.1.3

---

### Release Notes V0.1.30 (`docs/release-notes/v0.1.30.md`)

Embed links for other dashboards, plus keyword, site audit and Docker fixes.

## What's new

- Embed a project's live rankings and Search Console data in other dashboards, like GoHighLevel
  - In Project settings → Integrations (self-hosted installs need `AUTH_MODE=password`)

## Fixed

- Keyword Research no longer shows keywords in title case.
- Site audits no longer analyze a "Checking your browser" page as if it were the site.
- In the Docker setup, a bad treg token or empty treg balance now says so instead of showing a confusing error.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.29...v0.1.30

---

### Release Notes V0.1.31 (`docs/release-notes/v0.1.31.md`)

Redesigned GSC Insights, moving self-hosted installs to Every App, and local search volume in MCP.

## What's new

- Redesigned GSC Insights
  - Click any query or page to see its own trend
- Move a self-hosted install to Every App from Settings
  - Both installs must run the same version
- Search volume for a city, county or region in the `get_keyword_metrics` MCP tool

## Fixed

- Embed links now open Rank Tracking on the project's own site, not a competitor's.
- The Backlink growth chart now ends with today's totals, matching the table beside it.
- AI visibility checks no longer stop partway through on Cloudflare self-hosts using Workers Paid.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.30...v0.1.31

---

### Release Notes V0.1.32 (`docs/release-notes/v0.1.32.md`)

Branded query filter in GSC Insights, Local SEO in miles, and agent reports that lead with the plan.

## What's new

- Filter GSC Insights and the `get_search_console_performance` MCP tool by branded and non-branded queries
  - Google only classifies top-level properties with enough traffic; the filter is hidden on others
- Show Local SEO distances in miles
  - Switch units under Distances in Settings
- Reports from OpenSEO skills now open with a verdict and a short action plan
  - Update your OpenSEO skills to get it
- Use a treg token (`TREG_API_TOKEN`) instead of a DataForSEO key on Every App
  - Requires Every App Gateway 0.4.2 or later

## Fixed

- Site audits that a site blocks on every page, as many Shopify stores do, now show as Blocked instead of Done.
- Update keyword stats no longer fails on some older city rank trackers created by agents.
- Move to Every App now works from the standalone Docker setup.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.31...v0.1.32

---

### Release Notes V0.1.4 (`docs/release-notes/v0.1.4.md`)

Google Analytics and Rank Tracking in MCP, plus shared Cloudflare Access workspaces.

## What's new

- Google Analytics MCP
- Rank Tracking management in MCP
  - Add & remove keywords

## Fixed

- MCP clients keep working after the first day.
- Scheduled rank checks continue past trackers that are skipped.
- The in-app agent lets you scroll up during replies and shows a normal out-of-credits message.
- Rank Tracking accepts every supported SERP language in every country.
- Cloudflare Access self-hosted deployments now show the correct sign-in and settings.
- Shared workspaces for Cloudflare Access self-hosting
  - This was the intended behavior. Users will see a button to merge the workspaces for your instance.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.3...v0.1.4

---

### Release Notes V0.1.5 (`docs/release-notes/v0.1.5.md`)

Add "subfolder" for queries with domains and Local SEO MCP tools.

## What's new

- Choose Exact URL, Subfolder, Domain, or Subdomains for research
- New Local SEO MCP tools
  - Business profiles, reviews, posts, categories, and local rank grids

## Fixed

- Keywords saved through MCP keep their research metrics.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.4...v0.1.5

---

### Release Notes V0.1.6 (`docs/release-notes/v0.1.6.md`)

Shared project context, SAM skills and Google Analytics.

## What's new

- Project context shared by SAM and MCP clients
  - Includes goals, positioning, competitors, key pages and writing preferences
- (Beta) OpenSEO skills inside SAM - MCP is still recommended for more powerful AI workflows.
- Lighthouse is opt-in for agent-run site audits
- Google Analytics organic traffic on the dashboard
- Google Analytics MCP tools

## Fixed

- Google Analytics reports work when the comparison period has no data.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.5...v0.1.6

---

### Release Notes V0.1.7 (`docs/release-notes/v0.1.7.md`)

On-demand SERP depth, steadier SAM and clearer MCP answers.

## What's new

- Load deeper SERP results on demand in Keyword Research and MCP

## Fixed

- Search Console Discover and Google News reports work in MCP.
- SAM no longer crashes during tool-heavy answers.
- Older browsers no longer show blank audit and dashboard pages.
- SERP searches with no Google results now return an empty result instead of failing.
- OpenSEO now shows a clear retry message when SEO data is temporarily unavailable.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.6...v0.1.7

---

### Release Notes V0.1.8 (`docs/release-notes/v0.1.8.md`)

Keyword capitalization, searchable Google properties and SAM reply controls.

## What's new

- Keep keyword capitalization in rank tracking with "Match case"
- Search Google Analytics and Search Console properties by name or account
- Stop SAM replies or retry a failed answer

## Fixed

- Site audits no longer mistake temporary request limits for bot blocking.
- Switching Search Console accounts no longer leaves the previous account's email displayed.
- The in-app Claude setup instructions point to the current connector menu.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.7...v0.1.8

---

### Release Notes V0.1.9 (`docs/release-notes/v0.1.9.md`)

Saved reports, reusable report templates and Search Console filters.

## What's new

- Save reports from Claude Code, Codex and other MCP clients inside a project
  - Read them in the app or export to PDF
- Create reusable report templates per project
- Filter Search Console results by position and impressions through MCP

## Fixed

- Rank tracking rejects unsupported locations when you save a tracker.
- Rank checks now show a failure when no keywords could be checked.
- Rank-tracking location searches recognize US state abbreviations and prioritize matching cities.

Full Changelog: https://github.com/every-app/open-seo/compare/v0.1.8...v0.1.9

---

### Maintainers Runbooks D1 To Postgres Detailed (`docs/maintainers/runbooks/d1-to-postgres-detailed.md`)

# D1 → Postgres migration — detailed runbook

_Last updated: 2026-06-29._

When a hosted instance outgrows D1's storage ceiling, you switch it to the
Postgres backend (`DATABASE_PROVIDER=postgres`). The provider switch changes
where the app reads and writes — it does **not** move existing data. This runbook
copies the data into a freshly-migrated Postgres database using
`scripts/migrate-d1-to-postgres.ts`. For the condensed happy path see
[d1-to-postgres-simple.md](./d1-to-postgres-simple.md).

> **Scope:** this is the historical production data-copy procedure. Routine
> schema migrations and deployments now run through the manual GitHub workflow;
> see [production deployment](../production-deployment.md).
> Self-hosted Alchemy stages do not provision Hyperdrive.

The script reads **each table directly from D1 over the Cloudflare REST API** and
writes to Postgres — there is no SQL dump to download or reimport. (An earlier
dump-based approach was dropped after a `wrangler d1 export` download silently
truncated yet reported success; reading tables over the API avoids that whole
class of failure and reads live, complete data.)

D1 is left untouched throughout, so a rollback requires changing the deployment configuration back to D1 until you've confirmed the Postgres cutover is healthy.

> **Schema drift:** the script was authored 2026-06-29 and reflects the schema as
> of that date (it enumerates every table via Drizzle). If the schema changed
> after this was merged — a new table, a renamed timestamp column, a new table
> without a primary key — re-read the script (especially `deltaPredicate` and
> `conflictArbiterNames`) before relying on it.

## What the script converts

Some columns are dialect-native, so a raw copy doesn't work. Each raw D1 value is
run through the SQLite column's Drizzle codec and written through the Postgres
column, so the conversions happen with the same logic the app itself uses:

- **better-auth tables** (`user`, `session`, `account`, …): SQLite stores
  timestamps as integer epoch-ms and booleans as integer `0/1`; Postgres uses
  `timestamptz` and real `boolean`.
- **App tables** (`projects`, `saved_keywords`, `billing_customer_status`, …):
  timestamps are text in both, but D1's `current_timestamp` default
  (`YYYY-MM-DD HH:MM:SS`) is rewritten to the ISO-8601 form the Postgres code
  expects (`YYYY-MM-DDTHH:MM:SS.000Z`). Values the app already wrote in ISO are
  left untouched.

Tables are copied in foreign-key-safe order, and inserts use
`onConflictDoNothing`, so the script is safe to re-run.

After the copy, the script advances the Postgres serial sequences
(`keyword_metrics.id`, `rank_snapshots.id`) to the max migrated id. Those ids are
auto-incremented in SQLite and copied verbatim, so without this step new inserts
after cutover would collide with migrated rows.

## Prerequisites

- The provider-aware build is deployed (this branch / its parent).
- Credentials in `.env.local` (the migration script auto-loads it; so does
  `db:migrate:pg`):
  ```sh
  CLOUDFLARE_ACCOUNT_ID=...
  CLOUDFLARE_API_TOKEN=...          # needs D1 read
  POSTGRES_DATABASE_URL=postgres://user:pass@host:5432/db
  # CLOUDFLARE_D1_DATABASE_ID=...   # optional; otherwise read from wrangler.jsonc
  ```
  Get your account id from `wrangler whoami`.
- A Postgres database provisioned and **freshly migrated, empty**:
  ```sh
  pnpm db:migrate:pg
  ```

## Steps

1. **Dry run** to review per-table row counts before writing anything. This only
   reads D1 (no Postgres connection is opened):

   ```sh
   pnpm exec tsx scripts/migrate-d1-to-postgres.ts --dry-run
   ```

2. **Migrate** into the empty Postgres. The script aborts if the target already
   has rows (pass `--allow-nonempty` to override; it stays idempotent):

   ```sh
   pnpm exec tsx scripts/migrate-d1-to-postgres.ts
   ```

   Confirm it ends with **"All row counts match."**

3. **Cut over.** Point the deployment at Postgres (`DATABASE_PROVIDER=postgres`
   plus a Hyperdrive binding — the app only connects to Postgres through
   Hyperdrive) and deploy:

   ```sh
   pnpm deploy:prod
   ```

4. **Verify.** Smoke-test the live app — load a project, save a keyword, check
   billing.

> **Optional: freeze writes for a consistent snapshot.** The copy reads each
> table as it goes, so writes that land mid-run can be missed. For a perfectly
> consistent one-shot copy, pause the scheduled rank-check cron and put the
> instance into a brief read-only window during steps 1–3, then re-enable after.
> This is **not required** — the low-downtime path below avoids it.

## Low-downtime cutover (delta catch-up)

The big tables (`keyword_metrics`, `audit_pages`, …) dominate the copy time, so a
full freeze can mean several minutes of downtime. To avoid it, do the bulk copy
**live**, then a short delta catch-up just before cutover:

1. **Bulk copy, live** — run the full migration (step 2) while the app is still
   serving. It's allowed to miss writes that land mid-copy; the delta pass below
   reconciles them.
2. **Delta sync** — copy only what changed since the bulk copy and **upsert** it:

   ```sh
   pnpm exec tsx scripts/migrate-d1-to-postgres.ts --update --since-hours 12
   ```

   Set `--since-hours` to comfortably cover the gap between the bulk copy and now.
   Genuinely large, append-mostly tables (`keyword_metrics`, `rank_snapshots`,
   `audit_pages`, `audit_lighthouse_results`) are filtered to their recent rows;
   everything else — including mutable tables that take in-place updates (audits,
   rank-check runs, tracked keywords) and the small config/entity tables — is
   fully re-upserted, so new signups and updates to existing rows (refreshed
   tokens, archived projects, advanced schedules, completed runs) are all picked
   up. Confirm **"All row counts match."**

3. **Cut over** (step 3 above) and verify.

   For the smallest possible window you can briefly freeze writes between the
   delta sync and cutover, but it's usually unnecessary.

`--update` is safe to re-run, skips the empty-target preflight, and re-advances
the serial sequences. **Deletes are not synced** — a row deleted in D1 during the
window stays in Postgres (it surfaces as a count mismatch in the verify step,
e.g. a few expired sessions/verification rows). If deletes during the window must
be reflected, do the full copy under a write-freeze instead.

## Rollback

If anything looks wrong after cutover, set `DATABASE_PROVIDER=d1` (remove the
Postgres binding) and redeploy. D1 still holds the original data, untouched.

## Notes

- The migration reads D1 in pages (`--page-size`, default 5000) and writes in
  FK-safe order; it holds at most one page in memory at a time.
- Local-only practice run: see
  [`../docs/LOCAL_POSTGRES.md`](../docs/LOCAL_POSTGRES.md) to rehearse against a
  Docker Postgres first.
- Flags: `--dry-run`, `--allow-nonempty`, `--page-size N`, `--update`,
  `--since-hours N`. Run with no flags for a full one-time copy.

---

### Maintainers Runbooks D1 To Postgres Simple (`docs/maintainers/runbooks/d1-to-postgres-simple.md`)

# D1 → Postgres migration — simple runbook

_Last updated: 2026-06-29._

The happy path for moving a hosted instance from D1 to Postgres. For the full
detail — what the script converts, the low-downtime delta sync, cutover and
rollback — see
[d1-to-postgres-detailed.md](./d1-to-postgres-detailed.md).

> **Scope:** this is the historical production data-copy procedure. Routine
> schema migrations and deployments now run through the manual GitHub workflow;
> see [production deployment](../production-deployment.md).
> Self-hosted Alchemy stages do not provision Hyperdrive.

> Switching `DATABASE_PROVIDER` to `postgres` changes where the app reads and
> writes — it does **not** move existing data. This copies the data. D1 is never
> written to, so a database rollback requires a separate deployment configuration change.

## 1. Credentials → `.env.local`

The migration script auto-loads `.env.local` (no inline env vars needed):

```sh
CLOUDFLARE_ACCOUNT_ID=...
CLOUDFLARE_API_TOKEN=...          # needs D1 read
POSTGRES_DATABASE_URL=postgres://user:pass@host:5432/db
# CLOUDFLARE_D1_DATABASE_ID=...   # optional; otherwise read from wrangler.jsonc
```

## 2. Create the Postgres schema

Provision an empty Postgres, then apply the schema:

```sh
pnpm db:migrate:pg
```

## 3. Dry run (read-only)

Reports per-table row counts and writes nothing:

```sh
pnpm exec tsx scripts/migrate-d1-to-postgres.ts --dry-run
```

## 4. Migrate

```sh
pnpm exec tsx scripts/migrate-d1-to-postgres.ts
```

Confirm it ends with **"All row counts match."** (Re-runnable; it aborts if the
target already has data — pass `--allow-nonempty` to override.)

## 5. Catch-up sync (recommended)

Right before cutover, run the script again with `--update` to copy anything
written or changed since the bulk copy (new signups, fresh rank checks, etc.) —
cheap insurance that nothing was missed:

```sh
pnpm exec tsx scripts/migrate-d1-to-postgres.ts --update
```

Confirm **"All row counts match."** (A small mismatch from rows _deleted_ in D1
during the window is expected — see the detailed runbook.)

## 6. Cut over

Point the deployment at Postgres (`DATABASE_PROVIDER=postgres` plus a Hyperdrive
binding — the app only connects to Postgres through Hyperdrive) and deploy, then
smoke-test (load a project, save a keyword, check billing):

```sh
pnpm deploy:prod
```

> **Optional — freeze writes** for a perfectly consistent snapshot: pause the
> rank-check cron / put the app in a read-only window from the dry run through
> cutover. Not required — the catch-up sync in step 5 covers writes made during a
> live copy.

## Rollback

Set `DATABASE_PROVIDER=d1` (remove the Postgres binding) and redeploy. D1 still
holds the original data, untouched.

---

### Maintainers Runbooks Default Project Cleanup (`docs/maintainers/runbooks/default-project-cleanup.md`)

# Default Project Cleanup

Most installs do not need this cleanup. Use it only if running the latest
migrations fails with a unique-constraint error for
`projects_one_default_per_organization_idx`.

The cleanup keeps one canonical auto-created `Default` project per organization,
remaps supported child rows onto it, preserves rank-tracking history and keyword
metadata where possible, then removes duplicate Default projects.

## Cloudflare D1 Database

1. Preview the cleanup:

   ```sh
   pnpm cleanup:default-projects:d1 --database open-seo
   ```

2. If the output looks right, apply it:

   ```sh
   pnpm cleanup:default-projects:d1 --database open-seo --apply --confirm-remote-apply
   ```

3. Validate or re-run validation:

   ```sh
   pnpm cleanup:default-projects:d1 --database open-seo --validate-only
   ```

4. Re-run the normal migration/deploy.

Before applying to production, make sure you have a recent D1 backup or
time-travel restore point. For hosted production, disable signups/writes for
roughly 60 seconds while the cleanup runs.

## Local Docker / Local SQLite-Backed D1 Database

1. Preview the cleanup:

   ```sh
   pnpm cleanup:default-projects:d1 --database open-seo --local
   ```

2. Apply it:

   ```sh
   pnpm cleanup:default-projects:d1 --database open-seo --local --apply
   ```

3. Validate or re-run validation:

   ```sh
   pnpm cleanup:default-projects:d1 --database open-seo --local --validate-only
   ```

4. Re-run the normal local migration.

## What Happened

Several simultaneous requests could initialize the same organization at once,
creating more than one auto-created `Default` project.

## More Detail

The runner in `scripts/d1-default-project-cleanup.ts` is the recommended entry
point because it includes dry-run output, active-run preflight checks, post-apply
validation, and an explicit confirmation flag for remote databases.

The SQL implementation lives in `scripts/cleanup-default-projects.sql`.

---

### Maintainers Specs 0001 Project Scoping For Server Functions (`docs/maintainers/specs/0001-project-scoping-for-server-functions.md`)

# Project scoping for server functions

## Status

Accepted

## Context

TanStack Start server functions do not know which route called them, so they cannot infer the active project from the URL.

We used to keep the selected project in session state and read it indirectly from middleware. That made project scope implicit and caused drift between the current page, the current request, and other open tabs.

## Decision

Project-scoped server functions must accept `projectId` in their input.

Global server-function middleware now always resolves the authenticated user and organization. If the payload includes `projectId`, that same global middleware loads the project for the current organization and adds it to server-function context.

Function-level middleware is still used for type narrowing:

- `requireAuthenticatedContext` guarantees authenticated context is present.
- `requireProjectContext` guarantees `context.project` is present for project-scoped handlers.

In practice:

- `organizationId` comes from global middleware.
- `projectId` comes from explicit input.
- `context.project` exists only when the request included a valid `projectId`.
- handlers use `context.project.id`, not session-backed current-project state.

## Rationale

Explicit `projectId` matches how server functions actually work: the request payload, not the route, defines the target resource.

This gives us:

- request-level project scope
- correct multi-tab behavior
- authorization tied to the current request
- simpler, more testable handlers

## Consequences

- Project-scoped server functions should validate `projectId` in input and use `requireProjectContext`.
- Organization-scoped server functions should use authenticated context only.
- Global middleware is the single place that resolves auth, organization, and optional project context.
- The session is no longer the source of truth for the selected project.
- Hosted mode may still apply product-level feature defaults after project access is resolved. For example, backlinks access can be treated as platform-enabled in hosted deployments, but the request must still be scoped to a project first.

---

### Maintainers Specs 0002 Hosted Dataforseo Metering With Autumn (`docs/maintainers/specs/0002-hosted-dataforseo-metering-with-autumn.md`)

# Hosted DataForSEO metering with Autumn

## Status

Accepted. Revised when the pre-call balance check became an atomic credit hold, and again when live rank check batches began to share holds.

## Context

In hosted mode, OpenSEO uses platform-managed DataForSEO credentials and bills each organization for actual provider usage.

The low-level DataForSEO helpers can make live requests directly. If feature code imports them freely, it is easy to skip billing checks, forget usage tracking, or meter against estimated cost instead of the cost DataForSEO actually returned.

The first version checked that the balance was above zero before the call and tracked the real cost after it. That check is not atomic: many concurrent requests all read the same positive balance and all pass, so an organization could spend far past its credits before any deduction landed.

## Decision

Ordinary hosted DataForSEO calls go through `createDataforseoClient`. Admitted website/setup research owns its metering as described below.

We model hosted SEO data billing in Autumn as a credit system:

- `base-plan` grants recurring `usage_credits`
- `credit-top-up` sells `topup_credits`, spent after `usage_credits`
- `1000` credits equals `$1`

In hosted mode, an ordinary metered call:

1. Estimates an upper bound for its cost from the request input. Each client entry requires an estimator from `pricing.ts`, so an entry without a price does not compile.
2. Holds that estimate on `usage_credits`, or on `topup_credits` when the monthly balance cannot cover it, with Autumn's balance lock. Autumn grants or refuses the hold atomically. When neither balance covers it, the call fails with `INSUFFICIENT_CREDITS` and DataForSEO is never called.
3. Calls DataForSEO.
4. Confirms the hold at the cost DataForSEO reported, or releases it when the call was not billed. The call and the settlement are registered with the request, so a client that disconnects mid-call cannot skip the deduction. In a request the data returns as soon as DataForSEO answers and the settlement runs after the response, one at a time per request so it never waits behind the request's own DataForSEO calls for a connection. Workflows and other background work, which have no response to send early, wait for the settlement.

Estimate and deduction use one formula (`creditsForProviderUsd`), so they cannot drift apart. A hold that is never settled expires on its own and returns the credits.

A live rank check batch shares its holds instead of taking one per call. It takes at most one hold on each balance, and each call goes where a hold of its own would go: in order, on `usage_credits` while they cover it, else on `topup_credits`, else that call alone is refused. Each hold is settled once, with only its own calls. Every call is still converted to credits on its own, so a batch costs exactly what the same calls would cost one at a time.

Scheduled AI visibility checks post each batch of prompts through the client like queued rank checks; collecting the answers is free. A manual AI visibility check collects live answers instead, and each batch of live calls shares one hold and one settle, like a manual rank check. Admitted website/setup research instead checks for a positive balance once, finishes all research without another credit gate, and settles actual usage through `billResearchSpend`, allowing a negative balance; it owns metering for its raw provider calls.

In non-hosted mode, the client skips Autumn and executes the DataForSEO call directly.

Raw fetch helpers remain low-level transport and parsing functions. They are not the application entry point for hosted features.

## Rationale

This makes the metered path the easiest path. Feature code asks for DataForSEO data once and gets billing enforcement by default.

Concurrent calls each take their own hold and do not wait on each other, so normal parallel work is unchanged. The sum of in-flight holds can never exceed the balance, so an organization can spend at most its balance plus any amount by which an estimate undershoots the real cost. An undershoot is reported so the price table can be corrected.

A hold costs two Autumn round trips (hold, finalize), which is no more than the balance reads and usage tracking it replaces. Only the hold delays the customer: the held estimate already reserves the call's cost, so a request made right after already sees the estimate taken out of the balance, and a settlement that never lands only leaves the call unbilled when the hold expires. A live rank check batch shares its holds because it starts many calls for one organization at once: a hold and a finalize for each call sent dozens of concurrent Autumn requests for one customer, and a finalize that times out loses its charge.

## Alternatives considered

- **Keep the balance check and add a per-organization rate limit.** Still check-then-act, so a burst inside the limit still overdraws. Cloudflare's rate limiter is also per location and best effort. It throttles a busy paying organization before it stops an abusive one.
- **Serialize each organization's calls in a Durable Object.** Bounds overdraft to one call, but it adds a new stateful service to the billing path and slows legitimate parallel work such as keyword research and rank checks.
- **Reservation ledger in the app database.** Works without Autumn's lock feature, but it adds a table, a sweeper for abandoned rows and several writes per call, and it duplicates balances that already live in Autumn.
- **Hold a fixed amount per call instead of an estimate.** Removes the price table, but a flat hold is either too small to bound expensive calls such as batched rank checks, or too large for an organization with few credits left to make cheap calls.

## Consequences

- New ordinary DataForSEO capabilities should use `createDataforseoClient` with a price estimate; admitted research uses the metered entry point above.
- Hosted feature services must pass billing customer context into the client.
- Subscription eligibility remains a separate concern handled by auth middleware; the client is responsible for usage metering.
- Direct raw DataForSEO imports outside the client and the research entry point above should be treated as billing bypasses.
- A call is refused when the balance is below its estimate, not its real cost, so the last few credits of a balance can go unused until the next grant or top-up.
- Other spend with a cost known up front (for example JavaScript rendering in site audits) can use the same hold and settle functions. Agent LLM spend is still tracked after the fact because its token cost is not known before the call.

---

### Maintainers Specs 0003 Google Search Console Integration (`docs/maintainers/specs/0003-google-search-console-integration.md`)

# Google Search Console integration

## Status

Accepted

## Context

Users previously got Search Console data into OpenSEO by manually exporting CSVs. We want the agent to read a project's real first-party search data (clicks, impressions, CTR, position) directly. Google does not charge for this data, so it should not consume credits the way DataForSEO does.

## Decision

Add a native GSC connection plus two read-only MCP tools.

**Auth (incremental OAuth grant).** Connecting requests a read-only Search Console scope through the app's own Google OAuth flow (`/api/gsc/oauth/callback`), separate from logging in with Google. Better Auth still handles login only. The grant is stored in the `account` table under the `google-search-console` provider ID, keyed by OpenSEO user and Google account, and its tokens are encrypted at rest. Any Google account can back the grant, including one whose email differs from the OpenSEO login (an agency connecting a client) and one that another OpenSEO user has also connected. The OAuth state is a single-use nonce stored server-side and deleted by the first callback that presents it, so a captured consent URL cannot be replayed. It binds the flow to the user and the provider, and a PKCE verifier derived from that state binds the code to the flow.

The first version used a Better Auth `genericOAuth` provider. Better Auth treats every linked account as a login identity, so it refused to link one Google account to a second OpenSEO user. That blocked people with two OpenSEO logins and members of one organization who share a client Google account, so the flow moved out of Better Auth.

**Scoping.** A connection maps one verified property to one project (`gsc_connections`, unique per project). The connection belongs to the project/workspace; any member can query it, and requests run under the connecting member's grant. Property selection lives in the Integrations UI (account dropdown) and, for agent-driven setup, in the `list_search_console_sites` / `set_search_console_site` MCP tools, which run the same service checks; connecting a Google account is dashboard-only.

**MCP tools** — read-only, free (no Autumn metering), scoped to a project the caller's workspace owns:

- `get_search_console_performance`: thin pass-through of Search Analytics (group by query/page/country/device/date, simple AND filters, ≤1000 rows with offset paging, 16-month and ~3-day-lag clamps).
- `inspect_urls`: URL Inspection for 1–10 URLs with per-URL partial results; connection-level failures (not connected / expired grant) abort the call with a reconnect prompt.

Whether an inspected URL belongs to the property is enforced by Google's API, not re-checked locally, so both `sc-domain:` and URL-prefix properties work.

**Disconnect** removes the project's property mapping and unlinks the OAuth grant only when its connector has no other connected project — never as a side effect of a different member disconnecting.

## Rationale

Leaning on Better Auth's incremental OAuth keeps token storage and refresh out of feature code. Per-project property mapping matches how teams work (a different site per project) and keeps queries scoped to a workspace the caller owns. Treating GSC reads as free reflects that Google doesn't bill for them and makes connecting an activation hook rather than a metered cost.

## Consequences

- The read-only scope is a Google "sensitive" scope: until the OAuth app clears verification, only test users can connect and their grant expires ~weekly.
- "Connected by" surfaces the OpenSEO member who connected, not the Google account's email.
- One property per project (re-selecting replaces it); no history or caching — every query hits Google live.
- New GSC capabilities should extend `GscService` and the MCP tools, keeping reads free and project-scoped.

---

### Maintainers Specs 0004 Keyword Data Source Routing (`docs/maintainers/specs/0004-keyword-data-source-routing.md`)

# Keyword data source routing and the clickstream default

## Status

Accepted (June 2026). Superseded in part (September 2026): auto mode blends
`keyword_suggestions` + `keyword_ideas` at half the result limit each instead
of cascading related → suggestions → ideas, and Labs live pricing has risen to
$0.012/task + $0.00012/row (measured against the live API). The default
150-row research call is now two tasks, $0.042 raw → 54 credits, not $0.025 →
32 credits. The routing, clickstream, and Google-Ads-coverage decisions below
still hold.

## Context

Keyword research is the largest credit spend for OpenSEO users, and coverage
has a hard gap: DataForSEO Labs supports 94 countries, so a customer in
Iceland (location 2352) cannot run keyword research at all.

Three data sources were on the table:

- **DataForSEO Labs** — our existing source. Per-row pricing ($0.01/task +
  $0.0001/row), and the only source for keyword difficulty, search intent,
  and SERP-feature context. Its `include_clickstream_data` flag doubles the
  request cost; its only effect is refined volume numbers — the standard
  `keyword_info.search_volume` is the same Google-Ads-derived volume every
  mainstream tool shows.
- **DataForSEO Keywords Data (Google Ads endpoints)** — same vendor, flat
  $0.075 per live request (up to 1,000 keywords for `search_volume`, up to
  20 seeds for `keywords_for_keywords`), 217 countries including Iceland. No
  difficulty, intent, or SERP data; volumes are bucketed and aggregate close
  variants.
- **Direct Google Ads API** — free, but not usable in a SaaS: Google's
  Targeting-data policy forbids collecting Keyword Planner data "for any
  purposes other than creating or managing Google Ads campaigns," and
  exposing it to users requires the full Required Minimum Functionality (a
  campaign-management suite). Volumes are bucketed without active ad spend.

## Decision

Every supported country has exactly one keyword-data provider, resolved by
`getKeywordDataProvider(locationCode)` in `src/shared/keyword-locations.ts`.
There is no user-facing provider choice.

1. **Labs is the default provider.** Countries Labs does not cover are
   flagged `googleAdsOnly` in `LOCATION_OPTIONS` and are served by the
   Keywords Data Google Ads endpoints. Unknown location codes fall back to
   Labs, which rejects them with its own error.
2. **Routing per feature:**

   | Feature                                             | Labs country                   | Google-Ads-only country (e.g. Iceland)                                                          |
   | --------------------------------------------------- | ------------------------------ | ----------------------------------------------------------------------------------------------- |
   | Keyword research (UI + `research_keywords`)         | Labs suggestions + ideas blend | `keywords_for_keywords` (single source)                                                         |
   | `get_keyword_metrics`, rank-tracking metric refresh | Labs keyword_overview          | `search_volume`                                                                                 |
   | SERP analysis, `get_serp_results`, rank tracking    | SERP API                       | SERP API (supports all countries)                                                               |
   | Domain overview, ranked keywords, SERP competitors  | Labs                           | **Unavailable** — pickers filtered to Labs countries; MCP tools return a clear validation error |

3. **Google-Ads-sourced rows carry no keyword difficulty or intent**
   (`keywordDifficulty: null`, `intent: "unknown"`). The research page and
   the MCP tool descriptions state this whenever such a country is in play.
4. **Clickstream refinement is opt-in per call and defaults to off**, for
   the Labs research endpoints (related/suggestions/ideas) and keyword
   overview. Users opt in via the labeled checkbox on the research page
   (URL param `cs`, carried per keyword tab, hidden for Google-Ads-only
   countries) or via `includeClickstreamData` on the `research_keywords` and
   `get_keyword_metrics` MCP tools. The label and tool descriptions must
   state the 2× credit cost. The flag is part of the research cache key.
5. **Language codes for Google-Ads-only countries must exist in both the
   Google Ads and SERP language lists** — the country picker is shared with
   rank tracking, which uses the SERP API. Google Ads names some languages
   differently (`no` for `nb`, `iw` for `he`, `zh_TW` for `zh-TW`, `zh_CN` for
   `zh-CN`), so the Google Ads client translates them. Five Labs countries
   default to a language Google Ads does not have at all (Albanian, Armenian,
   Azerbaijani, Bosnian, Macedonian). Their local volume calls send no
   language, because Google Ads fails a task with a language it does not
   know and returns the same volumes with no language as with English.
6. **The picker offers every country in both the Google Ads and SERP country
   lists**, plus Hong Kong, Macao, Palestine, and Taiwan, which DataForSEO
   lists as regions. China is left out because Google search does not
   meaningfully operate there. Territories with no permanent population
   (Antarctica, Heard Island and McDonald Islands, South Georgia, the French
   Southern and Antarctic Lands, the United States Minor Outlying Islands)
   are left out too. Saint Barthelemy, South Sudan, Sudan, and Syria have
   Google Ads data but no SERP location, so rank tracking could not run
   there.
7. **Billing is unchanged.** `keywords_data/*` task costs flow through the
   same envelope → markup → Autumn pipeline as Labs calls and map to the
   `keyword_research` credit feature (rank tracking overrides to
   `rank_tracking`).

## Rationale

Cost at our actual defaults (research default = 150 rows/seed; credits =
USD × 1.28 markup × 1000):

| Call               | Labs (with clickstream) | Labs (default) | Google Ads     |
| ------------------ | ----------------------- | -------------- | -------------- |
| research, 150 rows | $0.050 → 64 cr          | $0.025 → 32 cr | $0.075 → 96 cr |
| research, 500 rows | $0.120 → 154 cr         | $0.060 → 77 cr | $0.075 → 96 cr |
| metrics, 100 kw    | $0.020 → 26 cr          | same           | $0.075 → 96 cr |
| metrics, 700 kw    | $0.080 → 103 cr         | same           | $0.075 → 96 cr |

- A wholesale switch to Google Ads data would raise the cost of typical
  calls and lose difficulty/intent; replicating difficulty alone via
  `bulk_keyword_difficulty` ($0.11/1k) erases any savings. Hybrid keeps the
  better data where it exists and adds coverage where it doesn't.
- Always-on clickstream silently doubled the #1 spend feature for a marginal
  volume refinement. Off-by-default halves default research cost
  (~64 → ~32 credits per seed); the opt-in keeps the refinement available to
  users who want it, priced visibly.
- The direct Google Ads API is rejected on policy, not effort — revisit only
  if OpenSEO ships campaign management.

## Consequences

- Iceland and 116 other countries are selectable for keyword research and
  rank tracking; a Google-Ads-served research or metrics call costs a flat
  ~96 credits.
- Cross-country volume numbers stay roughly comparable: both providers'
  standard volumes derive from Google Ads data.
- Google Ads live endpoints allow 12 requests/min per DataForSEO account.
  Research fans out at most 5 seeds per call, so a single user stays under
  it; sustained multi-user traffic on these countries would queue.
- `keywords_for_keywords` has no limit parameter (up to 20k suggestions per
  flat-fee request); results are sorted by volume server-side and truncated
  to the requested limit.
- The research cache version was bumped (2→3) so pre-change
  clickstream-priced volumes never mix with standard ones.
- Reverting the clickstream default is a one-line change per fetcher in
  `src/server/lib/dataforseo/labs.ts`; the opt-in plumbing stays either way.

## Local volume (city, county, region)

Keyword research can target one city, county, or region inside the selected
country. Labs and clickstream serve countries only, so the keyword list,
keyword difficulty, and intent stay national. One Google Ads `search_volume`
call with the area's canonical `location_name` then replaces volume, trend,
CPC, and competition for every row. The SERP panel fetches the organic results
for the same area.

- The area must be a row of the country's location registry, the same list
  the rank tracking picker searches. The check runs before any paid call. The
  registry has no postal codes, so ZIP targeting is not offered.
- A keyword that Google Ads does not return gets empty metrics, never the
  national numbers. Google Ads fails a whole task on one keyword with certain
  symbols, an emoji, more than 80 characters, or more than 10 words, so those
  keywords are not sent.
- Local rows are not stored as keyword metrics, because stored metrics are
  keyed by country. Saved keywords keep national metrics.

Alternatives considered:

- **Append the city to the keyword** ("plumber austin"). This is a different
  query with its own, much smaller volume, not demand for the head term in
  that city.
- **Automatic fallback to the county or metro area when a small city has no
  volume.** Google geotargets link a city to its state, not to its county or
  metro area, so the fallback would need a separate city-to-county mapping.
  The results instead suggest a larger area when no keyword has local volume.
- **Coordinates or postal codes.** Coordinates resolve to country volume and
  postal codes return no volume.

---

### Maintainers Specs 0005 Onboarding Agent (`docs/maintainers/specs/0005-onboarding-agent.md`)

# Onboarding agent

## Status

Proposed (June 2026) — v1 product spec, pending technical design.

> **Update (June 2026):** what shipped is a chat where Sam analyzes the site
> on demand (via `read_website` + `get_seo_metrics` tools) and writes the
> strategy in-stream, rather than the staged synthesize → persist pipeline
> described below. Persisting the strategy (the "Project Context" store + R2
> versioning) and the `get_project_context` MCP tool are **deferred to a later
> PR** — the strategy is shown in the chat but not yet saved. Sections below
> describe the original plan.

## Goal

Turn signup into activation. When a new user onboards, an "agent" analyzes
their actual website live, then proposes a tailored SEO strategy. The strategy
is free and stands on its own; _acting on it_ (rank tracking, content briefs,
the ongoing coach) is the paid surface. The strategy becomes the project's
durable "Project Context" — readable in the app and over MCP.

This is the top activation priority because it gives every new user a concrete,
personalized "here's what to do" moment before they're asked to pay.

## What "agent" means here

A **guided pipeline narrated live**, not an LLM agent loop. The steps are
mostly deterministic (scrape, fetch keyword data); a single LLM call at the end
synthesizes the strategy narrative. The "agent" feeling comes from streaming the
steps in real time ("Reading your homepage… you look like a Notion
alternative… 4 keywords ranking, 30 worth targeting…") and streaming the final
write-up token-by-token. No Anthropic SDK / agent infra is required for v1.

## The experience

**Stage 0 — Profile (extend existing onboarding forms).** Collect: domain,
experience level, and primary goal. **Website and default country are captured
on the same step**, since the country is a property of the site/project being
analyzed — keeping them together makes the relationship obvious and avoids a
stray standalone country field. That step carries a short note that they can add
more projects with different websites (and their own countries) later, so users
don't feel they must cram every site into this first one. Keep the whole stage
to ~4 fields — the onboarding UX audit flagged form friction. Country and
language become the project's default location (see Project defaults) and are
reused for every DataForSEO call going forward.

**Stage 1 — Discover (live).** Sitemap-first using existing robots.txt +
sitemap discovery; fall back to a shallow crawl. Produces a map of the site's
shape from URLs/titles. Discover many URLs (cheap); scrape few.

**Stage 2 — Read (live).** Scrape ~3–5 key pages (home + top product/nav pages)
to markdown. This is the one net-new capability: page → markdown via Cloudflare
Browser Rendering. Honest "we couldn't read your site" flagging with a manual
"tell us what you do" fallback so the run never dead-ends.

**Stage 3 — Signal (live).** See Stage 3 data below.

**Stage 4 — Synthesize (streaming LLM).** One LLM call over
{profile + scraped markdown + keyword data} produces: a positioning statement,
3–5 themes/clusters, a starter keyword table (volume/difficulty), and a
prioritized "do this next" list. Must produce a credible strategy even when the
site has zero existing rankings — the cold-start case is the _default_ for the
indie-founder ICP, not an edge case.

**Stage 5 — Persist + gate.** Save as the Project Context artifact (markdown,
MCP-readable). Present the full strategy free; the paywall lands on _executing_
it.

## Stage 3 data (v1 — kept minimal)

Stage 3 is **archetype-conditional**: detect the site type cheaply, then frame
the goal accordingly. For v1 the archetype branches the _narrative_, not a large
matrix of API calls. Two calls baseline:

| Call                   | Endpoint                                               | Purpose                                              | When                                                                 |
| ---------------------- | ------------------------------------------------------ | ---------------------------------------------------- | -------------------------------------------------------------------- |
| `domain_rank_overview` | `/v3/dataforseo_labs/google/domain_rank_overview/live` | traffic + # ranking keywords; the archetype detector | always                                                               |
| `keyword_ideas`        | `/v3/dataforseo_labs/google/keyword_ideas/live`        | starter keyword list, seeded from scraped themes     | always                                                               |
| `ranked_keywords`      | `/v3/dataforseo_labs/google/ranked_keywords/live`      | what they already rank for                           | only if overview shows real rankings (usually skipped for new sites) |

Archetypes (narrative only in v1): **new/pre-traffic**, **established content
site**, **local business**, **SaaS/product** (core ICP).

**Clarifying question:** for **beginners**, skip it and use the archetype's
default goal (fewer decisions = less drop-off). For **non-beginners**, ask one
targeted question after detection to confirm intent (e.g. "grow existing
rankings, or expand into new topics?") — agency without a survey.

**Deferred to v2:** `serp_competitors`, local-business tools
(`get_local_serp_results`, `search_local_businesses`,
`get_google_business_questions`), and Google Ads volume for non-Labs countries.

## Cost per free onboarding

The whole run is free (paywall is after), so cost-per-signup must be bounded:

- DataForSEO: ~$0.04–0.08 (2 Labs live calls; metered from the real `cost`
  field in the response envelope, so we can hard-cap).
- Browser Rendering scrape: ~negligible.
- LLM synthesis: ~$0.05–0.15 (one call over a few pages of markdown).
- **Total ≈ $0.10–0.25 per onboarding.**

Guardrails: one run per user, results cached hard, and **email verification
gates Stage 3** (the DataForSEO spend) to kill drive-by abuse.

## Project Context artifact (MCP-readable)

The strategy is stored as a **markdown document** — a living "Project Context"
that is the shared source of truth across the in-app agent, the web UI, and any
MCP client.

- Storage: a `project_context` row in D1 (`projectId`, `markdown`, `updatedAt`,
  `version`). Small enough for D1; R2 only if it grows.
- MCP: a `get_project_context` tool (and ideally an MCP _resource_ so it
  auto-loads into the agent's context). The user's own Claude/Codex reads the
  same strategy the app shows.
- The onboarding agent **authors** the context; the paid execution actions
  (rank tracking, briefs, coach) **read from and append to** it. That append-back
  is the natural shape of the gated surface.

## Project defaults (country/language)

Projects don't currently store a default location — only `rank_tracking_configs`
does (defaults 2840/US, "en"). Add `location_code` + `language_code` to
`projects`, set from the Stage 0 country, and reuse them everywhere project work
needs a location. A small curated country → `location_code` map is enough for
v1.

## Paywall

Free: the full strategy, positioning, themes, capped starter keyword list
(~15–20), and the "do next" list. Gated (execution): rank-tracking the proposed
keywords, full keyword expansion, content briefs per theme, and the ongoing
`seo-coach`. Every gated action is a named thing tied to a strategy item the
user already believes in — stronger pull than "refine further." GSC stays behind
the gate; we do **not** prompt for it during onboarding (connecting then hitting
a paywall is exactly the bait-and-switch the UX audit warned against).

## Unify the seo-coach skill

Update the `seo-coach` skill (and `onboarding-checklist`) so the coach and the
onboarding agent are one continuous experience: the coach reads Project Context
via MCP, picks up where onboarding left off ("here's your strategy — let's work
the backlog"), and can answer both SEO questions and OpenSEO product questions.
The onboarding agent sets the backlog; the coach executes it.

## Open questions

- Country → `location_code` source: hand-curate a short list for v1, or reuse an
  existing DataForSEO locations dataset?
- Re-run policy: confirmed one strategy per project, regenerate in place; new
  domain = new project (a soft upgrade nudge).
- Synthesis model choice (cost vs quality) — decide at technical design.

## Out of scope for v1

Conversational/iterative agent loop, competitor and local-business analysis,
GSC-enriched strategy, multi-language strategies, automatic content generation.
These are incremental improvements once the core activation loop is proven.

---

### Maintainers Specs 0006 Onboarding Agent Implementation (`docs/maintainers/specs/0006-onboarding-agent-implementation.md`)

# Onboarding agent — implementation plan (chat + seed function)

## Status

Accepted (June 2026) — technical plan for `specs/0005-onboarding-agent.md`.

Supersedes an earlier draft that proposed Cloudflare Project Think + Durable
Objects + a Workflow. We dropped all of that (see "Why not Think / Workflows").

> **Update (June 2026):** the shipped implementation diverged from the plan
> below. The deterministic seed + synthesis pipeline — and its `claimRun`
> run-status guard and `skipBalanceAssert` bypass — was replaced by an on-demand
> chat: Sam calls two tools (`read_website`, `get_seo_metrics`) and writes the
> strategy itself in-stream (see `src/routes/api/onboarding/chat.ts`). Strategy
> **persistence** (the `project_context_versions` store + R2 versioning) and the
> `get_project_context` **MCP tool** are deferred to a later PR. Onboarding
> spend — DataForSEO **and** LLM tokens — draws down the org's onboarding-plan
> trial credits via the normal balance gate. The sections below describe the
> original plan, not what shipped.

## TL;DR

Onboarding has two simple pieces, no agent framework:

1. **A seed function** (plain async): discover sitemap → scrape 3–5 pages to
   markdown (Browser Rendering) → 2 paid DataForSEO calls → one OpenRouter
   synthesis call → save the result as the project's first **Project Context**
   version. Runs once when onboarding kicks off.
2. **A normal streaming chat** (Vercel AI SDK `streamText` over OpenRouter):
   the user asks questions / refines; an `update_project_context` tool writes a
   new version. Backed by a plain API route on the existing better-auth session.

The Project Context is **versioned**: immutable markdown blobs in R2, an
append-only log in D1. Reverts reuse a prior blob's key. It's exposed over MCP
via `get_project_context`.

## Why not Think / Workflows (and why `agents` stays)

- **No durable execution needed.** The paid DataForSEO services are _cache-first_
  (`getCached` runs before `createDataforseoClient`/metering), so a crash-and-retry
  of the same domain re-hits the 12h R2 cache → no double-spend. That removed the
  only reason for fibers/Workflows.
- **No agent host needed.** The capabilities we want (stream answers, a future
  docs tool, save/update the artifact) are all plain `streamText({ tools })`.
  Think's distinctive value (durable DO sessions, scheduled turns, sub-agents)
  isn't used by any of them.
- **The `agents` package stays** — it's used by the MCP handler
  (`agents/mcp` → `createMcpHandler` in `src/server/mcp/transport.ts`), not as an
  agent runtime. No version bump.
- **Graduate later** only when a capability genuinely needs durable sessions,
  `schedule` (weekly rank tracking), or sub-agents (per-competitor). The seed
  function and chat route port straight over.

## Data model

**`projects`** — add `location_code` (int, default 2840), `language_code` (text,
default `'en'`), `onboarding_run_status` (text nullable:
`running|complete|failed`), `onboarding_run_at` (text nullable).

**`project_context_versions`** (new, append-only log):
`id` pk · `project_id` FK · `r2_key` · `author` (`onboarding|chat|user`) ·
`note` nullable · `reverted_from_id` nullable · `created_at`. Current version =
latest row per project. Index on `(project_id, created_at)`.

**R2** — immutable markdown blob per version at
`project-context/{projectId}/{versionId}.md`. **Write R2 first, then the D1
row** (a failure leaves a harmless orphan blob, never a row pointing at nothing).
A revert inserts a new row reusing the target's `r2_key` (no new blob).

## The seed function

`runOnboardingSeed({ projectId, organizationId, userId, userEmail, domain })`:

1. **Admission marker** — atomic `UPDATE projects SET onboarding_run_status =
'running' WHERE id = ? AND onboarding_run_status IS NULL`; proceed only if
   one row changed (else a run is already in flight). This is the at-most-once
   guard.
2. **Discover** — `fetch()` robots.txt + sitemap.xml; shallow fallback.
3. **Read** — scrape 3–5 key pages to markdown via the `BROWSER` binding,
   sequentially. Failure → flag it, never throw the whole run.
4. **Signal** — `DomainService.getOverview` (always) + keyword research seeded
   from scraped themes, both with `creditFeature: 'onboarding'`;
   `getSuggestedKeywords` only if the overview shows real rankings.
5. **Synthesize** — one OpenRouter `generateText`/`streamText` over
   {profile + markdown + signal} → strategy markdown.
6. **Persist** — write version `v1` (author `onboarding`); set
   `onboarding_run_status = 'complete'`. On any throw → `'failed'` (re-runnable;
   retry is cache-backed and cheap).

**Metering** is unchanged: paid calls go through the existing
`createDataforseoClient` seam. A new `'onboarding'` `CreditFeature` tags spend.
A `skipBalanceAssert` flag on the metering path lets a zero-balance new signup
run Stage "Signal" without dead-ending on `INSUFFICIENT_CREDITS`, while still
calling `trackDataforseoCost` (spend metered, not balance-gated). Self-host
already skips Autumn entirely.

## The chat

`POST /api/onboarding/chat` (TanStack `createFileRoute` server handler):

- Auth: resolve the better-auth session from the request; assert the user owns
  `projectId` (org scoping via `ProjectRepository.getProjectForOrganization`).
  No new transport, so no extra auth surface.
- `streamText({ model: openrouter(MODEL), system: seededWithContext, messages,
tools: { update_project_context } })`, returned as a UI message stream.
- `update_project_context({ markdown, note })` writes a new version (author
  `chat`). For v1 it applies directly; the append-only log makes any unwanted
  change one revert away.

Client: AI SDK `useChat({ api: '/api/onboarding/chat' })`. The strategy renders
above the chat; the upgrade CTA is a UI state shown once `v1` exists.

## Auth + email-verify

- Surface `emailVerified` on `EnsuredUserContext` (from
  `session.user.emailVerified`); self-host = treated verified.
- The seed asserts `emailVerified` before the paid "Signal" stage. Discover +
  Read (free) may run unverified.

## MCP

`get_project_context(projectId)` — read-only tool (`readOnlyHint: true`) using
`withMcpProjectAuth`; resolves the latest version → R2 get → returns markdown.
`list_project_context_versions` is a fast-follow.

## Local testing

Real providers, no fixture system:

- Add `OPENROUTER_API_KEY` to `.env.local` (the one new key), `wrangler login`
  for the `BROWSER` binding (`remote: true` in dev).
- DataForSEO creds you already have; the cache makes repeat runs free.
- Drive the real onboarding UI with the Playwriter skill, screenshotting each
  step. **Test domain: `openseo.so`.**

## Build order (stacked PRs)

1. **Foundation** — schema + migration (`projects` cols, `project_context_versions`);
   `emailVerified` on context; `'onboarding'` CreditFeature + label +
   `skipBalanceAssert` flag; country→`location_code` map. No behavior.
2. **Stage 0 form** — domain + country on one step → `projects`.
3. **Project Context store** — R2 blob helper + versions repository +
   `get_project_context` MCP tool.
4. **Scrape + seed + synthesis** — `BROWSER` binding, scrape-to-markdown, the
   seed function, OpenRouter dep, the "generating → strategy" UI.
5. **Chat** — `/api/onboarding/chat` + `update_project_context` tool +
   `useChat` UI + revert.

(There is no fixture-provider PR — we test against real providers.)

## Out of scope (v1)

Think/DO/Workflows, sub-agents, scheduled rank tracking, GSC-enriched strategy,
multi-language, auto content generation, the MCP context _resource_ (tool only).

---

### Maintainers Specs 0007 Google Analytics Mcp Integration (`docs/maintainers/specs/0007-google-analytics-mcp-integration.md`)

# Google Analytics MCP integration

## Status

Accepted (2026-08-05) by the OpenSEO maintainer under EVE-33.

Implementation update (2026-08-06): the EVE-33 branch now implements the
connection lifecycle, dashboard/settings UI, and the four reports specified
below. Follow-up work on the same branch adds six bounded read-only tools for
organic overview, traffic acquisition, measurement health, ecommerce, site
search, and audience breakdowns. The implementation has been verified locally
but is not shipped until the branch is reviewed, merged, and deployed. The
remainder of this document preserves the originally accepted decision and
milestone language.

## Context

OpenSEO can read a project's Google Search Console (GSC) property, but an agent
cannot see what visitors do after the click. GA4 adds first-party signals such
as organic sessions, engagement, key events, transactions, and revenue. The
first release should answer SEO questions without exposing an unrestricted
analytics report builder.

GA4 and GSC remain separate sources. They use different attribution rules,
reporting time zones, and definitions, so their counts are not interchangeable.
The supported join is page-level correlation: search demand and visibility
from GSC alongside engagement and business value from GA4.

## Maintainer decision

Accept the design proposed in [PR #106](https://github.com/every-app/open-seo/pull/106)
with these clarifications:

- The GA4 grant and the project-to-property mapping have separate owners and
  lifecycles.
- Each MCP tool has a fixed request body, bounded inputs, a discriminated
  success/error output, and stable privacy and quota metadata.
- A restricted metric is `null`; an omitted or thresholded row is unknown and
  is never synthesized as zero.
- GA4 page joins use a host-and-path key because the `hostName` and
  `landingPage` dimensions do not provide a URL scheme.
- GSC dates use `America/Los_Angeles`; GA4 dates use the selected property's
  IANA time zone. The combined tool reports both.
- Implementation is divided into backend/service milestones and thin adapter
  milestones. Merging this document alone does not expose a tool or UI.

PR #106's review found that the key-events report could attribute all-channel
events to organic traffic. The proposal fixed that finding. This accepted
contract keeps `Organic Search` as the default and makes any all-channel
request explicit in both the input and output.

## Decision

The original decision adds a native GA4 connection and four read-only,
project-scoped MCP tools. The implementation update above records the six
subsequently approved tools without rewriting the historical contract.

### Authentication and grant ownership

Use a dedicated Google OAuth grant with the provider ID `google-analytics`.
The app's own Google OAuth flow issues it, the same flow as Search Console
(see spec 0003). It first shipped as a Better Auth `genericOAuth` provider,
which could not link one Google account to two OpenSEO users. It requests
these scopes:

- `openid`, `email`, and `profile` identify the connected Google account.
- `https://www.googleapis.com/auth/analytics.readonly` discovers properties
  and reads reports.

Do not add the Analytics scope to `google-search-console`. A separate grant
keeps GSC access unchanged, allows an agency to use different Google accounts
for GSC and GA4, and gives GA4 its own reconnect and disconnect lifecycle. No
Analytics write scope is allowed.

The connecting OpenSEO user owns the grant. The app stores its OAuth access
and refresh tokens, encrypted at rest with the Better Auth secret, in the
`account` table under the `google-analytics` provider ID. The row is keyed by
OpenSEO user and Google account, so two OpenSEO users can each connect the
same Google account. Feature tables must not copy those
tokens. Refresh-token rotation preserves the existing encrypted refresh token
when Google omits a new one.

Hosted OpenSEO reuses its Google OAuth client and registers
`/api/ga4/oauth/callback` on it. A self-hosted operator reuses
`GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, and `BETTER_AUTH_SECRET`, enables
the Google Analytics Admin API and Google Analytics Data API, and registers
`/api/ga4/oauth/callback`. GA4 adds no application secret.

### Property mapping ownership

Property discovery paginates Admin API v1beta `accountSummaries.list` and then
calls `properties.get` for the selected property's time zone and currency.
The Integrations UI and the `list_google_analytics_properties` /
`set_google_analytics_property` MCP tools select a property through the same
service checks; only the UI can connect a Google account. Reporting tools accept
a `projectId` and read the property bound to it.

The `ga4_connections` row belongs to the OpenSEO project and organization, not
to the connecting user. Any current member who can access the project can read
through the mapping. The service still executes the Google request through the
specific connector account that selected the property.

`ga4_connections` has matching SQLite and Postgres definitions:

- `id`, `project_id` (unique), and `organization_id`;
- `property_id`, stored as the canonical `properties/{id}` resource name;
- `property_display_name`, `property_time_zone`, and
  `property_currency_code`;
- `connected_by_user_id`, `ga4_account_id`, and
  `connected_account_email`; and
- created and updated timestamps.

The server function for selection receives `projectId`, `propertyId`, and the
connector account ID. Project authorization supplies `organizationId` and the
current user. `Ga4Service` verifies that the current user owns that connector
grant and that the exact property appears in a fresh discovery response before
upserting the mapping. Clients cannot submit `organizationId`,
`connectedByUserId`, account email, time zone, currency, or display name.

Disconnecting always deletes the project's mapping. It deletes the
grant only when the caller owns that grant and no other GA4 connection refers
to the same `(connected_by_user_id, ga4_account_id)` pair. A different project
member may remove the project mapping but cannot unlink another user's grant.

### Fixed report inputs

Every tool requires `projectId`. The three GA4-only tools also accept this
common input:

| Field       | Contract                                        |
| ----------- | ----------------------------------------------- |
| `startDate` | `YYYY-MM-DD`; must be supplied with `endDate`   |
| `endDate`   | `YYYY-MM-DD`; must be supplied with `startDate` |
| `limit`     | Integer from 1 through 1,000; default 100       |
| `offset`    | Non-negative integer; default 0                 |

With no explicit dates, the range is the last 28 complete days in the GA4
property time zone. Explicit ranges are inclusive and honored in full; there is
no maximum range. The report builder caps the end at the last complete property
day. The response returns requested and resolved dates plus an
`end_date_clamped` warning, which the text output also states. The organic
overview trend is capped at 1,000 rows and reports `trend_truncated` (also
stated in the text) when a range exceeds that. Invalid date
formats, reversed dates, and a single date without its pair return
`validation_error` before an API call.

Only these tool-specific inputs are accepted:

- `get_google_analytics_organic_landing_pages` has no additional report input.
- `get_google_analytics_page_performance` accepts `includeDate` (boolean,
  default `false`) and `channel` (`organic_search | all`, default
  `organic_search`).
- `get_google_analytics_key_events` accepts `breakdown`
  (`event | event_and_landing_page`, default `event`) and the same `channel`
  enum and default.
- `get_search_opportunities` accepts the shared date pair and `limit` from 1
  through 100, default 50. It does not expose source offsets or report-builder
  inputs.

The adapters reject unknown fields. Callers cannot provide property IDs,
dimensions, metrics, filter expressions, order clauses, currency, time zone,
or arbitrary GA4 request JSON.

### Fixed reports

The first three tools call Data API v1beta `properties.runReport`. Every
request sets `keepEmptyRows: false` and `returnPropertyQuota: true`.

| Tool                                         | Fixed request                                                                                                                                                                                                                                                                   |
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `get_google_analytics_organic_landing_pages` | Dimensions `hostName`, `landingPage`; metrics `sessions`, `activeUsers`, `engagedSessions`, `engagementRate`, `keyEvents`, `sessionKeyEventRate`, `transactions`, `purchaseRevenue`; exact `sessionDefaultChannelGroup = Organic Search` filter; order by `sessions` descending |
| `get_google_analytics_page_performance`      | Dimensions `hostName`, `pagePath`, plus `date` only when requested; metrics `screenPageViews`, `activeUsers`, `userEngagementDuration`, `keyEvents`; exact organic channel filter unless `channel = all`; order by `screenPageViews` descending                                 |
| `get_google_analytics_key_events`            | Dimension `eventName`, plus `hostName`, `landingPage` only for the requested breakdown; metrics `keyEvents`, `totalUsers`; exact organic channel filter unless `channel = all`; order by `keyEvents` descending                                                                 |

The service owns these arrays and builders. `getMetadata` and
`checkCompatibility` may validate the key-event landing-page combination. An
unsupported combination returns `ga4_report_incompatible`; it never falls back
to a custom report.

Properties without ecommerce events return numeric zeros where GA4 returned a
row with zero ecommerce metrics. If response metadata says the caller's role
restricts `purchaseRevenue`, the service returns `purchaseRevenue: null` and
includes the restriction. It does not turn a restricted value into zero.

Realtime, demographic, interest, audience, user-level, custom-dimension, and
custom-metric inputs are excluded from v1. These reports do not consume OpenSEO
credits.

### Success output

Each GA4-only tool returns the same envelope with a tool-specific `rows` type:

```text
{
  status: "ok",
  source: {
    provider: "google_analytics",
    propertyId,
    propertyDisplayName
  },
  request: {
    requestedDateRange,
    resolvedDateRange,
    propertyTimeZone,
    currencyCode,
    channel,
    limit,
    offset
  },
  rowCount,
  totalRowCount,
  rows,
  pageInfo: { offset, limit, hasMore, nextOffset },
  reportMetadata: {
    dataLossFromOtherRow,
    subjectToThresholding,
    sampling: [{ samplesReadCount, samplingSpaceSize }],
    restrictedMetrics: [{ metricName, restrictedMetricTypes }],
    emptyReason,
    hasLimitedData
  },
  quota: {
    tokensPerDay,
    tokensPerHour,
    concurrentRequests,
    serverErrorsPerProjectPerHour,
    potentiallyThresholdedRequestsPerHour,
    tokensPerProjectPerHour
  } | null,
  warnings
}
```

`rowCount` is the number of rows in this response. `totalRowCount` is Google's
validated `rowCount` for the full query before `limit` and `offset`.
`hasMore` is `offset + rowCount < totalRowCount`; `nextOffset` is
`offset + rowCount` when `hasMore` is true and `null` otherwise. Each quota
field is `{ consumed, remaining }` when Google provides it. Quota numbers never
include OAuth credentials.

`sampling` keeps Google's integer counts as decimal strings. The other metrics
are parsed to finite numbers after the REST response passes Zod validation.
`hasLimitedData` is true when thresholding, sampling, an `(other)`-row loss, or
a metric restriction is present. Thresholding does not prove that a particular
row is absent, so agent-facing text says the report may be limited. Missing
rows remain missing.

The MCP adapter validates this output schema and renders text from the same
object. Structured and text outputs must agree about source, date range,
channel, row count, limitations, and errors.

### Combined search opportunities

`get_search_opportunities` uses the native GSC connection and the GA4 organic
landing-page report. It never depends on an optional GA4-to-GSC product link.

The default range is the 28 days ending three days ago. Both sources receive
the same inclusive date strings. GSC interprets them in
`America/Los_Angeles`; GA4 interprets them in the selected property's time
zone. The response includes both zones and a `source_time_zones_differ`
warning when they differ.

The service considers at most 1,000 rows from each source in v1. GSC returns
top rows rather than guaranteed complete data. The result therefore includes
`coverage` with source row counts and `gscRowsTruncated` and
`ga4RowsTruncated` flags. Agent-facing text must not call a truncated result a
complete site inventory. `gscRowsTruncated` is true whenever GSC fills its
1,000-row cap because GSC does not return a total row count;
`ga4RowsTruncated` is true when GA4's `totalRowCount` exceeds the number of rows
considered.

The combined success envelope includes `gscTimeZone`, `ga4TimeZone`,
`coverage`, `rows`, `unmatchedRows`, `warnings`, the full GA4
`reportMetadata`, and the GA4 `quota` object defined above. If GA4 reports
thresholding, sampling, other-row loss, or metric restrictions, the combined
tool preserves the same fields, sets `ga4_data_limited`, and says that an
unmatched GSC page may have omitted GA4 data. It never interprets an unmatched
page as having zero sessions, engagement, events, transactions, or revenue.

The join key is normalized host plus path:

1. Lowercase the host and remove a default port.
2. Ignore the URL scheme, fragment, and query string.
3. Remove a trailing slash except at the root.
4. Preserve path case and preserve subdomains. Do not equate `www.example.com`
   with `example.com`.
5. Treat `(not set)`, an empty host/path, and invalid GSC URLs as unmatched.

GA4 supplies `hostName` and `landingPage`; GSC supplies a full page URL. The
response keeps the raw source values and the normalized key. Unparseable rows
appear in `unmatchedRows` with a stable reason code instead of disappearing.

Candidate pages have GSC impressions and average position from 4 through 20.
A candidate with no joined GA4 row remains in the output with
`joinStatus: "gsc_only"`, `ga4: null`, `businessValue: null`, and
`opportunityScore: null`. The service does not include it in the scoring
population. If GA4's metadata indicates limited data, every computed score has
`scoreDataLimited: true`; the score still ranks returned aggregates but cannot
be used to rank unmatched pages below matched pages.

For candidates with a joined GA4 row, calculate percentile ranks for
`log1p(impressions)`, `sessionKeyEventRate`, and ranking reachability, where
position 4 is highest and 20 is lowest. Ties receive the same percentile rank.
Use this versioned formula:

```text
opportunityScoreV1 = round(
  100 * (0.5 * demand + 0.3 * businessValue + 0.2 * reachability)
)
```

If all joined candidate rows report zero key events, substitute
`engagementRate` for those returned rows and set
`businessValueFallback: "engagementRate"`. This fallback describes the rows
returned by GA4; it does not claim that the property has no key events. The
output contains the components, formula version, raw GSC and GA4 metrics, join
status, and coverage. The score ranks the joined rows; it is not a forecast.

### Error contract

Services throw typed domain errors. Server-function and MCP adapters map them
to the same discriminated output:

```text
{
  status: "error",
  error: {
    code,
    message,
    retryable,
    reconnectUrl?,
    retryAfterSeconds?,
    details?
  }
}
```

Stable codes and mappings:

| Code                        | Cause and adapter behavior                                                                              |
| --------------------------- | ------------------------------------------------------------------------------------------------------- |
| `validation_error`          | Zod or report-builder rejection; no Google call                                                         |
| `project_forbidden`         | Project authorization failed; no connection details returned                                            |
| `ga4_not_connected`         | Project has no GA4 mapping; return the project Integrations URL                                         |
| `ga4_reconnect_required`    | Token minting failed, `invalid_grant`, or Google returned 401; include a reconnect URL                  |
| `ga4_property_inaccessible` | Google returned 403 for the mapped property; keep the mapping and ask a human to reselect or fix access |
| `ga4_report_incompatible`   | Compatibility check or Google 400 rejected a fixed combination; not retryable                           |
| `ga4_quota_exhausted`       | Google 429 or `RESOURCE_EXHAUSTED`; retryable and include a safe retry delay when available             |
| `ga4_upstream_unavailable`  | Google 5xx or network failure; retryable                                                                |
| `ga4_malformed_response`    | A 2xx response failed schema or numeric validation; not retryable                                       |
| `gsc_not_connected`         | Combined tool only; project has no GSC mapping                                                          |
| `gsc_reconnect_required`    | Combined tool only; the mapped GSC grant cannot mint a token                                            |

A 403 is not treated as proof that the OAuth grant is revoked. Adapters return
only allow-listed field names, constraints, and Google reason categories in
`details`; they never pass through a raw upstream body, OAuth credential,
account identifier, or report filter.

### Privacy, retention, and instrumentation

The service copies these GA4 response metadata fields into the success output:
`dataLossFromOtherRow`, `samplingMetadatas`, `schemaRestrictionResponse`,
`emptyReason`, and `subjectToThresholding`. Tests cover each field alone and in
combination. Agent-facing text states that limited rows are unknown, not zero.

OpenSEO does not persist report rows in v1. A later cache needs an approved
retention policy and keys scoped to project, property, normalized request, and
date range. Instrumentation records tool name, project and organization IDs,
duration, outcome, row count, and quota/error category. It does not log raw
rows, event names, page paths, filters, property IDs, connected account data,
or credentials.

## Architecture

Follow the existing application boundary:

```text
SQLite/Postgres repository -> Ga4Service -> server-function and MCP adapters
```

- `Ga4ConnectionRepository` owns mapping persistence and dialect parity.
- A small GA4 REST client owns HTTP, token use, pagination, and Zod validation
  of Admin and Data API responses.
- `Ga4Service` owns grant lookup, property verification, typed errors, fixed
  report builders, date clamps, quota/privacy normalization, URL joins, and
  opportunity scoring.
- Project-scoped TanStack server functions own session/project authorization
  and expose grant status, property listing, selection, and disconnect.
- MCP handlers own annotations, input/output schemas, response formatting, and
  registration. They do not build GA4 requests or query repositories.

The Integrations UI and MCP are consumers of the same service rules. Neither
adapter duplicates property ownership, date, channel, privacy, quota, URL, or
error logic.

## Implementation milestones

Each milestone is a focused change that can merge after its own tests pass.

### 1. Grant and mapping backend

Add shared provider constants, hosted and self-hosted OAuth paths, SQLite and
Postgres schemas/migrations, `Ga4ConnectionRepository`, the Admin API client,
and the connection lifecycle in `Ga4Service`. Verify scope isolation,
refresh-token preservation, property ownership, reconnect, shared-grant
disconnect, and dialect parity. This milestone has no MCP tools.

### 2. Fixed-report service

Add the validated Data API client, fixed request builders, typed rows and
errors, date and row clamps, privacy/quota normalization, and deterministic
fixtures. Unit tests assert the exact `runReport` body for every allowed input
variant. This milestone has no server-function or MCP report adapter.

### 3. Opportunity service

Add host/path normalization, native GSC and GA4 orchestration, coverage and
unmatched-row reporting, the v1 score, tie behavior, and time-zone warnings.
Tests use synthetic GSC and GA4 fixtures and no live API.

### 4. Server-function and UI adapter

Add project-scoped server functions and the Integrations card for grant,
property, reconnect, and disconnect states. The functions call `Ga4Service` and
do not access the repository or Google client directly. This milestone makes
connection management visible but does not claim that MCP tools exist.

### 5. MCP adapter

Register the four tools with read-only, non-destructive annotations, Zod input
and output schemas, no-credit behavior, instrumentation, and text/structured
output agreement. Add authorization and error-mapping tests. The capability is
shipped only when this milestone and its deployment verification are complete.

## Tests and fixtures

The implementation is incomplete without deterministic tests for:

- exact hosted and self-hosted OAuth URLs, callbacks, scopes, encrypted grant
  storage, refresh-token preservation, revoked grants, and independent
  GSC/GA4 accounts;
- paginated discovery, inaccessible properties, selection through the wrong
  connector, reconnect, member-initiated mapping removal, and shared-grant
  disconnect behavior;
- SQLite/Postgres schema parity and one-property-per-project enforcement;
- exact report bodies for each tool and allowed variant, including organic
  filter, order, dates, clamps, limit, offset, `keepEmptyRows: false`, and
  `returnPropertyQuota: true`;
- normal, empty, zero-ecommerce, restricted-revenue, thresholded, sampled,
  other-row-loss, incompatible, 401, 403, 429, 5xx, network, and malformed
  responses;
- MCP project authorization, annotations, no-credit behavior, stable error
  codes, output-schema validation, and text/structured agreement;
- host/path joins across schemes, query strings, fragments, trailing slashes,
  default ports, subdomains, `(not set)`, invalid URLs, and case-sensitive
  paths;
- score components, ties, no-key-event fallback, source truncation, null scores
  for GSC-only rows, GA4 limitation propagation, unmatched rows, and differing
  GSC/GA4 time zones; and
- UI grant/property states and self-hosted missing-API guidance.

Fixtures are minimal recorded-shape JSON owned by the test suite. Property IDs,
domains, emails, tokens, event names, and business data use obvious synthetic
values. Tests never call live Google APIs.

## Non-goals

- GA4 Admin API writes, tag setup, key-event creation, or user access changes.
- A generic dashboard, arbitrary report JSON, realtime reports, funnels,
  audiences, cohorts, BigQuery export, advertising reports, or user-level data.
- Requiring GSC and GA4 to use one Google account or requiring a GA4-to-GSC
  product link.
- Claiming that GSC clicks equal GA4 sessions, or treating their dates as one
  reporting time zone.
- Historical report storage, scheduled imports, cross-project rollups, or
  automatic SEO changes based on the score.
- Presenting this accepted specification as a released integration.

## Consequences

- Existing GSC users must connect Analytics explicitly; no current grant is
  widened or invalidated.
- Self-hosted setup adds two API-enable steps and a second callback URL, but no
  new credential.
- Fixed reports give agents stable contracts and defer arbitrary analytics
  questions.
- The combined tool preserves source provenance and exposes the limits of its
  join and score.
- Acceptance authorizes implementation work. It does not advertise GA4 as an
  available OpenSEO capability.

## References

- [Google Analytics Admin API: `accountSummaries.list`](https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1beta/accountSummaries/list)
- [Google Analytics Admin API: `properties.get`](https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1beta/properties/get)
- [Google Analytics Data API: `runReport`](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport)
- [Google Analytics Data API: `RunReportResponse`](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/RunReportResponse)
- [Google Analytics Data API dimensions and metrics](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema)
- [Google Analytics Data API quotas](https://developers.google.com/analytics/devguides/reporting/data/v1/quotas)
- [Google Analytics Data API: `checkCompatibility`](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/checkCompatibility)
- [Google Analytics Data API: `getMetadata`](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/getMetadata)
- [Google Analytics Data API response metadata](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/ResponseMetaData)
- [Search Console Search Analytics query](https://developers.google.com/webmaster-tools/v1/searchanalytics/query)
- [OpenSEO GSC integration decision](./0003-google-search-console-integration.md)

---

### Maintainers Specs 0008 Local Rank Tracking Locations (`docs/maintainers/specs/0008-local-rank-tracking-locations.md`)

# 0008 — Local Rank Tracking: Location Data & Search

How city/region-level rank tracking stores and searches DataForSEO's location
registry, and why it works the way it does. Shipped July 2026; future
directions are listed at the end.

## The feature

Rank tracking configs take an optional `location_name` — a canonical DataForSEO
location string like `Enid,Oklahoma,United States`. Null means the existing
country-level behavior, unchanged. Uniqueness is enforced by two partial
indexes: one config per (project, domain, country) for national trackers, one
per (project, domain, country, location) for local ones.

When set, the location flows through verbatim:

- **SERP checks** (live and queued task-post) send `location_name` instead of
  `location_code`, so positions reflect what a searcher in that city sees.
  SERP pricing is location-independent, so cost estimates are unchanged.
- **Keyword metrics** come city-scoped: volume / CPC / competition from Google
  Ads `search_volume` (the only DataForSEO source that accepts sub-country
  geotargets), merged per keyword with national KD / intent from Labs (which
  is country-only). This matters: "rv storage near me" is 135K/mo nationally
  but 70/mo in Pittsburgh — a national number on a local tracker overstates
  demand by orders of magnitude. Keywords Google Ads collapses away get
  explicit nulls rather than a leaked national value; the UI column reads
  "Local volume" and exports name the city. Adds ~$0.09 per metrics refresh.
- **The picker** is a debounced combobox in the config modal, searching the
  country's registry and storing the selected canonical name. Local mode
  requires a selection; switching country clears it.

## Location data: how search works

The registry endpoint (`/v3/serp/google/locations/{iso}`) is free but has no
search parameter and returns the full country list per call — 9.5 MB / 60k
entries for the US. Slimmed to the five types users target (City, County,
Municipality, DMA Region, Region) it is ~23k entries / 1.5 MB. The data
changes roughly quarterly (Google geotarget updates).

The search path: combobox (350 ms debounce) → `searchSerpLocations` server fn
→ per-country list from **KV** (`serp-locations:{iso}`, 30-day
`expirationTtl`, hot reads edge-cached with `cacheTtl: 86400`) → substring
filter, top 10. A KV miss triggers the origin fetch + slim + store, with
concurrent cold fills coalesced in-isolate so the prewarm and a fast first
keystroke can't both download the 9.5 MB payload.

Selecting **Local** in the modal fires `prewarmSerpLocations` (a `useQuery`
keyed on country, `staleTime: Infinity`), so the one slow cold fill (~3 s)
usually happens before the first keystroke. Warm searches are tens of ms.

## Why KV

| Alternative                  | Why not                                                                                                                                                  |
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Workers Cache API layer      | Documented no-op on workers.dev (self-hosters), per-colo only, no persistence guarantees. KV's `cacheTtl` provides the same hot-read caching, managed.   |
| R2 (+ cache in front)        | Works (an earlier iteration shipped it) but needs a second layer for read latency; KV is one primitive with the same profile.                            |
| D1 / Postgres table          | Schema + migrations on two providers for quarterly-static reference data; revisit if server-side validation or MCP location search justify a real table. |
| Durable Object per country   | Pins to its first-request region forever; new binding for self-host; buys coordination this read-only data doesn't need.                                 |
| Static assets, client search | Refresh requires redeploy — self-hosters would be pinned to release-time snapshots.                                                                      |
| "Just accept zip codes"      | Doesn't avoid the registry: DataForSEO only accepts canonical values, and zips are registry entries themselves (~32k for the US).                        |

Cost is noise either way: KV bills per operation, so storage for all supported
countries is ~$0.02/month and each search read is fractions of a cent.

## Future directions (not built)

- **Picker quality**: prominence-ranked results (offline GeoNames/Census tier
  table — the registry has no population data, so "Portland" currently ranks
  the Maine DMA above Portland, OR), cities-first with a type filter,
  recently-used/suggested locations (must come from our own config history —
  GSC has no city dimension), and a selection-confirmation line.
- **ZIP fast path**: numeric queries search a separate cached Postal Code
  blob; useful for sub-metro service areas inside large cities.
- **Multi-city fan-out**: multi-select in the picker creating one config per
  city with a shared keyword set — the agency 3–5-metro workflow.
- **Server-side `location_name` validation** at config save, closing the gap
  where a hand-crafted request can store an arbitrary string (fails at
  DataForSEO at cost 0 today, so client-side validation suffices).

---

### Maintainers Specs 0009 Site Audit Crawl Architecture (`docs/maintainers/specs/0009-site-audit-crawl-architecture.md`)

# Site audit crawl architecture

## Status

Accepted

## Context

The site audit runs as a Cloudflare Workflow. The original design kept all
crawl state inside the workflow run: the URL frontier and page summaries lived
in workflow memory and step returns, pages were parsed with a full DOM parser
(cheerio), and link edges were bulk-inserted into the app database during the
crawl. On large or slow sites this collided with platform limits:

- **Isolate memory.** DOM parsing expands a page several times over, multiplied
  by concurrent parses, plus a whole-crawl summaries array that was rebuilt on
  every workflow replay.
- **Step-output cap (~1 MiB).** Sitemap seed lists flowed through step returns
  and could exceed it outright.
- **Step timeout × retry.** The default 10-minute step timeout with default
  retries meant a deterministically failing step burned about an hour before
  the audit died.
- **Batch head-of-line blocking.** Fixed-size crawl batches waited on their
  slowest fetch; one tarpit URL stalled a whole batch.
- **Invisible failure.** Workflow-level kills (OOM, CPU) skip the error
  handler, so audit rows could stay `running` forever with no recorded reason,
  and the UI refused to show the pages that had already been crawled and
  persisted.

## Decision

Split the audit into a control plane and a data plane.

### Orchestration stays in Workflows; crawl state moves to a Durable Object

`SiteAuditWorkflow` remains the orchestrator (phase ordering, durable steps,
retries). All transient crawl state lives in `AuditScratchpad`, a SQLite-backed
Durable Object, one instance per audit (`idFromName(auditId)`):

- **frontier** — URL queue and dedup set (URL primary key), with
  `pending / leased / crawled` states keyed by chunk number;
- **links** — internal link edges, primary-keyed for idempotent re-insert;
- **page_mirror** — the few columns the finalize link checks need.

The app database (D1/Postgres) keeps only what the product reads: `audits`
(plus failure columns), `audit_pages`, `audit_issues`,
`audit_lighthouse_results`. Link edges are never persisted to the app DB; the
cross-page link checks (broken internal links, orphan pages) run as SQL inside
the DO at finalize.

Rejected alternatives: Cloudflare Queues (no dedup, no counters, no completion
signal — a frontier is mostly those things), a Postgres frontier table (chatty
hot-path writes, dual-dialect surface), R2 spill files (not queryable).

### Chunked rolling crawl

The crawl phase is a loop of `crawl-chunk-N` steps. Each chunk leases up to
~200 URLs from the DO and crawls them with a rolling concurrency window: the
moment a fetch settles, the next URL launches. The window self-adjusts between
5 and 40 based on recent fetch health (errors, blocked fetches, slow responses,
oversized bodies shrink it; clean fast batches grow it). A soft deadline ends
the chunk early and releases unfetched leases. Persistence is pipelined with
fetching but serialized with itself: page rows and per-page issues go to the
app DB, link edges and frontier updates go to the DO, and progress counters
update per sub-batch. Step returns carry only counters, so no step output
scales with site size.

Everything is idempotent under step retries: chunk-keyed leases (a retried
step re-receives exactly the URLs its failed attempt held, and refuses a fresh
claim for an already-crawled chunk number), deterministic page-row ids, and
insert-or-ignore/replace writes on stable keys.

### Crawl order and the page limit

A chunk leases pages a link has reached first, oldest first, then pages only
the sitemap lists. Link-found pages go first because a link is what gives a
page its click depth, which the deep-page check reads; a page crawled straight
from the sitemap has none.

Left at that, the order can spend the whole page limit on pages the sitemap
doesn't list. Tag archives and filter pages link to more of themselves, so the
link queue never runs dry and the crawl never gets back to the sitemap. So a
chunk leases pages the sitemap doesn't list only while the limit, after that
chunk, still has room for every sitemap page waiting. Once it doesn't, chunks
lease sitemap pages and the start page until those are done, and unlisted
pages take what is left.

Rejected alternative: always lease sitemap pages before unlisted ones. It gives
the same coverage, but a sitemap page that is only linked from unlisted pages
(an older post behind `/page/2/`) would be crawled before the link that gives
it a depth, on every audit, including the ones that fit the limit.

### Excluded paths

An audit can carry a short list of path patterns to skip, set on the launch
form or the `run_site_audit` tool and stored in the audit's config. A pattern
is matched against a URL's path and query string from the start, with `*` as a
wildcard and a trailing `$` as an end anchor: the semantics of a robots.txt
`Disallow` rule, which is the syntax people who run crawlers already know.

The patterns are applied at the same gate as robots.txt, when a URL would
enter the frontier (the start page, sitemap seeds, links, redirect targets).
An excluded URL is therefore never fetched, never counted against the page
limit, and never becomes a page row. The broken-link check only reports
targets the crawl fetched, so links to excluded URLs are not reported. Orphan
detection is skipped for an audit with excluded paths, the same way it is for
a truncated crawl: links from the skipped pages are unknown, so "no inbound
link" would not be evidence.

Rejected alternatives: regular expressions (easy to get wrong, and user
patterns run against every discovered URL, so backtracking is a cost risk);
crawling excluded pages for their links but hiding them from results (keeps
orphan detection, but the pages would still be fetched and would have to
bypass the page limit); a separate patterns table (the list is a setting of
one audit, read and written whole, like the rest of its config).

### Streaming HTML parsing

Pages are parsed with htmlparser2's streaming tokenizer — no DOM is built, so
per-page memory is constant. cheerio (which uses the same tokenizer
internally) remains only as a test reference: the parser test suite asserts
extraction parity against it, and the badseo fixture harness asserts identical
issue output end to end.

### Failure handling and graceful degradation

- `audits` carries `error_code` (a closed vocabulary mapped from real platform
  error strings — `step_timeout`, `oom`, `cpu_limit`, `db_error`,
  `step_output_too_large`, `workflow_internal`, `instance_lost`, `unknown`),
  `error_detail`, and `failed_phase`.
- A watchdog on the existing `*/15` cron reconciles audit rows stuck in
  `running` against the Workflows API; the audit status read path does the
  same lazily. Only confirmed instance-not-found errors (after a grace period)
  count as a lost instance, so transient API failures never fail a live audit.
- A failed audit shows everything crawled before the failure ("stopped early
  after N pages") instead of hiding results.
- The start URL follows redirects (with per-hop SSRF revalidation) before the
  crawl anchors its origin, so apex→www and cross-TLD redirects don't dead-end
  the crawl after one page.

### DO lifecycle and platform-limit guards

- `destroy()` (delete alarm, then all storage) runs on audit success and on
  audit deletion. Every DO construction schedules a 7-day self-cleanup alarm,
  so any instantiation — including a write racing in after destroy, or a
  workflow that dies before seeding — is eventually wiped. Failed audits keep
  their scratchpad for those 7 days as the resume/debug artifact.
- Guards where the platform has hard edges: link writes stop at a storage
  budget (below the free-plan per-object SQLite cap; orphan detection is
  skipped when the link graph was truncated), discovered-URL batches are
  capped below the serialized-RPC limit, and sitemap documents are read up to
  a byte cap and skipped whole beyond it.

## Consequences

- Workflow heap and step state are O(one chunk) regardless of site size; the
  OOM/step-output failure classes are gone by construction.
- Hostile or slow sites degrade to a slower window and finish (or fail with a
  classified reason and visible partials) instead of burning an hour of
  retries.
- Every failure is aggregable by `error_code` in plain SQL, and zombie
  `running` rows self-heal.
- Crawl-state code is provider-independent (DO SQLite exists in workerd), so
  self-host does not add a dialect surface for the frontier or links.
- The scratchpad is opaque from outside the DO; the 7-day retention of failed
  audits' state is the debugging window.
- Resume-from-frontier ("retry finishes the last N pages instead of
  recrawling") is enabled by the retained frontier but intentionally not
  built yet.

---

### Maintainers Specs 0010 Project Memory (`docs/maintainers/specs/0010-project-memory.md`)

# Project memory (shared AI context per project)

## Status

Accepted

## Context

Qualitative knowledge about a project — what the business does, the current
goal, positioning, writing preferences, competitors, which pages matter — is
scattered across surfaces that cannot see each other:

- **SAM** keeps it in `sam_project_memory`, two free-form markdown blobs
  (`memory`, `research_log`) per project, writable only by the model via
  Think's `set_context`. There is no UI; users cannot see or correct what SAM
  believes.
- **Skills** (Claude Code / Codex users) keep it in a local folder the
  `seo-project-setup` skill scaffolds — a `README.md` with goals, sites, and
  preferences that never reaches the server, so SAM and the app never benefit.
- **Competitors are never persisted anywhere.** `find_serp_competitors`
  results are returned and discarded.
- The onboarding chat agent produces a positioning/themes/keywords strategy
  and persists none of it.

The result: every surface re-interviews the user or re-infers the same facts,
paid research gets repeated because no surface knows another already ran it,
and there is no place a user can inspect or edit what the AI knows about their
project.

## Decision

One project-scoped memory store, shared by SAM, the MCP server, and a new
settings UI. Hybrid shape: a fixed set of typed sections with real schemas,
plus agent-creatable custom sections for anything that doesn't fit yet. It
replaces `sam_project_memory` entirely.

### Data model

List-shaped entities are normalized tables; prose lives in a sections table.
All tables follow the D1 + Postgres dual-schema convention (`src/db/*.schema.ts`
mirrored in `src/db/pg/*.schema.ts`, schema-parity test, `pnpm db:generate`
for both dialects).

```
project_context_sections
  project_id   FK → projects (cascade)
  key          text        -- typed key or "custom:<slug>"
  title        text?       -- custom sections only
  content      text        -- markdown
  updated_at   text
  updated_by   text        -- "user" | "sam" | "mcp"
  PK (project_id, key)

project_competitors
  id, project_id FK (cascade)
  domain       text        -- normalized host, unique per project
  name         text?
  notes        text?       -- "direct competitor, strong on comparison pages"
  updated_at, updated_by
  UNIQUE (project_id, domain)

project_key_pages
  id, project_id FK (cascade)
  url          text        -- unique per project
  role         text        -- "hub" | "spoke" | "money" | "other"
  topic        text?       -- target topic/keyword
  notes        text?
  updated_at, updated_by
  UNIQUE (project_id, url)

project_research_log
  id, project_id FK (cascade)
  entry_date   text        -- YYYY-MM-DD, server-stamped
  summary      text        -- "<what>: <inputs>. Verdict: <conclusion>"
  created_by   text        -- "user" | "sam" | "mcp"
```

Typed section keys: `business_overview` (what the business does, who it's
for, target market/locales), `current_goal`, `positioning`,
`writing_preferences` (voice, banned words/phrases, topics to avoid).

Guardrails: prose sections capped at ~4,000 chars; custom sections capped at
20 per project and ~4,000 chars each; competitors and key pages capped at 100
rows each; research log pruned to 90 days on append. Caps keep the full
context small enough to inject into every SAM turn and return cheaply from
MCP.

**Deliberately not stored:** a sitemap or crawl copy. The page inventory
lives in `audit_pages` (latest audit) and GSC, reachable through existing
tools. `project_key_pages` is a curated shortlist, not an inventory; agents
may propose entries from audit/GSC data.

### MCP tools (two, free, no credits)

- **`get_project_context(projectId)`** — read-only. Returns everything:
  typed sections, competitors, key pages, custom sections, recent research
  log. `text` is a rendered markdown digest; `structuredContent` carries the
  typed data. Empty sections are listed explicitly ("missing: positioning,
  writing_preferences") so agents know what to fill and can suggest
  `seo-project-setup`.
- **`update_project_context(projectId, updates[])`** — an array of patch
  ops, discriminated union:
  - `{ section, content }` — set a typed section (empty string clears)
  - `{ customSection, title?, content }` / `{ deleteCustomSection }`
  - `{ addCompetitors: [{domain, name?, notes?}] }` (upsert by domain),
    `{ removeCompetitors: [domain] }`
  - `{ addKeyPages: [{url, role, topic?, notes?}] }` (upsert by url),
    `{ removeKeyPages: [url] }`
  - `{ appendResearchLog: { summary } }` — server stamps the date;
    `{ removeResearchLog: [id] }`

Both use `withMcpProjectAuth`, standard layering (tool → `ProjectContextService`
→ repository), `readOnlyHint` annotations, deep-link `meta` to the Context
settings page. Writes record `updated_by: "mcp"`. Register in
`src/server/mcp/server.ts` and the hand-maintained catalogue in
`src/client/features/ai-mcp/AvailableTools.tsx`.

### SAM integration

`sam_project_memory` is removed; the `SamChatAgent` block provider seam is
where the swap happens:

- The writable `memory`/`research_log` blocks are replaced by a single
  **read-only** context block rendering `get_project_context` output
  (refreshed after each turn, as today, so cross-session writes land).
- SAM writes through the same adapted `update_project_context` tool that
  MCP clients use (via `adaptMcpTool`, projectId injected), recorded as
  `updated_by: "sam"`. One write path, one validation surface.
- The system prompt keeps its contract but points at the typed sections:
  intake mode triggers when `business_overview` is empty; the bootstrap flow
  (read site, infer, confirm, write) now writes typed sections and
  competitors instead of a prose blob; the 30-day research-staleness rule
  reads `project_research_log`.

**Migration:** none. SAM usage is low, so `sam_project_memory` is dropped
outright (schema removal + drop migration); existing SAM memories are
discarded and SAM re-runs its intake flow on next use.

### UI

Project settings gets a gear button on the project switcher (replacing its
absence from any navigation) and splits into sub-pages:

- **General** — existing name/domain/market form
- **Context** (new) — the memory UI: editable forms for the four prose
  sections, tables with inline add/edit/delete for competitors and key pages,
  cards for custom sections (rename/edit/delete), research log list
  (read-only + delete). Every item shows provenance: "Updated by SAM · 2d
  ago". Edits record `updated_by: "user"`.
- **Integrations** — Search Console + Analytics cards move here

The gear lives on the switcher, so settings is reachable from every view
(including SAM's chat tab); existing deep links
(`#google-analytics`, GSC connect) keep working via redirects to the
Integrations sub-page. Server functions follow the standard
`requireProjectContext` → service → repository path with Zod schemas in
`src/types/schemas/`.

### Skills

Skills reach the store only through the two MCP tools (skills are distributed
by file copy; there is no server-side delivery).

- **`seo-project-setup` rewritten** to be the canonical populate flow: the
  interview steps (site scope, goals, positioning, competitors, key assets)
  now end in `update_project_context` writes instead of a local `README.md`.
  Local-folder scaffolding remains only for file-based work (GSC CSV
  fallback, drafts).
- **Every SEO skill gets a standard "Project context" preamble**:
  1. Call `get_project_context` first; use it to ground the work.
  2. If the sections this skill _requires_ are empty, run a minimal inline
     setup — ask (or infer from the site and confirm) just enough to fill
     them, write them back, then continue the actual task. Suggest the full
     `seo-project-setup` at the end. Never front-load the full interview.
  3. Before paid research, check the research log (30-day staleness rule).
  4. On finish, write back: durable learnings → sections/entities, research
     spend → `appendResearchLog`.

  Required sections per skill: keyword-research → business_overview +
  current_goal; competitive-landscape / competitor-analysis → competitors;
  keyword-clustering → key pages; link-prospecting → positioning +
  competitors; seo-audit → business_overview; seo-coach → reads everything,
  requires nothing. Content-drafting flows additionally require
  writing_preferences.

Hand-maintained lists to update when skills change: `src/routes/_app/ai.tsx`
(`SKILL_NAMES` etc.) and `web/content/docs/skills/*`.

### Rollout

1. **Schema + service + MCP tools** (with the `sam_project_memory` drop) —
   the store exists, Claude Code users can use it end-to-end.
2. **SAM cutover** — block provider swap, prompt update, tool adaptation.
3. **UI** — switcher gear, settings sub-pages, Context page.
4. **Skills pass** — rewrite `seo-project-setup`, add the preamble to the
   SEO skills, update docs pages.

In practice all four phases landed together on one branch.

## Consequences

- One source of truth: SAM, MCP clients, and the UI read and write the same
  records; users can finally inspect and correct agent beliefs, with
  provenance on every item.
- Cross-surface research dedupe: the shared log stops SAM and Claude Code
  from independently re-buying the same research.
- Competitors and key pages become joinable product data — future
  rank-tracker comparisons, share-of-voice, and audit cross-references can
  reference them without parsing prose.
- Typed sections require a code change to extend; the custom-section
  overflow is the pressure valve and tells us which section to promote next.
- Two more MCP tool schemas in every client's token budget (mitigated by
  keeping the patch union compact).
- The onboarding chat agent still discards its strategy output; persisting it
  into these sections is a natural follow-up, out of scope here.

---

### Maintainers Specs 0011 Multi User Organizations (`docs/maintainers/specs/0011-multi-user-organizations.md`)

# 0011 — Multi-user organizations

Decisions behind PR #473 (multi-user organizations). Hosted mode only; self-host
never mounts the organization endpoints and delegated identities resolve as
implicit owners.

## Roles

Better Auth access control with three app statements on top of the built-ins
(`src/lib/org-permissions.ts`):

- `billing:manage` — **owner only** (subscribe, top-up, portal, cancel).
- `project:create/delete` and `integration:manage` (GSC/GA4 connect,
  disconnect) — owner + admin.
- **Every invitee is an admin** (deliberate v1 call, confirmed twice): full
  access to each project except billing. The `member` role is defined in code
  but not invitable — enforced server-side in `beforeCreateInvitation`, which
  also blocks owner-role invites (an owner minting a second owner and leaving
  would re-mint a fresh org + free grant at next sign-in).

Roles are resolved from the member row per request and never baked into
sessions or tokens.

## Membership invariants

- Every user has at least one org once they use the app; org resolution
  (`resolveActiveHostedOrganization`) creates a default organization on demand.
- **Invitations are the only path to multi-org membership**: users cannot
  create additional orgs (`allowUserToCreateOrganization: false`) and cannot
  delete orgs (`disableOrganizationDeletion: true` — deletion cascades all
  data and would re-mint free-plan grants; it stays a support action).
- **Invite sign-ups get no personal organization.** The session-create hook
  (`resolveSignInHostedOrganization`) defers default-organization creation for a
  membership-less user with a pending invitation, so they land in exactly the
  inviter's org. Abandoned/declined invites self-heal: the request path still
  creates a organization on the next app visit. Existing users keep their
  organization and simply gain the new org.
- Active org = `user.lastActiveOrganizationId` (validated against a live
  membership) → newest membership → create default. The column is
  load-bearing for the organization switcher and deliberately NOT a better-auth
  `userAdditionalFields` field (it must not be user-writable via
  `/update-user`).

## Authorization

- Every request re-validates the member row; removing a member revokes access
  on their next request, including MCP credentials (per-request membership
  check in the transport, role stamped per request).
- **MCP credentials are bound to one organization.** An OAuth grant is bound
  to the org active at consent and an API key to the org active when it was
  created; project-scoped tools authorize the project against that org and
  bill it. Losing that membership kills the credential; it is never rebound
  to another org the user belongs to. See
  [0017 — MCP credential scope](./0017-mcp-credential-scope.md).
- Chat (SAM) re-checks membership every turn and fails closed in hosted mode
  when the member row is gone — WebSockets authorize at connect time only,
  so the per-turn check is what revokes a removed member's open socket.

## Invitations

- 7-day expiry; re-invite of a pending address re-mails the same link with a
  refreshed expiry (the Team UI's Resend).
- The invite email is sent by the `sendTeamInvitation` server function, NOT
  better-auth's `sendInvitationEmail` callback — better-auth swallows throws
  from that callback, so a failed send would read as "sent". Send failures
  fail the call visibly; the pending row stays for retry. Consequence: the
  raw `/api/auth/organization/invite-member` endpoint creates pending rows
  but emails nobody.
- Abuse bounds: 20 pending invitations per org (better-auth
  `invitationLimit`) plus KV daily send counters — 5 sends/address, 50/org
  (`src/server/auth/invitation-send-limit.ts`). In-memory rate limiting is a
  per-isolate no-op on Workers; KV is the only counter that holds.
- Accepting works signed-out through sign-up + email verification and back;
  accept sets the active org and skips first-run onboarding (which would
  spend org credits and overwrite the shared project's domain).
- Free-plan audit quota is counted per organization, not per user.

## Accepted residuals

- Onboarding completion is stored per user, so an invitee's later personal
  organization starts empty with no onboarding.
- `resolveHostedContext` runs twice on owner-only Autumn mutations.
- KV send counters race under concurrency — they are abuse bounds, not exact
  quotas.

## Future (explicitly deferred)

- Per-project authorization inside an org (org membership without access to
  every project). The single choke points to extend: `withMcpProjectAuth`
  (MCP) and the canonical project-access path (web). Tracked as EVE-50's
  remaining scope.
- Roles tighter than admin (expose `member`, decide its rank-tracking rights).
- Intentional multi-org creation, org deletion flow, seats.

---

### Maintainers Specs 0012 Dynamic Reports (`docs/maintainers/specs/0012-dynamic-reports.md`)

# Reports (agent-written HTML reports per project)

## Status

Accepted. Shipped in PR #570. Report templates (`specs/0013-report-templates.md`) and public share links (`specs/0014-public-share-links.md`) build on it.

## What it does

- When an agent finishes a workflow such as `seo-audit`, it writes the result as one self-contained HTML page and saves it to the project with the free MCP tool `save_report`. `list_reports` and `get_report` read them back. SAM, the in-app agent, does not get them.
- The project's Reports page lists them. A report page renders the document in a locked-down viewer, with Export (the browser's print dialog), full screen, open in a new tab, and delete.
- Saving with an existing report id replaces the content in place. There is no version history.
- A report can be up to 500 KB. Storage stops at 10,000 reports per project and 5 GB per organization, runaway guards rather than product limits.

## How it works

**Data.** One `reports` table: `id`, `project_id` (cascades from the project), `title`, `summary` (markdown, up to 2,500 characters), `html`, `skill` (the slug that wrote it), `created_by` (a client label such as "Claude Code"), `created_by_user_id`, `size_bytes`, timestamps, plus `template_id`, `share_token` and `shared_at` for the follow-up specs. One index on `(project_id, updated_at, id)` serves the list, newest first.

**Invariants.**

- Every query is scoped by project id. The one lookup by report id alone returns the owning project id, which the caller authorizes before any content is read.
- List queries never select `html`; only the render path reads the document. Worker memory, not storage, is the constraint.
- Attribution is stamped at create time from the session and the request's client identity, never from the model, and never re-stamped on update. Nothing authorizes or bills on the client label.
- The service validates before any write: title and summary length, UTF-8 byte size, and a cheap document-shape check (the HTML contains `<html` and ends with `</html>`), because a model that stops mid-document would otherwise overwrite the previous good report.
- Titles are unique within a project. The count cap is a guardrail, not a strict invariant: parallel saves can briefly exceed it, and the next save refuses.
- Error messages read as instructions, because agents see them verbatim.

**Rendering.** The stored document is served byte for byte on the app's own origin behind sign-in and project membership. The response carries a Content Security Policy with a `sandbox` directive, so the document has an opaque origin whether framed or opened as a top-level tab: no cookies, no storage, no session cookie on anything it issues. `default-src 'none'` blocks scripts, fetches, forms and external resources; inline styles and `data:` images and fonts are allowed. The only sandbox tokens granted let links open a new tab, with the opener severed so the popup cannot navigate the reader's tab. The in-app viewer is an iframe whose `sandbox` attribute carries exactly the header's token list; `allow-same-origin` is never added, because with scripts it lets a frame remove its own sandbox and alone it hands the frame the app's cookies. Print mode is hash-authorized: the one script the app ever appends is an attribute-free tag allowed by its hash, so the report's own scripts stay blocked.

Not signed in bounces to sign-in and back. An unknown report and another organization's report get the same 404. A report in an archived project answers 404 naming the project, since the viewer is already a member.

**Skills.** A new public skill, `seo-report`, owns the save rules (list first, reuse the id when redoing the same job, reply with the link and a verdict rather than the report), the writing rules (no external resources, no scripts, no backticks or `${` because some clients pass HTML through a template literal), and the single starter template with inline CSS and one light look on screen and paper. The seven workflow skills deliver through it.

Both self-host modes get reports with no new binding or store. Erasing a user re-attributes their reports and revokes links on them; deleting a project cascades. Saves, deletes and opens are counted in telemetry.

## Alternatives considered

- HTML in object storage instead of a text column: a second store that can half-fail on every update and a second thing to erase, for documents of tens of kilobytes.
- Immutable snapshots instead of update in place: more rows, a "which one is current" rule and a UI to browse them, for a deliverable agents redo rather than revise. The shape check is the price of update in place.
- Credits per report instead of free with caps: reports only touch the app database. The caps bound the one free surface that stores large blobs.
- Per-skill templates instead of one starter: one template gives every skill one thing to keep good.
- Allowing scripts in v1: blocking is the one-way door in the safe direction. Reports saved without scripts keep working after a later flip; the reverse is not true.
- A nonce instead of a hash for the print script: the tag is spliced into a document the app did not parse, and a dangling tag in the report could absorb the nonce.
- An injected print banner: the document it warns about could hide or fake it with CSS.
- Server-side PDF: the report is a real document with its own print CSS, so the browser prints it.
- A separate report domain: covered in `specs/0014-public-share-links.md`.

## Not in scope

Server-side PDF, version history, scheduled reports and email, `updated_by` attribution, list search and filters, keyset paging, a chunked save path.

## Later

Interactive charts via `allow-scripts` without `allow-same-origin`: the frame stays origin-less, so a chart can run but has no cookies, storage or network.

---

### Maintainers Specs 0013 Report Templates (`docs/maintainers/specs/0013-report-templates.md`)

# Report templates (reusable report briefs per project)

## Status

Accepted. Shipped in PR #615, on top of reports (`specs/0012-dynamic-reports.md`).

## What it does

- A template is a reusable brief for a kind of report: who it is for, which sections it has and in what order, how it sounds, how it signs off, and an accent color. It is instructions, not a document; the agent still writes the HTML from the `seo-report` starter.
- Templates belong to a project, up to 10 each. The Templates page, reached from Reports, holds the table, the form and delete.
- Agents see a project's templates in project context and follow one when the user names it or asks for the kind of report it describes. A plain skill run keeps the skill's own format.
- Two free MCP tools, `list_report_templates` and `save_report_template` (create or update); SAM, the in-app agent, does not get them. `save_report` accepts an optional template id, and the reports list shows the template name as the report's type.

## How it works

**Data.** One `report_templates` table: `id`, `project_id` (cascades from the project), `name` (up to 80 characters, unique per project), `description` (one line, up to 200 characters), `instructions` (markdown, up to 3,000 characters), `created_by`, `created_by_user_id`, timestamps. The uniqueness check is case-insensitive in the service, with the unique index as the backstop, because "use the monthly check-in template" must never be ambiguous.

`reports.template_id` is nullable with no foreign key: deleting a template neither deletes nor blocks the reports written from it, and the name is resolved by a project-scoped read that shows nothing for a dangling id.

**Invariants.**

- Every template query is scoped by project id, including updates, deletes, the template check on `save_report` and the name resolution on the reports list. A template id from another project reads exactly like a deleted one.
- Reuse across projects is a copy, not a shared row: list the template in one project, save it in the other.
- A template replaces the section list, audience and tone. It never changes the HTML constraints, so the report still prints and still opens on a phone.

**Discovery.** The project-context digest that every skill reads first, and that SAM sees every turn, gains a "Report templates" section listing name and description, omitted when there are none. The `seo-report` skill carries the opt-in rule. The starter CSS gains an accent variable used by bar fills, the plan numbers and the "Do this" box; a template may set that, the byline and the footer, and nothing else in the CSS.

Template saves are counted in telemetry. Erasing a user re-attributes the templates they created.

## Alternatives considered

- A prose list of templates in project context instead of a table: custom sections are free text, so renames and caps would be policed by hand, and a caller could not address a template by id. What that option got right, discovery in the context agents already read, is kept.
- Organization-wide templates as a scope on the row: built, then removed. It needed a cross-scope name rule, an immutable scope, a who-can-edit rule and two caps, for a reuse case that copying already covers.
- Stored starter HTML per template instead of instructions only: a second thing to keep in sync with the skill's starter, for a benefit the accent, byline and footer hooks already deliver.
- A foreign key on `reports.template_id`: it would delete or block reports when their template goes.
- A delete tool: the app page owns deletion, and an agent has no reason to remove a brief the user wrote.
- A default template applied without asking: it would silently change every report a skill produces.

## Not in scope

Organization-wide templates, a template picker in the app, a default template, stored starter HTML, deleting templates from an agent.

## Later

Seeing every template across the organization and cloning one into a project. Stored starter HTML would arrive as an additive column.

---

### Maintainers Specs 0014 Public Share Links (`docs/maintainers/specs/0014-public-share-links.md`)

# Public share links for reports

## Status

Accepted. Shipped in PR #616 on top of reports (`specs/0012-dynamic-reports.md`); the edge cache followed in PR #620.

## What it does

- A report gets a Share button with a "Public link" toggle. On, anyone with the link can open the report without signing in. Off, the link stops working. Sharing again mints a new link, so an old one never comes back.
- The link always shows the latest saved version and is hidden from search engines.
- The public page lives on the app domain and looks like a shared document: a slim bar with the title, "Made with OpenSEO", a Share button and a "Try OpenSEO" button, with the report filling the rest of the screen in the same sandboxed frame the in-app viewer uses.
- Sharing is hosted-only. A self-hosted deployment sits behind Cloudflare Access or has no auth at all, and neither can serve a link to a reader who is not signed in, so the Share button is not rendered and the server refuses the mint.

## How it works

**Data.** Two columns on `reports`: `share_token` (nullable, unique) and `shared_at`. The token is 192 random bits as 32 base64url characters, stored as-is; it is a capability, and revoking it means nulling it. Sharing mints, unsharing nulls, and content saves never touch either column.

**Public page** at `/s/<token>`: a hand-written HTML document the worker serves, not a route in the app, with no auth guard, `noindex`, and Open Graph tags from the title and the summary's first line. The bar, the frame and the preview tags are all in the first response, and the page ships no JavaScript beyond the Share button's clipboard handler. The reader is usually someone who has never opened OpenSEO, and the app's root shell renders only on the client, so a page inside it would have cost them the whole app bundle before the frame existed. The summary is markdown and the preview does not try to render it: a stray `##` costs less than a stripper that eats the minus sign off a number.

**Raw endpoint** at `/s/<token>/raw` serves the stored HTML with the same sandbox policy as the in-app route, `frame-ancestors 'self'` and a noindex header. The raw document only renders inside the frame: a request whose fetch destination is not an iframe is redirected to the wrapped page, and a client that sends no destination header is served the document, since it cannot load the wrapper's frame either. A token of the wrong shape is answered before any query.

**Edge cache.** The raw response is cacheable at the edge for 60 seconds and never in the browser, so revoking a link stops new readers within a minute. A request carrying a query string is redirected to the bare path before any lookup, so the cache key cannot be varied.

**States.** Unknown, unshared or deleted: one "not shared" page with a 404 status, so tokens cannot be probed. Archived project: 404 with the archived message; restoring the project brings the link back.

**One gate.** The mint, the public page and the raw endpoint ask the same question — is this a hosted deployment — so they cannot disagree. A self-hosted deployment is behind Cloudflare Access or has no auth at all, and neither can serve a link to a reader who is not signed in, so there sharing is refused with an ordinary validation error and every share path answers as if the link never existed.

**Sandbox facts**, checked in the three major engines: meta refresh, `javascript:` and `data:` navigations, form submission and a `<meta>` policy that adds scripts are all refused, and the origin is opaque. A clicked link only replaces the frame's content; links that open a new tab do so with the opener severed.

Shares, unshares and public views are counted in telemetry, the last with a hashed token and the user agent so link-preview bots can be excluded. Erasing a user revokes the links on the reports they created; deleting a report or project kills the link by cascade.

## Alternatives considered

- An `is_public` boolean instead of a token: the URL would be the report id, so an old link would resurrect on re-share.
- Signed URLs: expiry and signing keys for links meant to stay live until revoked, and revocation would still need a database read.
- A separate shares table: a report has at most one public link, so a table adds a join for nothing.
- Raw HTML at top level on the app hostname: one abusive account could get the hostname flagged. Wrapping every shared document in our chrome is what makes the app domain the right place.
- A separate registrable domain: overkill once the document is wrapped in our chrome.
- Sharing under the no-auth self-host mode, with a dedicated error code explaining the Cloudflare Access refusal: one hosted-only check reads better than two modes and an error code that existed for one sentence.
- ETag revalidation: a revalidation answered before the token lookup would make revocation advisory.
- Print on the public page: a cancelled print dialog leaves a bare report open top-level on the app domain. Members print from the app.
- An agent-facing share tool: sharing is a human decision made on the report page.
- A per-organization cap and a rate limit: deferred until abuse shows up.
- Edge caching: deferred out of the first PR, then added as the 60-second cache above once the query-string redirect closed the cache-key hole.
- A React route for the public page: shipped first and replaced once measured. The frame could not mount until the app bundle had loaded and hydrated, so a first-time reader waited on hundreds of kilobytes of JavaScript that a two-button bar does not need.

## Not in scope

An agent-facing share tool, a per-organization cap, rate limiting, an abuse-report link, view counts in the app, per-report preview images, embedding on third-party sites, passwords or expiry on links, indexable reports, a separate share domain.

## Later

Interactive reports are the one flip spec 0012 describes: `allow-scripts` without `allow-same-origin`, so a chart can run but has no cookies, storage or network. It is a one-way door: reports saved with scripts stop working if it is turned off again.

---

### Maintainers Specs 0015 Website Dashboard (`docs/maintainers/specs/0015-website-dashboard.md`)

# Website dashboard

The dashboard is the home for monitoring the current project's website. Research pages remain available for investigating other websites and exploring larger datasets.

## Views

The dashboard has addressable Overview, Keywords and Backlinks tabs. Opening a tab mounts its detail view; inactive views do not fetch their data. Rank tracking remains in its existing workflow and is omitted from the dashboard.

Overview shows the setup checklist until every step is done and nothing is saved for later. The checklist describes the workspace, not one project: a step done on any project counts on every project. The competitor and keyword steps complete the first time the workspace runs a domain overview or keyword research, from the research pages or an agent. An audit of any project completes the audit step, and the Site health card still offers a scan for a project without one. The agent step completes when an agent connects. Once an agent is connected, a skills step appears to point people to OpenSEO skills — opening a prefilled chat in ChatGPT or Claude when that web chat is connected, with a copyable prompt fallback otherwise. A skill-generated report on any project completes the skills step, and dismissing it also marks it complete. A skip applies to that person on every project in the workspace. The competitor, keyword, audit and agent steps can be skipped for now: they wait under "saved for later" until restored. Dismissing the skills, teammate or projects step marks it complete. The agent card above the checklist is separate from the agent step: dismissing the card hides only the card, for that person on every project in the workspace, and skipping the step leaves the card. Dismissals made before the two were split still hide both. The checklist appears only on Overview.

Hiding the checklist after a fixed time, or for everyone who uses an agent, was considered. Both would hide it from people who still have steps left. Because agent research now completes the research steps, neither is needed.

Overview includes new search queries and recent link activity. New referring domains take precedence over new backlinks. When the provider reports no new domains, the card shows new backlinks; when neither exists, it offers a path to the full backlink view. Domain discovery dates identify newly observed referring sites, rather than assuming every recently discovered link comes from a new domain.

Keywords uses Search Console for New keywords, Top keywords and Striking distance. Top keywords sorts by clicks. Striking distance shows query/page pairs at average positions 5–20, sorted by impressions. A link opens full GSC Insights for deeper exploration. New keywords have at least ten impressions in seven completed days and no observations in the preceding 28 days. When the baseline reaches its row limit, each candidate is checked directly against the earlier period. The new view examines up to 25 candidates from the first 25,000 recent queries. Top keywords shows up to 25,000 queries from the last 28 days. The views display Google's average position over the relevant period, rather than a live rank. Keyword tables support text and metric filters, sorting and pagination. Google can omit some queries, so these views do not promise exhaustive coverage. Search Console results are saved and reused between visits. Paid provider snapshots remain available through research workflows.

Backlinks displays recently discovered links, recently checked lost links, and the latest live links, with up to 25 referring domains per view. Text, link type, domain rank and spam score filters refine loaded results. Date semantics and source details are available through an information popover.

Saving a website in the app starts its first 50-page audit with JavaScript rendering, subject to the account's audit capacity and rendering credits. Concurrent saves share one startup attempt. Existing audits are not restarted on later saves. A failed startup preserves the website and tells the user why the scan could not start. The overview Site health card links to Site Audit and shows the latest saved audit matching the project website, progress while running, and a manual scan action when no audit exists. Dashboard visits do not start audits.

The unconnected Google Analytics card first asks whether the user uses GA4. Yes opens the existing connection flow. No permanently dismisses the optional card for that project and suggests using another analytics provider's MCP with their agent. Connecting GA4 later restores the data card.

## Refresh behavior

Provider usage draws from the customer's credits. Link activity, backlink detail views and Search Console keyword views refresh after 24 hours. Refreshes happen on visits, with empty results cached too. Failed refreshes preserve saved data and delay another attempt. Concurrent refresh attempts share a claim. The overview does not request backlink totals.

Client and server cache identities include the relevant site, market or connected property. Changing project settings must not show a previous site's results as current.

## Alternatives

Fetching every view on entry would improve immediate tab switching but spend credits on data the customer never opens. Loading paid detail views on demand keeps the first visit lighter. Free Search Console discovery remains visible on Overview.

Scheduled refreshes would provide updates while customers are away. Visit-triggered refreshes fit this version because inactive projects do not need background updates. Alerts and scheduled digests can be evaluated separately.

Provider keyword snapshots alone cannot reliably identify newly acquired keywords. Search Console comparison gives stronger first-party evidence; source popovers acknowledge both datasets' limits.

A manual first audit would avoid starting work for an unintended site, but delay the first useful result. Automatically scanning a newly saved website shortens that wait. JavaScript rendering makes the initial scan useful for sites whose content depends on scripts.

A complete replacement of audit and performance workflows would duplicate existing capabilities. The dashboard reuses their data and offers direct paths to the full tools.

---

### Maintainers Specs 0016 Indexnow (`docs/maintainers/specs/0016-indexnow.md`)

# IndexNow

IndexNow lets a site tell search engines which of its pages were added, changed, redirected or removed, so they recrawl those pages sooner. Bing, Yandex, Seznam, Naver, Yep and other participants share every submission with each other. Google does not use IndexNow.

## How it works

Each project has one IndexNow key: 32 random hexadecimal characters, created the first time someone sets up IndexNow or submits URLs. The key proves ownership only when the site hosts it, at `https://{host}/{key}.txt` with the key as the file's only content, so it is not secret and is stored as plain text. A key is created only when the project has none, so concurrent first uses cannot leave the site hosting a key that was replaced.

Submissions accept up to 10,000 URLs, the protocol's per-request limit. URLs on the project's domain or any of its subdomains are grouped by host and sent in one request per host. Other URLs are skipped and reported. The project must have a website.

Before submitting for a host, OpenSEO fetches that host's key file. A missing file, a page served in its place, or a redirect stops the submission for that host with instructions to fix the file. Engines expect the file on the exact host, without redirects, so `www.` and the bare domain each need their own copy. Bot protection, server errors and timeouts make the check inconclusive, and the submission goes ahead.

Submissions go to Bing's endpoint first, so status codes come from the largest participant. Any engine shares an accepted submission with the others, so when Bing rate-limits, has a server error or doesn't respond, the same request goes to Yandex and then Yep. Some engines rate-limit requests from shared hosting networks regardless of the site. A rejected key or bad request is reported without trying another engine, since every engine would reject it the same way. Engines answer 202 while a new key is unverified, which is why the key file is checked first. Results are reported per host as submitted or failed, with a message naming the cause or noting that the key is still being verified.

Submitting is free. Any member of the organization can set up the key and submit, as with other project research actions.

## Surfaces

- **Settings → Integrations** has an IndexNow card. It explains which engines participate, creates the key, offers the key file for download, and checks the file on the bare domain and its `www.` host, with a status for each. A host that redirects to the same file on the other host, or doesn't load, has no pages to submit and is left out. Once every remaining host serves the file, the setup instructions collapse. The card accepts a list of URLs to submit and suggests asking a connected agent to submit pages, or to add the key file when it can edit the site's code.
- **MCP**: `submit_indexnow_urls` submits URLs for a project and creates the key on first use. When a key file is missing, the result names the file and its contents, so an agent with access to the site's code can add it and try again.

## Alternatives

Automatic submission of pages a site audit found changed would save users a step, but audits are run on demand, and a wrong change diff would send unchanged pages to every engine. A "submit these pages" action on audit results was left out for the same reason: it would encourage resubmitting the whole site. Both can be revisited with change detection.

Letting users reuse a key they already host, for example from a WordPress plugin, would avoid a second file. Engines accept several keys per host, so the generated key works alongside an existing one.

Sending each submission to every engine would not depend on sharing, but the protocol asks sites to submit to one engine because participants share, and duplicates add load for no gain. Trying engines in order sends one request in the usual case.

A submission history would show what was sent and when. Bing Webmaster Tools already reports what IndexNow received, so v1 shows only the latest result.

Hosting the key at a `keyLocation` outside the root would help site builders that cannot serve root files. The protocol limits such a key to URLs in its own directory, so it does not cover a site's pages.

---

### Maintainers Specs 0017 Credit Auto Reload (`docs/maintainers/specs/0017-credit-auto-reload.md`)

# Credit auto-reload

## Status

Accepted.

## Context

Hosted organizations get monthly usage credits with their plan and can buy top-up credits that never expire (see [hosted metering](0002-hosted-dataforseo-metering-with-autumn.md)). Every purchase goes through Stripe Checkout. An organization that runs out mid-task stops: rank checks are refused, agents report insufficient credits, and someone with the billing role has to notice, open Billing and buy credits by hand.

Customers asked to buy credits automatically, with a cap on how much that can cost them in a month.

## Decision

Billing managers on a paid plan can turn on auto-reload on the Billing page, under the one-off purchase. It has two whole-dollar settings: the amount each reload buys, and a monthly budget, the most the organization spends on top-up credits in a billing cycle. The threshold that triggers a reload is fixed at $5 of top-up credits.

Autumn holds both settings as billing controls on the customer's `topup_credits` balance and enforces them itself. The reload is an `auto_topups` control: after every deduction from or refused check on the top-up balance, Autumn compares the remaining balance with the threshold and, when at or below it, charges the organization's saved card for the reload amount through the existing one-off `credit-top-up` price, adding the credits to the top-up balance. The budget is a `usage_limits` control: a hard cap on top-up credits spent per month, aligned to the billing cycle. Autumn refuses the hold that would take the cycle's spend past it, with credits still in the balance, and counts open holds against it. The budget counts every top-up credit spent, including credits bought by hand, and is in force only while auto-reload is on.

Autumn refuses the hold that would exceed the budget while credits remain, so the spend rarely lands on the limit itself; the app treats the budget as spent once less than the threshold, the largest single hold, is left of it. When the budget is spent, top-up credits are paused until the budget is raised or the cycle resets. The Billing page shows the cycle's spend against the budget and, once it is spent, a notice with a one-click raise; the banner, the insufficient-credits error, the chat agent and the MCP tools say the same and point at Billing. Raising the budget keeps the cycle's count, so the organization carries on from where it stopped. A one-off purchase does not lift the pause, so the page holds the purchase button while the budget is spent and says why.

Turning auto-reload on buys the first reload immediately, before the controls are written, when the organization has never bought a top-up, or when its top-up balance is already at or below the threshold and auto-reload is off or its last reload failed. The server decides this from the customer and the page reads the same decision, so the button says so before the click. A balance above the threshold never buys now, which also means a second click after a charge that landed cannot charge again. Changing the settings while auto-reload already runs leaves the next purchase to Autumn. Turning it off is one click, needs no paid plan, and lifts the budget with it. The cycle's spend is kept while it is off, so turning it back on under a budget that spend has reached is refused, and the page says what budget would do.

Monthly plan credits are still spent first and top-up credits after, so the threshold is in practice a floor on the total balance once the monthly credits are gone, and a spent budget only stops work once they are gone too.

A paid plan that ends turns auto-reload off: the billing webhook that records the plan change disables the controls for a customer who no longer holds the paid entitlement.

When a reload cannot be charged, Autumn reports why through a webhook. The reason is recorded on the Autumn customer so the Billing page, the out-of-credits banner and the insufficient-credits error can say what happened: a declined card points at the billing portal and a retry, anything else at support. Billing managers get an email for card problems. A successful reload, or a successful retry from the page, clears the notice. Autumn's own waits between attempts are not failures.

## Rationale

The budget caps what is spent rather than what is bought. That is the number customers have in mind and the way other prepaid products present it: a monthly spending cap next to the reload, with the card charged only as credits are spent. A cap on purchases makes the customer reason in reloads, and the window Autumn keeps for it is a rolling month from the first reload rather than the billing cycle; the budget resets with the cycle and reads as one number. It bounds the card as well: a cycle's reloads cannot exceed the budget by more than one reload, the one that can land as the budget is reached.

The budget counts credits bought by hand too. A budget on reloaded credits alone would need every deduction to tell the two apart, which Autumn's limit cannot do, and a customer at their budget who wants to spend more says so by raising it.

The first reload is bought by the app rather than left to Autumn because Autumn prices a reload from the organization's own top-up purchase, which an organization that never bought credits does not have, and because Autumn otherwise buys only when a deduction or a refused check crosses the threshold, so the first attempt after enabling would fail before the credits arrived. Buying first also leaves the balance above the threshold, so Autumn's own enable-time purchase does not double up. The same purchase is the retry after a failed reload: a successful charge is what lifts Autumn's pause on a card that kept declining.

The threshold is fixed and below the smallest amount. A user-set threshold is a question most customers cannot answer, and one at or above the amount would make every reload trigger the next. $5 covers the largest single hold a call takes; a larger one is refused and succeeds after smaller usage brings the balance down.

The budget is capped at $1,000 a month because reloads are charged off-session, without Stripe Checkout's confirmation; the budget is what bounds what a stolen card can cost. A purchase-count limit stays on the reload control as a backstop, at twice the reloads a cycle's budget can need plus one, which the budget keeps out of reach.

The failure notice lives in the Autumn customer's metadata because the billing page already reads that customer on every page load and Autumn is the source of truth for the controls it describes; a table of our own would add a second read and a migration for one flag.

## Alternatives considered

- **A cap on purchases.** A monthly limit on how many reloads Autumn may buy, which is what some API platforms offer. It bounds the card directly, but customers would have to think in reloads, the limit would be a multiple of the reload amount, its window is a rolling month, and credits bought by hand would fall outside it. Rejected for the budget on spend.
- **A budget on reloaded credits only.** Would let hand-bought credits spend freely under a spent budget. Autumn's limit counts all spend on the balance, and separating the two would put the budget back in the app on every deduction.
- **Post-paid overage.** Price top-up credits as overage on the plan's invoice with a spend limit, as some developer tools do. One number and no balance to watch, but it extends credit for real provider costs, so a declined card after a month of use is a loss, and it needs a new plan version. Rejected while the plan is $10 a month.
- **A user-set threshold.** Lets an agency keep a larger floor for big batches, but it is a question most customers cannot answer, and one at or above the reload amount would chain reloads.
- **Recurring top-up subscription.** Buys the same amount every month whether or not it is needed. Auto-reload buys only when the balance is low.
- **Reloading from inside the metered call path.** The app could buy credits when a hold is refused and retry. It would duplicate Autumn's purchase counting and put a card charge on the hot path of every DataForSEO call.

## Consequences

- Autumn's own trigger covers the reloads and its usage limit the budget; the app turns them on and off, primes the first purchase, reads the state back and handles the webhooks. No catalog change and no schema change.
- The budget resets with the billing cycle, so the page shows the monthly credits' refill date as the reset. Spend from before the budget was created does not count, and nothing counts while auto-reload is off.
- A hold refused by the budget comes back with the balance still showing credits. The metering code reads a positive balance that refuses as the budget, refuses the batch without retrying it smaller, and says so in the error; the chat gate refuses on it without the stale-balance confirmation it does for an empty balance.
- The first call refused after the monthly credits run out can still fail while Autumn's purchase is in flight; the next call succeeds. The threshold is what keeps that rare.
- A reload can land as the budget is reached, when the balance is at the threshold. Those credits wait for the next cycle or a raised budget; they never expire.
- Research priced after the fact (LLM usage) is admitted on the balance before it runs. If the budget is reached during such a run, the part of that run's top-up deduction past the budget is not deducted; Autumn stops deducting there. Bounded to one run.
- Repeated card declines make Autumn pause reloads until a payment method succeeds. The notice on the Billing page points at the billing portal and offers the retry.

---

### Maintainers Specs 0017 Mcp Credential Scope (`docs/maintainers/specs/0017-mcp-credential-scope.md`)

# 0017 — MCP credential scope

Every hosted MCP credential is bound to exactly one organization: the one the
user was working in when the credential was created. Self-host deployments and
the in-app agent already worked this way; this record makes the hosted OAuth
and API-key paths match.

## What a credential is bound to

A credential carries the user and one organization id. On every `/mcp` request
the server requires a live membership for that user in that organization and
stamps the member row's role into the request; roles are never stored on a
token or key. Tools that take a `projectId` authorize the project against the
bound organization, and billing goes to that organization.

## How credentials bind

- **OAuth grants.** Accepting the consent page binds the grant to the active
  organization. For people who belong to more than one, the page names it and
  offers a switcher; switching there is the same as switching in the app, so
  the app follows. Everyone else has only one and sees no label. The same id
  is kept in the grant metadata so Settings can show which workspace each
  connected agent reaches.
- **API keys.** Creating a key binds it, server-side, to the session's active
  organization after confirming the user is a member there. The key's
  organization is stored with the key; the client cannot choose it.

Keys that predate this binding were assigned the organization the runtime
would have resolved for them at the time (the user's last-active organization
if still a member, otherwise the one joined most recently). A key with no
organization is refused.

## Membership removal and revocation

- Removing a user from an organization kills every credential bound to it on
  the next request: OAuth grants answer 401 with a Bearer challenge so a
  compliant client re-authorizes, and the new grant binds to whichever
  organization is active at that consent; API keys answer 403.
- Settings lists the user's connected agents (one entry per OAuth grant) with
  a Disconnect action. Disconnecting deletes the grant and every access token
  issued under it, so the client's next call fails and it must authorize
  again. API keys are revoked from the same Settings page as before.

## Alternatives considered

- **User-scoped credentials** (the model this replaces): one credential worked
  across every organization the user belongs to, including ones joined later,
  with the organization derived per call from the project. Rejected because the
  consent page reads as access to one workspace, and a later invitation to
  another organization silently widened what an already-connected agent could
  reach.
- **A per-key organization picker.** Rejected: multi-organization membership
  is rare (invitations are the only way in), and the picker adds UI for a case
  the active organization already answers. Switching organizations and
  creating a key there covers it.

---

### Maintainers Specs 0018 Docker Self Hosting (`docs/maintainers/specs/0018-docker-self-hosting.md`)

# Docker self-hosting

OpenSEO is written for Cloudflare Workers: D1, KV, R2, Durable Objects, Workflows and cron. Docker self-hosting runs that same code, unchanged, on a prebuilt image instead of rebuilding the app and running Cloudflare's local development server inside a container.

## How it works

The image (`deploy/standalone/Dockerfile`, published as `ghcr.io/every-app/open-seo-standalone`) contains the compiled app and [celld](https://github.com/denoland/celld), an open-source runtime for Workers code. celld provides D1 and Durable Objects on SQLite, KV, R2, Workflows and cron, and keeps their state in an S3-compatible bucket. `vite build --mode standalone` produces a single server module, because celld loads one module per deployment, and `scripts/celld/package.mjs` packages it with its assets and migrations.

The Compose stack (`deploy/standalone/compose.yaml`) runs:

- `runtime`: celld with the app.
- `storage`: RustFS, the S3-compatible store for celld's state.
- `init`: runs once at each start. It generates the secrets on the first start, writes the deployment configuration, loads the app, applies database migrations and writes Nginx's site config.
- `crawl-gateway`: the proxy every outbound crawl goes through. It resolves each target, rejects private and reserved addresses, and pins the connection to the address it checked, including on redirects.
- `web`: Nginx, the only published service. It blocks the operator endpoints from outside the stack.

The Compose file reads nothing else from the repository, so Compose-based platforms can run it on its own; `compose.build.yaml` adds the build for people running their own changes.

Sign-in is chosen at the first start with `AUTH_MODE`. `password` gives Better Auth accounts with none of the hosted service's billing, email or telemetry. Registration is open only for the first account and for addresses with a pending invitation. `local_noauth` runs without sign-in as one admin, as the original Docker image did. The server tells the client which mode is running, so one image serves both. Operator commands (create a user, reset a password, claim the old admin) go through an endpoint that requires a secret generated at the first start.

The original single-container image (`deploy/docker/`, `ghcr.io/every-app/open-seo`) keeps being published from the same workflow. Existing installations auto-update from its `:latest` tag and could not run a multi-container stack or read its storage, so the new image never takes that name. That image shows a notice that links to the migration. The `migrate` service in `compose.migrate.yaml` reads the old volume with Miniflare and imports it once into an unused database. It carries projects, keywords, rank history, audits, reports and SAM conversations, and leaves out sessions, API keys, OAuth grants, Google connections and caches.

## Alternatives

Rewriting the server for Node with a job queue and a separate actor system would have removed the Workers dependency, at the cost of a second implementation of every background feature that would drift from the hosted one. celld runs the hosted code as it is.

Keeping the original image and only skipping its startup build would have left Cloudflare's local development server, which is not built for long-running use, as the production runtime.

A separate repository for the Docker edition was planned, carrying its own changes to the app. Keeping one codebase and choosing behavior by `AUTH_MODE` avoids a fork that conflicts with every change to main.

MinIO's community images stopped being published in September 2026. Garage accepts but does not enforce conditional writes, which celld relies on. RustFS passes celld's storage checks.

---

### Maintainers Specs 0019 Mcp Guest Accounts (`docs/maintainers/specs/0019-mcp-guest-accounts.md`)

# Guest accounts for MCP connections

When someone adds OpenSEO to an AI app (Claude, ChatGPT, Claude Code, Cursor) and the browser that opens has no OpenSEO session, they get a guest account instead of a sign-up form. The window closes on its own and the agent can use OpenSEO right away. The person creates a real account only when they want something a guest can't have.

## How it works

The MCP authorize step checks whether the browser qualifies for a guest. If it does, the browser goes to a short "Connecting OpenSEO" page instead of the sign-in page. That page passes Cloudflare Turnstile and asks the server for a guest. The server runs every check again, creates the guest, approves the connection, and sends the browser back to the AI app. When a check fails, the person lands on the normal sign-in page. A browser that already has an OpenSEO session still sees the consent screen, because approving a real account without a click would let any app take it over silently.

A guest is a user with a placeholder email on a reserved domain that can never receive mail, plus its own organization. The organization starts on the free plan like any new account, so a guest has the same free credits. Email sends skip the placeholder address.

A browser qualifies when:

- the deployment is the hosted app, and the kill switch (a feature flag) is off;
- the authorization code goes to a known AI chat app or back to the person's own computer (a loopback address or an app's own URL scheme). Without a click, any other destination would let a website send its visitors through our authorize URL and collect a free account from each one;
- the request doesn't come from a large cloud or hosting provider's network;
- the browser has never signed in to a real account. A sign-in leaves a long-lived cookie, so someone whose session lapsed gets the sign-in page instead of an empty guest workspace;
- the IP address has made fewer than two guests, ever. Only a keyed hash of the address is stored.

## Becoming a real account

A guest can't add credits, connect Google Search Console or Google Analytics, or use the web app. When the agent hits one of those (the out-of-credits error, `whoami`, a Search Console connect link), the response gives a sign-up link and says to open it in the browser that connected OpenSEO. The server instructions also tell the agent it's working with a guest.

The connecting page leaves a claim cookie in the browser, holding a random token that names the guest. At the next sign-up or sign-in from that browser, before the default organization would be created, the guest's organization moves to the signing-in user, the claim is recorded, and the guest user is deleted. A new user ends up with exactly the guest's organization, projects and remaining credits, not a second empty one with fresh free credits. An existing user gains it as another organization but stays in their own, which holds their plan; a new user opens the guest's. A link into the guest's organization, such as an audit the agent ran, opens that organization, as any link to a project in another of the user's organizations does. The billing customer's email switches to the real account's address.

The agent's connection keeps working. Its token still names the guest, and each MCP request from a claimed guest's token acts as the account that claimed it, in the same organization. That connection appears under the account's connected agents, where it can be revoked, and deleting the account revokes it. The per-IP record outlives the claim, so claiming doesn't free a guest slot.

Only the connecting page sets the claim cookie. Because a claim hands over the agent's connection, a claim must come from the browser that connected the agent: a claim link that anyone could send would let its sender's agent act as whoever opened it. The cost is that someone who connects on one device and signs up on another doesn't bring the guest's work along; they start a fresh account and reconnect. On a shared computer, the next person to sign in within the cookie's 30 days claims the guest; the guest was made in that browser, and the connection can be revoked.

## Alternatives

- **No sign-in for some tools (lazy authentication).** Claude supports serving some tools anonymously and asking for sign-in only for others. Calls from Claude's web and desktop apps come from Anthropic's servers, so an anonymous call can't be tied to a person or a credit balance; the only option would be one shared pool anyone could drain.
- **A guest button on the sign-in page.** Still one click and a decision in a window people want to close. The automatic version removes both, and the "Already have an account? Sign in" link stays on the connecting page.
- **Better Auth's anonymous plugin.** It creates anonymous sessions in the browser and links them at sign-up. Guests here never need a browser session, and the plugin's public sign-in endpoint would have needed the same checks bolted on. The claim cookie gives the same handover with less surface.
- **A claim link.** An earlier version handed the agent a link carrying the claim token, which set the cookie in whatever browser opened it. It covered people who sign up on another device, but once a claim also hands over the agent's connection, a link someone else sends is a way into the opener's account.
- **Asking the person to reconnect after a claim.** Deleting the guest's token is simpler, but the person has to find the connector in their AI app's settings and connect again, and the agent fails until they do.
- **Moving the guest's projects into the user's own organization.** Projects, connections and billing hang off the organization in many tables, so moving the membership is far simpler and keeps the credits where they were spent.

---

### Maintainers Specs 0020 Self Serve Plan Upgrades (`docs/maintainers/specs/0020-self-serve-plan-upgrades.md`)

# Self-serve plan upgrades

## Status

Accepted.

## Context

Hosted organizations subscribe to a monthly plan that grants usage credits each month (see [hosted metering](0002-hosted-dataforseo-metering-with-autumn.md)). Checkout sells a plan to an organization on the free plan, but a paying organization had no way to move to a bigger plan in the app: the Billing page opened the Stripe portal, and a pricing-page plan link told them to email support.

A plan sells credits, not time, so the usual mid-cycle change does not fit. Autumn's default upgrade charges the price difference for the rest of the cycle and grants the new plan's whole monthly allowance at once. An upgrade the day before renewal then buys a month of the bigger plan's credits for a day's price. A downgrade has the mirror problem: spend the bigger plan's credits, then move down and pay the smaller plan's price.

## Decision

A billing manager on a monthly plan can upgrade to a pricier tier (Base to Pro or Agency, Pro to Agency) from the plan picker. Billing's "Change plan" button and pricing-page plan links open it. Moving to a cheaper plan, moving to a yearly plan, changing a yearly plan and changing a plan granted by hand stay with support. The picker marks the current plan and offers "Email us to switch" for the rest. Checkout sells the yearly plans only to an organization without a plan, so under the picker's Yearly switch each plan opens a dialog that points to support.

An upgrade is prorated by credits instead of days:

- It starts a new monthly cycle today, at the new plan's full price, charged to the saved card.
- There is no refund for the old plan's unused days.
- The credits left from the old plan carry over, and last until the new cycle's first refill.
- Top-up credits are not touched.

The confirm step shows Autumn's preview of the charge, the credits the organization will have, and the renewal date and price. The upgrade is an Autumn attach with the billing cycle anchored to now, proration turned off and the monthly credit balance carried over. Autumn keeps carried-over credits until the old plan's refill date, so the app moves them to the new refill date right after the charge. The charge has landed by then, so if that last step fails it is reported and the upgrade still succeeds; the credits then end at the old date.

The server decides whether an organization can upgrade and builds every Autumn request from fixed plan IDs. An organization whose last payment failed updates its card first. Checkout refuses a tier plan to an organization that already pays, so Autumn's default proration cannot be reached that way.

## Rationale

Every dollar charged buys credits at the new plan's rate, and nothing already paid for is lost, so the timing of an upgrade gains nothing. Restarting the cycle also gives the customer one date to read: everything they have lasts until the renewal the confirm step shows.

Carrying credits over instead of refunding unused days is the credit-based version of proration. A refund for unused days would also pay back a cycle whose credits were already spent.

Downgrades stay manual because their abuse case has no clean credit-based answer. Few customers need them, and support can settle each one.

## Alternatives considered

- **Autumn's default proration.** Charges the rest of the month's difference and grants the full allowance. Rejected: a late-cycle upgrade buys a month of credits for a few days' price.
- **Charge the difference, keep the renewal date.** Charge the full-month price difference now and subtract the credits already used from the new allowance. It is fair, but an upgrade late in the cycle buys credits that reset days later, and our Autumn SDK does not offer that proration mode.
- **Refund unused days and drop the old credits.** The common SaaS model. It pays back days whose credits may already be spent, and loses credits the customer paid for.
- **Leave carried-over credits on the old refill date.** One Autumn call fewer, but the confirm step would need two dates, and credits could lapse days after an upgrade.

## Consequences

- The renewal date and the monthly refill move to the day of the upgrade.
- The Billing page reads the plan's monthly credits from that plan's own grant, since the balance also holds carried-over credits until the refill.
- When the bank asks the customer to confirm the charge, the app sends them to Autumn's payment page; the carried-over credits then keep the old refill date.
- Lifecycle emails stay silent on a change between paid plans; referral sales count the upgrade's invoice like any other.

---

### Maintainers Specs 0021 Stripe Projects Provider (`docs/maintainers/specs/0021-stripe-projects-provider.md`)

# Stripe Projects provider

[Stripe Projects](https://projects.dev) lets a developer or coding agent run `stripe projects add <provider>/<service>` to create an account with a provider, provision a resource, and get its credentials written to `.env`. OpenSEO is a provider with one service, `openseo/api`: an OpenSEO account plus an MCP API key. It runs on OpenSEO Cloud only.

## How it works

Stripe calls OpenSEO over the Agentic Provisioning Protocol (version `0.1d`). The Stripe App manifest (`deploy/stripe-app/stripe-app.json`) points Stripe at `https://app.openseo.so/api/stripe-projects/`, and `src/server/stripe-projects/` serves:

- `provisioning/health` and `provisioning/services`, the catalog. It lists one free deployable service, `api`.
- `provisioning/account_requests`. Stripe sends the developer's email, what it has verified about them, and their Stripe account id. The rule is the one Google sign-in follows. Unless Stripe lists `email` in `kyc.verified_fields`, the request is refused with `requires_kyc`. An existing OpenSEO account that never confirmed its own email is refused too. Otherwise OpenSEO creates a verified user and default organization for a new email, or reuses the existing account and organization. It answers with a five-minute, single-use authorization code.
- `oauth/token`. Stripe exchanges the code (with PKCE when it sent a challenge, otherwise with its signature) for an access token and a rotating refresh token. The token response says `payment_credentials: "provider"`: OpenSEO bills its own plans, so Stripe sends no payment tokens.
- `provisioning/resources` create, read, `rotate_credentials` and `remove`. A resource is one MCP API key in the organization, returned as `access_configuration.key` with the MCP URL. Each provision gets its own resource and key. Rotate mints the replacement before deleting the old key. Remove deletes the resource and its key, and keeps the account, its data and its credits. A bearer only reaches resources created by its own user, in its organization, for its Stripe account.
- `provisioning/deep_links`. `stripe projects open openseo` gets a ten-minute, single-use link to `/stripe-projects/login`. That page names the account and asks before signing in; its button posts the token to a Better Auth endpoint that creates the session and lands the user in the provisioned organization.

Every request carries `Stripe-Signature` (HMAC-SHA256 over the timestamp and raw body, the scheme Stripe uses for webhooks) and `API-Version`. Resource and deep-link calls also need the bearer from the token exchange, and the user's membership in the organization is re-checked on each one. Bearers and refresh tokens are stored only as SHA-256 hashes in `stripe_projects_grant`; `stripe_projects_resource` maps each resource to its current API key. Codes and login links are short-lived rows in Better Auth's verification store, keyed by the token's hash and consumed atomically. The endpoints return 404 unless the signing secret is configured, and do not exist outside hosted mode.

Keys are ordinary organization-bound MCP API keys: they show up under Settings → API keys and can be revoked there. Each Stripe account linked to an organization also appears as a Stripe Projects row under Settings → Connected agents. Disconnecting it deletes Stripe's tokens, so it can't mint new keys, and removes every resource it provisioned, so its keys stop working. Accounts created through Stripe go through the same user-creation hooks as any sign-up, including the disposable-email check and the starter credit grant. Provisioning counts as accepting OpenSEO's terms under Stripe's developer terms.

## Alternatives

Charging paid plans through Stripe's shared payment tokens would let an agent upgrade with `stripe projects upgrade`. A token can only be charged through a PaymentIntent, never saved as a card for a subscription, and Autumn has no way to charge one. OpenSEO would have had to run renewals, failures and downgrades itself next to Autumn. Plans and top-ups stay on the billing page until Stripe's recurring-token billing can feed the existing subscription path.

An existing account could be linked only after the user confirms in a browser, as Supabase and Sentry do. Stripe verifies every Stripe Projects email, its provider guide recommends headless linking when the email is verified, and the browser-confirm half of the protocol isn't published. OpenSEO links silently when the email is verified. It refuses unverified emails outright, for new accounts too: an account created for an address the requester doesn't own would leave them holding a key and a grant into it after the real owner signs in. A request with no `kyc` block counts as unverified.

A separate organization for Stripe-provisioned access, as Firecrawl does, would keep Stripe and card billing apart. OpenSEO has one billing path, so the key goes into the account's existing organization and no second free-credit grant is created.

The dashboard link could have been a plain URL to the sign-in page. Accounts created through Stripe have no password, so the one-time link is the only way in that needs no Google account or password reset.

The link could have signed the visitor in as soon as it was opened. Then anyone with a Stripe Projects account could send someone a link into their own account, and a link preview would use the link up. The confirm page costs one click.

Codes and login links could have had their own table. Better Auth's verification store already holds short-lived single-use values, clears expired rows, and consumes them atomically.

Better Auth's `account` table could have held the Stripe link. It has no organization, and its token columns hold tokens a provider issued to OpenSEO, not ones OpenSEO issued.

Better Auth's magic-link and one-time-token plugins could have minted the login link. Magic link adds a public endpoint that emails and creates accounts; one-time tokens need a session to exist before the link is opened.

---

### Maintainers Specs 0022 Embed Links (`docs/maintainers/specs/0022-embed-links.md`)

# Embed links

## Status

Accepted. Builds on public share links (`specs/0014-public-share-links.md`) and the MCP App widgets.

## What it does

- Owners and admins (the roles that manage integrations) turn on a project's embed link in Project settings → Integrations. One switch covers the project. A view picker (Overview, Rank Tracking, Search Console) builds the URL to copy: the overview has every widget, the others one widget each. A new embeddable view is one more option in the picker.
- The pages are live and read-only. Viewers can switch trackers and devices, sort, page, change Search Console views and refresh. Nothing they do changes the project or spends credits.
- Any site can frame the pages. Agencies frame them from their own white-label domains, so there is no allowlist to keep.
- Turning the switch off revokes every URL; turning it on again mints a new token. The link also stops answering when its creator leaves the organization or can no longer manage integrations, and erasing the creator deletes it.
- Like share links, embed links need a deployment with its own accounts, so they are refused under Cloudflare Access and no-auth self-hosting.

## How it works

**One widget layer, two hosts.** A widget is a tool's structured result drawn by the widget bundle that MCP clients already load as an MCP App: the same React components, the app's own UI kit and stylesheet, and the app's own table columns where a feature has them (the rank tracker reuses the app's rank columns in a read-only mode). Widgets talk to a small host interface: the current snapshot (tool, arguments, structured result), a way to call the tool again with new arguments, and a way to open links. An MCP client's conversation is one host. An embed link is the other: the page carries the token and the list of widgets, and each widget's calls go to the link's data endpoint. Conversation-only actions, such as saving keywords or sending a selection to the assistant, exist only on the conversation host, so the shared widgets hide them on embeds.

**Data.** One `project_embeds` row per project: the project (primary key, cascades), the token (unique), the creator (cascades from the user) and a timestamp. The token is minted like a share token. Revoking deletes the row.

**Public routes.** `/e/<token>` and `/e/<token>/<widget>` serve the widget bundle's document with the page config inlined and a policy that allows any frame ancestor, the bundle's one script by nonce, and connections to the app only. `/e/<token>/data` takes a tool call and runs the MCP tool itself, as the creator, in the link's project: the project id in the request is replaced, and only the tools the embed widgets use are accepted. Both are read-only tools that use no credits. Every dead end (bad token shape, unknown or revoked token, archived project, creator gone, embeds unavailable) answers the same 404, which a framing dashboard shows as a plain message. Data calls are rate limited per token, because Search Console calls spend the project's Google quota.

## Alternatives considered

- A server-rendered page per widget, like the share page: a second rendering of data the app and the MCP widgets already draw, and a third set of layouts to keep in step.
- Framing the signed-in app: every app page refuses framing to prevent clickjacking, session cookies are SameSite=Lax and blocked in third-party frames by Safari, and Google sign-in refuses to load in a frame.
- Letting share links be framed: a report is a snapshot an agent wrote, so it can't refresh, and the request was for live data.
- Native GoHighLevel widgets by writing data into GoHighLevel custom objects: a per-sub-account OAuth integration and sync job, and its dashboard charts only count, sum and average, which can't show a keyword's position over time.
- A GoHighLevel marketplace app with SSO: worth it only for one-click install or knowing who is viewing; its custom pages are iframes too, so it could serve these same pages later.
- Listing every embed URL on the settings page: the list grows with each view. A picker shows one URL at a time, as analytics tools' embed builders do.
- An Embed button on each page: most users never embed, so it would be noise in every header.
- A token per view, or several named links per project: more to manage and revoke, for no access difference while a project is one client.
- A per-dashboard frame-ancestors allowlist: each agency's white-label domain differs, and a read-only page has no action to protect.
- Running link calls under a synthetic identity instead of the creator: the creator's membership is what ties a public link to someone who can still see the project.

## Not in scope

Starting rank checks or any other paid call from an embed, more than one link per project, per-widget links that differ in access, branding controls, view counts, a GoHighLevel marketplace listing, and showing the rank tracker widget in MCP clients (it needs only a `show_` tool now that the widget exists).

---

### Web Content Docs Agent Setup (`web/content/docs/agent-setup.mdx`)

---
title: "Agent setup"
description: "Connect your AI agent to OpenSEO and keep its SEO skills up to date."
---

OpenSEO connects your agent to live SEO data through MCP. Skills give it reusable workflows for keyword research, audits, competitor research, and other SEO tasks.

The OpenSEO plugins include the skills. Connectors and MCP connections don't. [Install skills](/docs/skills/setup) shows how to check what your agent has and how to add them.

## Claude and ChatGPT

Add OpenSEO from their directories and sign in with your OpenSEO account. You don't need the setup prompt or a terminal.

<AddToAgentButtons />

- **Claude:** add the [OpenSEO connector](https://claude.ai/directory/connectors/openseo). It gives Claude OpenSEO's tools on the web, desktop and mobile. For Claude Code, Claude Cowork and the SEO skills, see the [Claude guide](/docs/claude-code-plugin).
- **ChatGPT:** install the [OpenSEO plugin for ChatGPT](https://chatgpt.com/plugins/plugin_asdk_app_6abddd2c7e4c819191f1398c4bd8e9b3). It adds OpenSEO's tools and SEO skills on chatgpt.com and in the desktop app. The [ChatGPT setup guide](/docs/chatgpt) has the install steps and a custom connection for accounts without the plugin. If you paste the setup prompt below into a regular ChatGPT chat, it sends you to the plugin.

## Set up your agent

Copy this prompt into Claude Code, Claude Cowork, Codex, Grok Bot, Hermes, or another agent. It asks your agent to use its supported installation method and guide you through any steps you need to do yourself.

<AgentPrompt kind="setup" />

Approve the OpenSEO sign-in in your browser when prompted. Once setup is complete, ask your agent to use **SEO Coach** to help you choose what to do next.

You can also copy this prompt from [Agent setup in OpenSEO](https://app.openseo.so/ai). For a self-hosted instance, use its Agent setup page so the prompt includes your own server address.

Prefer to set it up yourself? Follow the instructions for your agent below. If the setup prompt already completed installation, skip to [Update your skills](#update-your-skills).

### Claude Code

Run inside Claude Code to install MCP and the public SEO skills:

```text
/plugin marketplace add every-app/open-seo
/plugin install openseo@openseo
```

If Claude asks you to activate the plugin, run `/reload-plugins`. Follow the sign-in prompt, then try `/openseo:seo-coach`. See the [Claude Code plugin guide](/docs/claude-code-plugin) for troubleshooting.

### Claude Cowork

Install the OpenSEO plugin from **Customize → Plugins → Add marketplace → Add from a repository** with `https://github.com/every-app/open-seo`. It adds MCP and the public SEO skills. See the [Claude Cowork steps](/docs/claude-code-plugin#install-in-claude-cowork) for details and the Free plan option.

### Codex in the ChatGPT desktop app

Open **Codex**, start a new chat, and paste the setup prompt above. Approve the OpenSEO sign-in when prompted, then start a new chat if Codex needs to load the tools. Ask: “Use OpenSEO to check my connection and list my projects.” This check uses no OpenSEO credits.

For manual setup, follow the [Codex plugin guide](/docs/codex-plugin#desktop-app). Check [OpenAI's current plan support](https://learn.chatgpt.com/docs/pricing) for Codex access. A local Codex install does not connect chatgpt.com.

### Codex CLI

Run in your terminal:

```bash
codex plugin marketplace add every-app/open-seo
codex plugin add openseo@openseo
```

Reload or restart Codex if the plugin is not available yet, then sign in:

```bash
codex mcp login openseo
```

Ask Codex to use SEO Coach. See the [Codex plugin guide](/docs/codex-plugin) for troubleshooting. For plugins installed through a desktop directory, use that directory's controls.

### Hermes

Use the setup prompt above to connect MCP. To install SEO Coach through the Hermes skills hub, run in your terminal:

```bash
hermes skills install every-app/open-seo/plugins/openseo/skills/seo-coach
```

Repeat with the names of other [OpenSEO skills](/docs/skills) you want. Hub installations retain their source so Hermes can check for updates later. See [Hermes skill management](https://hermes-agent.nousresearch.com/docs/user-guide/features/skills).

### Grok Bot

Paste the setup prompt into your Bot. Open **Marketplace** in the sidebar to manage packaged skills and connectors. Find private skills under **Your plugins → Manage plugins and skills → Private skills**. Private skills are shared across your Bots.

Follow the Bot's instructions for any steps you need to complete yourself. See [Grok Bot skills](https://docs.x.ai/grok-bot/skills-routines-and-automations).

### Claude web and other agents

Follow the [MCP connection guide](/docs/mcp), then install skills through your agent's supported skill manager. Claude manages custom skills under **Customize → Skills**. On a paid Claude plan, the [OpenSEO plugin](/docs/claude-code-plugin#install-in-claude-cowork) installs both in one step.

For agents using the skills CLI, choose public OpenSEO skills interactively:

```bash
npx skills add https://github.com/every-app/open-seo/tree/main/plugins/openseo/skills
```

Choose the current agent and your preferred installation scope. Skip this if the OpenSEO plugin already supplies your skills. See [manual skill setup](/docs/skills/setup) for other options.

## Update your skills

For ChatGPT, use the [plugin or custom connection update steps](/docs/chatgpt#update-openseo). A custom MCP connection has no bundled skill files to update.

When OpenSEO releases improved skills, update the copies installed in your agent. Updating the MCP connection alone does not update those files.

Paste this prompt into the agent where you use OpenSEO. It asks the agent to check how the skills were installed and preserve your connection settings and personal edits.

<AgentPrompt kind="update" />

To update manually, use the method that matches your installation below.

### Update the Claude Code plugin

Run inside Claude Code:

```text
/plugin marketplace update openseo
/plugin update openseo@openseo
/reload-plugins
```

You can enable automatic updates in `/plugin` → **Marketplaces** → **openseo** → **Enable auto-update**. Third-party marketplaces have this off by default. Reload when Claude prompts you to activate an update. See [Claude's plugin update documentation](https://code.claude.com/docs/en/discover-plugins#configure-auto-updates).

### Update the Codex CLI plugin

Run in your terminal:

```bash
codex plugin marketplace upgrade openseo
```

Reload or restart Codex if the updated skills are not available. If your CLI rejects a command, check `codex plugin --help` for the commands supported by your version. See [OpenAI's marketplace documentation](https://developers.openai.com/plugins/build/plugins).

### Update Hermes hub skills

Check for updates, then update each installed OpenSEO skill by name. For example:

```bash
hermes skills check
hermes skills update seo-coach
```

Repeat for your other installed OpenSEO skills. Hermes skips locally edited skills by default. Review those edits before replacing them; only add `--force` if you want to discard them. See [Hermes's update lifecycle](https://hermes-agent.nousresearch.com/docs/user-guide/features/skills#update-lifecycle).

### Update skills installed with the skills CLI

List your installations, then update the OpenSEO skills by name. For example:

```bash
npx skills list
npx skills update seo-coach seo-audit
```

Use the names you actually installed and choose the same project or global scope. Pass `-g` for global skills or `-p` for project skills. Back up personal edits before updating. Run the setup command to select any newly added workflows separately. See the [skills CLI documentation](https://github.com/vercel-labs/skills#skills-update).

### Update Grok Bot or manually copied skills

Use the update prompt above. For Grok Bot, open **Marketplace → Your plugins → Manage plugins and skills** to find the installed skill or plugin. Its public documentation does not currently specify an upstream skill-update command, so use the management controls available in your version.

For manually copied skills, compare your installed copies with the [public OpenSEO skill folders](https://github.com/every-app/open-seo/tree/main/plugins/openseo/skills). Preserve personal edits and replace the complete skill folder, including supporting files. Use your agent's skill manager for uploaded skills, such as Claude's **Customize → Skills**.

After updating, reload the skills or start a new session if needed. Ask the agent to confirm it can find the updated OpenSEO skills before starting your next SEO task.

---

### Web Content Docs Ai Visibility (`web/content/docs/ai-visibility.md`)

---
title: "AI Visibility"
description: "Research prompts, compare AI answers, and track brand mentions and citations."
---

AI Visibility helps you choose questions to track and see whether AI answers mention your brand, cite your website, or include competitors.

## Set up your project

Add your website, then complete the setup shown on the AI visibility pages. Research fills missing project context and generates keywords; existing context and competitors are preserved. Generating keywords does not automatically run paid prompt research for each one.

## Research, explore, and track

- **Prompt Research:** analyze a keyword to find the questions people ask about it, with ChatGPT's answers and cited sources. Research currently covers US English. The questions come from DataForSEO's dataset, built mostly from Google "People also ask" questions; they are not logged ChatGPT prompts, and OpenSEO does not estimate how often they are asked in AI. The Relevant keywords list is yours to change: select **Edit** to add, reword, or remove keywords. Topics you track stay on the list.
- **Prompt Explorer:** try one prompt in ChatGPT, or add Claude, Gemini, and Perplexity to compare answers and available citations. These are API model answers and can differ from consumer-site answers collected by tracking.
- **Prompt Tracking:** save exact questions under topics, select engines and a market, then run a check or enable daily, weekly, or monthly tracking. Editing a question's wording starts a new question, so earlier answers keep the wording they were collected for. ChatGPT and Gemini are selected by default; Google AI Overviews, Google AI Mode, Claude, and Perplexity are also supported. Enabling tracking starts an initial check.
- **Competitors and Citations:** open these tabs in Prompt Tracking to review saved brand mentions, competitor appearances, and cited pages. Competitors come from shared Project context. Your brand counts as mentioned when its name or domain appears in an answer, and as cited when the answer links to your site. A Google AI Mode answer is saved with its product cards, so the product name and store on a card count too, and a site it links to in its text counts as cited. The name comes from **Brand name** in project context, or from the project name when that's blank, so you can name a project anything. A project still named "Default" goes by its domain, so `acme.com` and "Acme" both count. A new brand name applies from the next check. A failed check is not evidence that your brand was absent.

The trend chart includes manual and scheduled checks, using the latest finished run per day. Review and export saved results without using credits.

## Credits and cost

Prompt research costs about $0.25 in credits per keyword. Explorer charges actual usage for uncached answers. Tracking shows a cost estimate before a check or schedule is started and bills each check as it collects answers. Run now collects live answers, which usually arrive within a minute and cost more per answer than scheduled checks. Checks stop when your credits run out.

Tracking collects ChatGPT and Gemini answers from their consumer sites. Claude and Perplexity have no consumer-site collection, so every check, scheduled or Run now, asks their model API at live API pricing, which costs more per answer.

On hosted OpenSEO, Prompt Research and Prompt Explorer require the paid plan; prompt tracking only needs credits. Setup research uses available credits and is billed after completion.

Self-hosted users pay providers directly: set `DATAFORSEO_API_KEY` for research and answer collection, and `OPENROUTER_API_KEY` for setup research, Prompt Research, and generated prompt suggestions. See the [self-hosting guides](/docs/self-hosting).

## Use your assistant

Connect [OpenSEO MCP](/docs/mcp) to research prompts, configure tracking and read saved results from your assistant. For a one-off answer, ask the assistant to use `explore_prompt`; it defaults to ChatGPT.

Use [AI Prompt Research](/docs/skills/ai-prompt-research) to find questions before tracking, or [AI Visibility Audit](/docs/skills/ai-visibility-audit) to investigate improvements using answers and cited pages.

---

### Web Content Docs Billing (`web/content/docs/billing.md`)

---
title: "Plans, credits and billing"
description: "What each plan includes, what uses credits, and how to manage top-ups, plan changes and invoices on hosted OpenSEO."
---

Hosted OpenSEO has a monthly plan that includes credits. Looking up new SEO data spends those credits. The app shows credits in dollars, so $1 of credits buys $1 of usage. For current prices and a usage estimator, see [Pricing](/pricing).

## Plans

| Plan   | Price      | Credits included                       |
| ------ | ---------- | -------------------------------------- |
| Free   | $0         | $0.50 when you sign up; doesn't refill |
| Base   | $10/month  | $10 each month                         |
| Pro    | $30/month  | $36 each month                         |
| Agency | $100/month | $120 each month                        |

Signing up needs no card. A paid plan adds:

- Rank checks. On the free plan you can set up trackers, but checks don't run until you upgrade.
- Prompt Research, Prompt Explorer and Brand Lookup.
- Site audits of up to 10,000 pages, instead of 50.
- Buying extra credits and auto-reload.

Yearly plans cost the same as 10 months. Choose Yearly when you subscribe. To move a monthly plan to yearly, write to [support@openseo.so](mailto:support@openseo.so).

## What uses credits

Credits pay for new data you look up. Each lookup costs what the data costs OpenSEO plus 28%.

**Uses credits:**

- Keyword research, SERPs, domain overviews and backlinks
- [Rank checks](/docs/rank-tracking)
- [AI visibility](/docs/ai-visibility) research, prompt answers and tracking checks
- Local SEO searches and rank grids
- Lighthouse and JavaScript rendering in [site audits](/docs/site-audits)

**Uses no credits:**

- Projects, project context and saved keywords
- Saved results, exports and [reports](/docs/reports)
- [Search Console and Google Analytics](/docs/google-integrations) data
- Site audit crawls without Lighthouse or rendering

Running the same lookup again soon after is free, because the result is reused within the same project. Keyword research and Prompt Research results are reused for 24 hours, SERPs and domain data for 12 hours, backlinks for 6 hours, and Prompt Explorer answers for 7 days.

Features that can run up a bill show the cost first. Rank tracking and AI visibility tracking show an "up to" estimate before you start a check or a schedule, and a rendered audit shows its maximum cost on the form.

## When you run out

Your plan's monthly credits are spent first, then any extra credits you bought. When both run out, actions that need credits stop with "You don't have enough credits for this." Scheduled rank checks and AI visibility checks are skipped until you have credits again. Nothing you've saved is deleted.

To keep going, upgrade from the free plan, buy credits, or wait for your plan to refill on its renewal date.

## Buy credits and auto-reload

On the **Billing** page, click **Buy credits** to buy $10 to $99 of credits at a time. Bought credits never expire. The credits included with your plan reset each billing cycle and don't roll over.

**Auto-reload** buys credits for you when your bought credits fall to $5. Choose how much to add each time ($10 to $99) and a monthly budget (up to $1,000). The budget includes credits you buy by hand. If your bought credits are already low, turning auto-reload on buys credits straight away.

## Manage your plan

Open **Billing** from the menu under your email at the bottom of the sidebar. Only the organization's owner can change the plan or buy credits; teammates see the Usage tab. See [Teams](/docs/teams).

- **Upgrade:** click **Change plan**, then **Upgrade** on the plan you want. You pay the new plan's full price today, and your billing cycle starts over. Credits you haven't used carry over until the new plan renews.
- **Downgrade:** choose **Email us to switch** on the cheaper plan.
- **Cancel or change your card:** click **Manage subscription** to open the Stripe billing portal. After you cancel, your plan stays active until the end of the period you paid for.
- **Failed payment:** OpenSEO emails you a link to a **Fix your payment** page. Nothing is turned off straight away. Click **Open billing portal** to update your card.

## Usage and invoices

- **Usage** shows what your organization spent in the last 30 days, by day, by feature and by project.
- **Invoices** lists your last 12 invoices with a **PDF** download for each. Older invoices are in **Manage subscription**. Turn on **Email me a receipt for each invoice** to have Stripe email a receipt to your billing email after each payment.

Checkout asks for your company name, tax ID and billing address so they appear on invoices. To correct them on an invoice, email [support@openseo.so](mailto:support@openseo.so).

## Refunds

Subscriptions have a 30-day money-back guarantee: email [support@openseo.so](mailto:support@openseo.so) within 30 days of the charge. The guarantee doesn't cover bought credits.

If a check or audit failed and still used credits, email support with the project, what you ran and when it ran.

## Self-hosting

Self-hosted OpenSEO has no plan, no credits and no Billing page. You pay DataForSEO directly for SEO data, and OpenRouter for AI features if you use them. See [Self-hosting](/docs/self-hosting).

---

### Web Content Docs Chatgpt (`web/content/docs/chatgpt.md`)

---
title: "Use OpenSEO with ChatGPT"
description: "Install the OpenSEO plugin in ChatGPT, or add a custom connection, and check that it works."
---

Install the [OpenSEO plugin for ChatGPT](https://chatgpt.com/plugins/plugin_asdk_app_6abddd2c7e4c819191f1398c4bd8e9b3) to use OpenSEO on chatgpt.com and in the ChatGPT desktop app. It adds the OpenSEO tools and SEO skills, and you sign in with your OpenSEO account.

If you paste the setup prompt into a regular ChatGPT chat, it sends you to the plugin. ChatGPT cannot install it by itself.

## Choose your setup path

| Where you want to work                   | How to connect                                                     |
| ---------------------------------------- | ------------------------------------------------------------------ |
| ChatGPT on the web or in the desktop app | [Install the OpenSEO plugin](#install-the-openseo-plugin)          |
| Plugin unavailable, or self-hosted       | [Add a custom connection](#custom-connection)                      |
| Codex in the ChatGPT desktop app         | [Paste the agent setup prompt in Codex](#codex-in-the-desktop-app) |

OpenSEO billing is separate from your ChatGPT subscription. See [OpenAI's plan support](https://learn.chatgpt.com/docs/pricing) for Codex access.

## Install the OpenSEO plugin

1. Open the [OpenSEO plugin in ChatGPT](https://chatgpt.com/plugins/plugin_asdk_app_6abddd2c7e4c819191f1398c4bd8e9b3).
2. Select **Install plugin**, then sign in to OpenSEO in the window that opens and approve the connection. No account yet? Create one from that sign-in page.
3. Start a **new chat**. Type `@` and select OpenSEO, or open the **+** menu and choose OpenSEO.
4. Send the [connection check](#check-that-openseo-is-connected) below.

You do not need an OpenSEO API key. The plugin connects to hosted OpenSEO.

## Custom connection

Use a custom connection if the plugin isn't available for your account, or to connect a self-hosted instance. It works on ChatGPT Free and paid plans. It gives ChatGPT the OpenSEO tools but not the SEO skills. To use it in the ChatGPT desktop app, add it on chatgpt.com first.

1. Sign in to [chatgpt.com](https://chatgpt.com).
2. If your version shows it, open **Settings → Security and login** and enable **Developer mode**. Some versions expose the custom connection flow directly in Plugins.
3. Open **Plugins**, select **+**, then **Create MCP App**. In versions with the older interface, look for **Settings → Apps → Advanced settings → Developer mode**, then **Create** or **Add custom app**.
4. Enter these details:

   | Field          | Value                        |
   | -------------- | ---------------------------- |
   | Name           | `OpenSEO`                    |
   | Server URL     | `https://app.openseo.so/mcp` |
   | Authentication | `OAuth`                      |

   Type the full URL, including `https://`. These settings apply to hosted OpenSEO. For a self-hosted instance, use a publicly reachable HTTPS endpoint with authentication supported by ChatGPT; localhost URLs cannot work from ChatGPT web. Follow the [self-hosting guide](/docs/self-hosting) or use a local Codex connection instead.

5. Review the custom connection notice and create the connection. Sign in to OpenSEO in the window that opens and approve the connection. Return to ChatGPT. If the new plugin needs installation, open it under **Personal** and select **Install** or **+**.
6. Start a **new chat**. Open the **+ / tools** menu and select OpenSEO. In versions that show **Developer mode** in that menu, choose it and enable OpenSEO there. If the composer offers plugin mentions, you can also type `@` and select OpenSEO.
7. Send the connection-check request below.

Use OAuth for this flow. You do not need to create an OpenSEO API key or paste one into ChatGPT. Without the skills, you can still ask for keyword research, audits, or competitor research in plain language.

See [OpenAI's connection guide](https://developers.openai.com/plugins/deploy/connect-chatgpt) for its current interface.

## Codex in the desktop app

If you already use Codex in the desktop app, start a new **Codex** chat, then copy the [agent setup prompt](/docs/agent-setup#set-up-your-agent) into that chat. Codex can configure its own connection and guide you through sign-in. Approve the OpenSEO login when prompted.

If you prefer manual setup, follow the [Codex plugin guide](/docs/codex-plugin#desktop-app), or add the [MCP connection alone](/docs/codex-plugin#mcp-only-in-the-desktop-app). Start a new Codex chat after installation if needed, then run the connection check below.

Codex and ChatGPT chats use separate connections. Run the connection check in the chat where you want to use OpenSEO. For the current mode controls, see [OpenAI's desktop guide](https://learn.chatgpt.com/docs/app).

## Check that OpenSEO is connected

Send this in a new chat with OpenSEO selected:

```text
Use OpenSEO to check my connection and list my projects. Do not run SEO research or create anything.
```

ChatGPT should call OpenSEO and return your connection status and project list. An empty project list is a successful connection check too. These reads use no OpenSEO credits.

If it says it cannot access OpenSEO, or only describes how to connect, setup is still incomplete. Check that OpenSEO is installed, signed in, and selected in this chat. Start a new chat after changing the connection.

Once the check succeeds, try:

```text
Use OpenSEO to help me choose one SEO task for my website. Ask about my goal before starting paid research.
```

The OpenSEO plugin also includes SEO skills, such as SEO Audit. The `@` menu shows OpenSEO itself, not its skills. Select OpenSEO and ask for a workflow by name, for example: "Use the OpenSEO SEO Audit skill on example.com."

## Troubleshooting

| What you see                                            | What to do                                                                                                                                                                                                   |
| ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| The OpenSEO plugin isn't available                      | Availability depends on your ChatGPT plan, workspace, and region. On a workspace plan, ask your admin to allow it. Otherwise, add a [custom connection](#custom-connection).                                 |
| No Developer mode or Create MCP App option              | Check **Settings → Security and login** and **Settings → Plugins → Developer mode**. On a workspace plan, ask your admin whether custom connections are allowed.                                             |
| "Error fetching OAuth configuration: Unsafe URL"        | Enter the server URL in full as `https://app.openseo.so/mcp`, with no spaces. A URL without `https://` is rejected.                                                                                          |
| ChatGPT asks for a client ID or secret                  | Keep OAuth selected and wait for discovery. Open Advanced OAuth settings and use Dynamic Client Registration (DCR) if offered. You should not need to supply your own client credentials for hosted OpenSEO. |
| The login window never appears                          | Allow the sign-in window to open, then retry authentication from the OpenSEO connection's details.                                                                                                           |
| Login succeeds but tools are unavailable                | Finish installing the plugin if prompted, start a new chat, and select OpenSEO from the tools menu.                                                                                                          |
| ChatGPT gives general advice instead of calling OpenSEO | Select OpenSEO and resend the connection-check request. Check that ChatGPT calls an OpenSEO tool.                                                                                                            |
| Codex works, but chatgpt.com cannot find OpenSEO        | Connect ChatGPT web separately. It does not read your desktop Codex configuration.                                                                                                                           |
| You have no projects                                    | An empty project list still confirms the connection. Create a project in OpenSEO when you are ready to start research.                                                                                       |

If setup still fails, contact [support@openseo.so](mailto:support@openseo.so) with your ChatGPT plan, web or desktop version, the step that failed, and the error message. Do not include passwords, API keys, or sign-in codes.

## Update OpenSEO

For the OpenSEO plugin, start a new chat to load the latest tools. The plugin's skills update when OpenSEO publishes a new version of the plugin. Reconnect if ChatGPT reports that sign-in needs attention. Local Codex update commands do not update ChatGPT web.

For a custom MCP connection, open its details under **Plugins**, select **Refresh** to reload the tools, and start a new chat. Refresh updates tool definitions; it does not add repository skills. If sign-in has expired, authenticate again.

For Codex, use the [agent update prompt or plugin commands](/docs/agent-setup#update-your-skills) in your Codex environment.

---

### Web Content Docs Claude Code Plugin (`web/content/docs/claude-code-plugin.md`)

---
title: "Use OpenSEO with Claude"
description: "Add the OpenSEO connector to Claude, or install the plugin to get OpenSEO MCP and Agent Skills in Claude Code and Claude Cowork."
---

**Quickest way:** add the [OpenSEO connector](https://claude.ai/directory/connectors/openseo) from Claude's directory. It gives Claude OpenSEO's tools on the web, desktop and mobile, and in Cowork and Claude Code when you're signed in to the same Claude account. Sign in with your OpenSEO account when Claude asks. If the link doesn't open the listing, open **Customize → Connectors** in Claude, search for OpenSEO, and select **Connect to Claude**.

The connector doesn't include the SEO skills. To get them, install the OpenSEO plugin below instead. It includes the same tools, so you don't need both. Added under **Customize → Plugins**, it works in Claude chat, Cowork and Claude Code. On the Free plan, keep the connector and [upload the skills](/docs/skills/setup#claude) instead.

## Choose your setup path

| Where you want to work                        | How to connect                                                              |
| --------------------------------------------- | --------------------------------------------------------------------------- |
| Claude on the web, desktop or mobile          | Add the [OpenSEO connector](https://claude.ai/directory/connectors/openseo) |
| Claude Code                                   | [Install the plugin](#install-in-claude-code)                               |
| Claude Cowork                                 | [Install the plugin](#install-in-claude-cowork)                             |
| Self-hosted, or the connector isn't available | [Add a custom connector](#custom-connector)                                 |

The OpenSEO plugin bundles OpenSEO MCP and all twelve SEO Agent Skills into one install. This is the preferred way to set up OpenSEO in Claude Code and in Claude Cowork.

## Install in Claude Code

Run these two commands in Claude Code:

```bash
/plugin marketplace add every-app/open-seo
/plugin install openseo@openseo
```

If the install summary says `Run /reload-plugins to activate.`, run that command.

Claude Code connects OpenSEO MCP at `https://app.openseo.so/mcp` and enables twelve skills:

- SEO Project Setup
- SEO Coach
- SEO Audit
- AI Visibility Audit
- AI Prompt Research
- Keyword Research
- Keyword Clustering
- Competitive Landscape
- Competitor Analysis
- Local SEO
- Link Prospecting
- SEO Report

### MCP only in Claude Code

Use this if you want OpenSEO's tools without the skills. Use user scope to make OpenSEO available across projects. Use local scope for the current repository.

```bash
claude mcp add --transport http --scope user openseo https://app.openseo.so/mcp
```

After adding the server, approve the OpenSEO login when prompted. To use an API key instead of signing in, see [Connect with an API key](/docs/mcp#connect-with-an-api-key).

## Finish the login

Claude Code should prompt you to log in to OpenSEO right after install. If it doesn't, run `/mcp` and approve the OpenSEO connection from there.

## Run a skill

In Claude Code, plugin skills are namespaced by the plugin name:

```
/openseo:seo-project-setup
/openseo:seo-coach
/openseo:seo-audit
/openseo:ai-visibility-audit
/openseo:ai-prompt-research
/openseo:keyword-research
/openseo:keyword-clustering
/openseo:competitive-landscape
/openseo:competitor-analysis
/openseo:local-seo
/openseo:link-prospecting
/openseo:seo-report
```

## Install in Claude Cowork

Claude Cowork and the Claude desktop app install plugins through the Customize menu, not slash commands. An agent can't click these steps for you.

1. Open **Customize** in the left sidebar. In Cowork, open the **Cowork** tab first.
2. Open **Plugins**, click **+** or **Add**, and choose **Add marketplace**.
3. Choose **Add from a repository** and enter `https://github.com/every-app/open-seo`.
4. Find **OpenSEO** in the new marketplace and click **Install** or **Add**.
5. Sign in to OpenSEO and approve the connection when Claude asks.
6. Start a new task, type `/`, and check that the OpenSEO skills appear. Then try "Use OpenSEO to check my connection and list my projects." This check uses no OpenSEO credits.

If Claude can list your projects but no OpenSEO skills appear under `/`, you have a connector, not the plugin. Install the plugin, then remove the OpenSEO connector under **Customize → Connectors** so you keep one connection.

Plugins need a paid Claude plan (Pro, Max, Team, or Enterprise). Your organization can limit which marketplaces you can add. On the Free plan, add the [OpenSEO connector](https://claude.ai/directory/connectors/openseo) and [upload the skills](/docs/skills/setup#claude) under **Customize → Skills**. With a self-hosted instance, [add a custom connector](#custom-connector) instead. The plugin connects only to hosted OpenSEO. See [Anthropic's plugin guide](https://support.claude.com/en/articles/13837440-use-plugins-in-claude).

## Custom connector

Use a custom connector to connect a self-hosted instance, or if the OpenSEO connector isn't available to you. It gives Claude OpenSEO's tools but not the SEO skills. Claude labels custom connectors **Custom** and doesn't suggest them in chats, so use the OpenSEO connector unless you self-host.

1. Open Customize -> Connectors.
2. Click Add (or +), then choose Add custom connector.
3. Paste `https://app.openseo.so/mcp`. For a self-hosted instance, use your instance's address followed by `/mcp`.
4. Approve the OpenSEO login when prompted.

Claude Desktop custom connectors are available on Free, Pro, Max, Team, and Enterprise plans. Free plans support one custom connector. To add the skills without the plugin, [upload them](/docs/skills/setup#claude) under **Customize → Skills**.

## Update

Run inside Claude Code:

```text
/plugin marketplace update openseo
/plugin update openseo@openseo
/reload-plugins
```

Updates land in the cache immediately, but the running session keeps the old version until you run `/reload-plugins` or restart Claude Code.

You can enable automatic updates in `/plugin` → **Marketplaces** → **openseo** → **Enable auto-update**. Third-party marketplaces have this off by default. Reload when Claude prompts you to activate an update. See [Claude's plugin update documentation](https://code.claude.com/docs/en/discover-plugins#configure-auto-updates).

For other installation methods, see [Agent setup and skill updates](/docs/agent-setup#update-your-skills).

## Remove

```text
/plugin uninstall openseo@openseo
```

## Troubleshooting

To check what's actually installed, run `/plugin list` rather than bare `/plugin` — `/plugin` alone opens an interactive panel that doesn't show plain text.

If `/reload-plugins` reports `0 skills`, that's normal, not a failure — its summary only counts a plugin's `commands/` directory, not `skills/`. Confirm the skills loaded by running one directly, for example `/openseo:seo-audit`.

If `/plugin uninstall openseo@openseo` reports "not installed in this project," you likely installed to a different scope than the one being checked (User, Project, or Local). Run `/plugin list` to see the actual scope, or sidestep the picker entirely with the shell form: `claude plugin uninstall openseo@openseo --scope user`.

If plugin skills don't appear, clear the plugin cache with `rm -rf ~/.claude/plugins/cache` — this clears every installed plugin's cache, not just OpenSEO's, so reinstall anything else you have after — then restart Claude Code and reinstall the plugin.

If the OpenSEO connection doesn't show as authenticated, run `/mcp`, select OpenSEO, and complete the login.

## Other clients

This page covers Claude. For Codex in the CLI or the ChatGPT desktop app, see [Use OpenSEO with Codex](/docs/codex-plugin). For ChatGPT, see the [ChatGPT guide](/docs/chatgpt). For Cursor or an API key setup, see [Set up OpenSEO MCP](/docs/mcp) and [Set up OpenSEO Agent Skills](/docs/skills/setup).

---

--- METRICS ---
- Files Extracted: 124
- Estimated Token Budget: ~126356 tokens
- Canonical Reference: https://codewiki.google/github.com/every-app/open-seo
