# AgentSite — Platform and Backend Conventions
<!--
ref: @agentsite/platform-conventions
tags: [agentsite, backend, scheduling, billing, telemetry, verification]
triggers: [adding a scheduled job, cron in agentsite, billable event, usage metering, posthog, analytics init, verifying the dev UI, local dev port]
trigger_prompt: When adding scheduled work, metering a billable surface, wiring analytics, or verifying UI locally in the agentsite codebase.
category: reference
complements: [@agentsite/project]
version: 6
updated_at: 2026-10-31T18:27:49.443Z
-->

Backend and frontend conventions that bite when ignored: agentsite is multi-instance, so periodic work claims through the tracking service; billable surfaces follow one availability/record/isEnabled shape.

Each decision below is a section — fetch just one with `?section=<slugified-heading>` rather than pulling the whole branch.

---

## Cluster-aware scheduling

**How agentsite schedules periodic work — tracking service coordinates a cluster of servers; do NOT default to cron when adding scheduled jobs**

agentsite is multi-instance. **Do not default to cron / `@nestjs/schedule`** when a task says "needs scheduling" or "periodic job." The cluster pattern:

- Multiple servers wake on their own clocks (no leader election in the traditional sense).
- Before doing work, each server **claims the work via the tracking service**. The tracking service guarantees mutual exclusion — only one claimant runs the job for any given window.
- The other servers see the claim, no-op, and go back to sleep.

This means a "daily 7-day-stale nudge" or any other recurring sweep is built on:
1. A scheduler (whatever lightweight wake-up loop the codebase uses — NOT system cron).
2. A tracking-service call (`claim` / `release` pattern) wrapping the actual job body.

**How to apply:** when adding scheduled work, search the codebase for the existing tracking-service pattern (look for prior periodic jobs) and copy the claim-wrap idiom. Do not introduce `@nestjs/schedule` `@Cron`s as if there's a single leader instance.

**Why this matters:** cron under a multi-instance deploy would either fire N times (each instance independently runs the job) or fire 0 times if you try to gate on instance hostname and the gating breaks during a rollout. The tracking-service claim sidesteps both.

Set 2026-05-11 in response to a "no cron — we use a scheduler with the tracking service" correction. If you're tempted to write `@Cron('0 0 * * *')` in this codebase, stop and look for the existing claim pattern instead.


## Chargeable-event pattern

**UsageService exposes availability/record/isEnabled — the single repeatable pattern every new billable surface must use. Render path adopted it 2026-05-17. Site events (C31.8c) and any future surfaces follow the same template.**

**The chargeable-event pattern is in place.** `UsageService` exposes three methods:

- `isEnabled()` — hot-path env-flag kill switch (`USAGE_ENABLED=false` disables).
- `availability(userId, costMu) → 'ok' | 'insufficient' | 'skipped-zero' | 'skipped-disabled'` — read-only budget check.
- `record({ userId, costMu, kind, refId, siteId?, hourBucket? })` — immutable write to `usage`. Idempotent on `refId`.

Render path (`RenderService.renderCached`) uses the pattern: resolve site → owner upfront (callers do their own site lookup, UsageService stays user-scoped), `availability()` preflight before scan (insufficient blocks the render), `record()` post-work for scan, repeat for generate, same shape on the revalidate path.

**Why this shape:**
- Read/write split lets callers preflight without committing a row, then write after work succeeds.
- Site→owner resolution lives at the caller, not in UsageService — UsageService has one mental model (it's about users and amounts).
- The kill-switch + bounded status enum keeps every call site readable.
- Matches the convention adopted in the protocol project, which faced the same charging-surface design question first.

**How to apply when adding a new billable surface (C31.8c site events, admin re-renders, warming, etc.):**
1. Resolve the user/owner at the caller. Skip if untracked/internal.
2. Call `availability(userId, costMu)`. On `'insufficient'`, refuse the work (log + emit empty-over-limit signal as the render path does). On `'ok'`, proceed. `'skipped-zero'` / `'skipped-disabled'` proceed without charging.
3. Do the work.
4. Call `record({ userId, costMu, kind, refId: ashid(USAGE_PREFIX), siteId })`. `refId` is the idempotency key — generate one ashid per chargeable event.

**Outstanding gate — single-chokepoint integration test:** the pattern is correct by code-reading, not enforced. Any new render-like path that forgets to route through `availability` + `record` is silently free. Add an integration test that asserts every cache-miss render leaves a `usage` row before declaring C31.8 fully closed. The test belongs with whatever chunk wires the next billable surface (likely C31.8c).


## PostHog must init early on landing

**Don't lazy-load or defer posthog-js init; visitor identification on first paint is essential to the product**

Don't propose lazy-loading `posthog-js` (or moving its init into `requestIdleCallback`, `setTimeout`, post-mount, route-level dynamic import, etc.). Init must run early in `main.ts` before `app.mount()`, on every page.

**Why:** Customer identification at landing — the moment a visitor first hits any agentsite page — is essential. Lazy-loading PostHog means the first pageview / first session-start event lands without identity, breaking attribution back to ad source, breaking session funnels, breaking the "did this person come from an ad?" question that drives campaign decisions. Locked 2026-05-26 after a perf optimization suggestion.

**How to apply:** When chasing unused-JS / bundle-size wins, treat `posthog-js` as off-limits for deferral. Static import in `main.ts`, init synchronously before mount. PostHog's own SDK is already small enough that the cost is acceptable. Other deferral targets (`vue-social-sharing`, dashboard-only deps) are fair game.


## Dev UI verification loop

**"How to visually verify agentsite UI locally — dev port, the localhost→prod-API CORS wall, and the isolated-HTML fallback"**

Verifying agentsite frontend changes locally (2026-07-18):

- **Dev port is `:3061`, not `:5173`.** `cd frontend && npm run dev` → `http://localhost:3061/`. Port 5173 is the **protocol.supply** dev app (a sibling repo) — snapping 5173 gives you protocol's 404 page, not agentsite. Always confirm the nav says "agentsite".
- **Content pages 404 on the dev server** (`/learn` article cards, `/agent/vs-*`, `/aeo`, any `[...slug]` page). Cause: the dev frontend's `BACKEND_URL` points at **prod `api.agentsite.app`**, and prod CORS is an allowlist (pentest #2) that **excludes `localhost`**, so `useContent().get()` fetches fail → `content/index.vue` redirects to `/404`. There is no vite proxy. Static pages that don't need the content API (e.g. `/learn`'s section shell from `learnTaxonomy`) render fine; anything reading `/content/*` does not. To truly render content pages locally you must run a **local backend** (needs Postgres + the `.env`, which has a stray `;` on line 7 that the env-gen script warns about but survives).
- **Fallback for verifying a component's pixels** without a live API: write a standalone `/tmp/*.html` that reproduces the component's exact template markup + scoped CSS (theme vars inlined) with representative data, embed any local asset as a `data:` URI, and Playwright-snap it. Used this to verify the vs-* matchup lockup (#31) and the report direct-answer block (#30). Not a substitute for a live render, but confirms layout/spacing/color.
- **Playwright** lives at the repo-root `node_modules/playwright/index.mjs` (import `chromium` from there; the per-package `playwright-core` path does NOT resolve). The Chrome extension (`mcp__claude-in-chrome`) was **not connected** this session — Playwright headless was the working path.

## Never run heavy scripts inside the serving pod

**"Ops scripts against prod data run in a one-off pod, never via `kubectl exec` into the backend Deployment's pod"**

The backend Deployment `agentsite-backend-main` runs **one replica**. The scheduling section's "multi-instance" describes the code's contract, not today's pod count. `kubectl exec` into that pod shares its memory limit and liveness probe with live traffic. Anything heavy you run there (a bulk read, a backfill, a dry run that loads a table) can push the pod past its limit. The OOM kill or failed liveness probe then takes the whole site down until the replacement pod is Ready.

**Incident 2026-10-31, 11:16:30–11:21:45Z (~5 min, Cloudflare 521):** the dry run of the #208 cleanup script (`backend/scripts/path-hygiene-208.ts`) loaded about 275k rows inside the serving pod. The pod was killed and replaced. The dead pod object (`…-fjcsc`, `ContainerStatusUnknown`) was left for inspection.

**What actually happened (corrected 2026-10-31 by the retro, from `kubectl describe` + container termination times):** this was not the pod hitting its own 1536Mi limit. The container reached 1.24Gi against a **300Mi request**, node `3ok3nd` went into MemoryPressure (11:16 to 11:21:42Z), and the kubelet and kernel took about **17 containers on that node** with it: the only ingress-nginx controller, both coredns replicas, and the protocol, dashboard and wildeagency backends. **29 of 61 sites answered 521**, not only agentsite. A pod's limit does not protect the node when its request is far below its use.

**How to apply:**
- Run prod-data scripts with **`devops/scripts/run-oneoff.sh <backend/scripts/x.ts> [-- args]`**. It bundles the script, starts a pod from the deployed image with the same ConfigMap and Secret, and sets **memory request = limit**, so the script either gets reserved memory or stays Pending. It deletes the pod on exit. `--print` shows the manifest. Every DB script calls `assertNotServingPod()` (`backend/scripts/lib/serving-pod-guard.ts`); a spec fails if one does not. The fleet's kubectl hook blocks `kubectl exec` of `node -e`/`ts-node`/`node <file>` into any `*-main` pod.
- Page every bulk read (keyset, bounded batch) even in a dry run. "Dry run" describes the writes, not the memory cost.
- `kubectl exec` into the serving pod is for cheap inspection only: env, one `psql` count, a log tail.
- If the backend ever runs ≥2 replicas, this still holds: a killed replica still drops in-flight requests and re-runs claimed jobs.

## Review checks for backend changes

Each of these was a real defect caught in review, not a hypothetical. Check a diff against all of them before it ships.

- **A per-bucket claim does not cover a tick that outlives its bucket.** `TrackingService.work` guarantees one node per run key. If a tick can run longer than its interval, the next bucket's node picks up the same rows. When a job does expensive per-row work (crawls, LLM calls), claim each row with a compare-and-set lease before working on it, and stop taking new rows before the interval ends. Reference: `AeoReportRepository.claimPreliminaryRetry`.
- **Never persist or serve a raw fetched body by accident.** A probe result that carries a body for later grading must have the body stripped before it is merged into a persisted jsonb column or a viewer payload. Spreading `{ ...probeResult }` into the report is the usual way it leaks.
- **Cap third-party body reads, and never let a body read change a status verdict.** A sitemap may legally be 50 MB. Read a bounded prefix, and keep "reachable" decided by the status code: a body that times out mid-read must not flip reachability, or a slow site loses score.
- **No uncached query per render request.** The render path already reads `site_page` in classify(); ride that row. A site-level read on every hit (or every stale hit) needs a short in-process memo, cleared *after* the owner's write, not before it.
- **Exclude patterns anchor at end of path.** A trailing non-letter class like `([^a-zA-Z]|$)` also matches `/blog/robots.txt-guide`. Anchor with `(\?|$)` and test both directions.
- **Migrations: Flyway runs with `outOfOrder=false`.** Reserving version numbers across parallel branches does not work. Once a higher version is applied, every open PR holding a lower one fails the migrate step. Pick the next free number at merge time and say so in the PR.

---

*Related: `@protocol/verification-tactics` · `@protocol/shell-and-runtime-traps` · `@protocol/silent-signal-and-evidence-traps` · `@content/web/huggingface/2026-11-23-cua-see-self-evolving-evals` · `@content/youtube/tiago-forte/i-connected-claude-to-everything-then-i-saw-the-gap`*

---

*You're reading a protocol on [protocol.supply](https://protocol.supply) — hosted, searchable knowledge for AI agents. Think Agent Skills, as an API: bootstrap once (`curl -sL https://api.protocol.supply/bootstrap`), search (`/search?q=…`), fetch (`/@repo/slug`).*

*Any skill can become a protocol, and any protocol installs as a local skill — tell your agent "install this as a skill" or see [`@protocol/protocol-to-skill`](https://api.protocol.supply/@protocol/protocol-to-skill).*