# Connect this machine to Metricsjar

You are an agent setting up Metricsjar for your user: a live SEO dashboard
(rankings, target keywords, movers, backlinks) computed **locally on this
machine with the user's own credentials** and published to their Metricsjar
account. Nothing is OAuth'd to Metricsjar — Google queries run through the
user's own gcloud auth, DataForSEO calls use their own key, and only the
computed dashboard rows are uploaded.

The user pasted this file's URL alongside a **Server** URL and a **Pair
token**. Use those below. Work through the steps in order; ask the user only
the questions in Step 3.

## Step 1 — Install the CLI

One self-contained file, run with bun. Read it first if you or the user want
to audit what it does — that's the point of it being one file.

```sh
mkdir -p ~/.metricsjar && curl -fsSL <SERVER>/cli.ts -o ~/.metricsjar/cli.ts
bun ~/.metricsjar/cli.ts version
```

If `bun` is missing, install it (`brew install oven-sh/bun/bun` on macOS) or
ask the user how they'd like it installed.

## Step 2 — Pair

```sh
bun ~/.metricsjar/cli.ts pair <PAIR_TOKEN> --server <SERVER>
```

This stores the token at `~/.config/metricsjar/auth.json` (0600). Treat it
like a password: never commit it, never echo it into logs.

## Step 3 — Discover the site's data sources

Gather these facts. Discover what you can yourself; ask the user only for
what you can't.

1. **Domain + slug.** Ask which site to connect (e.g. `example.com`). Derive
   the slug from the domain (`example-com` style: lowercase, dashes).
2. **gcloud account.** Run `gcloud auth list`. If more than one account,
   ask which one owns this site's analytics. Always pass it via
   `--gcloud-account` — the CLI pins it per-command with
   `CLOUDSDK_CORE_ACCOUNT`. **Never run `gcloud config set account`** (it
   silently breaks every other project on the machine).
3. **BigQuery project + GSC dataset.** Run
   `gcloud projects list --format='value(projectId)'` (with the pinned
   account via `CLOUDSDK_CORE_ACCOUNT=<email> gcloud …`) and look for the
   project holding the site's analytics, then
   `bq ls --project_id=<project>` to find the Search Console export
   dataset — usually named `searchconsole`, but check for variants like
   `searchconsole_searchconsole` (pick the one that actually contains
   `searchdata_site_impression` / `searchdata_url_impression`).
4. **GA4 dataset (optional).** In the same project list, look for
   `analytics_<propertyId>`. If present, pass `--ga4-dataset`. If not, skip —
   the dashboard works from GSC alone.
5. **DataForSEO key (optional but recommended).** Ask the user if they have
   one (it powers true SERP rank checks + backlinks; costs are pennies —
   roughly $0.03/keyword-check-batch and ~$0.05/backlink refresh, all on
   their own prepaid balance). If yes, store it:
   `echo 'DATAFORSEO_API_KEY=<base64 login:password>' >> ~/.config/metricsjar/.env && chmod 600 ~/.config/metricsjar/.env`
   If no, continue — those sections show as "not configured".
6. **Target keywords (optional).** If the repo has a keyword research file,
   offer to create `targets.csv` from it (columns: `keyword` required,
   `volume`, `page` optional; one row per keyword the user is deliberately
   chasing, max 150). Otherwise start without targets — the dashboard still
   tracks every query GSC sees, and targets can be added later.

### If the site has no GSC→BigQuery export yet

The export can only be enabled by a human in the Search Console UI (there is
no API): Search Console → Settings → Bulk data export → set the BigQuery
project. Walk the user through it, then note: **the export has no backfill**
— data flows from enablement day forward, so the dashboard fills up over the
following days. Same for GA4: Admin → BigQuery links.

## Step 4 — Register the site

```sh
bun ~/.metricsjar/cli.ts site add \
  --slug <slug> --domain <domain> --name "<Site Name>" \
  --bq-project <project> --gsc-dataset <dataset> \
  --ga4-dataset <dataset-or-omit> \
  --gcloud-account <email> \
  --geo 2840 \
  --targets <path-or-omit>
```

`--geo` is the DataForSEO location code for SERP checks (2840 = US,
2036 = AU).

## Step 5 — Doctor

```sh
bun ~/.metricsjar/cli.ts doctor <slug>
```

Fix anything 🔴 before continuing (the notes say what's wrong: usually a
wrong dataset name, a missing gcloud login, or a dead DataForSEO key). 🟡
warnings are fine — they mark optional pieces.

## Step 6 — First refresh

```sh
bun ~/.metricsjar/cli.ts refresh <slug> --serp --backlinks
```

The `--serp --backlinks` flags force the paid pulls on the first run so the
dashboard starts complete (skip them if the user has no DataForSEO key).
The command prints the dashboard URL when it lands. Open it and show the
user.

## Step 7 — Keep it fresh

```sh
bun ~/.metricsjar/cli.ts cron install
```

Installs a launchd agent (macOS) that runs `refresh --all` every 5 minutes. The
refresh only uploads when the computed payload actually changed, and SERP /
backlink spends are cadence-gated (default: weekly) regardless of how often
the cron fires — so the background cost stays at pennies per week. Check it
anytime with `bun ~/.metricsjar/cli.ts cron status`; logs land in
`~/Library/Logs/metricsjar-refresh.log`.

On Linux, skip this and add an equivalent cron entry:
`*/5 * * * * bun ~/.metricsjar/cli.ts refresh --all`.

## Collectors (optional) — put any metric on the dashboard

A collector is any local script that prints
`{ "tabs": [{ "id": "app", "label": "App", "sections": [...] }] }` to
stdout — sections are simple primitives (`tiles`, `chart`, `table`,
`list`). Register one with `--collector "node /path/to/collector.mjs"` on
`site add` (or edit the site's JSON under `~/.config/metricsjar/sites/`),
and its tabs appear on the dashboard and in the `/md` twin on every
refresh. App-store stats, revenue, CI health — anything the machine can
query can live in the jar. A failing collector degrades to a health warning;
it never breaks the refresh.

## Done — tell the user

Report back with:

- the dashboard URL (`<SERVER>/j/<slug>`) — dashboards are **private**: only
  the owner's signed-in account can view
- the agent-readable twin at `<SERVER>/j/<slug>/md` — point your future
  sessions at it when deciding what SEO work to do next. Private dashboards
  need the pair token:
  `curl -H "Authorization: Bearer <PAIR_TOKEN>" <SERVER>/j/<slug>/md`
- what's 🟡 (missing GA4? no DataForSEO key? export still warming up?) and
  the one-line fix for each
