diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 104ee33..ac50e84 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -134,6 +134,57 @@ jobs: done exit $failed + analytics-content-ops: + name: analytics-content-ops (Node ${{ matrix.node-version }}) + runs-on: ubuntu-latest + environment: analytics-content-ops + strategy: + matrix: + node-version: [20, 22] + defaults: + run: + working-directory: analytics-content-ops + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + - run: pnpm install + - name: Format check + run: pnpm run format:check + - name: Lint + run: pnpm run lint + - name: Typecheck + run: pnpm run typecheck + env: + SANITY_STUDIO_PROJECT_ID: ${{ vars.SANITY_PROJECT_ID }} + SANITY_STUDIO_DATASET: ${{ vars.SANITY_DATASET }} + - name: Validate template + run: pnpm run validate + - name: Manifest extract + run: pnpm --filter studio exec sanity manifest extract + env: + SANITY_STUDIO_PROJECT_ID: ${{ vars.SANITY_PROJECT_ID }} + SANITY_STUDIO_DATASET: ${{ vars.SANITY_DATASET }} + - name: Check function bundle sizes + run: | + max_kb=512 + failed=0 + for dir in functions/dist/*/; do + bundle="$dir/index.js" + [ -f "$bundle" ] || continue + size_kb=$(( $(wc -c < "$bundle") / 1024 )) + name=$(basename "$dir") + if [ "$size_kb" -gt "$max_kb" ]; then + echo "::error::$name bundle is ${size_kb} KB (max ${max_kb} KB)" + failed=1 + else + echo "$name: ${size_kb} KB ✓" + fi + done + exit $failed + scaffold: name: _scaffold runs-on: ubuntu-latest diff --git a/README.md b/README.md index 9315e15..5bfa6db 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ pnpm create sanity@latest --template sanity-labs/starters/ | ------------------------------------------------ | ----------------------------------------------------------------------------------------- | | [agentic-localization](./agentic-localization) | AI translation with glossaries, style guides, quality evals, and a translations dashboard | | [ai-shopping-assistant](./ai-shopping-assistant) | Ecommerce storefront with a Claude chatbot powered by Context MCP | +| [analytics-content-ops](./analytics-content-ops) | Analytics signal → Studio triage, GROQ intelligence rails, and Content Agent overnight | | [knowledge-base](./knowledge-base) | Governed knowledge base feeding external and internal AI chat surfaces from one dataset | ## Repo structure diff --git a/analytics-content-ops/.env.example b/analytics-content-ops/.env.example new file mode 100644 index 0000000..4faf100 --- /dev/null +++ b/analytics-content-ops/.env.example @@ -0,0 +1,40 @@ +# ───────────────────────────────────────────────────────────────────────────── +# Root env — used by `sanity.blueprint.ts` (blueprint/function deploys). +# Copy this file to `.env` (not only `.env.local`) and fill in. +# +# Required alongside: +# cp studio/.env.example studio/.env +# cp frontend/.env.example frontend/.env +# +# Studio CLI loads studio/.env; blueprint loads this root `.env`. +# A root-only `.env.local` is not enough for `pnpm bootstrap`. +# ───────────────────────────────────────────────────────────────────────────── + +# Your Sanity project ID and dataset (from sanity.io/manage) +SANITY_STUDIO_PROJECT_ID= +SANITY_STUDIO_DATASET=production + +# ── Content Agent triage (agent-triage scheduled function) ──────────────────── +# Deployed schema id that Agent Actions resolves against. The blueprint defaults +# this to `_.schemas.default` (the "default" workspace), so you only need to set +# it if you renamed the Studio workspace in studio/sanity.config.ts — then use +# `_.schemas.`. Confirm the deployed id with: +# cd studio && npx sanity schema list +# SANITY_SCHEMA_ID= + +# ── Analytics sync (Phase 1: GitHub Actions cron / standalone script) ───────── +# A write-enabled token is only needed when running the sync outside the Studio +# CLI (e.g. in CI). `pnpm bootstrap`/`pnpm seed`/`pnpm analytics-sync` use your +# CLI login token instead. Create at: sanity.io/manage → API → Tokens (Editor). +# SANITY_API_WRITE_TOKEN= + +# Which analytics provider the sync reads from. "fixture" ships deterministic +# demo data so the sync runs with no external credentials. Set to "ga4" to read +# from Google Analytics 4 (requires the GA4 vars below). +ANALYTICS_PROVIDER=fixture + +# ── GA4 provider (only when ANALYTICS_PROVIDER=ga4) ─────────────────────────── +# GA4 property ID, e.g. "properties/123456789" +# GA4_PROPERTY_ID= +# Base64-encoded service-account JSON with the Analytics Data API (read-only) +# GA4_SERVICE_ACCOUNT_KEY= diff --git a/analytics-content-ops/.github/workflows/analytics-sync.yml b/analytics-content-ops/.github/workflows/analytics-sync.yml new file mode 100644 index 0000000..8526261 --- /dev/null +++ b/analytics-content-ops/.github/workflows/analytics-sync.yml @@ -0,0 +1,33 @@ +name: Analytics Sync + +# Phase 1 sync: an external cron that reads analytics and upserts performance +# signal into Sanity. Phase 2 replaces this with the scheduled Function in +# `functions/analytics-sync` (see sanity.blueprint.ts) — the sync logic is +# identical, so retiring this workflow is an infrastructure swap, not a rewrite. + +on: + schedule: + # 07:00 UTC ≈ nightly, after the previous day closes in the Americas. + - cron: '0 7 * * *' + workflow_dispatch: + +jobs: + sync: + name: Sync analytics into Sanity + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - run: pnpm install + - name: Run analytics sync + run: pnpm analytics-sync + env: + SANITY_STUDIO_PROJECT_ID: ${{ vars.SANITY_PROJECT_ID }} + SANITY_STUDIO_DATASET: ${{ vars.SANITY_DATASET }} + SANITY_API_WRITE_TOKEN: ${{ secrets.SANITY_API_WRITE_TOKEN }} + ANALYTICS_PROVIDER: ${{ vars.ANALYTICS_PROVIDER || 'fixture' }} + GA4_PROPERTY_ID: ${{ vars.GA4_PROPERTY_ID }} + GA4_SERVICE_ACCOUNT_KEY: ${{ secrets.GA4_SERVICE_ACCOUNT_KEY }} diff --git a/analytics-content-ops/.github/workflows/ci.yml b/analytics-content-ops/.github/workflows/ci.yml new file mode 100644 index 0000000..950ff59 --- /dev/null +++ b/analytics-content-ops/.github/workflows/ci.yml @@ -0,0 +1,56 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +jobs: + build: + name: Build & Validate (Node ${{ matrix.node-version }}) + runs-on: ubuntu-latest + environment: analytics-content-ops + strategy: + matrix: + node-version: [20, 22] + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + - run: pnpm install + - name: Format check + run: pnpm run format:check + - name: Lint + run: pnpm run lint + - name: Typecheck + run: pnpm run typecheck + env: + SANITY_STUDIO_PROJECT_ID: ${{ vars.SANITY_PROJECT_ID }} + SANITY_STUDIO_DATASET: ${{ vars.SANITY_DATASET }} + - name: Validate template + run: pnpm run validate + - name: Manifest extract + run: pnpm --filter studio exec sanity manifest extract + env: + SANITY_STUDIO_PROJECT_ID: ${{ vars.SANITY_PROJECT_ID }} + SANITY_STUDIO_DATASET: ${{ vars.SANITY_DATASET }} + - name: Check function bundle sizes + run: | + max_kb=512 + failed=0 + for dir in functions/dist/*/; do + bundle="$dir/index.js" + [ -f "$bundle" ] || continue + size_kb=$(( $(wc -c < "$bundle") / 1024 )) + name=$(basename "$dir") + if [ "$size_kb" -gt "$max_kb" ]; then + echo "::error::$name bundle is ${size_kb} KB (max ${max_kb} KB)" + failed=1 + else + echo "$name: ${size_kb} KB ✓" + fi + done + exit $failed diff --git a/analytics-content-ops/.gitignore b/analytics-content-ops/.gitignore new file mode 100644 index 0000000..bdaa949 --- /dev/null +++ b/analytics-content-ops/.gitignore @@ -0,0 +1,43 @@ +# Dependencies +node_modules/ + +# Environment files — only .env.example is committed +.env +.env.* +!.env.example + +# Temporary Sanity runtime, generated by the CLI +.sanity/ + +# Sanity Functions build output +.build/ + +# Compiled Sanity Studio +dist/ + +# Next.js build output and generated files +.next/ +next-env.d.ts + +# Logs +*.log + +# OS files +.DS_Store + +# IDE +.vscode/ +.idea/ + +# TypeScript +*.tsbuildinfo + +# Generated Sanity artifacts +schema.json +sanity.types.ts + +# Claude Code +.claude/ + +# Internal +notes/ diff --git a/analytics-content-ops/.npmrc b/analytics-content-ops/.npmrc new file mode 100644 index 0000000..6c59086 --- /dev/null +++ b/analytics-content-ops/.npmrc @@ -0,0 +1 @@ +enable-pre-post-scripts=true diff --git a/analytics-content-ops/.oxfmtrc.json b/analytics-content-ops/.oxfmtrc.json new file mode 100644 index 0000000..9f3f91d --- /dev/null +++ b/analytics-content-ops/.oxfmtrc.json @@ -0,0 +1,6 @@ +{ + "semi": false, + "singleQuote": true, + "printWidth": 100, + "bracketSpacing": false +} diff --git a/analytics-content-ops/AGENT.md b/analytics-content-ops/AGENT.md new file mode 100644 index 0000000..606efa1 --- /dev/null +++ b/analytics-content-ops/AGENT.md @@ -0,0 +1,130 @@ +# Analytics Content Ops — Agent Guide + +Analytics-informed content operations starter. Performance signal from any +analytics platform flows into Sanity as **derived, action-enabling signal** so +editors act on it in Studio, developers power content-intelligence features with +GROQ, and Content Agent triages the catalog automatically. + +## Stack + +- **Studio** — Sanity Studio v5 (`studio/`): schemas, triage views, performance badge + panel +- **Frontend** — Next.js 16 + React 19 + Tailwind v4 (`frontend/`): media site + GROQ intelligence rails +- **Functions** — Sanity Functions (`functions/`): scheduled analytics sync + Content Agent triage +- **Sync logic** — framework-agnostic package (`packages/@starter/analytics-sync/`) + +## Commands + +Run from the repo root: + +- `pnpm install` — install all workspaces +- `pnpm dev` — Studio (3333), frontend (3000), functions concurrently +- `pnpm bootstrap` — deploy blueprint + schema, typegen, seed content + signal +- `pnpm seed` — seed demo content and run the fixture sync +- `pnpm analytics-sync` — run the analytics sync on demand (Phase 1 path) +- `pnpm fn:sync` / `pnpm fn:triage` — run the `analytics-sync` / `agent-triage` + Function locally (loads root `.env` + your CLI token, no deploy needed) +- `pnpm typegen` / `pnpm typecheck` / `pnpm lint` / `pnpm format` + +## Environment setup (required before bootstrap) + +This starter does **not** cascade a single root `.env.local`. Create and fill +**all three** files before `pnpm bootstrap`: + +```sh +cp studio/.env.example studio/.env +cp frontend/.env.example frontend/.env +cp .env.example .env +``` + +| File | Who loads it | Must set | +| --------------- | ---------------------------------------------- | ------------------------------------------------------------- | +| `studio/.env` | `studio/sanity.cli.ts` (`process.loadEnvFile`) | `SANITY_STUDIO_PROJECT_ID`, `SANITY_STUDIO_DATASET` | +| `frontend/.env` | Next.js | `NEXT_PUBLIC_SANITY_PROJECT_ID`, `NEXT_PUBLIC_SANITY_DATASET` | +| `.env` (root) | `sanity.blueprint.ts` via `dotenv/config` | `SANITY_STUDIO_PROJECT_ID`, `SANITY_STUDIO_DATASET` | + +If only root `.env.local` exists, bootstrap fails with +`Unable to resolve project ID/dataset from CLI configuration`. + +## Code style + +- ESM-first (`"type": "module"`), no semicolons, single quotes, no bracket spacing +- Format with `oxfmt`, lint with `eslint` +- Shared configs in `packages/@starter/` (eslint, tsconfig, sanity-types, analytics-sync) + +## Content model (the key architectural decisions) + +- **`article`** — the editorial document. Adds `editorialPriority` (the editor's + response to signal) and an `agentReview` object (workflow status: + `idle → queued → in_progress → staged`, reset to `idle` once a human accepts or + dismisses; the outcome is recorded by `reviewedAt`, not a status) plus + `seoTitle` / `seoDescription` that the triage agent drafts. +- **`articlePerformance`** — a **companion document**, synced nightly, **never + edited by humans**. It is deliberately separate from `article` so that + `article._updatedAt` stays a purely _editorial_ signal and webhooks can filter + sync writes by `_type`. Join with + `*[_type == "articlePerformance" && article._ref == ^._id][0]`. +- **Derived signal + display snapshot** — Sanity stores `performanceTier`, + `trendDirection`, `lifecycleState`, `topReferrer`, `catalogPercentile`, plus a + Studio display snapshot (`sessions30d`, `sessionsVsCatalogAvgPct`, + `dailySessions`) written by the sync. The analytics platform stays the system + of record; Sanity is where signal becomes action. +- **`analyticsContext`** — a read-only singleton with catalog-level counts for + cheap Content Agent context queries. + +Vocabulary lives in two mirrored places: `studio/lib/performance.ts` (Studio) +and `packages/@starter/analytics-sync/src/types.ts` (sync). Keep them in sync. + +## The sync pipeline (two phases, one codebase) + +The real work lives in `@starter/analytics-sync` (`runSync`). Two thin +entrypoints call it with identical logic: + +- **Phase 1 (ships today):** `scripts/analytics-sync.ts`, run by the GitHub + Actions cron in `.github/workflows/analytics-sync.yml`. Needs + `SANITY_API_WRITE_TOKEN`. +- **Phase 2 (Sanity-native):** `functions/analytics-sync/` scheduled Function, + registered in `sanity.blueprint.ts`. Migrating is an infrastructure swap — + retire the workflow, keep the logic. + +Providers are pluggable (`src/providers/`). `fixture` (default) needs no +credentials and drives the demo; `ga4` is a skeleton to fill in with the GA Data +API. Select via `ANALYTICS_PROVIDER`. + +Classification is catalog-relative (`src/classify.ts`): tiers/percentiles are +computed across the whole catalog, so "stale" means "underperforming its peers." + +## Content Agent triage + +`functions/agent-triage/` runs 30 min after the sync. It loads +`agentReview.status == "queued"` articles, uses Agent Actions to write +`agentReview.agentNotes` plus improved SEO metadata into the article's **draft** +(never the published doc — the draft is the review gate), and marks each +`staged`. The ops lead finds these under **Triage → Awaiting Approval** and +**publishes to accept** — a publish-event Function (`functions/agent-review-resolve/`) +then resets the article to `idle` — or uses the **Dismiss** action to reject, +which discards the draft and resets it. Either path stamps +`agentReview.reviewedAt`, which the sync honours as a re-queue cooldown. + +Production upgrade (Enterprise-only): promote the per-run batch to a first-class +**Content Release** via the Releases API (the batch name is tracked in +`agentReview.releaseId`). + +## Studio surfaces + +- `PerformanceTierBadge` — document badge (trending / stale / archive candidate) +- Performance panel — read-only second view on every article + (`structure.ts` → `defaultDocumentNode`), live-subscribed to the companion doc +- Triage views in `structure.ts`: Awaiting Approval (staged — needs a human), + Underperforming, Trending Now, Archive Candidates, Content Agent Queue + +## Deploying functions + +Build from `functions/`, deploy the blueprint from the **repo root**: + +```sh +pnpm --filter @starter/functions build +npx sanity blueprints deploy # run from repo root, not functions/ +``` + +Set the schema id for Agent Actions on the function runtime, or via `.env` +(`SANITY_SCHEMA_ID`) so the blueprint injects it. diff --git a/analytics-content-ops/CLAUDE.md b/analytics-content-ops/CLAUDE.md new file mode 120000 index 0000000..ac534a3 --- /dev/null +++ b/analytics-content-ops/CLAUDE.md @@ -0,0 +1 @@ +AGENT.md \ No newline at end of file diff --git a/analytics-content-ops/README.md b/analytics-content-ops/README.md new file mode 100644 index 0000000..bc0239b --- /dev/null +++ b/analytics-content-ops/README.md @@ -0,0 +1,155 @@ +# Analytics-informed content operations + +A Sanity starter that closes the loop between **analytics** and **editorial +action**. Performance signal from any analytics platform (GA4, Amplitude, Heap, +…) syncs into Sanity as derived, action-enabling signal — so editors act on it +inside Studio, developers power "trending" and "most-read" features with plain +GROQ, and Content Agent triages the catalog automatically overnight. + +```sh +pnpm create sanity@latest --template sanity-labs/starters/analytics-content-ops --package-manager pnpm +``` + +> Using npm? Run `npm create sanity@latest -- --template sanity-labs/starters/analytics-content-ops` (note the extra `--`). + +> Sanity is not the analytics platform. It's where signal from that platform +> becomes editorial action. + +This demo is styled as **Friluft Media**, a Norwegian outdoor publication, using +real articles from the [Sanity blog](https://www.sanity.io/blog). + +## What it demonstrates + +| Persona | In this starter | +| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Author** — "how is my work doing?" | A performance badge + read-only **Performance panel** on every article, with a one-line editorial cue. Set `editorialPriority` to flag a piece — no leaving Studio. | +| **Section editor** — triaging a section | Structure Builder **triage views**: Underperforming, Trending Now, Archive Candidates. | +| **Content ops lead** — running the catalog | An **Awaiting Approval** list of articles the agent drafted notes + SEO for (staged in a draft) — publish to accept, or dismiss to reject. | +| **Developer** — content intelligence | A nightly **sync** upserts `articlePerformance` companion docs; the "Trending" and "Most read" rails on the site are just GROQ joins. | +| **Content Agent** — automated triage | A scheduled Function loads queued articles, writes reasoning + improvements, and stages them for human review. | + +## Architecture at a glance + +``` +Analytics platform (GA4, Amplitude, …) + │ nightly batch + ▼ +Sync layer ── Phase 1: GitHub Actions cron (scripts/analytics-sync.ts) + └─ Phase 2: Scheduled Function (functions/analytics-sync/) + │ classifies catalog-relative tiers, upserts companion docs, + │ flags newly-stale articles for triage + ▼ +Sanity Content Lake + ├── Studio: performance badge, Performance panel, triage views, editorialPriority + ├── GROQ: trending / most-read rails on the frontend + └── Content Agent (functions/agent-triage/): drafts improvements → review queue +``` + +Both sync phases call the same `runSync` from `@starter/analytics-sync`, so the +Phase 1 → Phase 2 migration is an infrastructure swap, not a rewrite. + +## Getting started + +Prerequisites: **Node ≥ 20.19** and **pnpm 10**. + +This starter does **not** cascade a single root `.env.local` into every workspace. +You need three separate env files before `pnpm bootstrap` will work. + +```sh +pnpm install + +# 1. Create all three env files (required — not optional) +cp studio/.env.example studio/.env +cp frontend/.env.example frontend/.env +cp .env.example .env + +# 2. Fill in the same project ID / dataset in each file +# studio/.env → SANITY_STUDIO_PROJECT_ID, SANITY_STUDIO_DATASET +# frontend/.env → NEXT_PUBLIC_SANITY_PROJECT_ID, NEXT_PUBLIC_SANITY_DATASET +# .env (root) → SANITY_STUDIO_PROJECT_ID, SANITY_STUDIO_DATASET +# +# A root-only `.env.local` is not enough: Studio CLI loads `studio/.env`, and +# blueprint deploy loads root `.env`. Missing either fails bootstrap with +# "Unable to resolve project ID/dataset from CLI configuration". + +# 3. Deploy schema, generate types, and seed demo content + performance signal +pnpm bootstrap + +# 4. Run everything (Studio :3333, frontend :3000) +pnpm dev +``` + +Prefer to seed without deploying functions? Run `pnpm seed` instead of +`pnpm bootstrap`. Re-run the sync any time with `pnpm analytics-sync` (needs +`SANITY_API_WRITE_TOKEN` in `.env`, or use the seed which uses your CLI login). + +The default `ANALYTICS_PROVIDER=fixture` ships deterministic demo metrics, so +everything works with **no analytics credentials**. Point it at real data by +setting `ANALYTICS_PROVIDER=ga4` and implementing the GA4 provider skeleton in +`packages/@starter/analytics-sync/src/providers/ga4.ts`. + +## Project structure + +``` +analytics-content-ops/ +├── studio/ # Sanity Studio v5 +│ ├── schemaTypes/ # article, articlePerformance, analyticsContext, author, category +│ ├── components/ # PerformanceTierBadge, PerformancePanel +│ ├── lib/performance.ts # tier/lifecycle vocabulary + editorial cues +│ ├── structure.ts # triage views + Performance panel view +│ └── seed/ # demo articles + images +├── frontend/ # Next.js 16 + React 19 + Tailwind v4 +│ ├── app/ # home (trending rail), article pages +│ └── sanity/queries.ts # GROQ intelligence features +├── functions/ # Sanity Functions +│ ├── analytics-sync/ # Phase 2 scheduled sync +│ └── agent-triage/ # Content Agent nightly triage +├── packages/@starter/ +│ └── analytics-sync/ # framework-agnostic sync + tier classification +├── scripts/analytics-sync.ts # Phase 1 standalone / CI sync +├── sanity.blueprint.ts # scheduled + on-publish functions, robot token +└── .github/workflows/ # ci.yml + analytics-sync.yml (Phase 1 cron) +``` + +## Environment variables + +Each workspace manages its own `.env` (never committed). Copy from the matching +`.env.example` and set the same project ID / dataset in all three: + +| File | Loaded by | Required vars | +| --------------- | ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- | +| `studio/.env` | Studio CLI (`sanity.cli.ts` → `process.loadEnvFile`), `pnpm bootstrap`, `sanity dev` | `SANITY_STUDIO_PROJECT_ID`, `SANITY_STUDIO_DATASET`, optional `SANITY_STUDIO_PREVIEW_URL` | +| `frontend/.env` | Next.js | `NEXT_PUBLIC_SANITY_PROJECT_ID`, `NEXT_PUBLIC_SANITY_DATASET`, optional `SANITY_API_READ_TOKEN` / `NEXT_PUBLIC_SANITY_STUDIO_URL` | +| `.env` (root) | Blueprint (`dotenv/config` in `sanity.blueprint.ts`), Phase 1 sync | `SANITY_STUDIO_PROJECT_ID`, `SANITY_STUDIO_DATASET`, `ANALYTICS_PROVIDER`, optional `SANITY_API_WRITE_TOKEN` + GA4 vars | + +**Common failure:** putting values only in root `.env.local`. That file is used by +`scripts/analytics-sync.ts`, but **not** by Studio CLI or blueprint deploy. Without +`studio/.env` and root `.env`, bootstrap exits with +`Unable to resolve project ID/dataset from CLI configuration`. + +## Scripts + +| Command | Description | +| --------------------------- | --------------------------------------------------------- | +| `pnpm dev` | Studio + frontend + functions concurrently | +| `pnpm bootstrap` | Deploy blueprint + schema, typegen, seed content + signal | +| `pnpm seed` | Seed demo content and run the fixture sync | +| `pnpm analytics-sync` | Run the analytics sync (Phase 1 / on demand) | +| `pnpm build` | Build all workspaces | +| `pnpm typegen` | Regenerate Sanity TypeGen types | +| `pnpm typecheck` | Type-check all workspaces | +| `pnpm lint` / `pnpm format` | Lint / format | +| `pnpm validate` | Validate the starter template structure | + +## Key design decisions + +- **Companion document, not embedded fields.** Analytics lives in + `articlePerformance`, not on `article`, so `article._updatedAt` stays a purely + editorial signal and webhooks can distinguish sync writes by `_type`. +- **Derived signal only.** No raw pageviews in Sanity — the analytics platform + stays authoritative. `catalogPercentile` (0–100) is the one human-readable + number. +- **Draft as the review gate.** The triage agent stages changes in the draft; a + human publishes to approve. Nothing goes live automatically. + +See [`AGENT.md`](./AGENT.md) for the full agent-facing guide. diff --git a/analytics-content-ops/eslint.config.mjs b/analytics-content-ops/eslint.config.mjs new file mode 100644 index 0000000..164f049 --- /dev/null +++ b/analytics-content-ops/eslint.config.mjs @@ -0,0 +1,8 @@ +import config from '@starter/eslint-config' + +export default [ + { + ignores: ['functions/**/vendor/', '**/dist/', '**/.sanity/', '**/sanity.types.ts', '**/.next/'], + }, + ...config, +] diff --git a/analytics-content-ops/frontend/.env.example b/analytics-content-ops/frontend/.env.example new file mode 100644 index 0000000..b241143 --- /dev/null +++ b/analytics-content-ops/frontend/.env.example @@ -0,0 +1,16 @@ +# Copy this file to frontend/.env and fill in your values. +# Use the same project ID / dataset as studio/.env and the root .env. + +# Sanity project ID +NEXT_PUBLIC_SANITY_PROJECT_ID= + +# Sanity dataset name (usually "production") +NEXT_PUBLIC_SANITY_DATASET=production + +# URL of the deployed Studio (used for Visual Editing stega links). +# Defaults to "/studio" when unset. +# NEXT_PUBLIC_SANITY_STUDIO_URL=http://localhost:3333 + +# Sanity API token with Viewer permissions (read-only), for draft previews. +# Create at: sanity.io/manage -> Your Project -> API -> Tokens +# SANITY_API_READ_TOKEN= diff --git a/analytics-content-ops/frontend/app/api/draft-mode/disable/route.ts b/analytics-content-ops/frontend/app/api/draft-mode/disable/route.ts new file mode 100644 index 0000000..ab8ef32 --- /dev/null +++ b/analytics-content-ops/frontend/app/api/draft-mode/disable/route.ts @@ -0,0 +1,8 @@ +import {draftMode} from 'next/headers' +import {NextResponse} from 'next/server' + +export async function GET(request: Request) { + const dm = await draftMode() + dm.disable() + return NextResponse.redirect(new URL('/', request.url)) +} diff --git a/analytics-content-ops/frontend/app/api/draft-mode/enable/route.ts b/analytics-content-ops/frontend/app/api/draft-mode/enable/route.ts new file mode 100644 index 0000000..cf44886 --- /dev/null +++ b/analytics-content-ops/frontend/app/api/draft-mode/enable/route.ts @@ -0,0 +1,7 @@ +import {defineEnableDraftMode} from 'next-sanity/draft-mode' + +import {client, token} from '@/sanity/client' + +export const {GET} = defineEnableDraftMode({ + client: client.withConfig({token}), +}) diff --git a/analytics-content-ops/frontend/app/article/[slug]/page.tsx b/analytics-content-ops/frontend/app/article/[slug]/page.tsx new file mode 100644 index 0000000..43af390 --- /dev/null +++ b/analytics-content-ops/frontend/app/article/[slug]/page.tsx @@ -0,0 +1,181 @@ +import type {Metadata} from 'next' +import Image from 'next/image' +import Link from 'next/link' +import {notFound} from 'next/navigation' +import {ArticleCard} from '@/components/article-card' +import {PortableText} from '@/components/portable-text' +import {SiteFooter} from '@/components/site-footer' +import {SiteHeader} from '@/components/site-header' +import {sanityFetch} from '@/sanity/live' +import {urlFor} from '@/sanity/image' +import {ARTICLE_QUERY, ARTICLE_SLUGS_QUERY, RELATED_QUERY} from '@/sanity/queries' +import { + type ArticleCardData, + type ArticleData, + formatAuthors, + formatDate, + readingTimeLabel, +} from '@/lib/types' + +export async function generateStaticParams() { + // Resilient to an empty/unconfigured dataset so the first `next build` + // succeeds before any content has been seeded. + try { + const {data} = await sanityFetch({ + query: ARTICLE_SLUGS_QUERY, + perspective: 'published', + stega: false, + }) + return ((data ?? []) as Array<{slug: string | null}>) + .filter((p): p is {slug: string} => Boolean(p.slug)) + .map((p) => ({slug: p.slug})) + } catch { + return [] + } +} + +export async function generateMetadata({ + params, +}: { + params: Promise<{slug: string}> +}): Promise { + const {slug} = await params + const {data} = await sanityFetch({query: ARTICLE_QUERY, params: {slug}, stega: false}) + const article = data as ArticleData | null + if (!article) return {title: 'Not found — Friluft Media'} + return { + title: article.seoTitle || `${article.title} — Friluft Media`, + description: article.seoDescription || article.dek || undefined, + } +} + +export default async function ArticlePage({params}: {params: Promise<{slug: string}>}) { + const {slug} = await params + + const [{data: postData}, {data: relatedData}] = await Promise.all([ + sanityFetch({query: ARTICLE_QUERY, params: {slug}}), + sanityFetch({query: RELATED_QUERY, params: {slug}}), + ]) + + const article = postData as ArticleData | null + if (!article) notFound() + + const related = (relatedData ?? []) as ArticleCardData[] + const authors = formatAuthors(article.authors) + const leadImage = article.image + ? urlFor(article.image).width(1600).height(900).fit('crop').url() + : '/placeholder.svg' + + return ( +
+ + +
+
+
+ + ← + Back to journal + + +
+ {article.category && {article.category}} + · + {readingTimeLabel(article.readingTimeMinutes)} +
+ +

+ {article.title} +

+

+ {article.dek} +

+ +
+
+ {authors} + + · + + {formatDate(article.date)} +
+ {article.sourceUrl && ( + + Read on Sanity ↗ + + )} +
+
+ +
+
+ +
+
+ +
+ {article.body && } + + {article.sourceUrl && ( +
+

+ This is a real article originally published on the Sanity blog, written by{' '} + {authors}. Read the full, original version at{' '} + + sanity.io/blog + + . +

+
+ )} +
+
+ + {related.length > 0 && ( +
+
+
+

+ Keep reading +

+ + All stories + +
+
+ {related.map((rel) => ( + + ))} +
+
+
+ )} +
+ + +
+ ) +} diff --git a/analytics-content-ops/frontend/app/globals.css b/analytics-content-ops/frontend/app/globals.css new file mode 100644 index 0000000..8eda82b --- /dev/null +++ b/analytics-content-ops/frontend/app/globals.css @@ -0,0 +1,67 @@ +@import 'tailwindcss'; + +@theme inline { + --font-sans: var(--font-inter), ui-sans-serif, system-ui, sans-serif; + --font-serif: var(--font-fraunces), ui-serif, Georgia, serif; + --color-ring: var(--ring); + --color-input: var(--input); + --color-border: var(--border); + --color-destructive: var(--destructive); + --color-accent-foreground: var(--accent-foreground); + --color-accent: var(--accent); + --color-muted-foreground: var(--muted-foreground); + --color-muted: var(--muted); + --color-secondary-foreground: var(--secondary-foreground); + --color-secondary: var(--secondary); + --color-primary-foreground: var(--primary-foreground); + --color-primary: var(--primary); + --color-card-foreground: var(--card-foreground); + --color-card: var(--card); + --color-foreground: var(--foreground); + --color-background: var(--background); + --radius-sm: calc(var(--radius) * 0.6); + --radius-md: calc(var(--radius) * 0.8); + --radius-lg: var(--radius); +} + +:root { + color-scheme: light; + /* Birch off-white background, warm charcoal ink, deep fjord-pine accent */ + --background: oklch(0.968 0.006 95); + --foreground: oklch(0.235 0.012 75); + --card: oklch(0.988 0.005 95); + --card-foreground: oklch(0.235 0.012 75); + --primary: oklch(0.4 0.045 175); + --primary-foreground: oklch(0.97 0.01 95); + --secondary: oklch(0.93 0.008 95); + --secondary-foreground: oklch(0.3 0.015 75); + --muted: oklch(0.93 0.008 95); + --muted-foreground: oklch(0.52 0.014 80); + --accent: oklch(0.6 0.09 55); + --accent-foreground: oklch(0.97 0.01 95); + --destructive: oklch(0.55 0.16 28); + --border: oklch(0.885 0.009 90); + --input: oklch(0.885 0.009 90); + --ring: oklch(0.4 0.045 175); + --radius: 0.25rem; +} + +@layer base { + * { + @apply border-border; + } + body { + @apply bg-background text-foreground; + } +} + +/* Drop cap on the first paragraph of an article body */ +.article-body > p:first-of-type::first-letter { + float: left; + margin-right: 0.75rem; + font-family: var(--font-serif); + font-size: 3.75rem; + font-weight: 500; + line-height: 0.8; + color: var(--primary); +} diff --git a/analytics-content-ops/frontend/app/layout.tsx b/analytics-content-ops/frontend/app/layout.tsx new file mode 100644 index 0000000..e89f96f --- /dev/null +++ b/analytics-content-ops/frontend/app/layout.tsx @@ -0,0 +1,36 @@ +import './globals.css' + +import type {Metadata, Viewport} from 'next' +import {Fraunces, Inter} from 'next/font/google' +import {draftMode} from 'next/headers' +import {VisualEditing} from 'next-sanity/visual-editing' + +import {SanityLive} from '@/sanity/live' + +const fraunces = Fraunces({subsets: ['latin'], variable: '--font-fraunces', display: 'swap'}) +const inter = Inter({subsets: ['latin'], variable: '--font-inter', display: 'swap'}) + +export const metadata: Metadata = { + title: 'Friluft Media — analytics-informed content operations', + description: + 'A Sanity starter that turns analytics signal into editorial action: trending rails powered by GROQ, performance context in Studio, and automated Content Agent triage.', +} + +export const viewport: Viewport = { + colorScheme: 'light', + themeColor: '#f2efe9', +} + +export default async function RootLayout({children}: {children: React.ReactNode}) { + const {isEnabled: isDraftMode} = await draftMode() + + return ( + + + {children} + + {isDraftMode && } + + + ) +} diff --git a/analytics-content-ops/frontend/app/page.tsx b/analytics-content-ops/frontend/app/page.tsx new file mode 100644 index 0000000..d933eed --- /dev/null +++ b/analytics-content-ops/frontend/app/page.tsx @@ -0,0 +1,200 @@ +import Image from 'next/image' +import Link from 'next/link' +import {ArticleCard} from '@/components/article-card' +import {SiteFooter} from '@/components/site-footer' +import {SiteHeader} from '@/components/site-header' +import {sanityFetch} from '@/sanity/live' +import {urlFor} from '@/sanity/image' +import {ARTICLES_QUERY, TRENDING_QUERY} from '@/sanity/queries' +import {type ArticleCardData, formatAuthors, formatDate} from '@/lib/types' + +export default async function HomePage() { + const [{data: articlesData}, {data: trendingData}] = await Promise.all([ + sanityFetch({query: ARTICLES_QUERY}), + sanityFetch({query: TRENDING_QUERY}), + ]) + + const articles = (articlesData ?? []) as ArticleCardData[] + const trending = ((trendingData ?? []) as Array<{article: ArticleCardData | null}>) + .map((row) => row.article) + .filter((a): a is ArticleCardData => Boolean(a)) + + if (articles.length === 0) { + return ( +
+ +
+
+

+ No stories yet +

+

+ Your Sanity dataset is empty. Run{' '} + pnpm seed to import the demo + content, then{' '} + pnpm analytics-sync to + populate performance signal. +

+
+
+ +
+ ) + } + + const [featured, ...rest] = articles + const secondary = rest.slice(0, 2) + const grid = rest.slice(2) + + const featuredImage = featured.image + ? urlFor(featured.image).width(1200).height(825).fit('crop').url() + : '/placeholder.svg' + + return ( +
+ + +
+ {/* Hero */} +
+
+
+

+ Stories from the open air. +

+

+ Friluft Media covers the culture of the Norwegian outdoors — and the modern craft + behind the stories we tell, straight from the team at Sanity. +

+
+ + +
+ +
+
+
+ + Featured + + {featured.category && {featured.category}} +
+

+ {featured.title} +

+

+ {featured.dek} +

+
+ {formatAuthors(featured.authors)} + + · + + {formatDate(featured.date)} +
+
+ +
+
+ + {/* Trending — powered by synced analytics signal (GROQ, no extra integration) */} + {trending.length > 0 && ( +
+
+
+

+ Trending now +

+ + Powered by analytics signal + +
+
+ {trending.map((article) => ( + + ))} +
+
+
+ )} + + {/* Secondary stories */} + {secondary.length > 0 && ( +
+
+ {secondary.map((article) => ( + + ))} +
+
+ )} + + {/* Latest grid */} + {grid.length > 0 && ( +
+
+
+

+ Latest dispatches +

+ + Journal + +
+
+ {grid.map((article) => ( + + ))} +
+
+
+ )} + + {/* Newsletter */} +
+
+
+

+ Dispatches from the trail, twice a month. +

+

+ Join readers across Scandinavia for essays, routes, and field notes. No noise — just + the good stuff. +

+
+
+ + + +
+
+
+
+ + +
+ ) +} diff --git a/analytics-content-ops/frontend/components/article-card.tsx b/analytics-content-ops/frontend/components/article-card.tsx new file mode 100644 index 0000000..fed066e --- /dev/null +++ b/analytics-content-ops/frontend/components/article-card.tsx @@ -0,0 +1,43 @@ +import Image from 'next/image' +import Link from 'next/link' +import {urlFor} from '@/sanity/image' +import {type ArticleCardData, formatAuthors, readingTimeLabel} from '@/lib/types' + +export function ArticleCard({ + article, + priority = false, +}: { + article: ArticleCardData + priority?: boolean +}) { + const imageUrl = article.image + ? urlFor(article.image).width(800).height(600).fit('crop').url() + : '/placeholder.svg' + + return ( + +
+ +
+
+ {article.category && {article.category}} + · + {readingTimeLabel(article.readingTimeMinutes)} +
+

+ {article.title} +

+

+ {article.dek} +

+

{formatAuthors(article.authors)}

+ + ) +} diff --git a/analytics-content-ops/frontend/components/portable-text.tsx b/analytics-content-ops/frontend/components/portable-text.tsx new file mode 100644 index 0000000..fcf6290 --- /dev/null +++ b/analytics-content-ops/frontend/components/portable-text.tsx @@ -0,0 +1,81 @@ +import Image from 'next/image' +import { + PortableText as PortableTextComponent, + type PortableTextComponents, + type PortableTextBlock, +} from '@portabletext/react' +import {urlFor} from '@/sanity/image' + +const components: PortableTextComponents = { + block: { + normal: ({children}) => ( +

{children}

+ ), + h2: ({children}) => ( +

+ {children} +

+ ), + h3: ({children}) => ( +

+ {children} +

+ ), + blockquote: ({children}) => ( +
+ {children} +
+ ), + }, + list: { + bullet: ({children}) => ( +
    {children}
+ ), + number: ({children}) => ( +
    {children}
+ ), + }, + marks: { + link: ({children, value}) => ( + + {children} + + ), + }, + types: { + image: ({value}) => { + if (!value?.asset) return null + return ( +
+
+ {value.alt +
+ {value.caption && ( +
+ {value.caption} +
+ )} +
+ ) + }, + }, +} + +export function PortableText({value}: {value: PortableTextBlock[]}) { + return ( +
+ +
+ ) +} diff --git a/analytics-content-ops/frontend/components/site-footer.tsx b/analytics-content-ops/frontend/components/site-footer.tsx new file mode 100644 index 0000000..d667db2 --- /dev/null +++ b/analytics-content-ops/frontend/components/site-footer.tsx @@ -0,0 +1,75 @@ +import Link from 'next/link' + +const columns = [ + { + heading: 'Sections', + links: ['Journal', 'Adventures', 'Field Notes', 'Gear Reviews', 'Photography'], + }, + { + heading: 'Friluft', + links: ['About us', 'Contributors', 'Editorial ethics', 'Careers', 'Contact'], + }, + {heading: 'Follow', links: ['Newsletter', 'Instagram', 'YouTube', 'Podcast', 'RSS']}, +] + +export function SiteFooter() { + return ( +
+
+
+
+
+ + Friluft + + + Media + +
+

+ An independent outdoor publication based in Norway — and a Sanity demo for + analytics-informed content operations. Trending rails and triage views are powered by + synced performance signal, not a separate analytics integration. +

+
+ + {columns.map((col) => ( +
+

+ {col.heading} +

+
    + {col.links.map((link) => ( +
  • + + {link} + +
  • + ))} +
+
+ ))} +
+ +
+

© {new Date().getFullYear()} Friluft Media. A Sanity starter demo.

+

+ Featured articles are real posts from the{' '} + + Sanity blog + + . +

+
+
+
+ ) +} diff --git a/analytics-content-ops/frontend/components/site-header.tsx b/analytics-content-ops/frontend/components/site-header.tsx new file mode 100644 index 0000000..51f3220 --- /dev/null +++ b/analytics-content-ops/frontend/components/site-header.tsx @@ -0,0 +1,50 @@ +import Link from 'next/link' + +const nav = [ + {label: 'Journal', href: '/'}, + {label: 'Adventures', href: '/'}, + {label: 'Field Notes', href: '/'}, + {label: 'Gear', href: '/'}, + {label: 'About', href: '/'}, +] + +export function SiteHeader() { + return ( +
+
+ + + Friluft + + + Media + + + + + +
+ + Oslo · 4°C + + + Subscribe + +
+
+
+ ) +} diff --git a/analytics-content-ops/frontend/lib/types.ts b/analytics-content-ops/frontend/lib/types.ts new file mode 100644 index 0000000..1074d9f --- /dev/null +++ b/analytics-content-ops/frontend/lib/types.ts @@ -0,0 +1,41 @@ +import type {SanityImageSource} from '@sanity/image-url/lib/types/types' +import type {PortableTextBlock} from '@portabletext/react' + +// Hand-written result shapes for the card/detail projections so the app +// type-checks without a connected project. After `pnpm typegen` you can switch +// to the generated `*_QUERYResult` types in `@starter/sanity-types`. +export type ArticleCardData = { + _id: string + title: string | null + slug: string | null + dek: string | null + date: string | null + category: string | null + authors: Array | null + image: SanityImageSource | null + readingTimeMinutes: number | null +} + +export type ArticleData = ArticleCardData & { + body: PortableTextBlock[] | null + sourceUrl: string | null + seoTitle: string | null + seoDescription: string | null +} + +export function readingTimeLabel(minutes: number | null | undefined): string { + return `${Math.max(1, Math.round(minutes ?? 1))} min read` +} + +export function formatAuthors(authors: ArticleCardData['authors']): string { + return (authors ?? []).filter(Boolean).join(' & ') +} + +export function formatDate(date: string | null | undefined): string { + if (!date) return '' + return new Date(date).toLocaleDateString('en-US', { + year: 'numeric', + month: 'long', + day: 'numeric', + }) +} diff --git a/analytics-content-ops/frontend/next.config.ts b/analytics-content-ops/frontend/next.config.ts new file mode 100644 index 0000000..f686147 --- /dev/null +++ b/analytics-content-ops/frontend/next.config.ts @@ -0,0 +1,9 @@ +import type {NextConfig} from 'next' + +const config: NextConfig = { + images: { + remotePatterns: [{hostname: 'cdn.sanity.io'}], + }, +} + +export default config diff --git a/analytics-content-ops/frontend/package.json b/analytics-content-ops/frontend/package.json new file mode 100644 index 0000000..6a59633 --- /dev/null +++ b/analytics-content-ops/frontend/package.json @@ -0,0 +1,31 @@ +{ + "name": "frontend", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "next dev", + "build": "next build", + "start": "next start", + "lint": "next lint", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@portabletext/react": "catalog:", + "@sanity/image-url": "catalog:", + "next": "^16.1.6", + "next-sanity": "^12.1.1", + "react": "catalog:", + "react-dom": "catalog:" + }, + "devDependencies": { + "@starter/sanity-types": "workspace:*", + "@starter/tsconfig": "workspace:*", + "@tailwindcss/postcss": "^4.2.1", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "postcss": "^8.5.8", + "tailwindcss": "^4.2.1", + "typescript": "catalog:" + } +} diff --git a/analytics-content-ops/frontend/postcss.config.mjs b/analytics-content-ops/frontend/postcss.config.mjs new file mode 100644 index 0000000..a7f73a2 --- /dev/null +++ b/analytics-content-ops/frontend/postcss.config.mjs @@ -0,0 +1,5 @@ +export default { + plugins: { + '@tailwindcss/postcss': {}, + }, +} diff --git a/analytics-content-ops/frontend/public/icon.svg b/analytics-content-ops/frontend/public/icon.svg new file mode 100644 index 0000000..5c11e6c --- /dev/null +++ b/analytics-content-ops/frontend/public/icon.svg @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/analytics-content-ops/frontend/public/placeholder.svg b/analytics-content-ops/frontend/public/placeholder.svg new file mode 100644 index 0000000..e763910 --- /dev/null +++ b/analytics-content-ops/frontend/public/placeholder.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/analytics-content-ops/frontend/sanity/client.ts b/analytics-content-ops/frontend/sanity/client.ts new file mode 100644 index 0000000..11b548a --- /dev/null +++ b/analytics-content-ops/frontend/sanity/client.ts @@ -0,0 +1,15 @@ +import {createClient} from 'next-sanity' + +import {apiVersion, dataset, projectId, studioUrl} from './env' + +export const client = createClient({ + projectId, + dataset, + apiVersion, + useCdn: true, + stega: { + studioUrl, + }, +}) + +export const token = process.env.SANITY_API_READ_TOKEN diff --git a/analytics-content-ops/frontend/sanity/env.ts b/analytics-content-ops/frontend/sanity/env.ts new file mode 100644 index 0000000..43459fe --- /dev/null +++ b/analytics-content-ops/frontend/sanity/env.ts @@ -0,0 +1,20 @@ +export const apiVersion = process.env.NEXT_PUBLIC_SANITY_API_VERSION || '2025-01-01' + +export const dataset = assertValue( + process.env.NEXT_PUBLIC_SANITY_DATASET, + 'Missing environment variable: NEXT_PUBLIC_SANITY_DATASET', +) + +export const projectId = assertValue( + process.env.NEXT_PUBLIC_SANITY_PROJECT_ID, + 'Missing environment variable: NEXT_PUBLIC_SANITY_PROJECT_ID', +) + +export const studioUrl = process.env.NEXT_PUBLIC_SANITY_STUDIO_URL || '/studio' + +function assertValue(v: T | undefined, errorMessage: string): T { + if (v === undefined) { + throw new Error(errorMessage) + } + return v +} diff --git a/analytics-content-ops/frontend/sanity/image.ts b/analytics-content-ops/frontend/sanity/image.ts new file mode 100644 index 0000000..0540983 --- /dev/null +++ b/analytics-content-ops/frontend/sanity/image.ts @@ -0,0 +1,10 @@ +import createImageUrlBuilder from '@sanity/image-url' +import type {SanityImageSource} from '@sanity/image-url/lib/types/types' + +import {dataset, projectId} from './env' + +const builder = createImageUrlBuilder({projectId, dataset}) + +export function urlFor(source: SanityImageSource) { + return builder.image(source) +} diff --git a/analytics-content-ops/frontend/sanity/live.ts b/analytics-content-ops/frontend/sanity/live.ts new file mode 100644 index 0000000..c6ba452 --- /dev/null +++ b/analytics-content-ops/frontend/sanity/live.ts @@ -0,0 +1,9 @@ +import {defineLive} from 'next-sanity/live' + +import {client, token} from './client' + +export const {sanityFetch, SanityLive} = defineLive({ + client, + serverToken: token, + browserToken: token, +}) diff --git a/analytics-content-ops/frontend/sanity/queries.ts b/analytics-content-ops/frontend/sanity/queries.ts new file mode 100644 index 0000000..ba3908f --- /dev/null +++ b/analytics-content-ops/frontend/sanity/queries.ts @@ -0,0 +1,62 @@ +import {defineQuery} from 'next-sanity' + +// Card projection shared across listings. `readingTimeMinutes` is derived from +// the body so listings don't need to over-fetch. +const cardFields = /* groq */ ` + _id, + title, + "slug": slug.current, + "dek": excerpt, + "date": publishedAt, + "category": category->title, + "authors": authors[]->name, + "image": mainImage, + "readingTimeMinutes": round(length(pt::text(body)) / 1100) +` + +export const ARTICLES_QUERY = defineQuery(` + *[_type == "article" && defined(slug.current)] | order(publishedAt desc) { + ${cardFields} + } +`) + +// Content-intelligence feature #1: a "Trending" rail powered entirely by the +// synced analytics signal — no separate analytics integration. When the nightly +// sync updates tiers, this rail updates automatically. +export const TRENDING_QUERY = defineQuery(` + *[_type == "articlePerformance" && performanceTier == "trending"] + | order(catalogPercentile desc)[0...6] { + "article": article->{ ${cardFields} } + } +`) + +// Content-intelligence feature #2: "Most read", ranked by catalog percentile +// across every scored article. +export const MOST_READ_QUERY = defineQuery(` + *[_type == "articlePerformance" && defined(catalogPercentile)] + | order(catalogPercentile desc)[0...5] { + "article": article->{ ${cardFields} }, + catalogPercentile + } +`) + +export const ARTICLE_QUERY = defineQuery(` + *[_type == "article" && slug.current == $slug][0] { + ${cardFields}, + body, + sourceUrl, + seoTitle, + seoDescription + } +`) + +export const RELATED_QUERY = defineQuery(` + *[_type == "article" && defined(slug.current) && slug.current != $slug] + | order(publishedAt desc)[0...3] { + ${cardFields} + } +`) + +export const ARTICLE_SLUGS_QUERY = defineQuery(` + *[_type == "article" && defined(slug.current)] { "slug": slug.current } +`) diff --git a/analytics-content-ops/frontend/tsconfig.json b/analytics-content-ops/frontend/tsconfig.json new file mode 100644 index 0000000..bf9927b --- /dev/null +++ b/analytics-content-ops/frontend/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@starter/tsconfig/base.json", + "compilerOptions": { + "plugins": [{"name": "next"}], + "paths": {"@/*": ["./*"]} + }, + "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/analytics-content-ops/functions/agent-review-resolve/index.ts b/analytics-content-ops/functions/agent-review-resolve/index.ts new file mode 100644 index 0000000..b6f1a57 --- /dev/null +++ b/analytics-content-ops/functions/agent-review-resolve/index.ts @@ -0,0 +1,34 @@ +// Agent review resolution — closes the triage loop on *accept*. +// +// Accepting an agent suggestion is a document-lifecycle action (the editor +// publishes the staged draft), not a field edit, so nothing in the schema can +// record the outcome. This Function is the hook: when a staged draft is +// published, its content — including `agentReview.status == "staged"` — lands on +// the published document, and we reset the live article's workflow status to +// `idle` and stamp `reviewedAt` (the cooldown the sync reads before re-queuing). +// +// Why the filter is `status == "staged"`: that value only ever reaches the +// *published* document by publishing a staged draft. The sync writes `queued` +// and the triage function writes `in_progress` to the published doc and `staged` +// only to the draft — so `staged` on the published doc is a unique signature of +// "a human just accepted this," and resetting it to `idle` also stops the +// Function from re-triggering itself. +import {documentEventHandler} from '@sanity/functions' +import {createClient} from '@sanity/client' + +interface ArticleData { + _id: string + _type: string +} + +export const handler = documentEventHandler(async ({context, event}) => { + const client = createClient({...context.clientOptions, apiVersion: '2025-01-01', useCdn: false}) + const id = event.data._id + + await client + .patch(id) + .set({'agentReview.status': 'idle', 'agentReview.reviewedAt': new Date().toISOString()}) + .commit({dryRun: context.local}) + + console.log(`[agent-review-resolve] Accepted agent review for ${id} — reset to idle`) +}) diff --git a/analytics-content-ops/functions/agent-triage/index.ts b/analytics-content-ops/functions/agent-triage/index.ts new file mode 100644 index 0000000..d29e251 --- /dev/null +++ b/analytics-content-ops/functions/agent-triage/index.ts @@ -0,0 +1,145 @@ +// Content Agent triage — the automated "nightly catalog triage" journey. +// +// Runs after the analytics sync. Loads the articles the sync flagged +// (`agentReview.status == "queued"`), asks Agent Actions to write reasoning + +// improvement opportunities and to draft better SEO metadata, and stages the +// result as an unpublished *draft* so a human reviews before anything goes +// live. Marks each article "staged" for the ops lead to pick up. +// +// Safety layers (per PRD): the GROQ filter scopes the agent to queued articles; +// all writes land in the draft, never the published document; and the agent +// only touches editorial/SEO fields — never the read-only analytics signal. +import {scheduledEventHandler} from '@sanity/functions' +import {createClient} from '@sanity/client' +import {defineQuery} from 'groq' +import {env} from 'node:process' + +const QUEUED_QUERY = defineQuery(`*[_type == "article" && agentReview.status == "queued"]{ + _id, + title, + "tier": *[_type == "articlePerformance" && article._ref == ^._id][0].performanceTier, + "referrer": *[_type == "articlePerformance" && article._ref == ^._id][0].topReferrer, + "percentile": *[_type == "articlePerformance" && article._ref == ^._id][0].catalogPercentile +}`) + +interface QueuedArticle { + _id: string + title?: string + tier?: string + referrer?: string + percentile?: number +} + +const INSTRUCTION = `You are a content operations agent triaging an underperforming article. + +Its analytics signal — treat as read-only context, do not restate verbatim: +- performance tier: $tier +- top acquisition channel: $referrer +- catalog percentile: $percentile (0 = worst, 100 = best) + +First, write "agentReview.agentNotes": one short paragraph of reasoning about why this piece may be underperforming, followed by exactly three specific, concrete improvement opportunities as a numbered list. Ground everything in the article's actual content. + +Then draft improved SEO metadata that stays accurate to the content: +- "seoTitle": compelling and specific, 70 characters or fewer. +- "seoDescription": informative and enticing, 160 characters or fewer. + +Optimize primarily for the "$referrer" channel: organic → search intent and keywords; social → a scroll-stopping hook; email → narrative depth with a clear call to action; direct or referral → updated facts and internal linking.` + +export const handler = scheduledEventHandler(async ({context}) => { + const {SANITY_STUDIO_PROJECT_ID: projectId, SANITY_STUDIO_DATASET: dataset} = env + const token = context.clientOptions?.token + // Agent Actions resolves against the deployed schema id, which carries a + // `_.schemas.` prefix. The Studio workspace is named "default" + // (studio/sanity.config.ts), so the deployed id is `_.schemas.default`. + const schemaId = env.SANITY_SCHEMA_ID || '_.schemas.default' + + if (!projectId || !dataset || !token) { + throw new Error('Missing Sanity client configuration') + } + + // apiVersion "vX" enables Agent Actions. + const client = createClient({ + projectId, + dataset, + token, + apiVersion: 'vX', + useCdn: false, + requestTagPrefix: 'fn.analytics-content-ops.triage', + }) + + const queued = await client.fetch(QUEUED_QUERY, {}, {tag: 'triage.queued'}) + if (queued.length === 0) { + console.log('[agent-triage] No queued articles — nothing to do') + return + } + + // One named batch per nightly run — the "Stale Content Refresh" the ops lead + // reviews in the morning. (Promoting this to a first-class Content Release via + // the Releases API is the documented production upgrade — see AGENT.md.) + const releaseId = `stale-content-refresh-${new Date().toISOString().slice(0, 10)}` + console.log(`[agent-triage] Triaging ${queued.length} article(s) into "${releaseId}"`) + + let staged = 0 + for (const article of queued) { + const id = article._id.replace(/^drafts\./, '') + const draftId = `drafts.${id}` + try { + await client + .patch(id) + .set({'agentReview.status': 'in_progress'}) + .commit({tag: 'triage.start'}) + + // Ensure a draft exists so the agent's edits stage instead of publishing. + const published = await client.getDocument(id) + if (published) { + const {_rev: _drop, ...rest} = published + await client.createIfNotExists({...rest, _id: draftId}) + } + + await client.agent.action.generate({ + schemaId, + documentId: draftId, + instruction: INSTRUCTION, + instructionParams: { + tier: {type: 'constant', value: article.tier ?? 'stale'}, + referrer: {type: 'constant', value: article.referrer ?? 'organic'}, + percentile: {type: 'constant', value: String(article.percentile ?? 0)}, + }, + // `path` takes an array of segments, not a JSONMatch dot-string — a + // dot-string is read as one literal top-level field and silently + // dropped. (Note this differs from client.patch().set(), where dot + // notation is valid.) + target: [ + {path: ['agentReview', 'agentNotes']}, + {path: ['seoTitle']}, + {path: ['seoDescription']}, + ], + }) + + await client + .patch(draftId) + .set({ + 'agentReview.status': 'staged', + 'agentReview.releaseId': releaseId, + 'agentReview.reviewedAt': new Date().toISOString(), + }) + .commit({tag: 'triage.stage'}) + + staged++ + console.log(`[agent-triage] Staged ${id}`) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + console.error(`[agent-triage] Failed on ${id}: ${message}`) + // Return to the queue so the next run can retry. + await client + .patch(id) + .set({'agentReview.status': 'queued'}) + .commit({tag: 'triage.retry'}) + .catch(() => { + // best-effort requeue; the next scheduled run retries regardless + }) + } + } + + console.log(`[agent-triage] Done — staged ${staged}/${queued.length} into "${releaseId}"`) +}) diff --git a/analytics-content-ops/functions/analytics-sync/index.ts b/analytics-content-ops/functions/analytics-sync/index.ts new file mode 100644 index 0000000..bd101b1 --- /dev/null +++ b/analytics-content-ops/functions/analytics-sync/index.ts @@ -0,0 +1,45 @@ +// Analytics sync — Phase 2 (Sanity-native scheduled Function). +// +// This is the exact same pipeline as the Phase 1 GitHub Actions cron +// (`scripts/analytics-sync.ts`): both call `runSync` from +// `@starter/analytics-sync`. Migrating from Phase 1 to Phase 2 is an +// infrastructure swap — retire the workflow, keep the logic. +import {scheduledEventHandler} from '@sanity/functions' +import {createClient} from '@sanity/client' +import {env} from 'node:process' +import {resolveProvider, runSync, type SyncClient} from '@starter/analytics-sync' + +export const handler = scheduledEventHandler(async ({context}) => { + const startedAt = Date.now() + + // Scheduled functions have no triggering document, so projectId/dataset are + // injected by the blueprint's `env: {...}` (read from .env at deploy time). + const {SANITY_STUDIO_PROJECT_ID: projectId, SANITY_STUDIO_DATASET: dataset} = env + const token = context.clientOptions?.token + + if (!projectId || !dataset || !token) { + console.error( + `[analytics-sync] Missing client config: projectId=${Boolean(projectId)} dataset=${Boolean(dataset)} token=${Boolean(token)}`, + ) + throw new Error('Missing Sanity client configuration') + } + + const client = createClient({ + projectId, + dataset, + token, + apiVersion: '2025-01-01', + useCdn: false, + requestTagPrefix: 'fn.analytics-content-ops.sync', + }) + + const provider = resolveProvider(env.ANALYTICS_PROVIDER) + console.log(`[analytics-sync] Starting (provider=${provider.name} dataset=${dataset})`) + + const result = await runSync({client: client as unknown as SyncClient, provider}) + + console.log( + `[analytics-sync] Done in ${Date.now() - startedAt}ms — ${result.scored}/${result.totalArticles} scored, ` + + `${result.counts.trending} trending, ${result.counts.stale} stale, ${result.newlyQueued} newly queued`, + ) +}) diff --git a/analytics-content-ops/functions/package.json b/analytics-content-ops/functions/package.json new file mode 100644 index 0000000..2b34915 --- /dev/null +++ b/analytics-content-ops/functions/package.json @@ -0,0 +1,25 @@ +{ + "name": "@starter/functions", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "clean": "rm -rf dist", + "build": "pnpm run clean && rolldown -c rolldown.config.ts", + "typecheck": "tsc --noEmit", + "predev": "pnpm run build", + "dev": "sanity functions dev", + "predeploy": "pnpm run build", + "deploy": "sanity blueprints deploy" + }, + "devDependencies": { + "@sanity/client": "catalog:", + "@sanity/functions": "^1.3.1", + "@starter/analytics-sync": "workspace:*", + "@starter/tsconfig": "workspace:*", + "@types/node": "^22.19.13", + "groq": "catalog:", + "rolldown": "^1.0.0-rc.8", + "sanity": "catalog:" + } +} diff --git a/analytics-content-ops/functions/rolldown.config.ts b/analytics-content-ops/functions/rolldown.config.ts new file mode 100644 index 0000000..f659356 --- /dev/null +++ b/analytics-content-ops/functions/rolldown.config.ts @@ -0,0 +1,16 @@ +import {defineConfig} from 'rolldown' + +const fn = (name: string) => + defineConfig({ + input: {index: `${name}/index.ts`}, + output: { + dir: `dist/${name}`, + cleanDir: true, + codeSplitting: false, + minify: true, + comments: false, + }, + platform: 'node', + }) + +export default [fn('analytics-sync'), fn('agent-triage'), fn('agent-review-resolve')] diff --git a/analytics-content-ops/functions/tsconfig.json b/analytics-content-ops/functions/tsconfig.json new file mode 100644 index 0000000..eb05580 --- /dev/null +++ b/analytics-content-ops/functions/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@starter/tsconfig/base.json", + "compilerOptions": { + "lib": ["esnext"], + "noEmit": true + }, + "include": ["**/*.ts"], + "exclude": [".build", "node_modules"] +} diff --git a/analytics-content-ops/package.json b/analytics-content-ops/package.json new file mode 100644 index 0000000..fa9fc7e --- /dev/null +++ b/analytics-content-ops/package.json @@ -0,0 +1,61 @@ +{ + "name": "analytics-content-ops", + "version": "1.0.0", + "private": true, + "description": "Analytics-informed content operations starter. Sync performance signal from any analytics platform into Sanity so editors act on it in Studio, developers power content-intelligence features with GROQ, and Content Agent triages the catalog automatically. Built with Sanity Studio v5, Next.js 16, and Sanity Functions.", + "keywords": [ + "AI", + "Analytics", + "Content Agent", + "Content Operations", + "Editorial Workflow", + "GA4", + "GROQ", + "Media", + "Next.js", + "Sanity" + ], + "homepage": "https://github.com/sanity-labs/starters/tree/main/analytics-content-ops#readme", + "bugs": { + "url": "https://github.com/sanity-labs/starters/issues" + }, + "license": "MIT", + "type": "module", + "scripts": { + "dev": "concurrently -n studio,frontend,functions -c '#f03e2f,#8b5cf6,#f5a623' 'pnpm --filter studio dev' 'pnpm --filter frontend dev' 'pnpm --filter @starter/functions build && sanity functions dev'", + "build": "pnpm -r build", + "test": "pnpm -r test", + "lint": "eslint --cache --cache-location node_modules/.cache/eslint/ .", + "format": "oxfmt .", + "format:check": "oxfmt --check .", + "typegen": "pnpm --filter studio typegen", + "pretypecheck": "pnpm run typegen", + "typecheck": "pnpm -r typecheck", + "bootstrap": "pnpm --filter studio bootstrap", + "seed": "pnpm --filter studio seed", + "analytics-sync": "tsx scripts/analytics-sync.ts", + "fn:sync": "tsx scripts/fn.ts analytics-sync", + "fn:triage": "tsx scripts/fn.ts agent-triage", + "validate": "sanity-template-validate" + }, + "devDependencies": { + "@sanity/blueprints": "^0.17.1", + "@sanity/client": "catalog:", + "@sanity/functions": "1.3.1", + "@sanity/template-validator": "^3.1.0", + "@starter/analytics-sync": "workspace:*", + "@starter/eslint-config": "workspace:*", + "@types/node": "^22.19.13", + "concurrently": "^9.2.1", + "dotenv": "^17.4.2", + "eslint": "^9.39.3", + "groq": "catalog:", + "oxfmt": "^0.46.0", + "sanity": "catalog:", + "tsx": "^4.21.0" + }, + "engines": { + "node": ">=20.19 <22 || >=22.12" + }, + "packageManager": "pnpm@10.30.3" +} diff --git a/analytics-content-ops/packages/@starter/analytics-sync/package.json b/analytics-content-ops/packages/@starter/analytics-sync/package.json new file mode 100644 index 0000000..6edd2d6 --- /dev/null +++ b/analytics-content-ops/packages/@starter/analytics-sync/package.json @@ -0,0 +1,17 @@ +{ + "name": "@starter/analytics-sync", + "version": "1.0.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts", + "./providers": "./src/providers/index.ts" + }, + "scripts": { + "typecheck": "tsc --noEmit" + }, + "devDependencies": { + "@starter/tsconfig": "workspace:*", + "typescript": "catalog:" + } +} diff --git a/analytics-content-ops/packages/@starter/analytics-sync/src/classify.ts b/analytics-content-ops/packages/@starter/analytics-sync/src/classify.ts new file mode 100644 index 0000000..4a2bd42 --- /dev/null +++ b/analytics-content-ops/packages/@starter/analytics-sync/src/classify.ts @@ -0,0 +1,115 @@ +import type {AnalyticsMetric, LifecycleState, PerformanceSignal, TrendDirection} from './types' + +// Tuning knobs for tier classification. Tiers are catalog-*relative*: a piece +// is "stale" compared to its peers, not against an absolute pageview number. +// Adjust these in one place (or per-section in a real deployment). +export interface ClassifyOptions { + // Fraction of the catalog (by session growth) that counts as trending. + trendingTopFraction: number + // Fraction of the catalog (by sessions) that counts as stale… + staleBottomFraction: number + // …but only once an article is older than this many days. + staleMinAgeDays: number + // Articles younger than this are always classified "new". + newMaxAgeDays: number + // Growth thresholds for trend direction, as a ratio vs. the previous window. + risingRatio: number + fallingRatio: number + // Age past which a low-traffic, falling article becomes an archive candidate. + archiveMinAgeDays: number +} + +export const DEFAULT_OPTIONS: ClassifyOptions = { + trendingTopFraction: 0.1, + staleBottomFraction: 0.25, + staleMinAgeDays: 90, + newMaxAgeDays: 14, + risingRatio: 1.2, + fallingRatio: 0.8, + archiveMinAgeDays: 180, +} + +function trendOf(m: AnalyticsMetric, o: ClassifyOptions): TrendDirection { + const prev = m.previousSessions || 1 + const ratio = m.sessions / prev + if (ratio >= o.risingRatio) return 'rising' + if (ratio <= o.fallingRatio) return 'falling' + return 'flat' +} + +function lifecycleOf( + m: AnalyticsMetric, + trend: TrendDirection, + percentile: number, + o: ClassifyOptions, +): LifecycleState { + if (m.ageDays >= o.archiveMinAgeDays && percentile <= 15 && trend !== 'rising') { + return 'archive_candidate' + } + if (percentile <= 10 && trend === 'falling') return 'dormant' + if (trend === 'falling') return 'declining' + return 'active' +} + +// Classify the whole catalog at once — percentile and top/bottom cutoffs are +// only meaningful relative to the full set of metrics. +export function classifyCatalog( + metrics: AnalyticsMetric[], + options: Partial = {}, +): Map { + const o = {...DEFAULT_OPTIONS, ...options} + const result = new Map() + if (metrics.length === 0) return result + + // Rank by sessions to derive catalog percentile (0–100). + const bySessions = [...metrics].sort((a, b) => a.sessions - b.sessions) + const rank = new Map() + bySessions.forEach((m, i) => rank.set(m.slug, i)) + + // Session growth ranking feeds the trending cutoff. + const growth = (m: AnalyticsMetric) => m.sessions / (m.previousSessions || 1) + const byGrowth = [...metrics].sort((a, b) => growth(b) - growth(a)) + const trendingCutoff = Math.max(1, Math.ceil(metrics.length * o.trendingTopFraction)) + const trendingSlugs = new Set(byGrowth.slice(0, trendingCutoff).map((m) => m.slug)) + + const staleCutoffIndex = Math.floor(metrics.length * o.staleBottomFraction) + + // Catalog-average 30-day sessions — used for the "X% above/below average" cue. + const catalogAvgSessions = + metrics.reduce((sum, m) => sum + m.sessions, 0) / Math.max(metrics.length, 1) + + for (const m of metrics) { + const percentile = Math.round((rank.get(m.slug)! / (metrics.length - 1 || 1)) * 100) + const trend = trendOf(m, o) + + let tier: PerformanceSignal['performanceTier'] + if (m.ageDays < o.newMaxAgeDays) { + tier = 'new' + } else if (trendingSlugs.has(m.slug) && trend === 'rising') { + tier = 'trending' + } else if (rank.get(m.slug)! < staleCutoffIndex && m.ageDays >= o.staleMinAgeDays) { + tier = 'stale' + } else { + tier = 'stable' + } + + const lifecycleState = lifecycleOf(m, trend, percentile, o) + const sessionsVsCatalogAvgPct = + catalogAvgSessions > 0 + ? Math.round(((m.sessions - catalogAvgSessions) / catalogAvgSessions) * 100) + : 0 + + result.set(m.slug, { + performanceTier: tier, + trendDirection: trend, + lifecycleState, + topReferrer: m.topReferrer, + catalogPercentile: percentile, + sessions30d: m.sessions, + sessionsVsCatalogAvgPct, + dailySessions: m.dailySessions ?? [], + }) + } + + return result +} diff --git a/analytics-content-ops/packages/@starter/analytics-sync/src/index.ts b/analytics-content-ops/packages/@starter/analytics-sync/src/index.ts new file mode 100644 index 0000000..e1bb601 --- /dev/null +++ b/analytics-content-ops/packages/@starter/analytics-sync/src/index.ts @@ -0,0 +1,164 @@ +import {classifyCatalog, type ClassifyOptions} from './classify' +import type {AnalyticsProvider, ArticleRef, SyncClient, SyncResult} from './types' + +export * from './types' +export {classifyCatalog, DEFAULT_OPTIONS} from './classify' +export {resolveProvider, fixtureProvider, ga4Provider} from './providers' + +const ARTICLES_QUERY = `*[_type == "article" && defined(slug.current)]{ + _id, + "slug": slug.current, + publishedAt, + "agentStatus": agentReview.status, + "reviewedAt": agentReview.reviewedAt +}` + +interface ArticleRow { + _id: string + slug: string + publishedAt?: string + agentStatus?: string + // Set when a human last resolved an agent review (accept/dismiss). Used as a + // cooldown so a just-reviewed article isn't immediately re-queued. + reviewedAt?: string +} + +const ONE_DAY = 1000 * 60 * 60 * 24 + +// After a human resolves a review, don't re-queue the article for triage again +// until it has stayed stale for this long — otherwise the nightly sync would +// re-nag the editor the very next run. +const REQUEUE_COOLDOWN_MS = 30 * ONE_DAY + +function ageInDays(publishedAt?: string): number { + if (!publishedAt) return 0 + return Math.max(0, Math.floor((Date.now() - new Date(publishedAt).getTime()) / ONE_DAY)) +} + +export interface RunSyncOptions { + client: SyncClient + provider: AnalyticsProvider + classifyOptions?: Partial + // A run id used to name the companion documents' sync batch. Defaults to now. + now?: Date + tagPrefix?: string +} + +// The whole pipeline: read articles → fetch metrics → classify → write derived +// signal to companion documents, flag newly-stale articles for agent triage, +// and refresh the catalog summary. Pure of any framework — the CLI script and +// the scheduled Function both call this. +export async function runSync(options: RunSyncOptions): Promise { + const {client, provider, classifyOptions} = options + const now = options.now ?? new Date() + const syncedAt = now.toISOString() + const tag = options.tagPrefix ?? 'analytics-sync' + + // Read the *published* catalog only. With no perspective pinned the client + // defaults to `raw`, which returns each article's draft/version siblings as + // extra rows — inflating the catalog denominator (percentiles skew) and + // letting a draft shadow its published article in `bySlug` below (a stale + // article with a lingering draft would then never re-queue). Signal is about + // live content, so published is the canonical view — the same intent the + // `drafts.`-stripping on the write path already encodes. + const articles = await client.fetch( + ARTICLES_QUERY, + {}, + {tag: `${tag}.read`, perspective: 'published'}, + ) + + const refs: ArticleRef[] = articles.map((a) => ({ + slug: a.slug, + ageDays: ageInDays(a.publishedAt), + })) + + const metrics = await provider.fetchMetrics(refs) + const signals = classifyCatalog(metrics, classifyOptions) + + const bySlug = new Map(articles.map((a) => [a.slug, a])) + const mutations: unknown[] = [] + const counts = {trending: 0, stable: 0, stale: 0, new: 0, archiveCandidates: 0} + let newlyQueued = 0 + let scored = 0 + + for (const [slug, signal] of signals) { + const article = bySlug.get(slug) + if (!article) continue + const articleId = article._id.replace(/^drafts\./, '') + scored++ + + counts[signal.performanceTier]++ + if (signal.lifecycleState === 'archive_candidate') counts.archiveCandidates++ + + // Companion document — deterministic id keyed by the article, so re-running + // the sync updates in place instead of creating duplicates. + mutations.push({ + createOrReplace: { + _id: `articlePerformance.${articleId}`, + _type: 'articlePerformance', + article: {_type: 'reference', _ref: articleId}, + performanceTier: signal.performanceTier, + trendDirection: signal.trendDirection, + lifecycleState: signal.lifecycleState, + topReferrer: signal.topReferrer, + catalogPercentile: signal.catalogPercentile, + sessions30d: signal.sessions30d, + sessionsVsCatalogAvgPct: signal.sessionsVsCatalogAvgPct, + dailySessions: signal.dailySessions.map((d, i) => ({ + _type: 'dailySession', + _key: `d${i}-${d.date}`, + date: d.date, + sessions: d.sessions, + })), + syncedAt, + }, + }) + + // Flag articles that have *newly* entered the stale tier for agent triage. + // Only touch idle/unset reviews so we never disturb work already in the + // pipeline (queued/in_progress/staged), and respect a cooldown after a human + // has resolved a review so we don't immediately re-queue what they just + // accepted or dismissed. + const idle = !article.agentStatus || article.agentStatus === 'idle' + const reviewCooldownPassed = + !article.reviewedAt || + now.getTime() - new Date(article.reviewedAt).getTime() > REQUEUE_COOLDOWN_MS + if (signal.performanceTier === 'stale' && idle && reviewCooldownPassed) { + newlyQueued++ + mutations.push({ + patch: { + id: articleId, + setIfMissing: {agentReview: {}}, + set: {'agentReview.status': 'queued'}, + }, + }) + } + } + + // Catalog-level summary for cheap Content Agent context queries. + mutations.push({ + createOrReplace: { + _id: 'analyticsContext', + _type: 'analyticsContext', + totalArticles: articles.length, + trendingCount: counts.trending, + staleCount: counts.stale, + archiveCandidateCount: counts.archiveCandidates, + provider: provider.name, + lastSyncedAt: syncedAt, + }, + }) + + if (mutations.length > 0) { + await client.mutate(mutations, {tag: `${tag}.write`}) + } + + return { + provider: provider.name, + syncedAt, + totalArticles: articles.length, + scored, + newlyQueued, + counts, + } +} diff --git a/analytics-content-ops/packages/@starter/analytics-sync/src/providers/fixture.ts b/analytics-content-ops/packages/@starter/analytics-sync/src/providers/fixture.ts new file mode 100644 index 0000000..71dfa5c --- /dev/null +++ b/analytics-content-ops/packages/@starter/analytics-sync/src/providers/fixture.ts @@ -0,0 +1,139 @@ +import type { + AnalyticsMetric, + AnalyticsProvider, + ArticleRef, + DailySession, + TopReferrer, +} from '../types' + +export type {ArticleRef} from '../types' + +// Curated demo metrics for the seeded articles, tuned to produce a clear spread +// across the triage views: one trending, several stable, a couple of stale +// pieces, and one archive candidate. Slugs match the seed data. +const CURATED: Record< + string, + {sessions: number; previousSessions: number; topReferrer: TopReferrer} +> = { + 'we-dont-write-code-anymore': {sessions: 12034, previousSessions: 4200, topReferrer: 'organic'}, + 'sanity-studio-v6': {sessions: 6100, previousSessions: 6300, topReferrer: 'direct'}, + 'how-to-get-product-feedback-from-agents': { + sessions: 5200, + previousSessions: 5000, + topReferrer: 'social', + }, + 'skills-are-how-your-company-works': { + sessions: 4300, + previousSessions: 2600, + topReferrer: 'email', + }, + 'context-board-game-agent': {sessions: 3000, previousSessions: 3200, topReferrer: 'referral'}, + 'build-a-conference-concierge': {sessions: 2400, previousSessions: 2600, topReferrer: 'organic'}, + 'better-context-better-matches': {sessions: 900, previousSessions: 1500, topReferrer: 'organic'}, + 'how-to-write-for-an-agent': {sessions: 700, previousSessions: 1400, topReferrer: 'organic'}, + 'structure-powers-intelligence': {sessions: 300, previousSessions: 1200, topReferrer: 'social'}, +} + +const REFERRERS: TopReferrer[] = ['organic', 'social', 'direct', 'referral', 'email'] +const WINDOW_DAYS = 30 + +// Stable pseudo-random value in [0,1) seeded by a string — keeps unknown slugs +// deterministic across runs. +function hash01(input: string): number { + let h = 2166136261 + for (let i = 0; i < input.length; i++) { + h ^= input.charCodeAt(i) + h = Math.imul(h, 16777619) + } + return ((h >>> 0) % 1000) / 1000 +} + +function isoDateDaysAgo(daysAgo: number, now = new Date()): string { + const d = new Date(now) + d.setUTCHours(0, 0, 0, 0) + d.setUTCDate(d.getUTCDate() - daysAgo) + return d.toISOString().slice(0, 10) +} + +// Build a realistic-looking 30-day series that sums to ~`totalSessions`, with +// weekday lift, weekend dip, and a slope implied by previous→current growth. +function buildDailySeries( + slug: string, + totalSessions: number, + previousSessions: number, + now = new Date(), +): DailySession[] { + const growth = totalSessions / Math.max(previousSessions, 1) + // Slope across the window: rising pieces climb, falling pieces decay. + const slope = Math.max(-0.45, Math.min(0.55, (growth - 1) * 0.8)) + const weights: number[] = [] + + for (let i = 0; i < WINDOW_DAYS; i++) { + const t = i / (WINDOW_DAYS - 1) // 0 → oldest, 1 → newest + const trend = 1 + slope * (t - 0.5) * 2 + const day = new Date(now) + day.setUTCDate(day.getUTCDate() - (WINDOW_DAYS - 1 - i)) + const dow = day.getUTCDay() // 0 Sun … 6 Sat + const weekday = dow === 0 || dow === 6 ? 0.72 : dow === 1 || dow === 5 ? 0.92 : 1.08 + const noise = 0.85 + hash01(`${slug}:${i}`) * 0.3 + weights.push(Math.max(0.15, trend * weekday * noise)) + } + + const weightSum = weights.reduce((a, b) => a + b, 0) + const raw = weights.map((w) => (w / weightSum) * totalSessions) + + // Round while preserving the total as closely as possible. + const rounded = raw.map((v) => Math.max(0, Math.round(v))) + let diff = totalSessions - rounded.reduce((a, b) => a + b, 0) + let cursor = WINDOW_DAYS - 1 + while (diff !== 0 && WINDOW_DAYS > 0) { + const step = diff > 0 ? 1 : -1 + rounded[cursor] = Math.max(0, rounded[cursor] + step) + diff -= step + cursor = (cursor - 1 + WINDOW_DAYS) % WINDOW_DAYS + } + + return rounded.map((sessions, i) => ({ + date: isoDateDaysAgo(WINDOW_DAYS - 1 - i, now), + sessions, + })) +} + +// A demo analytics source. Requires no external credentials — set +// ANALYTICS_PROVIDER=ga4 for real data. +export function fixtureProvider(): AnalyticsProvider { + return { + name: 'fixture', + async fetchMetrics(articles: ArticleRef[]): Promise { + const now = new Date() + return articles.map((a) => { + const curated = CURATED[a.slug] + if (curated) { + return { + slug: a.slug, + ageDays: a.ageDays, + ...curated, + dailySessions: buildDailySeries( + a.slug, + curated.sessions, + curated.previousSessions, + now, + ), + } + } + // Fallback for any article not in the curated set. + const r = hash01(a.slug) + const sessions = Math.round(500 + r * 8000) + const previousSessions = Math.round(sessions * (0.7 + hash01(`${a.slug}:prev`) * 0.8)) + return { + slug: a.slug, + ageDays: a.ageDays, + sessions, + previousSessions, + topReferrer: REFERRERS[Math.floor(r * REFERRERS.length)], + dailySessions: buildDailySeries(a.slug, sessions, previousSessions, now), + } + }) + }, + } +} diff --git a/analytics-content-ops/packages/@starter/analytics-sync/src/providers/ga4.ts b/analytics-content-ops/packages/@starter/analytics-sync/src/providers/ga4.ts new file mode 100644 index 0000000..1b81237 --- /dev/null +++ b/analytics-content-ops/packages/@starter/analytics-sync/src/providers/ga4.ts @@ -0,0 +1,34 @@ +import type {AnalyticsMetric, AnalyticsProvider, ArticleRef} from '../types' + +// GA4 provider skeleton. This is where you connect the real Google Analytics +// Data API. It intentionally throws until you wire it up so the demo never +// silently reports fabricated numbers as if they were real. +// +// Implementation sketch (Phase 1): +// 1. Read GA4_PROPERTY_ID and GA4_SERVICE_ACCOUNT_KEY (base64 JSON) from env. +// 2. Call the GA Data API `runReport` for `sessions` by `pagePath` over the +// current and previous window, plus `sessionDefaultChannelGroup` for the +// top referrer. +// 3. Map each article slug to its pagePath (e.g. `/article/${slug}`) and +// return one AnalyticsMetric per matched article. +// +// The classification and Sanity write path do not change — only this file does. +export function ga4Provider(): AnalyticsProvider { + return { + name: 'ga4', + async fetchMetrics(_articles: ArticleRef[]): Promise { + const propertyId = process.env.GA4_PROPERTY_ID + const key = process.env.GA4_SERVICE_ACCOUNT_KEY + if (!propertyId || !key) { + throw new Error( + 'GA4 provider selected but GA4_PROPERTY_ID / GA4_SERVICE_ACCOUNT_KEY are not set. ' + + 'Set ANALYTICS_PROVIDER=fixture for the demo, or provide GA4 credentials.', + ) + } + throw new Error( + 'ga4Provider is a skeleton — implement the GA Data API call in ' + + 'packages/@starter/analytics-sync/src/providers/ga4.ts', + ) + }, + } +} diff --git a/analytics-content-ops/packages/@starter/analytics-sync/src/providers/index.ts b/analytics-content-ops/packages/@starter/analytics-sync/src/providers/index.ts new file mode 100644 index 0000000..aea1dec --- /dev/null +++ b/analytics-content-ops/packages/@starter/analytics-sync/src/providers/index.ts @@ -0,0 +1,18 @@ +import type {AnalyticsProvider} from '../types' +import {fixtureProvider} from './fixture' +import {ga4Provider} from './ga4' + +// Select a provider from an environment string so the same sync entrypoint +// works in the demo (fixture) and in production (ga4, or your own adapter). +export function resolveProvider(name = 'fixture'): AnalyticsProvider { + switch (name.toLowerCase()) { + case 'ga4': + return ga4Provider() + case 'fixture': + default: + return fixtureProvider() + } +} + +export {fixtureProvider} from './fixture' +export {ga4Provider} from './ga4' diff --git a/analytics-content-ops/packages/@starter/analytics-sync/src/types.ts b/analytics-content-ops/packages/@starter/analytics-sync/src/types.ts new file mode 100644 index 0000000..e7be972 --- /dev/null +++ b/analytics-content-ops/packages/@starter/analytics-sync/src/types.ts @@ -0,0 +1,86 @@ +// Vocabulary shared with the Studio schema (`studio/lib/performance.ts`). Kept +// duplicated here so this package stays dependency-free and bundles cleanly +// into a Sanity Function. + +export type PerformanceTier = 'trending' | 'stable' | 'stale' | 'new' +export type TrendDirection = 'rising' | 'flat' | 'falling' +export type LifecycleState = 'active' | 'declining' | 'dormant' | 'archive_candidate' +export type TopReferrer = 'organic' | 'social' | 'direct' | 'referral' | 'email' + +// One day of traffic in the current 30-day window. Used to render the Studio +// sparkline / area chart. The analytics platform remains the system of record; +// this series is a display snapshot written by the sync. +export interface DailySession { + date: string // YYYY-MM-DD + sessions: number +} + +// One row of *raw* analytics for an article, as returned by a provider. Most +// raw metrics stay in the pipeline and are classified into derived signal — +// except the 30-day display snapshot (sessions + daily series) which the +// Studio Performance panel needs to render GA-style traffic. +export interface AnalyticsMetric { + slug: string + // Sessions in the current 30-day window and the immediately preceding one, + // used to derive trend direction and the traffic hero number. + sessions: number + previousSessions: number + // Age of the article in days (derived from publishedAt when the provider + // doesn't know it). + ageDays: number + topReferrer: TopReferrer + // Optional 30-day daily series. Fixture always provides this; real providers + // should too when they can. Missing series still get sessions30d + vs-avg. + dailySessions?: DailySession[] +} + +// The articles to fetch metrics for. `ageDays` is derived from `publishedAt` by +// the sync so providers (and classification) can reason about content age. +export interface ArticleRef { + slug: string + ageDays: number +} + +// A provider adapts an analytics platform (GA4, Amplitude, a fixture, …) to the +// AnalyticsMetric shape. Swap providers without touching classification or the +// Sanity write path. +export interface AnalyticsProvider { + readonly name: string + fetchMetrics(articles: ArticleRef[]): Promise +} + +// The derived, action-enabling signal written to the companion document. +export interface PerformanceSignal { + performanceTier: PerformanceTier + trendDirection: TrendDirection + lifecycleState: LifecycleState + topReferrer: TopReferrer + catalogPercentile: number + // Display metrics for the Studio Performance panel (synced snapshot). + sessions30d: number + // Percent vs catalog average sessions. Negative = below average. + // e.g. -15 → "15% below average", 22 → "22% above average". + sessionsVsCatalogAvgPct: number + dailySessions: DailySession[] +} + +// Minimal structural client so the package doesn't depend on a specific +// @sanity/client version. Both `@sanity/client` and the Functions runtime +// client satisfy this. +export interface SyncClient { + fetch( + query: string, + params?: Record, + options?: {tag?: string; perspective?: 'published' | 'drafts' | 'raw'}, + ): Promise + mutate(mutations: unknown[], options?: {tag?: string}): Promise +} + +export interface SyncResult { + provider: string + syncedAt: string + totalArticles: number + scored: number + newlyQueued: number + counts: {trending: number; stable: number; stale: number; new: number; archiveCandidates: number} +} diff --git a/analytics-content-ops/packages/@starter/analytics-sync/tsconfig.json b/analytics-content-ops/packages/@starter/analytics-sync/tsconfig.json new file mode 100644 index 0000000..b1e8c25 --- /dev/null +++ b/analytics-content-ops/packages/@starter/analytics-sync/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "@starter/tsconfig/base.json", + "compilerOptions": { + "lib": ["esnext"], + "noEmit": true + }, + "include": ["src/**/*.ts"] +} diff --git a/analytics-content-ops/packages/@starter/eslint-config/index.js b/analytics-content-ops/packages/@starter/eslint-config/index.js new file mode 100644 index 0000000..1b8c8ba --- /dev/null +++ b/analytics-content-ops/packages/@starter/eslint-config/index.js @@ -0,0 +1,3 @@ +import studio from '@sanity/eslint-config-studio' + +export default [...studio] diff --git a/analytics-content-ops/packages/@starter/eslint-config/package.json b/analytics-content-ops/packages/@starter/eslint-config/package.json new file mode 100644 index 0000000..c6bd8fd --- /dev/null +++ b/analytics-content-ops/packages/@starter/eslint-config/package.json @@ -0,0 +1,12 @@ +{ + "name": "@starter/eslint-config", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + ".": "./index.js" + }, + "dependencies": { + "@sanity/eslint-config-studio": "^6.0.0" + } +} diff --git a/analytics-content-ops/packages/@starter/sanity-types/package.json b/analytics-content-ops/packages/@starter/sanity-types/package.json new file mode 100644 index 0000000..5c489d0 --- /dev/null +++ b/analytics-content-ops/packages/@starter/sanity-types/package.json @@ -0,0 +1,9 @@ +{ + "name": "@starter/sanity-types", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + ".": "./sanity.types.ts" + } +} diff --git a/analytics-content-ops/packages/@starter/tsconfig/base.json b/analytics-content-ops/packages/@starter/tsconfig/base.json new file mode 100644 index 0000000..990aefa --- /dev/null +++ b/analytics-content-ops/packages/@starter/tsconfig/base.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "es2024", + "lib": ["dom", "dom.iterable", "esnext"], + "allowJs": true, + "skipLibCheck": true, + "strict": true, + "forceConsistentCasingInFileNames": true, + "module": "Preserve", + "moduleDetection": "force", + "moduleResolution": "bundler", + "isolatedModules": true, + "verbatimModuleSyntax": true, + "jsx": "preserve", + "incremental": true + } +} diff --git a/analytics-content-ops/packages/@starter/tsconfig/package.json b/analytics-content-ops/packages/@starter/tsconfig/package.json new file mode 100644 index 0000000..bfc4e42 --- /dev/null +++ b/analytics-content-ops/packages/@starter/tsconfig/package.json @@ -0,0 +1,9 @@ +{ + "name": "@starter/tsconfig", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + "./base.json": "./base.json" + } +} diff --git a/analytics-content-ops/pnpm-workspace.yaml b/analytics-content-ops/pnpm-workspace.yaml new file mode 100644 index 0000000..152b4c8 --- /dev/null +++ b/analytics-content-ops/pnpm-workspace.yaml @@ -0,0 +1,21 @@ +packages: + - studio + - frontend + - functions + - packages/@starter/* + +catalog: + sanity: '^5.13.0' + '@sanity/client': '^7.16.0' + '@sanity/icons': '^3.7.4' + '@sanity/image-url': '^1.2.0' + '@sanity/ui': '^3.1.14' + '@sanity/vision': '^5.13.0' + '@portabletext/react': '^4.0.0' + groq: '^5.13.0' + react: '^19.2.4' + react-dom: '^19.2.4' + '@types/react': '^19.2' + '@types/react-dom': '^19.2.3' + styled-components: '^6.3.11' + typescript: '^5.9.3' diff --git a/analytics-content-ops/sanity.blueprint.ts b/analytics-content-ops/sanity.blueprint.ts new file mode 100644 index 0000000..bed404c --- /dev/null +++ b/analytics-content-ops/sanity.blueprint.ts @@ -0,0 +1,89 @@ +/// +import { + defineBlueprint, + defineDocumentFunction, + defineRobotToken, + defineScheduledFunction, +} from '@sanity/blueprints' +import 'dotenv/config' + +const {SANITY_STUDIO_PROJECT_ID, SANITY_STUDIO_DATASET, ANALYTICS_PROVIDER, SANITY_SCHEMA_ID} = + process.env + +if (!SANITY_STUDIO_PROJECT_ID || !SANITY_STUDIO_DATASET) { + throw new Error( + 'Missing required env vars for blueprint deploy: SANITY_STUDIO_PROJECT_ID and SANITY_STUDIO_DATASET must be set in .env', + ) +} + +// Runtime env shared by both scheduled functions. Scheduled functions get no +// triggering-document context, so projectId/dataset must be injected here. +const sharedEnv = { + SANITY_STUDIO_PROJECT_ID, + SANITY_STUDIO_DATASET, + ANALYTICS_PROVIDER: ANALYTICS_PROVIDER ?? 'fixture', +} + +export default defineBlueprint({ + resources: [ + // Scoped robot token the functions run as, so their writes use an explicit + // least-privilege (editor) identity rather than an ambient default token. + defineRobotToken({ + name: 'analytics-content-ops-robot', + label: 'Analytics Content Ops Robot', + memberships: [ + { + resourceType: 'project', + resourceId: SANITY_STUDIO_PROJECT_ID, + roleNames: ['editor'], + }, + ], + }), + + // Phase 2: nightly analytics sync. Replaces the GitHub Actions cron in + // .github/workflows/analytics-sync.yml with identical logic. + defineScheduledFunction({ + name: 'analytics-sync', + src: 'functions/dist/analytics-sync', + event: {expression: '0 3 * * *'}, + timezone: 'America/New_York', + timeout: 120, + robotToken: '$.resources.analytics-content-ops-robot.token', + env: sharedEnv, + }), + + // Content Agent triage, 30 minutes after the sync so newly-stale articles + // are already flagged. Needs the deployed schema id for Agent Actions. + defineScheduledFunction({ + name: 'agent-triage', + src: 'functions/dist/agent-triage', + event: {expression: '30 3 * * *'}, + timezone: 'America/New_York', + timeout: 300, + robotToken: '$.resources.analytics-content-ops-robot.token', + env: { + SANITY_STUDIO_PROJECT_ID, + SANITY_STUDIO_DATASET, + // Deployed schema id for Agent Actions. The Studio workspace is named + // "default" (studio/sanity.config.ts), so its deployed id is + // `_.schemas.default`. Override via SANITY_SCHEMA_ID in .env if renamed. + SANITY_SCHEMA_ID: SANITY_SCHEMA_ID ?? '_.schemas.default', + }, + }), + + // Closes the triage loop on accept. Fires when a staged draft is published + // (its `agentReview.status == "staged"` lands on the published doc) and + // resets the live article's status to idle + stamps reviewedAt. The + // `status == "staged"` filter both scopes it to genuine accepts and prevents + // it from re-triggering on its own idle write. Dismiss is handled in Studio. + defineDocumentFunction({ + name: 'agent-review-resolve', + src: 'functions/dist/agent-review-resolve', + event: { + on: ['create', 'update'], + filter: '_type == "article" && agentReview.status == "staged"', + }, + robotToken: '$.resources.analytics-content-ops-robot.token', + }), + ], +}) diff --git a/analytics-content-ops/scripts/analytics-sync.ts b/analytics-content-ops/scripts/analytics-sync.ts new file mode 100644 index 0000000..7701f68 --- /dev/null +++ b/analytics-content-ops/scripts/analytics-sync.ts @@ -0,0 +1,58 @@ +/** + * Analytics sync — Phase 1 entrypoint (standalone / GitHub Actions cron). + * + * Reads analytics from the configured provider, classifies each article into an + * action-enabling performance signal, and upserts `articlePerformance` + * companion documents in Sanity. Newly-stale articles are flagged for Content + * Agent triage. The heavy lifting lives in `@starter/analytics-sync` so this + * file — and the sibling scheduled Function — stay tiny. + * + * Usage: + * pnpm analytics-sync # uses .env in the repo root + * + * Required env: + * SANITY_STUDIO_PROJECT_ID, SANITY_STUDIO_DATASET, SANITY_API_WRITE_TOKEN + * Optional: + * ANALYTICS_PROVIDER=fixture|ga4 (default: fixture) + */ +import {createClient} from '@sanity/client' +import {config as loadEnv} from 'dotenv' +import {resolveProvider, runSync} from '@starter/analytics-sync' + +loadEnv({path: '.env.local'}) +loadEnv() + +const projectId = process.env.SANITY_STUDIO_PROJECT_ID +const dataset = process.env.SANITY_STUDIO_DATASET || 'production' +const token = process.env.SANITY_API_WRITE_TOKEN + +if (!projectId || !token) { + console.error( + 'Missing env. Set SANITY_STUDIO_PROJECT_ID and SANITY_API_WRITE_TOKEN (Editor token) in .env', + ) + process.exit(1) +} + +const client = createClient({ + projectId, + dataset, + token, + apiVersion: '2025-01-01', + useCdn: false, +}) + +const provider = resolveProvider(process.env.ANALYTICS_PROVIDER) + +console.log(`Running analytics sync (provider=${provider.name}, dataset=${dataset})…`) + +const result = await runSync({client, provider}) + +console.log('✓ Sync complete') +console.log( + ` ${result.scored}/${result.totalArticles} articles scored · ` + + `${result.counts.trending} trending · ${result.counts.stale} stale · ` + + `${result.counts.archiveCandidates} archive candidates`, +) +if (result.newlyQueued > 0) { + console.log(` ${result.newlyQueued} newly-stale article(s) queued for Content Agent triage`) +} diff --git a/analytics-content-ops/scripts/fn.ts b/analytics-content-ops/scripts/fn.ts new file mode 100644 index 0000000..db25648 --- /dev/null +++ b/analytics-content-ops/scripts/fn.ts @@ -0,0 +1,24 @@ +/** + * Run a scheduled Sanity Function locally against the root `.env`. + * + * `sanity functions test` runs the bundle in isolation: it doesn't receive the + * projectId/dataset the blueprint injects on deploy, nor a token — so the + * function's own config guard fails with "Missing Sanity client configuration". + * This wrapper loads the root `.env` (projectId + dataset) into the environment + * and passes `--with-user-token`, so `pnpm fn:triage` / `pnpm fn:sync` just work. + * + * Usage: tsx scripts/fn.ts [extra sanity flags] + */ +import 'dotenv/config' +import {execFileSync} from 'node:child_process' + +const [name, ...rest] = process.argv.slice(2) + +if (!name) { + console.error('Usage: tsx scripts/fn.ts (e.g. agent-triage, analytics-sync)') + process.exit(1) +} + +execFileSync('sanity', ['functions', 'test', name, '--with-user-token', ...rest], { + stdio: 'inherit', +}) diff --git a/analytics-content-ops/skills/analytics-content-ops/SKILL.md b/analytics-content-ops/skills/analytics-content-ops/SKILL.md new file mode 100644 index 0000000..2a495f6 --- /dev/null +++ b/analytics-content-ops/skills/analytics-content-ops/SKILL.md @@ -0,0 +1,89 @@ +--- +name: analytics-content-ops +description: Overview of the analytics-informed content operations starter — how performance signal flows from an analytics platform into Sanity as derived signal, and how Studio, GROQ, and Content Agent turn it into editorial action. Trigger on: analytics content ops, performance signal, articlePerformance, triage views, trending rail, content intelligence, stale content, editorial signal. +--- + +# Analytics-Informed Content Operations + +This starter closes the loop between an analytics platform and editorial action. +A nightly sync classifies the catalog and writes **derived signal** into Sanity; +editors act on it in Studio, developers power "trending"/"most-read" features +with GROQ, and Content Agent triages underperforming content automatically. + +## Core principle + +**Sanity is not the analytics platform.** Raw metrics (pageviews, sessions) +never enter Sanity. The sync classifies them into a small, human-legible +vocabulary (`performanceTier`, `trendDirection`, `lifecycleState`, `topReferrer`, +`catalogPercentile`) and writes only that. The analytics platform stays the +system of record; Sanity is where signal becomes action. + +## Content model + +- **`article`** (`studio/schemaTypes/article.ts`) — the editorial document. Adds + two signal-response fields: `editorialPriority` (the editor's flag) and + `agentReview` (state machine: `idle → queued → in_progress → staged → +approved | dismissed`), plus agent-drafted `seoTitle` / `seoDescription`. +- **`articlePerformance`** (`studio/schemaTypes/articlePerformance.ts`) — a + **companion document**, written only by the sync, never edited by humans. + Deterministic id `articlePerformance.` so re-runs upsert in place. + Deliberately separate from `article` so `article._updatedAt` stays an + _editorial_ signal and webhooks can filter sync writes by `_type`. +- **`analyticsContext`** (`studio/schemaTypes/analyticsContext.ts`) — a read-only + singleton with catalog-level counts for cheap Content Agent context queries. + +Vocabulary is mirrored in `studio/lib/performance.ts` (Studio) and +`packages/@starter/analytics-sync/src/types.ts` (sync). Keep the two in sync. + +## Joining performance to articles (GROQ) + +The companion pattern means you always join by reference: + +```groq +*[_type == "article" && defined(slug.current)]{ + ..., + "performance": *[_type == "articlePerformance" && article._ref == ^._id][0]{ + performanceTier, trendDirection, lifecycleState, catalogPercentile + } +} +``` + +The frontend rails live in `frontend/sanity/queries.ts`: + +- `TRENDING_QUERY` — orders by `articlePerformance` where `performanceTier == "trending"` +- `MOST_READ_QUERY` — orders by `catalogPercentile desc` + +## Studio surfaces + +- **`PerformanceTierBadge`** (`studio/components/PerformanceTierBadge.tsx`) — a + document badge: green "Trending", warning "Stale", red "Archive candidate". +- **Performance panel** (`studio/components/PerformancePanel.tsx`) — a read-only + second view on every article, live-subscribed to the companion doc. Wired via + `defaultDocumentNode` in `studio/structure.ts`. +- **Triage views** (`studio/structure.ts`) — Needs Attention, Trending Now, + Archive Candidates, Content Agent Queue. + +## The two-phase sync + +Both phases call the same `runSync` from `@starter/analytics-sync`: + +- **Phase 1** — `scripts/analytics-sync.ts`, run by GitHub Actions + (`.github/workflows/analytics-sync.yml`). Needs `SANITY_API_WRITE_TOKEN`. +- **Phase 2** — `functions/analytics-sync/`, a scheduled Function registered in + `sanity.blueprint.ts`. + +Migrating Phase 1 → Phase 2 is an infrastructure swap, not a rewrite. + +## Jobs to be done + +- **Add a new analytics source** → see the `analytics-provider-pattern` skill. +- **Change what counts as trending/stale** → tune `ClassifyOptions` in + `packages/@starter/analytics-sync/src/classify.ts` (catalog-relative). +- **Automate content improvement** → see the `content-agent-triage` skill. +- **Surface signal on the site** → add a GROQ join in `frontend/sanity/queries.ts`. + +## References + +- `packages/@starter/analytics-sync/src/index.ts` — `runSync` pipeline +- `studio/structure.ts` — triage views + performance panel wiring +- `README.md` / `AGENT.md` — setup and architecture diff --git a/analytics-content-ops/skills/analytics-provider-pattern/SKILL.md b/analytics-content-ops/skills/analytics-provider-pattern/SKILL.md new file mode 100644 index 0000000..fba4e25 --- /dev/null +++ b/analytics-content-ops/skills/analytics-provider-pattern/SKILL.md @@ -0,0 +1,134 @@ +--- +name: analytics-provider-pattern +description: Build analytics-platform-agnostic sync providers. Core AnalyticsProvider interface, fixture reference implementation, GA4 skeleton, and how to add Amplitude/Heap/Plausible. Trigger on: analytics provider, add analytics source, GA4 integration, fetchMetrics, provider adapter, sync classification, tier tuning. +--- + +# Analytics Provider Pattern + +Make the sync work with any analytics platform by writing one small adapter. The +pattern separates **fetching raw metrics** (provider) from **classifying them** +(catalog-relative) and **writing derived signal** (Sanity). Adding Amplitude or +Heap means writing a new provider, never touching classification or the write +path. + +## Core principle + +**Open–closed.** A new analytics source adds a new provider module and one +`case` in `resolveProvider`. The classification (`classify.ts`) and Sanity write +path (`index.ts` → `runSync`) never change. The provider's only job is to return +`AnalyticsMetric[]`. + +## Package: `@starter/analytics-sync` + +Lives at `packages/@starter/analytics-sync/`, framework-agnostic so it bundles +cleanly into a Sanity Function. + +**Exports:** + +- `.` — `runSync`, `classifyCatalog`, `resolveProvider`, and all types +- `./providers` — `resolveProvider`, `fixtureProvider`, `ga4Provider` + +## The interface + +```typescript +export interface ArticleRef { + slug: string + ageDays: number // derived from publishedAt by the sync +} + +export interface AnalyticsMetric { + slug: string + sessions: number // current window + previousSessions: number // prior window — drives trend direction + ageDays: number + topReferrer: TopReferrer // 'organic' | 'social' | 'direct' | 'referral' | 'email' +} + +export interface AnalyticsProvider { + readonly name: string + fetchMetrics(articles: ArticleRef[]): Promise +} +``` + +A provider is handed the article refs the sync wants metrics for and returns one +`AnalyticsMetric` per article it has data for. Raw metrics stop here — they are +never written to Sanity. + +## Reference implementation: fixture + +`src/providers/fixture.ts` produces deterministic demo metrics (curated per +slug so the seeded catalog spans every tier) — no credentials required. It is +the default (`ANALYTICS_PROVIDER=fixture`) and drives `pnpm seed`. + +## Skeleton: GA4 + +`src/providers/ga4.ts` throws until implemented, so the demo never reports +fabricated numbers as real. Implementation sketch: + +1. Read `GA4_PROPERTY_ID` and `GA4_SERVICE_ACCOUNT_KEY` from env. +2. Call the GA Data API `runReport` for `sessions` by `pagePath` over the current + and previous window, plus `sessionDefaultChannelGroup` for the top referrer. +3. Map each slug to its `pagePath` (e.g. `/article/${slug}`) and return one + `AnalyticsMetric` per matched article. + +## How to add a new provider (Amplitude example) + +### Step 1 — create the module + +```typescript +// packages/@starter/analytics-sync/src/providers/amplitude.ts +import type {AnalyticsMetric, AnalyticsProvider, ArticleRef} from '../types' + +export function amplitudeProvider(): AnalyticsProvider { + return { + name: 'amplitude', + async fetchMetrics(articles: ArticleRef[]): Promise { + const apiKey = process.env.AMPLITUDE_API_KEY + if (!apiKey) throw new Error('AMPLITUDE_API_KEY not set') + // Query Amplitude for sessions per article path, current + previous window, + // then map to AnalyticsMetric. + return articles.map((a) => ({ + slug: a.slug, + sessions: 0, + previousSessions: 0, + ageDays: a.ageDays, + topReferrer: 'organic', + })) + }, + } +} +``` + +### Step 2 — register it in `resolveProvider` + +```typescript +// packages/@starter/analytics-sync/src/providers/index.ts +case 'amplitude': + return amplitudeProvider() +``` + +Also re-export it and select it with `ANALYTICS_PROVIDER=amplitude`. **No other +file changes** — classification and the write path are untouched. + +## Tuning classification (not the provider) + +To change what "trending" or "stale" means, edit `ClassifyOptions` in +`src/classify.ts`. Tiers are **catalog-relative** — a piece is stale compared to +its peers, not against an absolute pageview number: + +- `trendingTopFraction` (0.1) — top 10% by session growth, and `rising` +- `staleBottomFraction` (0.25) + `staleMinAgeDays` (90) — bottom quartile once + old enough +- `newMaxAgeDays` (14) — always "new" while young +- `risingRatio` / `fallingRatio` — trend thresholds vs. the previous window +- `archiveMinAgeDays` (180) — old + bottom-15th percentile + not rising → + `archive_candidate` + +Pass overrides via `runSync({classifyOptions: {...}})` (e.g. per-section tuning). + +## References + +- `packages/@starter/analytics-sync/src/types.ts` — interfaces +- `packages/@starter/analytics-sync/src/providers/` — fixture + ga4 +- `packages/@starter/analytics-sync/src/classify.ts` — tier logic +- `packages/@starter/analytics-sync/src/index.ts` — `runSync` pipeline diff --git a/analytics-content-ops/skills/content-agent-triage/SKILL.md b/analytics-content-ops/skills/content-agent-triage/SKILL.md new file mode 100644 index 0000000..9f16370 --- /dev/null +++ b/analytics-content-ops/skills/content-agent-triage/SKILL.md @@ -0,0 +1,104 @@ +--- +name: content-agent-triage +description: Automate content improvement with Content Agent (Agent Actions) safely. The queued → staged review pipeline, draft-as-review-gate pattern, instruction design, and the Content Release upgrade. Trigger on: content agent, agent actions, agent.action.generate, triage, agentReview, stale content refresh, SEO drafting, review queue. +--- + +# Content Agent Triage + +Automate the "nightly catalog triage" journey: the sync flags underperforming +articles, and a scheduled Function uses Agent Actions to draft reasoning and +improved SEO — always into a **draft** a human approves. Nothing goes live +automatically. + +## Core principle + +**The draft is the review gate.** Every agent write lands in +`drafts.`, never the published document. The ops lead reviews the "Content +Agent Queue" in Studio and publishes to approve. The agent only touches +editorial/SEO fields — never the read-only analytics signal. + +## The state machine + +`agentReview.status` on `article` drives the whole pipeline: + +``` +idle → queued → in_progress → staged → approved | dismissed +``` + +- **`queued`** — set by the sync (`runSync`) when an article _newly_ enters the + `stale` tier and its review is idle/unset. Only idle reviews are touched, so + in-flight work is never disturbed. +- **`in_progress`** — set by the triage Function as it starts an article. +- **`staged`** — set after the agent writes; the draft is ready for review. +- **`approved` / `dismissed`** — the human decision (publish or discard draft). + +## The triage Function + +`functions/agent-triage/index.ts` runs ~30 min after the sync (schedule in +`sanity.blueprint.ts`). Per run: + +1. `QUEUED_QUERY` loads `agentReview.status == "queued"` articles, joining their + `articlePerformance` tier / referrer / percentile as context. +2. For each: set `in_progress`, ensure a draft exists (copy published minus + `_rev` into `drafts.`), call `client.agent.action.generate`, then set + `staged` + `releaseId` + `reviewedAt` on the draft. +3. On error, requeue (`status: 'queued'`) so the next run retries. + +## Agent Actions setup + +```typescript +// apiVersion "vX" is required for Agent Actions. +const client = createClient({projectId, dataset, token, apiVersion: 'vX', useCdn: false}) + +await client.agent.action.generate({ + schemaId, // 'default', or SANITY_SCHEMA_ID — must match the deployed schema + documentId: draftId, // always the draft, never the published id + instruction: INSTRUCTION, // uses $tier / $referrer / $percentile placeholders + instructionParams: { + tier: {type: 'constant', value: article.tier ?? 'stale'}, + referrer: {type: 'constant', value: article.referrer ?? 'organic'}, + percentile: {type: 'constant', value: String(article.percentile ?? 0)}, + }, + // Scope writes to exactly these fields — nothing else can change. + target: [{path: 'agentReview.agentNotes'}, {path: 'seoTitle'}, {path: 'seoDescription'}], +}) +``` + +### Safety layers (why this is trustworthy) + +- **Scoped input** — the GROQ filter limits the agent to queued articles. +- **Scoped output** — `target` restricts writes to editorial/SEO fields. +- **Draft-only** — writes go to `drafts.`; publishing is a human act. +- **Grounded instruction** — the prompt passes signal as read-only context and + tells the agent to ground everything in the article's actual content, then + optimize SEO for the article's top acquisition channel. + +## Instruction design + +The `INSTRUCTION` string channel-tailors the SEO advice: organic → search +intent/keywords; social → a scroll-stopping hook; email → narrative depth + CTA; +direct/referral → updated facts + internal linking. It asks for one reasoning +paragraph plus exactly three concrete improvement opportunities. Keep field +limits explicit (seoTitle ≤ 70 chars, seoDescription ≤ 160). + +## Reviewing in Studio + +`studio/structure.ts` defines the **Content Agent Queue** — articles with +`agentReview.status in ["queued", "in_progress", "staged"]`. Editors open a +staged article, read the agent notes in the `agentReview` object, compare the +drafted SEO, and publish (approve) or discard the draft (dismiss). + +## Production upgrade: Content Releases + +Each run currently tags staged drafts with a `releaseId` +(`stale-content-refresh-YYYY-MM-DD`). The documented upgrade is to promote this +batch to a first-class **Content Release** via the Releases API, so the whole +nightly triage can be reviewed and published atomically. See `AGENT.md`. + +## References + +- `functions/agent-triage/index.ts` — the triage Function +- `packages/@starter/analytics-sync/src/index.ts` — where articles get `queued` +- `studio/schemaTypes/article.ts` — `agentReview` object + status field +- `studio/structure.ts` — Content Agent Queue view +- `sanity.blueprint.ts` — schedule + env injection diff --git a/analytics-content-ops/studio/.env.example b/analytics-content-ops/studio/.env.example new file mode 100644 index 0000000..700f7fc --- /dev/null +++ b/analytics-content-ops/studio/.env.example @@ -0,0 +1,12 @@ +# Copy this file to studio/.env and fill in your values. +# Required for `pnpm bootstrap`, `sanity exec`, and `sanity dev`. +# Studio CLI loads THIS file (studio/.env) — not the root `.env.local`. + +# Your Sanity project ID (from sanity.io/manage) +SANITY_STUDIO_PROJECT_ID=your-project-id + +# Dataset name (usually "production") +SANITY_STUDIO_DATASET=production + +# Where the frontend runs — used by the Presentation tool for Visual Editing +SANITY_STUDIO_PREVIEW_URL=http://localhost:3000 diff --git a/analytics-content-ops/studio/components/DiscardOrDismissAction.tsx b/analytics-content-ops/studio/components/DiscardOrDismissAction.tsx new file mode 100644 index 0000000..7bcf09b --- /dev/null +++ b/analytics-content-ops/studio/components/DiscardOrDismissAction.tsx @@ -0,0 +1,61 @@ +import {useState} from 'react' +import { + DEFAULT_STUDIO_CLIENT_OPTIONS, + useClient, + useDocumentOperation, + type DocumentActionComponent, +} from 'sanity' +import {TrashIcon} from '@sanity/icons' + +// Workflow states in which the draft represents an agent suggestion to dismiss. +const IN_REVIEW = ['queued', 'in_progress', 'staged'] + +/** + * The single discard/reject action for articles — it replaces Studio's default + * "Discard changes" so editors have exactly one way to throw a draft away + * instead of a "Discard changes" and a "Dismiss" button competing side by side. + * + * When the draft carries an agent suggestion it doubles as "Dismiss suggestion": + * it resets the live article's review status to idle (stamping reviewedAt for + * the sync's re-queue cooldown) *before* discarding, so a dismissed article + * can't get stuck mid-pipeline. For an ordinary draft it's a plain discard. + */ +export const DiscardOrDismissAction: DocumentActionComponent = (props) => { + const {id, type, draft, onComplete} = props + const client = useClient(DEFAULT_STUDIO_CLIENT_OPTIONS) + const {discardChanges} = useDocumentOperation(id, type) + const [isBusy, setIsBusy] = useState(false) + + // Nothing to discard without a draft. + if (!draft) return null + + const reviewStatus = (draft as {agentReview?: {status?: string}}).agentReview?.status + const isSuggestion = Boolean(reviewStatus && IN_REVIEW.includes(reviewStatus)) + + const handle = async () => { + setIsBusy(true) + try { + // Close the review on the live article before throwing away the proposal, + // so the sync sees an idle (not stuck in_progress) article afterwards. + if (isSuggestion) { + await client + .patch(id) + .set({'agentReview.status': 'idle', 'agentReview.reviewedAt': new Date().toISOString()}) + .commit() + } + // Discard the draft via Studio's own operation. + discardChanges.execute() + } finally { + setIsBusy(false) + onComplete() + } + } + + return { + label: isSuggestion ? 'Dismiss suggestion' : 'Discard changes', + icon: TrashIcon, + tone: 'critical', + disabled: isBusy || Boolean(discardChanges.disabled), + onHandle: handle, + } +} diff --git a/analytics-content-ops/studio/components/PerformancePanel.tsx b/analytics-content-ops/studio/components/PerformancePanel.tsx new file mode 100644 index 0000000..919bdaf --- /dev/null +++ b/analytics-content-ops/studio/components/PerformancePanel.tsx @@ -0,0 +1,392 @@ +import {useEffect, useId, useMemo, useState} from 'react' +import {Badge, Box, Card, Flex, Inline, Label, Spinner, Stack, Text} from '@sanity/ui' +import {DEFAULT_STUDIO_CLIENT_OPTIONS, useClient} from 'sanity' +import {defineQuery} from 'groq' +import { + TIER_LABELS, + editorialCue, + type LifecycleState, + type PerformanceTier, + type TopReferrer, + type TrendDirection, +} from '../lib/performance' + +const PERFORMANCE_QUERY = defineQuery(`*[_type == "articlePerformance" && article._ref == $id][0]{ + performanceTier, + trendDirection, + lifecycleState, + topReferrer, + catalogPercentile, + sessions30d, + sessionsVsCatalogAvgPct, + dailySessions[]{date, sessions}, + syncedAt +}`) + +type DailySession = {date?: string; sessions?: number} + +type Performance = { + performanceTier?: PerformanceTier + trendDirection?: TrendDirection + lifecycleState?: LifecycleState + topReferrer?: TopReferrer + catalogPercentile?: number + sessions30d?: number + sessionsVsCatalogAvgPct?: number + dailySessions?: DailySession[] + syncedAt?: string +} | null + +const TIER_TONE: Record = { + trending: 'positive', + stable: 'primary', + stale: 'caution', + new: 'primary', +} + +const TREND_GLYPH: Record = { + rising: '↑ Rising', + flat: '→ Flat', + falling: '↓ Falling', +} + +function formatSessions(n: number): string { + return Math.round(n).toLocaleString('en-US') +} + +function formatShortDate(iso?: string): string { + if (!iso) return '' + const d = new Date(`${iso}T00:00:00Z`) + return d.toLocaleDateString('en-US', {month: 'short', day: 'numeric', timeZone: 'UTC'}) +} + +function formatAxisValue(n: number): string { + if (n >= 1000) return `${Math.round(n / 100) / 10}k` + return String(Math.round(n)) +} + +function vsAverageCopy(pct?: number): { + arrow: string + label: string + tone: 'positive' | 'caution' | 'default' +} { + if (typeof pct !== 'number' || pct === 0) { + return {arrow: '→', label: 'in line with catalog average', tone: 'default'} + } + const abs = Math.abs(pct) + if (pct > 0) { + return {arrow: '↑', label: `${abs}% above average`, tone: 'positive'} + } + return {arrow: '↓', label: `${abs}% below average`, tone: 'caution'} +} + +function Row({label, children}: {label: string; children: React.ReactNode}) { + return ( + + + {children} + + ) +} + +function TrafficChart({series}: {series: DailySession[]}) { + const gradientId = useId().replace(/:/g, '') + const points = series.filter((d) => d.date && typeof d.sessions === 'number') as { + date: string + sessions: number + }[] + + if (points.length < 2) { + return ( + + + Not enough daily data to chart yet. + + + ) + } + + const width = 560 + const height = 220 + const pad = {top: 16, right: 12, bottom: 28, left: 40} + const innerW = width - pad.left - pad.right + const innerH = height - pad.top - pad.bottom + const maxY = Math.max(...points.map((p) => p.sessions), 1) + const niceMax = Math.ceil(maxY / 4) * 4 || 4 + const gridYs = [0, 0.25, 0.5, 0.75, 1].map((t) => niceMax * t) + + const xAt = (i: number) => pad.left + (i / (points.length - 1)) * innerW + const yAt = (v: number) => pad.top + innerH - (v / niceMax) * innerH + + const linePath = points + .map((p, i) => `${i === 0 ? 'M' : 'L'} ${xAt(i).toFixed(1)} ${yAt(p.sessions).toFixed(1)}`) + .join(' ') + const areaPath = `${linePath} L ${xAt(points.length - 1).toFixed(1)} ${yAt(0).toFixed(1)} L ${xAt(0).toFixed(1)} ${yAt(0).toFixed(1)} Z` + + const xLabels = [ + {i: 0, label: formatShortDate(points[0].date)}, + { + i: Math.floor((points.length - 1) / 2), + label: formatShortDate(points[Math.floor((points.length - 1) / 2)].date), + }, + {i: points.length - 1, label: formatShortDate(points[points.length - 1].date)}, + ] + + return ( + + + + + Sessions over time + + + Last 30 days + + + + + + + + + + + + {gridYs.map((v) => ( + + + + {formatAxisValue(v)} + + + ))} + + + + + {/* End-point marker, GA-style */} + + + {xLabels.map(({i, label}) => ( + + {label} + + ))} + + + + + ) +} + +// Read-only Performance panel. Subscribes to the companion document so the tier +// updates live after a nightly sync — without ever mutating the article. +export function PerformancePanel(props: {documentId?: string; document?: {documentId?: string}}) { + const client = useClient(DEFAULT_STUDIO_CLIENT_OPTIONS) + const id = (props.documentId ?? props.document?.documentId ?? '').replace(/^drafts\./, '') + const [data, setData] = useState(null) + const [loading, setLoading] = useState(true) + + useEffect(() => { + if (!id) return + let cancelled = false + + const load = () => + client + .fetch(PERFORMANCE_QUERY, {id}, {tag: 'article.panel.performance'}) + .then((r) => { + if (!cancelled) { + setData(r) + setLoading(false) + } + }) + .catch(() => !cancelled && setLoading(false)) + + load() + // Live-update when the sync writes a new companion document. + const sub = client + .listen( + '*[_type == "articlePerformance" && article._ref == $id]', + {id}, + {visibility: 'query'}, + ) + .subscribe(() => load()) + + return () => { + cancelled = true + sub.unsubscribe() + } + }, [client, id]) + + const cue = useMemo( + () => editorialCue(data?.performanceTier, data?.lifecycleState), + [data?.performanceTier, data?.lifecycleState], + ) + + const vsAvg = useMemo( + () => vsAverageCopy(data?.sessionsVsCatalogAvgPct), + [data?.sessionsVsCatalogAvgPct], + ) + + if (loading) { + return ( + + + + ) + } + + if (!data) { + return ( + + + + No performance data yet + + This article has no articlePerformance companion document. Run the + analytics sync (pnpm analytics-sync) to populate it. Analytics stay in + your analytics platform — Sanity only stores derived, action-enabling signal. + + + + + ) + } + + return ( + + + + + + + {data.performanceTier ? TIER_LABELS[data.performanceTier] : 'Unclassified'} + + {data.trendDirection && ( + {TREND_GLYPH[data.trendDirection]} + )} + + {cue} + + + + {/* GA-style traffic hero */} + + + + + + {typeof data.sessions30d === 'number' ? formatSessions(data.sessions30d) : '—'} + + + + {vsAvg.arrow} {vsAvg.label} + + + + + Compared to average-performing content across the catalog + + + + + + + + + + {data.lifecycleState?.replace('_', ' ') ?? '—'} + + + {data.topReferrer ?? '—'} + + + + {typeof data.catalogPercentile === 'number' + ? `p${Math.round(data.catalogPercentile)}` + : '—'} + + + + + {data.syncedAt ? new Date(data.syncedAt).toLocaleString() : 'never'} + + + + + + + Synced display snapshot · analytics platform remains the system of record + + + + ) +} diff --git a/analytics-content-ops/studio/components/PerformanceTierBadge.tsx b/analytics-content-ops/studio/components/PerformanceTierBadge.tsx new file mode 100644 index 0000000..5ae2870 --- /dev/null +++ b/analytics-content-ops/studio/components/PerformanceTierBadge.tsx @@ -0,0 +1,61 @@ +import {useEffect, useState} from 'react' +import { + DEFAULT_STUDIO_CLIENT_OPTIONS, + useClient, + type DocumentBadgeComponent, + type DocumentBadgeDescription, +} from 'sanity' +import {defineQuery} from 'groq' +import {TIER_LABELS, type PerformanceTier} from '../lib/performance' + +// The companion document holds the signal; join to it from the article _id. +const TIER_QUERY = defineQuery( + `*[_type == "articlePerformance" && article._ref == $id][0]{performanceTier, lifecycleState}`, +) + +type TierResult = {performanceTier?: PerformanceTier; lifecycleState?: string} | null + +// Only the tiers worth surfacing get a badge — stable/new stay quiet to reduce +// noise, matching the "reduce noise" decision in the PRD. +const TIER_COLORS: Partial> = { + trending: 'success', + stale: 'warning', +} + +export const PerformanceTierBadge: DocumentBadgeComponent = (props) => { + const client = useClient(DEFAULT_STUDIO_CLIENT_OPTIONS) + const [result, setResult] = useState(null) + + const id = (props.published?._id ?? props.draft?._id ?? '').replace(/^drafts\./, '') + + useEffect(() => { + if (!id) return + let cancelled = false + client + .fetch(TIER_QUERY, {id}, {tag: 'article.badge.tier'}) + .then((r) => { + if (!cancelled) setResult(r) + }) + .catch(() => { + // badge is best-effort; stay silent if the companion doc can't load + }) + return () => { + cancelled = true + } + }, [client, id]) + + const tier = result?.performanceTier + + // Archive candidate is a lifecycle state, not a tier — surface it in red. + if (result?.lifecycleState === 'archive_candidate') { + return {label: 'Archive candidate', color: 'danger', title: 'Flagged as an archive candidate'} + } + + if (!tier || !(tier in TIER_COLORS)) return null + + return { + label: TIER_LABELS[tier], + color: TIER_COLORS[tier], + title: `Performance tier: ${TIER_LABELS[tier]}`, + } +} diff --git a/analytics-content-ops/studio/lib/performance.ts b/analytics-content-ops/studio/lib/performance.ts new file mode 100644 index 0000000..98ed941 --- /dev/null +++ b/analytics-content-ops/studio/lib/performance.ts @@ -0,0 +1,70 @@ +// Shared vocabulary for the analytics signal that flows into Sanity. +// +// Per the "action-enabling signals only" decision, Sanity is not the analytics +// platform. The sync writes *derived* tiers/lifecycle plus a small display +// snapshot (`sessions30d`, vs-average %, daily series) so the Studio +// Performance panel can render GA-style traffic without leaving Studio. +// Raw analytics remain in the provider (GA4, Amplitude, fixture, …). + +export const PERFORMANCE_TIERS = ['trending', 'stable', 'stale', 'new'] as const +export type PerformanceTier = (typeof PERFORMANCE_TIERS)[number] + +export const TREND_DIRECTIONS = ['rising', 'flat', 'falling'] as const +export type TrendDirection = (typeof TREND_DIRECTIONS)[number] + +export const LIFECYCLE_STATES = ['active', 'declining', 'dormant', 'archive_candidate'] as const +export type LifecycleState = (typeof LIFECYCLE_STATES)[number] + +export const TOP_REFERRERS = ['organic', 'social', 'direct', 'referral', 'email'] as const +export type TopReferrer = (typeof TOP_REFERRERS)[number] + +// The editor's response to the signal — set by hand, never by the sync. +export const EDITORIAL_PRIORITIES = ['needs_update', 'promote', 'archive', 'monitor'] as const +export type EditorialPriority = (typeof EDITORIAL_PRIORITIES)[number] + +// The agent-review workflow position of the *live* article: +// idle → queued (sync) → in_progress → staged (triage) +// The human then resolves it through the document lifecycle, not a status: +// - accept = publish the staged draft (a Function resets status to idle and +// stamps reviewedAt) +// - dismiss = the "Dismiss suggestion" action discards the draft and does the +// same reset +// So "approved"/"dismissed" are *outcomes* recorded by reviewedAt, never the +// live article's status — a resolved article is simply back to idle. +export const AGENT_REVIEW_STATUSES = ['idle', 'queued', 'in_progress', 'staged'] as const +export type AgentReviewStatus = (typeof AGENT_REVIEW_STATUSES)[number] + +export const TIER_LABELS: Record = { + trending: 'Trending', + stable: 'Stable', + stale: 'Stale', + new: 'New', +} + +// A short, human-readable cue for each (tier × lifecycle) combination. This is +// the "one-line editorial cue" surfaced on the Performance panel — enough +// signal to act on without opening the analytics platform. +export function editorialCue(tier?: PerformanceTier, lifecycle?: LifecycleState): string { + const key = `${tier ?? 'new'}:${lifecycle ?? 'active'}` + const cues: Record = { + 'trending:active': 'Riding a wave — consider a follow-up or promoting it wider.', + 'trending:declining': 'Still hot but cooling — refresh the hook while attention lasts.', + 'trending:dormant': 'Spiking after a quiet spell — find out what drove the resurgence.', + 'trending:archive_candidate': + 'Unexpected traffic on an old piece — update facts before promoting.', + 'stable:active': 'Dependable performer — leave it be, or add internal links.', + 'stable:declining': 'Slowly slipping — a light refresh could hold the line.', + 'stable:dormant': 'Quiet but steady — candidate for an evergreen refresh.', + 'stable:archive_candidate': 'Low traffic and aging — review whether it still earns its place.', + 'stale:active': 'Getting views but underperforming peers — sharpen the angle.', + 'stale:declining': 'Losing traction — prioritize a rewrite or new data.', + 'stale:dormant': 'Little traffic and going cold — queue for agent triage.', + 'stale:archive_candidate': + 'Underperforming and outdated — strong archive or rewrite candidate.', + 'new:active': 'Too new to judge — check back once analytics have synced.', + 'new:declining': 'Early drop-off — revisit the headline and intro.', + 'new:dormant': 'Launched quietly — consider redistribution.', + 'new:archive_candidate': 'Never found an audience — reassess the topic.', + } + return cues[key] ?? 'No editorial cue yet — waiting on the next analytics sync.' +} diff --git a/analytics-content-ops/studio/package.json b/analytics-content-ops/studio/package.json new file mode 100644 index 0000000..9b088ad --- /dev/null +++ b/analytics-content-ops/studio/package.json @@ -0,0 +1,33 @@ +{ + "name": "studio", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "sanity dev", + "build": "sanity build", + "deploy": "sanity deploy", + "typegen": "sanity schema extract && sanity typegen generate", + "bootstrap": "sanity exec scripts/bootstrap.ts --with-user-token", + "seed": "sanity exec scripts/seed.ts --with-user-token", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@sanity/icons": "catalog:", + "@sanity/ui": "catalog:", + "@sanity/vision": "catalog:", + "@starter/analytics-sync": "workspace:*", + "groq": "catalog:", + "react": "catalog:", + "react-dom": "catalog:", + "sanity": "catalog:", + "styled-components": "catalog:" + }, + "devDependencies": { + "@starter/tsconfig": "workspace:*", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "babel-plugin-react-compiler": "^1.0.0", + "typescript": "catalog:" + } +} diff --git a/analytics-content-ops/studio/sanity.cli.ts b/analytics-content-ops/studio/sanity.cli.ts new file mode 100644 index 0000000..d646556 --- /dev/null +++ b/analytics-content-ops/studio/sanity.cli.ts @@ -0,0 +1,35 @@ +import {defineCliConfig} from 'sanity/cli' + +// Load studio .env so CLI commands (schema extract, typegen, exec scripts) have +// access to SANITY_STUDIO_* variables. Vite handles this during `sanity dev`. +try { + process.loadEnvFile(`${import.meta.dirname}/.env`) +} catch {} + +export default defineCliConfig({ + api: { + projectId: process.env.SANITY_STUDIO_PROJECT_ID!, + dataset: process.env.SANITY_STUDIO_DATASET!, + }, + reactCompiler: { + target: '19', + }, + reactStrictMode: true, + deployment: { + autoUpdates: true, + }, + typegen: { + enabled: true, + path: [ + './schemaTypes/**/*.{ts,tsx}', + './components/**/*.{ts,tsx}', + './structure.ts', + '../frontend/app/**/*.{ts,tsx}', + '../frontend/sanity/**/*.{ts,tsx}', + '../functions/{analytics-sync,agent-triage}/*.ts', + '../packages/@starter/analytics-sync/src/**/*.ts', + ], + generates: '../packages/@starter/sanity-types/sanity.types.ts', + overloadClientMethods: true, + }, +}) diff --git a/analytics-content-ops/studio/sanity.config.ts b/analytics-content-ops/studio/sanity.config.ts new file mode 100644 index 0000000..dd342af --- /dev/null +++ b/analytics-content-ops/studio/sanity.config.ts @@ -0,0 +1,68 @@ +import {defineConfig, type DocumentActionComponent, type DocumentBadgeComponent} from 'sanity' +import {structureTool} from 'sanity/structure' +import {visionTool} from '@sanity/vision' +import {presentationTool, defineDocuments} from 'sanity/presentation' +import {schemaTypes} from './schemaTypes' +import {structure, defaultDocumentNode} from './structure' +import {PerformanceTierBadge} from './components/PerformanceTierBadge' +import {DiscardOrDismissAction} from './components/DiscardOrDismissAction' + +const projectId = process.env.SANITY_STUDIO_PROJECT_ID! +const dataset = process.env.SANITY_STUDIO_DATASET || 'production' +const previewUrl = process.env.SANITY_STUDIO_PREVIEW_URL ?? 'http://localhost:3000' + +// Sync-owned types that editors should never create by hand. +const SYNC_OWNED = ['articlePerformance', 'analyticsContext'] + +export default defineConfig({ + name: 'default', + title: 'Analytics Content Ops', + + projectId, + dataset, + + plugins: [ + presentationTool({ + previewUrl: { + origin: previewUrl, + previewMode: { + enable: '/api/draft-mode/enable', + }, + }, + resolve: { + mainDocuments: defineDocuments([ + { + route: '/article/:slug', + filter: '_type == "article" && slug.current == $slug', + }, + ]), + }, + }), + structureTool({structure, defaultDocumentNode}), + visionTool(), + ], + + document: { + badges: (prev, {schemaType}): DocumentBadgeComponent[] => { + if (schemaType === 'article') { + return [PerformanceTierBadge, ...prev] + } + return prev + }, + // Replace the default "Discard changes" with our review-aware action (in + // place, so it keeps its menu position) — one discard/dismiss path instead + // of a "Discard changes" and a "Dismiss" button competing. + actions: (prev, {schemaType}): DocumentActionComponent[] => { + if (schemaType !== 'article') return prev + return prev.map((action) => + action.action === 'discardChanges' ? DiscardOrDismissAction : action, + ) + }, + }, + + schema: { + types: schemaTypes, + templates: (prev) => + prev.filter((t) => !SYNC_OWNED.includes('schemaType' in t ? (t.schemaType as string) : '')), + }, +}) diff --git a/analytics-content-ops/studio/schemaTypes/analyticsContext.ts b/analytics-content-ops/studio/schemaTypes/analyticsContext.ts new file mode 100644 index 0000000..b46c778 --- /dev/null +++ b/analytics-content-ops/studio/schemaTypes/analyticsContext.ts @@ -0,0 +1,30 @@ +import {defineField, defineType} from 'sanity' +import {InfoOutlineIcon} from '@sanity/icons' + +// Catalog-level summary singleton, refreshed by the sync. Gives Content Agent a +// cheap, single-document view of catalog health for triage queries without +// scanning every companion document (PRD Phase 2, `analyticsContext`). +export const analyticsContext = defineType({ + name: 'analyticsContext', + title: 'Analytics context', + type: 'document', + icon: InfoOutlineIcon, + readOnly: true, + fields: [ + defineField({name: 'totalArticles', title: 'Total articles', type: 'number'}), + defineField({name: 'trendingCount', title: 'Trending', type: 'number'}), + defineField({name: 'staleCount', title: 'Stale', type: 'number'}), + defineField({name: 'archiveCandidateCount', title: 'Archive candidates', type: 'number'}), + defineField({name: 'provider', title: 'Analytics provider', type: 'string'}), + defineField({name: 'lastSyncedAt', title: 'Last synced at', type: 'datetime'}), + ], + preview: { + select: {trending: 'trendingCount', stale: 'staleCount', synced: 'lastSyncedAt'}, + prepare({trending, stale, synced}) { + return { + title: 'Catalog analytics summary', + subtitle: `${trending ?? 0} trending · ${stale ?? 0} stale${synced ? ` · synced ${new Date(synced).toLocaleString()}` : ''}`, + } + }, + }, +}) diff --git a/analytics-content-ops/studio/schemaTypes/article.ts b/analytics-content-ops/studio/schemaTypes/article.ts new file mode 100644 index 0000000..92c32ca --- /dev/null +++ b/analytics-content-ops/studio/schemaTypes/article.ts @@ -0,0 +1,160 @@ +import {defineArrayMember, defineField, defineType} from 'sanity' +import {DocumentTextIcon} from '@sanity/icons' +import {AGENT_REVIEW_STATUSES, EDITORIAL_PRIORITIES} from '../lib/performance' + +export const article = defineType({ + name: 'article', + title: 'Article', + type: 'document', + icon: DocumentTextIcon, + groups: [ + {name: 'content', title: 'Content', default: true}, + {name: 'seo', title: 'SEO'}, + {name: 'editorial', title: 'Editorial signal'}, + ], + fields: [ + defineField({ + name: 'title', + type: 'string', + group: 'content', + validation: (rule) => rule.required(), + }), + defineField({ + name: 'slug', + type: 'slug', + group: 'content', + options: {source: 'title', maxLength: 96}, + validation: (rule) => rule.required(), + }), + defineField({ + name: 'excerpt', + title: 'Excerpt (dek)', + type: 'text', + rows: 3, + group: 'content', + description: 'Short standfirst shown in listings and at the top of the article.', + validation: (rule) => rule.max(240).warning('Keep it under 240 characters.'), + }), + defineField({ + name: 'authors', + type: 'array', + group: 'content', + of: [defineArrayMember({type: 'reference', to: [{type: 'author'}]})], + validation: (rule) => rule.min(1).error('Add at least one author.'), + }), + defineField({ + name: 'category', + type: 'reference', + group: 'content', + to: [{type: 'category'}], + }), + defineField({ + name: 'publishedAt', + title: 'Published at', + type: 'datetime', + group: 'content', + initialValue: () => new Date().toISOString(), + validation: (rule) => rule.required(), + }), + defineField({ + name: 'mainImage', + title: 'Main image', + type: 'image', + group: 'content', + options: {hotspot: true}, + fields: [{name: 'alt', type: 'string', title: 'Alternative text'}], + }), + defineField({ + name: 'body', + type: 'blockContent', + group: 'content', + }), + defineField({ + name: 'sourceUrl', + title: 'Original source URL', + type: 'url', + group: 'content', + description: 'Optional link to the original article this post is based on.', + validation: (rule) => rule.uri({scheme: ['http', 'https']}), + }), + + // ── SEO ──────────────────────────────────────────────────────────────── + // The agent stages improvements to these fields during nightly triage. + defineField({ + name: 'seoTitle', + title: 'SEO title', + type: 'string', + group: 'seo', + validation: (rule) => rule.max(70).warning('Aim for under 70 characters.'), + }), + defineField({ + name: 'seoDescription', + title: 'SEO description', + type: 'text', + rows: 2, + group: 'seo', + validation: (rule) => rule.max(160).warning('Aim for under 160 characters.'), + }), + + // ── Editorial signal ───────────────────────────────────────────────────── + // The editor's action response to the performance signal shown on the + // Performance panel. Set by hand — never by the analytics sync. + defineField({ + name: 'editorialPriority', + title: 'Editorial priority', + type: 'string', + group: 'editorial', + description: 'Flag how this article should be handled after reviewing its performance.', + options: { + layout: 'radio', + list: EDITORIAL_PRIORITIES.map((value) => ({ + value, + title: value.replace('_', ' ').replace(/^\w/, (c) => c.toUpperCase()), + })), + }, + }), + + // Agent review workflow. The status is machine-managed — written by the sync + // (queued) and the triage function (in_progress → staged), and reset to idle + // when a human resolves the review by publishing (accept) or using the + // "Dismiss suggestion" action. It is read-only in the form on purpose: a + // hand-set status would contradict the Publish/Dismiss buttons (e.g. marking + // "dismissed" while Publish is still available). + defineField({ + name: 'agentReview', + title: 'Agent review', + type: 'object', + group: 'editorial', + options: {collapsible: true, collapsed: true}, + fields: [ + defineField({ + name: 'status', + type: 'string', + initialValue: 'idle', + readOnly: true, + options: { + list: AGENT_REVIEW_STATUSES.map((value) => ({ + value, + title: value.replace('_', ' ').replace(/^\w/, (c) => c.toUpperCase()), + })), + }, + }), + defineField({ + name: 'agentNotes', + title: 'Agent notes', + type: 'text', + rows: 5, + description: 'Reasoning plus improvement opportunities written by the triage agent.', + }), + defineField({name: 'releaseId', title: 'Release ID', type: 'string'}), + defineField({name: 'reviewedAt', title: 'Reviewed at', type: 'datetime'}), + ], + }), + ], + preview: { + select: {title: 'title', author: 'authors.0.name', media: 'mainImage'}, + prepare({title, author, media}) { + return {title, subtitle: author ? `by ${author}` : undefined, media} + }, + }, +}) diff --git a/analytics-content-ops/studio/schemaTypes/articlePerformance.ts b/analytics-content-ops/studio/schemaTypes/articlePerformance.ts new file mode 100644 index 0000000..a6a09f1 --- /dev/null +++ b/analytics-content-ops/studio/schemaTypes/articlePerformance.ts @@ -0,0 +1,119 @@ +import {defineField, defineType} from 'sanity' +import {TrendUpwardIcon} from '@sanity/icons' +import { + LIFECYCLE_STATES, + PERFORMANCE_TIERS, + TIER_LABELS, + TOP_REFERRERS, + TREND_DIRECTIONS, +} from '../lib/performance' + +// Companion document, synced nightly from the analytics platform. Never edited +// by humans — kept separate from `article` so that `article._updatedAt` stays a +// purely *editorial* signal and webhooks can filter sync writes by `_type`. +export const articlePerformance = defineType({ + name: 'articlePerformance', + title: 'Article performance', + type: 'document', + icon: TrendUpwardIcon, + // Read-only in the Studio: this data is owned by the sync, not editors. + readOnly: true, + fields: [ + defineField({ + name: 'article', + type: 'reference', + to: [{type: 'article'}], + validation: (rule) => rule.required(), + }), + defineField({ + name: 'performanceTier', + title: 'Performance tier', + type: 'string', + options: {list: PERFORMANCE_TIERS.map((value) => ({value, title: TIER_LABELS[value]}))}, + }), + defineField({ + name: 'trendDirection', + title: 'Trend direction', + type: 'string', + options: {list: [...TREND_DIRECTIONS]}, + }), + defineField({ + name: 'lifecycleState', + title: 'Lifecycle state', + type: 'string', + options: {list: [...LIFECYCLE_STATES]}, + }), + defineField({ + name: 'topReferrer', + title: 'Top referrer', + type: 'string', + options: {list: [...TOP_REFERRERS]}, + }), + defineField({ + name: 'catalogPercentile', + title: 'Catalog percentile', + type: 'number', + description: 'Relative performance across the catalog, 0–100. The one human-readable number.', + validation: (rule) => rule.min(0).max(100), + }), + defineField({ + name: 'sessions30d', + title: '30-day traffic', + type: 'number', + description: + 'Sessions in the last 30 days — a synced display snapshot for the Performance panel. The analytics platform remains the system of record.', + validation: (rule) => rule.min(0), + }), + defineField({ + name: 'sessionsVsCatalogAvgPct', + title: 'Vs catalog average (%)', + type: 'number', + description: + 'Percent difference vs the catalog average 30-day sessions. Negative means below average.', + }), + defineField({ + name: 'dailySessions', + title: 'Daily sessions (30 days)', + type: 'array', + of: [ + { + type: 'object', + name: 'dailySession', + fields: [ + defineField({name: 'date', type: 'date', validation: (rule) => rule.required()}), + defineField({ + name: 'sessions', + type: 'number', + validation: (rule) => rule.required().min(0), + }), + ], + preview: { + select: {date: 'date', sessions: 'sessions'}, + prepare({date, sessions}) { + return {title: date ?? '—', subtitle: `${sessions ?? 0} sessions`} + }, + }, + }, + ], + }), + defineField({ + name: 'syncedAt', + title: 'Synced at', + type: 'datetime', + }), + ], + preview: { + select: { + title: 'article.title', + tier: 'performanceTier', + percentile: 'catalogPercentile', + sessions: 'sessions30d', + }, + prepare({title, tier, percentile, sessions}) { + const parts = [tier ? TIER_LABELS[tier as keyof typeof TIER_LABELS] : 'Unsynced'] + if (typeof sessions === 'number') parts.push(`${sessions.toLocaleString()} sess`) + if (typeof percentile === 'number') parts.push(`p${Math.round(percentile)}`) + return {title: title ?? 'Untitled article', subtitle: parts.join(' · ')} + }, + }, +}) diff --git a/analytics-content-ops/studio/schemaTypes/author.ts b/analytics-content-ops/studio/schemaTypes/author.ts new file mode 100644 index 0000000..0f3b590 --- /dev/null +++ b/analytics-content-ops/studio/schemaTypes/author.ts @@ -0,0 +1,38 @@ +import {defineField, defineType} from 'sanity' +import {UserIcon} from '@sanity/icons' + +export const author = defineType({ + name: 'author', + title: 'Author', + type: 'document', + icon: UserIcon, + fields: [ + defineField({ + name: 'name', + type: 'string', + validation: (rule) => rule.required(), + }), + defineField({ + name: 'slug', + type: 'slug', + options: {source: 'name', maxLength: 96}, + validation: (rule) => rule.required(), + }), + defineField({ + name: 'role', + type: 'string', + description: 'e.g. Contributing editor, Photographer', + }), + defineField({ + name: 'image', + title: 'Portrait', + type: 'image', + options: {hotspot: true}, + fields: [{name: 'alt', type: 'string', title: 'Alternative text'}], + }), + defineField({name: 'bio', type: 'text', rows: 3}), + ], + preview: { + select: {title: 'name', subtitle: 'role', media: 'image'}, + }, +}) diff --git a/analytics-content-ops/studio/schemaTypes/blockContent.ts b/analytics-content-ops/studio/schemaTypes/blockContent.ts new file mode 100644 index 0000000..38ec2e8 --- /dev/null +++ b/analytics-content-ops/studio/schemaTypes/blockContent.ts @@ -0,0 +1,54 @@ +import {defineArrayMember, defineType} from 'sanity' +import {ImageIcon} from '@sanity/icons' + +// The rich text field used for article bodies. Kept intentionally lean. +export const blockContent = defineType({ + name: 'blockContent', + title: 'Block Content', + type: 'array', + of: [ + defineArrayMember({ + type: 'block', + styles: [ + {title: 'Normal', value: 'normal'}, + {title: 'Heading', value: 'h2'}, + {title: 'Subheading', value: 'h3'}, + {title: 'Quote', value: 'blockquote'}, + ], + lists: [ + {title: 'Bullet', value: 'bullet'}, + {title: 'Numbered', value: 'number'}, + ], + marks: { + decorators: [ + {title: 'Strong', value: 'strong'}, + {title: 'Emphasis', value: 'em'}, + ], + annotations: [ + defineArrayMember({ + name: 'link', + type: 'object', + title: 'Link', + fields: [ + { + name: 'href', + type: 'url', + title: 'URL', + validation: (rule) => rule.uri({scheme: ['http', 'https', 'mailto', 'tel']}), + }, + ], + }), + ], + }, + }), + defineArrayMember({ + type: 'image', + icon: ImageIcon, + options: {hotspot: true}, + fields: [ + {name: 'alt', type: 'string', title: 'Alternative text'}, + {name: 'caption', type: 'string', title: 'Caption'}, + ], + }), + ], +}) diff --git a/analytics-content-ops/studio/schemaTypes/category.ts b/analytics-content-ops/studio/schemaTypes/category.ts new file mode 100644 index 0000000..6d64865 --- /dev/null +++ b/analytics-content-ops/studio/schemaTypes/category.ts @@ -0,0 +1,26 @@ +import {defineField, defineType} from 'sanity' +import {TagIcon} from '@sanity/icons' + +export const category = defineType({ + name: 'category', + title: 'Category', + type: 'document', + icon: TagIcon, + fields: [ + defineField({ + name: 'title', + type: 'string', + validation: (rule) => rule.required(), + }), + defineField({ + name: 'slug', + type: 'slug', + options: {source: 'title', maxLength: 96}, + validation: (rule) => rule.required(), + }), + defineField({name: 'description', type: 'text', rows: 2}), + ], + preview: { + select: {title: 'title', subtitle: 'description'}, + }, +}) diff --git a/analytics-content-ops/studio/schemaTypes/index.ts b/analytics-content-ops/studio/schemaTypes/index.ts new file mode 100644 index 0000000..69b0833 --- /dev/null +++ b/analytics-content-ops/studio/schemaTypes/index.ts @@ -0,0 +1,15 @@ +import {analyticsContext} from './analyticsContext' +import {article} from './article' +import {articlePerformance} from './articlePerformance' +import {author} from './author' +import {blockContent} from './blockContent' +import {category} from './category' + +export const schemaTypes = [ + article, + author, + category, + blockContent, + articlePerformance, + analyticsContext, +] diff --git a/analytics-content-ops/studio/scripts/bootstrap.ts b/analytics-content-ops/studio/scripts/bootstrap.ts new file mode 100644 index 0000000..d375d2d --- /dev/null +++ b/analytics-content-ops/studio/scripts/bootstrap.ts @@ -0,0 +1,124 @@ +/** + * Bootstrap the project after `sanity init --template`. + * + * Steps: + * 1. Deploy blueprint + * 2. Deploy schema to the Content Lake + * 3. Run typegen (schema extract + type generation) + * 4. Import seed data (ndjson) + * + * Usage: + * pnpm bootstrap (from studio/) + */ + +import {execFileSync} from 'node:child_process' +import {existsSync, readFileSync, rmSync, writeFileSync} from 'node:fs' +import {resolve} from 'node:path' +import {getCliClient} from 'sanity/cli' +import {seed} from '../seed/seed' + +const dir = import.meta.dirname! +const rootDir = resolve(dir, '../..') + +const client = getCliClient({apiVersion: '2025-01-01'}) +const {projectId} = client.config() + +function run(cmd: string, args: string[], options?: {cwd?: string}) { + execFileSync(cmd, args, {stdio: 'inherit', ...options}) +} + +function sanity(...args: string[]) { + run('pnpm', ['exec', 'sanity', ...args]) +} + +function heading(label: string) { + console.log(`\n── ${label} ${'─'.repeat(60 - label.length)}`) +} + +// ── 1. Deploy blueprint ────────────────────────────────────────────────────── +// Init the stack (first run only), then deploy the blueprint. +// Must run from the monorepo root where sanity.blueprint.ts lives. + +heading('Deploy blueprint') + +run('pnpm', ['--filter', '@starter/functions', 'run', 'build'], {cwd: rootDir}) + +// Scheduled functions require an organization-scoped stack. Init creates a +// project-scoped stack; promote moves it to org scope (same pattern as +// email-marketing). +// +// Only skip init+promote when the local blueprint config is for THIS project. A +// stale config from a different project (e.g. after changing +// SANITY_STUDIO_PROJECT_ID) would otherwise silently deploy to the wrong stack. +// The config drops its `projectId` once promoted to org scope, so we also record +// the project in a sidecar marker to compare on later runs. +const blueprintConfig = resolve(rootDir, '.sanity/blueprint.config.json') +const projectMarker = resolve(rootDir, '.sanity/bootstrap-project') + +if (existsSync(blueprintConfig)) { + const marker = existsSync(projectMarker) ? readFileSync(projectMarker, 'utf8').trim() : null + const configProjectId = (() => { + try { + return (JSON.parse(readFileSync(blueprintConfig, 'utf8')).projectId as string) || null + } catch { + return null + } + })() + const linkedProject = marker ?? configProjectId + if (linkedProject && linkedProject !== projectId) { + console.log( + `Blueprint config is for project "${linkedProject}", not "${projectId}" — re-initializing`, + ) + rmSync(blueprintConfig) + } +} + +if (existsSync(blueprintConfig)) { + console.log('Blueprint already initialized for this project — skipping init + promote') +} else { + run( + 'pnpm', + [ + 'exec', + 'sanity', + 'blueprints', + 'init', + '--stack-name', + 'production', + '--project-id', + projectId!, + '--blueprint-type', + 'ts', + ], + {cwd: rootDir}, + ) + run( + 'pnpm', + ['exec', 'sanity', 'blueprints', 'promote', '--force', '--new-stack-name', `${projectId}-prod`], + {cwd: rootDir}, + ) +} + +// Record which project this stack belongs to, so a later run for a different +// project detects the mismatch above instead of deploying to the wrong stack. +writeFileSync(projectMarker, projectId!) + +run('pnpm', ['exec', 'sanity', 'blueprints', 'deploy'], {cwd: rootDir}) + +// ── 2. Deploy schema ───────────────────────────────────────────────────────── + +heading('Deploy schema') +sanity('schema', 'deploy') + +// ── 3. Run typegen ────────────────────────────────────────────────────────── + +heading('Run typegen') +sanity('schema', 'extract') +sanity('typegen', 'generate') + +// ── 4. Seed demo content + performance signal ──────────────────────────────── + +heading('Seed demo content') +await seed(client) + +console.log('\n✓ Bootstrap complete\n') diff --git a/analytics-content-ops/studio/scripts/seed.ts b/analytics-content-ops/studio/scripts/seed.ts new file mode 100644 index 0000000..706bf24 --- /dev/null +++ b/analytics-content-ops/studio/scripts/seed.ts @@ -0,0 +1,21 @@ +/** + * Seed the dataset with demo content + performance signal. + * + * Usage: + * pnpm seed (from the repo root) + * pnpm --filter studio seed + * + * Uses your Sanity CLI login token via `--with-user-token` — no write token + * needed for local seeding. + */ +import {getCliClient} from 'sanity/cli' +import {seed} from '../seed/seed' + +const client = getCliClient({apiVersion: '2025-01-01'}) +const {dataset, projectId} = client.config() + +console.log(`Seeding dataset "${dataset}" in project ${projectId}…`) + +await seed(client) + +console.log('\n✓ Seed complete — open the Studio or run the frontend to explore.') diff --git a/analytics-content-ops/studio/seed/articles.ts b/analytics-content-ops/studio/seed/articles.ts new file mode 100644 index 0000000..9cdbb7c --- /dev/null +++ b/analytics-content-ops/studio/seed/articles.ts @@ -0,0 +1,160 @@ +export type SeedArticle = { + slug: string + title: string + dek: string + authors: string[] + publishedAt: string + category: string + image: string + sourceUrl: string + body: string[] +} + +// Real articles published on the Sanity blog (sanity.io/blog), presented within +// the Friluft Media demo. Source links point to the originals. +export const articles: SeedArticle[] = [ + { + slug: 'we-dont-write-code-anymore', + title: "We don't write code anymore", + dek: 'An engineering manager’s field report from an AI-first engineering team.', + authors: ['Vincent Quigley'], + publishedAt: '2026-06-12', + category: 'Engineering', + image: 'ridge-hiker.png', + sourceUrl: 'https://www.sanity.io/blog/we-dont-write-code-anymore', + body: [ + 'Something has shifted in software engineering. Not in the abstract, future-of-work sense. In the daily mechanics of how code gets planned, produced, reviewed, shipped, and monitored. I think we are now in the fourth generation of coding. The deliberately uncomfortable version is that we no longer write code.', + "I'm Vincent, an engineering manager at Sanity who still codes, and I have been using AI in engineering work for about 2.5 years. Over the last few months, my team has become AI-first; we build, release, and monitor software with AI as the main working surface. Code still gets produced. Pull requests still get reviewed. Systems still ship. What has changed is the job's center.", + 'A few weeks ago, I asked the team how much code they still write by hand. This is a team of senior engineers, each with at least 10 years of experience. One person said 1%. Another said they had tried writing code directly, then found themselves going back to the agent because it no longer felt like the intuitive path. That can sound scary. I do not think it needs to be.', + 'For decades, writing code was one of the most expensive parts of software engineering. We built our habits around that cost. Those activities still matter. In some cases, they matter more. But the reason for them has changed. Writing code was never the point. Creating useful products and services for customers was the point. Code was the cost of getting there.', + 'When implementation stops being the bottleneck, the development pipeline reorganizes around context, autonomy, and review. Before an agent writes code, I need to tell it what matters: the goal, constraints, existing patterns, edge cases, success criteria, and the boundaries of the change. The first output is often not code. It is a plan or spec that I can review, challenge, and share with others.', + 'One rule matters more than almost anything else: keep reviews small. I train agents to produce small pull requests, ideally around 500 lines. If it becomes 10,000, the process has failed. No one is reviewing that properly. The review bar cannot drop just because the code was cheap to produce.', + 'The work did not disappear. It moved up a level. For engineers, the valuable skills are judgment, taste, verification, product thinking, and systems thinking. Syntax still matters, but it is not enough. Knowing what good looks like matters more. The teams that benefit most will not be the ones that generate the most code. They will be the ones who make better decisions faster.', + ], + }, + { + slug: 'how-to-write-for-an-agent', + title: 'How to write for an agent', + dek: 'Spoiler: it’s not prompting. It’s an old craft for a very new kind of reader.', + authors: ['Knut Melvær', 'Even Westvang'], + publishedAt: '2026-03-18', + category: 'Guide', + image: 'pine-forest.png', + sourceUrl: 'https://www.sanity.io/blog/how-to-write-for-an-agent', + body: [ + 'Imagine waking up. You can’t really see. You don’t know where you are, exactly what year it is, or actually, if you even have limbs right now. But you remember, with varying accuracy, every book and web page in the entire world. This is how most agents are instructed today. Commands shouted into the void. Rules stacked on rules. And then surprise when the output feels generic.', + 'There’s a difference between prompting and writing for agents. Prompting agents is what users do. You open a chat, ask a question, get an answer. Writing for agents is what builders do. You’re writing system prompts that define who the agent is, what it knows, how it behaves. The user never sees this text. But it shapes every interaction they’ll have.', + 'Every writer, whether they know it or not, needs to construct an implied reader. System prompts are the same. You’re constructing a reader. That reader happens to be an LLM, and LLMs are weird readers. It just woke up, with no memory of previous conversations. Most importantly: it really wants to help. If your instructions are unclear, it will guess.', + 'At Sanity, we’ve been building schema-aware AI products since 2023. Here’s what we’ve learned. Write like you’re onboarding a new colleague. Cut before you add — most system prompts are too long, not too short. Don’t shout; your tone carries through. One topic, one place. Show, don’t tell: one good example beats ten rules. Read it out loud.', + 'None of this is new. The specific skill is constructing a reader — figuring out their mental model, what context they’re missing, what language will land. Writers have always done this. The secret to good agents isn’t better code. It’s better writing. And better writing is a craft that people have been practicing, and teaching, for a very long time.', + ], + }, + { + slug: 'structure-powers-intelligence', + title: 'Structure powers intelligence', + dek: 'AI agents need structure, not scattered docs. Build the foundation now or clean up later.', + authors: ['Magnus Hillestad'], + publishedAt: '2026-03-03', + category: 'Content Strategy', + image: 'coast-archipelago.png', + sourceUrl: 'https://www.sanity.io/blog/structure-powers-intelligence', + body: [ + 'Not long ago, content used to be something you published. Now it’s something your systems run on. When an AI agent answers a customer’s question, it isn’t reading your website; it’s reaching for whatever context it can find and acting on it. Content has become context. And context has become infrastructure.', + 'You’ve heard this before. Just connect your Google Drive, your Notion workspace, and your internal wiki, and let the agents figure it out. It won’t. We keep seeing the same story. A team launches an AI assistant, then it starts hallucinating. Eventually someone realizes the problem was never the model; it was that their product information lived in 47 different documents, none authoritative.', + 'Agents don’t just need access to information. They need precise context they can act on. There’s a difference between handing someone a pile of papers and giving them an API. Structured content means knowing. You can query a deterministic answer. The agent isn’t interpreting. It’s operating.', + 'Start with the foundation. At the center is your system of record, where content and business logic are modeled clearly and deliberately. Around that foundation, humans and agents work together. Agents handle the routine; humans handle the exceptions, the decisions that actually matter.', + 'This is the architecture that’s emerging. Not a CMS with AI features bolted on. Something purpose-built for the world where content requires structure, where humans and AI collaborate, where content powers intelligence. Content has become context. Structure powers intelligence. The question is whether you’re building that structure or cleaning up after agents that guessed.', + ], + }, + { + slug: 'skills-are-how-your-company-works', + title: 'Skills are how your company works, written down for agents', + dek: 'How we built an internal skills platform on Sanity, so anyone can author what our agents know — not just engineers.', + authors: ['Knut Melvær'], + publishedAt: '2026-06-22', + category: 'Digital Strategy', + image: 'aurora.png', + sourceUrl: 'https://www.sanity.io/blog/skills-are-how-your-company-works', + body: [ + 'The knowledge that makes a company work rarely lives in one place. It’s spread across people, habits, half-written docs, and the muscle memory of whoever has been around longest. When you start handing work to agents, that diffuse knowledge suddenly becomes a bottleneck.', + 'We built an internal skills platform on Sanity so anyone at the company can author what our agents know. The point is that authoring skills should not require writing code. A skill is a written-down way of working — the steps, the context, the guardrails — modeled as structured content that both people and agents can read.', + 'Because it’s structured, the same skill can power an agent in Slack, a workflow in the Studio, or a script running on a schedule. Governance is built in: you know who changed what, when, and why. The result is that the people closest to the work can shape how agents behave, without waiting on an engineering queue.', + ], + }, + { + slug: 'how-to-get-product-feedback-from-agents', + title: 'How to get product feedback from agents', + dek: 'Agents are some of Sanity’s heaviest users, but none of them report bugs. Here’s how we started listening.', + authors: ['Jon Eide Johnsen'], + publishedAt: '2026-06-18', + category: 'Engineering', + image: 'kayak-fjord.png', + sourceUrl: 'https://www.sanity.io/blog/how-to-get-product-feedback-from-agents', + body: [ + 'Agents are some of our heaviest users. They call our APIs thousands of times a day, hit edge cases humans rarely reach, and stress the product in ways no manual QA pass would. And yet none of them ever file a bug report.', + 'That’s a strange gap. The users who exercise your product the hardest are also the quietest. So we started treating agent behavior as a feedback channel of its own — logging where agents retry, where they get confused, and where they give up.', + 'The patterns are surprisingly legible. When an agent repeatedly rephrases the same query, something about the interface is unclear. When it abandons a task, there’s usually a missing capability or an ambiguous response. Reading those receipts turns silent, high-volume usage into a steady stream of product signal.', + ], + }, + { + slug: 'sanity-studio-v6', + title: 'Sanity Studio v6: A focused upgrade', + dek: 'Builds got 2–9× faster on Vite 8 in our testing, with improvements to search and custom auth.', + authors: ['Bjørge Næss'], + publishedAt: '2026-06-09', + category: 'Product', + image: 'mountain-cabin.png', + sourceUrl: 'https://www.sanity.io/blog/sanity-studio-v6', + body: [ + 'Sanity Studio v6 is a focused upgrade. The headline is speed: builds got 2–9× faster on Vite 8 in our testing, which changes how quickly you can iterate on a customized Studio.', + 'Beyond the build system, v6 improves default search so editors find the right document faster, and it opens up custom authentication for teams with their own identity requirements. We’re also dropping support for end-of-life Node 20.', + 'None of these are flashy features on their own. Together they make the everyday experience of working in the Studio noticeably calmer and faster — which is exactly what a mature tool should do as it matures.', + ], + }, + { + slug: 'context-board-game-agent', + title: 'A board game agent built with Sanity Context and Vercel’s AI SDK', + dek: 'An OpenAI Agent, a board game API, and Sanity Context walk into a bar. The result: a CLI that returns exact recs with real-time data.', + authors: ['Jarod Reyes'], + publishedAt: '2026-05-26', + category: 'Guide', + image: 'autumn-tundra.png', + sourceUrl: 'https://www.sanity.io/blog/context-board-game-agent', + body: [ + 'An OpenAI Agent, a board game API, and Sanity Context walk into a bar. The result is a small CLI agent that returns exact game recommendations backed by real-time data instead of vibes.', + 'The trick is grounding. Left to its own knowledge, a model will happily recommend games that don’t match your player count, playtime, or complexity. By giving the agent structured queries against a real catalog, the recommendations become answers you can trust rather than guesses you have to double-check.', + 'Wiring it together with Vercel’s AI SDK is refreshingly little code. The agent describes what it needs, the tools fetch structured content, and the model composes a precise reply. It’s a tidy example of the broader pattern: structure in, reliable answers out.', + ], + }, + { + slug: 'better-context-better-matches', + title: 'Better context, better matches: an AI love story (for dogs)', + dek: 'Search filters force users to think in database terms. What happens when you let structured content do the work instead?', + authors: ['Ken Jones'], + publishedAt: '2026-04-06', + category: 'Content Strategy', + image: 'pine-forest.png', + sourceUrl: 'https://www.sanity.io/blog/better-context-better-matches-ai-love-story-for-dogs', + body: [ + 'Search filters force users to think in database terms. Breed, age, weight, distance — a wall of dropdowns that assumes you already know exactly what you want. Most people looking to adopt a dog don’t think that way. They think in feelings and situations.', + 'This AI-powered dog adoption app shows what happens when you let structured content do the work instead. A person can describe their apartment, their schedule, and their energy level in plain language, and the app matches them to dogs whose structured attributes actually fit.', + 'The magic isn’t the model — it’s the structure underneath it. Because each dog’s profile is modeled as clean, queryable content, the agent can translate a fuzzy human wish into precise matches. Better context, better matches.', + ], + }, + { + slug: 'build-a-conference-concierge', + title: 'Build a conference concierge with Agent Context and Anthropic', + dek: 'Agent Context gives you MCP tools for your content. Wire them into streamText, and now you have a chatbot.', + authors: ['Knut Melvær'], + publishedAt: '2026-04-22', + category: 'Guide', + image: 'coast-archipelago.png', + sourceUrl: + 'https://www.sanity.io/blog/build-a-conference-concierge-with-agent-context-and-anthropic', + body: [ + 'Agent Context gives you MCP tools for your content. Wire them into streamText with an Anthropic model, and you have a conference concierge that actually knows the schedule.', + 'The concierge can answer questions like which talks are on right now, what’s happening next in a given room, and which sessions match a visitor’s interests. Because it reads structured content rather than a static FAQ, it stays correct even when the schedule changes at the last minute.', + 'What makes this approach pleasant is how little glue code it needs. The tools expose your content, the model reasons over it, and the streaming response feels immediate. It’s a small build with a genuinely useful result.', + ], + }, +] diff --git a/analytics-content-ops/studio/seed/images/aurora.png b/analytics-content-ops/studio/seed/images/aurora.png new file mode 100644 index 0000000..0709b2e Binary files /dev/null and b/analytics-content-ops/studio/seed/images/aurora.png differ diff --git a/analytics-content-ops/studio/seed/images/autumn-tundra.png b/analytics-content-ops/studio/seed/images/autumn-tundra.png new file mode 100644 index 0000000..b68fce4 Binary files /dev/null and b/analytics-content-ops/studio/seed/images/autumn-tundra.png differ diff --git a/analytics-content-ops/studio/seed/images/coast-archipelago.png b/analytics-content-ops/studio/seed/images/coast-archipelago.png new file mode 100644 index 0000000..4f9524a Binary files /dev/null and b/analytics-content-ops/studio/seed/images/coast-archipelago.png differ diff --git a/analytics-content-ops/studio/seed/images/fjord-hero.png b/analytics-content-ops/studio/seed/images/fjord-hero.png new file mode 100644 index 0000000..0f7f3a6 Binary files /dev/null and b/analytics-content-ops/studio/seed/images/fjord-hero.png differ diff --git a/analytics-content-ops/studio/seed/images/kayak-fjord.png b/analytics-content-ops/studio/seed/images/kayak-fjord.png new file mode 100644 index 0000000..7910c36 Binary files /dev/null and b/analytics-content-ops/studio/seed/images/kayak-fjord.png differ diff --git a/analytics-content-ops/studio/seed/images/mountain-cabin.png b/analytics-content-ops/studio/seed/images/mountain-cabin.png new file mode 100644 index 0000000..b703f8b Binary files /dev/null and b/analytics-content-ops/studio/seed/images/mountain-cabin.png differ diff --git a/analytics-content-ops/studio/seed/images/pine-forest.png b/analytics-content-ops/studio/seed/images/pine-forest.png new file mode 100644 index 0000000..7974315 Binary files /dev/null and b/analytics-content-ops/studio/seed/images/pine-forest.png differ diff --git a/analytics-content-ops/studio/seed/images/ridge-hiker.png b/analytics-content-ops/studio/seed/images/ridge-hiker.png new file mode 100644 index 0000000..e7db6bb Binary files /dev/null and b/analytics-content-ops/studio/seed/images/ridge-hiker.png differ diff --git a/analytics-content-ops/studio/seed/seed.ts b/analytics-content-ops/studio/seed/seed.ts new file mode 100644 index 0000000..bdf3f1b --- /dev/null +++ b/analytics-content-ops/studio/seed/seed.ts @@ -0,0 +1,115 @@ +import {createReadStream} from 'node:fs' +import {resolve} from 'node:path' +import {randomUUID} from 'node:crypto' +import type {SanityClient} from '@sanity/client' +import {fixtureProvider, runSync, type SyncClient} from '@starter/analytics-sync' +import {articles} from './articles' + +const IMAGES_DIR = resolve(import.meta.dirname!, 'images') + +function slugify(input: string): string { + return input + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/(^-|-$)/g, '') +} + +function toPortableText(paragraphs: string[]) { + return paragraphs.map((text) => ({ + _type: 'block', + _key: randomUUID(), + style: 'normal', + markDefs: [], + children: [{_type: 'span', _key: randomUUID(), text, marks: []}], + })) +} + +// Seed the demo dataset: categories, authors, articles (with uploaded images), +// then run the analytics sync so the companion `articlePerformance` documents, +// triage queue, and trending rail are all populated on first run. +export async function seed(client: SanityClient): Promise { + const imageCache = new Map() + + async function uploadImage(file: string): Promise { + if (imageCache.has(file)) return imageCache.get(file)! + const asset = await client.assets.upload('image', createReadStream(resolve(IMAGES_DIR, file)), { + filename: file, + }) + imageCache.set(file, asset._id) + return asset._id + } + + // Categories + const categoryNames = [...new Set(articles.map((a) => a.category))] + const categoryId = new Map() + for (const name of categoryNames) { + const _id = `category-${slugify(name)}` + await client.createOrReplace({ + _id, + _type: 'category', + title: name, + slug: {_type: 'slug', current: slugify(name)}, + }) + categoryId.set(name, _id) + } + console.log(` ✓ ${categoryNames.length} categories`) + + // Authors + const authorNames = [...new Set(articles.flatMap((a) => a.authors))] + const authorId = new Map() + for (const name of authorNames) { + const _id = `author-${slugify(name)}` + await client.createOrReplace({ + _id, + _type: 'author', + name, + slug: {_type: 'slug', current: slugify(name)}, + }) + authorId.set(name, _id) + } + console.log(` ✓ ${authorNames.length} authors`) + + // Articles + for (const article of articles) { + const assetId = await uploadImage(article.image) + await client.createOrReplace({ + _id: `article-${article.slug}`, + _type: 'article', + title: article.title, + slug: {_type: 'slug', current: article.slug}, + excerpt: article.dek, + publishedAt: new Date(article.publishedAt).toISOString(), + sourceUrl: article.sourceUrl, + mainImage: {_type: 'image', asset: {_type: 'reference', _ref: assetId}}, + category: {_type: 'reference', _ref: categoryId.get(article.category)!}, + authors: article.authors.map((name) => ({ + _type: 'reference', + _key: randomUUID(), + _ref: authorId.get(name)!, + })), + body: toPortableText(article.body), + agentReview: {status: 'idle'}, + }) + } + console.log(` ✓ ${articles.length} articles`) + + // Reset leftover agent drafts for the seeded articles. Seeding is a + // known-state reset (createOrReplace above only touches published docs), and + // the triage function stages its work in article *drafts*. Without this, a + // re-seed leaves orphan `staged` drafts behind: the published-perspective + // sync ignores them, but they still clutter the Content Agent Queue and + // desync the review state from the freshly reset published docs. + const draftIds = articles.map((a) => `drafts.article-${a.slug}`) + const {results} = await client.delete({query: '*[_id in $ids]', params: {ids: draftIds}}) + console.log(` ✓ cleared ${results.length} leftover article draft(s)`) + + // Populate performance signal so the demo is fully interactive out of the box. + const result = await runSync({ + client: client as unknown as SyncClient, + provider: fixtureProvider(), + }) + console.log( + ` ✓ analytics sync — ${result.counts.trending} trending, ${result.counts.stale} stale, ` + + `${result.newlyQueued} queued for triage`, + ) +} diff --git a/analytics-content-ops/studio/structure.ts b/analytics-content-ops/studio/structure.ts new file mode 100644 index 0000000..8243b71 --- /dev/null +++ b/analytics-content-ops/studio/structure.ts @@ -0,0 +1,120 @@ +import type {StructureResolver, DefaultDocumentNodeResolver} from 'sanity/structure' +import { + ActivityIcon, + ArchiveIcon, + DocumentTextIcon, + InfoOutlineIcon, + RobotIcon, + TagIcon, + ThumbsUpIcon, + TrendUpwardIcon, + UserIcon, + WarningOutlineIcon, +} from '@sanity/icons' +import {PerformancePanel} from './components/PerformancePanel' + +// GROQ that joins from the companion `articlePerformance` document back to the +// articles it scores — the same join used by the front-end intelligence +// features, expressed as Studio triage views. +const inTier = (expr: string) => + `_type == "article" && _id in *[_type == "articlePerformance" && ${expr}].article._ref` + +export const structure: StructureResolver = (S) => + S.list() + .title('Analytics Content Ops') + .items([ + S.listItem() + .title('Articles') + .icon(DocumentTextIcon) + .child(S.documentTypeList('article').title('Articles')), + S.documentTypeListItem('author').title('Authors').icon(UserIcon), + S.documentTypeListItem('category').title('Categories').icon(TagIcon), + + S.divider(), + + S.listItem() + .title('Triage') + .icon(WarningOutlineIcon) + .child( + S.list() + .title('Triage') + .items([ + S.listItem() + .title('Awaiting Approval') + .icon(ThumbsUpIcon) + .child( + S.documentList() + .title('Awaiting Approval') + .filter('_type == "article" && agentReview.status == "staged"') + .defaultOrdering([ + { + field: 'agentReview.reviewedAt', + direction: 'desc', + }, + ]), + ), + S.listItem() + .title('Underperforming') + .icon(WarningOutlineIcon) + .child( + S.documentList() + .title('Underperforming') + .filter(inTier('performanceTier == "stale" || lifecycleState == "declining"')) + .defaultOrdering([{field: 'publishedAt', direction: 'asc'}]), + ), + S.listItem() + .title('Trending Now') + .icon(TrendUpwardIcon) + .child( + S.documentList() + .title('Trending Now') + .filter(inTier('performanceTier == "trending"')) + .defaultOrdering([{field: 'publishedAt', direction: 'desc'}]), + ), + S.listItem() + .title('Archive Candidates') + .icon(ArchiveIcon) + .child( + S.documentList() + .title('Archive Candidates') + .filter(inTier('lifecycleState == "archive_candidate"')), + ), + S.divider(), + + // ── Content Agent — the agent's work queues ──────────────────── + S.listItem() + .title('Content Agent Queue') + .icon(RobotIcon) + .child( + S.documentList() + .title('Content Agent Queue') + .filter('_type == "article" && agentReview.status in ["queued", "in_progress"]') + .defaultOrdering([{field: 'publishedAt', direction: 'asc'}]), + ), + ]), + ), + + S.divider(), + + // ── Sync-owned data (read-only) ────────────────────────────────────── + S.listItem() + .title('Performance data') + .icon(ActivityIcon) + .child(S.documentTypeList('articlePerformance').title('Performance data')), + S.listItem() + .title('Analytics context') + .icon(InfoOutlineIcon) + .child(S.document().schemaType('analyticsContext').documentId('analyticsContext')), + ]) + +// Attach the read-only Performance panel as a second view on every article, so +// authors and editors see the signal without leaving the document form. +export const defaultDocumentNode: DefaultDocumentNodeResolver = (S, {schemaType}) => { + if (schemaType === 'article') { + return S.document().views([ + S.view.form(), + S.view.component(PerformancePanel).title('Performance').icon(TrendUpwardIcon), + ]) + } + return S.document() +} diff --git a/analytics-content-ops/studio/tsconfig.json b/analytics-content-ops/studio/tsconfig.json new file mode 100644 index 0000000..2ce04cc --- /dev/null +++ b/analytics-content-ops/studio/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "@starter/tsconfig/base.json", + "include": [ + "schemaTypes/**/*.ts", + "components/**/*.tsx", + "lib/**/*.ts", + "structure.ts", + "sanity.config.ts", + "sanity.cli.ts", + "scripts/**/*.ts" + ], + "compilerOptions": { + "jsx": "react-jsx", + "noEmit": true + } +}