Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ pnpm create sanity@latest --template sanity-labs/starters/<starter-name>
| ------------------------------------------------ | ----------------------------------------------------------------------------------------- |
| [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
Expand Down
40 changes: 40 additions & 0 deletions analytics-content-ops/.env.example
Original file line number Diff line number Diff line change
@@ -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.<workspaceName>`. 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=
33 changes: 33 additions & 0 deletions analytics-content-ops/.github/workflows/analytics-sync.yml
Original file line number Diff line number Diff line change
@@ -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 }}
56 changes: 56 additions & 0 deletions analytics-content-ops/.github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -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
43 changes: 43 additions & 0 deletions analytics-content-ops/.gitignore
Original file line number Diff line number Diff line change
@@ -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/
1 change: 1 addition & 0 deletions analytics-content-ops/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
enable-pre-post-scripts=true
6 changes: 6 additions & 0 deletions analytics-content-ops/.oxfmtrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"semi": false,
"singleQuote": true,
"printWidth": 100,
"bracketSpacing": false
}
130 changes: 130 additions & 0 deletions analytics-content-ops/AGENT.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions analytics-content-ops/CLAUDE.md
Loading
Loading