Skip to content

Latest commit

 

History

History
342 lines (253 loc) · 23.3 KB

AGENTS.md

File metadata and controls

342 lines (253 loc) · 23.3 KB

AGENTS.md

Guide for AI coding agents (Claude Code, Cursor, Copilot, etc.) working in this repo.

Scope: the non-obvious architectural facts you need to change code safely. For content authoring (adding a paper, author, talk, blog post) read CONTRIBUTING.md; for the product overview read README.md.


0. TL;DR for agents

  • Canonical repo: github.com/protocol/plrd.org. The project moved here from daviddao/plrd.org (earlier plresearch.org). All work — branches, PRs, pushes — targets protocol/plrd.org.

  • Stack: Next.js 15 App Router + React 19 + Tailwind v4 CSS-first + TypeScript. Node node:test suite via npm test. Verify with npm test, npx tsc --noEmit, and npm run build.

  • Content pipeline: Markdown in content/ → scripts/build-content.mjs (prebuild) → JSON in src/data/generated/ → typed arrays in src/lib/content.ts → pages. JSON is checked into git.

  • Trailing slashes are mandatory on every internal href. skipTrailingSlashRedirect: true means missing slashes 404 silently.

  • Path alias: @/* → ./src/*. Never use relative imports across src/.

  • Dynamic route params are Promises in Next 15: const { slug } = await params.

  • GitHub-only editing: website login, CMS, browser publishing, deletion, and credential-based maintenance writers are retired. Repository Markdown/JSON own website content; preserve public read-only ATProto/Hypercert/profile/DID/metric integrations. See route migration.

  • FA2 (/areas/economies-governance/) is hardcoded and special-cased. Don't try to unify it with the generic areas/[slug]/ template.


1. Commands

npm run dev Runs build-content.mjs, then next dev.
npm run build Runs build-content.mjs, then next build.
npm start Production server.
npm test Standard Node tests, including auth retirement and scripts/site-content-*.test.mjs.
npx tsc --noEmit Type-check before committing.
node scripts/build-content.mjs Regenerate src/data/generated/*.json without starting Next.

The dev server does not watch content/ — edits to markdown require restarting npm run dev. After branch switches or content-script changes, rm -rf .next if pages show stale data.


2. Repository layout (where things actually live)

content/                        Markdown sources (publications, authors, talks, blog, areas, tutorials, outreach, sections)
scripts/
  build-content.mjs             Prebuild: Markdown → JSON + RSS + search index
src/
  app/                          Next.js App Router (see §4)
    api/                        Public readers + 410 tombstones for legacy write/auth routes
    .well-known/                AT-URI discovery
    areas/economies-governance/ HARDCODED FA2 tree (see §7)
    admin/ edit/ write/         Read-only GitHub contribution guidance (no login or editors)
  components/                   UI primitives (see §5)
  data/
    generated/                  ⚠ auto-generated JSON, checked into git
    fa2/                        Hand-curated FA2 JSON (projects, opportunity spaces, impact)
  lib/
    content.ts                  Typed re-exports of generated JSON
    site-config.ts              Nav + site metadata
    format.ts                   formatDate, stripFaPrefix, slugToName
    lexicons.ts                 Public ATProto collection IDs, record types, and read identity
    indexer.ts                  Content-read compatibility contract backed by repository JSON
    atproto-client.ts           Unauthenticated Bluesky helpers
public/
  icons/<name>.svg              Raw SVGs, referenced as /icons/<name>.svg
  images/authors/<slug>/        Author avatars (avatar.*, first match wins)
  feed.xml search-index.json    Auto-generated by build-content.mjs

3. Content pipeline

Build script (scripts/build-content.mjs)

  • Scans content/<section>/. Each subdirectory with index.md or _index.md is a record; loose *.md files in a section also work (slug = filename).
  • Slug = folder or filename — frontmatter cannot override it. Renaming the folder changes the URL.
  • Per-collection mappers (buildPublications, buildAuthors, etc.) define a fixed shape; unknown frontmatter keys are dropped silently. Adding a field needs edits in both the mapper and the Type in src/lib/content.ts.
  • Sorting: publications / talks / blog by date desc; authors by name asc (localeCompare); outreach by numeric weight asc; tutorials + areas use readdir order.
  • unaffiliated: true on a publication drops it from the site, RSS, and search index.
  • Avatars: buildAuthors probes public/images/authors/<slug>/ for any file starting with avatar. Frontmatter resources: is decorative and ignored.
  • Dependency-graph data: content/areas/economies-governance/dependency-graph/*.md parses bottlenecks/gates/strands/interventions/feedbackLoops arrays; per-node tooltip fields are hoisted into a sibling tooltips map keyed by node id.
  • RSS: top 20 publications + top 10 talks, capped at 50, written to public/feed.xml.
  • Search index: flattens publications, talks, authors, blog, tutorials, areas plus a hard-coded list of static pages (About, Team, FA2 sub-pages, etc.). Add new static pages to buildSearchIndex explicitly.

Generated JSON (src/data/generated/)

publications.json, authors.json, talks.json, tutorials.json, blog.json, areas.json, sections.json, dependency-graph.json, outreach.json.

All checked into git — Vercel needs them at build time. Commit regenerated files alongside content edits; a PR with stale JSON ships stale data.

outreach.json is generated but not consumed — outreach pages render from markdown elsewhere. Don't rely on it without wiring it up.

Typed API (src/lib/content.ts)

Pages must import { publications, authors, ... } from '@/lib/content'. Never read src/data/generated/*.json directly; never parse markdown at runtime.

Markdown quirks

  • remark-html runs with sanitize: false — raw HTML in markdown passes through and reaches the DOM via dangerouslySetInnerHTML.
  • Hugo shortcodes are not expanded. {{< youtube ID >}} survives into HTML; src/app/talks/[slug]/page.tsx regex-extracts the ID and replaces it with an iframe. No other shortcodes are handled — authors must use plain HTML/Markdown.
  • authors[] mixes author-folder slugs (internal) with quoted free-text (externals). Lookups must fall back to rendering the raw string.

4. App Router & routing

Layout & conventions

src/app/layout.tsx is the only root layout: loads Inter + Newsreader fonts, sets default metadata from siteConfig, and wraps children in <SiteShell>. Website authentication is retired.

Detail-page template (follow exactly — params is a Promise in Next 15):

type Props = { params: Promise<{ slug: string }> }

export function generateStaticParams() {
  return items.map(i => ({ slug: i.slug }))
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params
  const item = items.find(i => i.slug === slug)
  if (!item) return { title: 'Not Found' }
  return { title: item.title, description: item.summary }
}

export default async function Page({ params }: Props) {
  const { slug } = await params
  const item = items.find(i => i.slug === slug)
  if (!item) notFound()
  // ...
}
  • Dynamic segments are statically rendered only for items returned by generateStaticParams. Adding a record requires content files — you can't hand-edit src/lib/content.ts, it's regenerated.
  • Use notFound() inside the default export; return { title: 'Not Found' } from generateMetadata (don't throw).
  • Former CMS consumers retain the fetchPage/opportunity read contracts backed by editable src/data/site-content/ JSON. Do not reconnect live CMS overrides or replace approved copy with older fallback seeds.

Routing rules

  • trailingSlash: true + skipTrailingSlashRedirect: true in next.config.ts → every internal href must end with /. No auto-redirect.
  • Path alias @/* → ./src/*. Grep diffs for relative imports across src/.
  • Redirects live in next.config.ts:
    • /areas/upgrade-economies-governance/* → /areas/economies-governance/*
    • /research/:path* → /insights/:path* (don't add new pages under src/app/research/)
  • images.unoptimized: true: do not rely on next/image resizing; the codebase mostly uses raw <img>.

Special / dynamic routes

  • src/app/api/*/route.ts — all marked export const dynamic = "force-dynamic".
  • src/app/.well-known/site.standard.publication/route.ts — AT-URI discovery from src/data/site-content/publication.json; no environment override.
  • /admin, /edit, /write, and all former editor routes show GitHub PR guidance, with noindex metadata and canonical repository source links. They do not authenticate, load CMS records, or save.

Adding a new page — checklist

  1. Create src/app/<route>/page.tsx (server component unless you need hooks/auth).
  2. If markdown-backed: add source under content/<section>/ and extend both scripts/build-content.mjs (mapper) and src/lib/content.ts (type + re-export).
  3. For [slug] pages: implement generateStaticParams and generateMetadata.
  4. Add a <Breadcrumb items={...}/> above the page body.
  5. Wire nav via src/lib/site-config.ts (mainNav / footerNav) — pages are not auto-indexed.
  6. If it should be searchable, append it to buildSearchIndex in scripts/build-content.mjs.
  7. Keep content repository-owned. Do not add a CMS editor, site login, or runtime write endpoint; update the relevant Markdown/JSON and its tests through a PR.
  8. Link it as /your-route/ (trailing slash).

5. UI layer

Site shell

SiteShell (src/components/SiteShell.tsx, client) renders SiteHeader + OffCanvasNav (mobile drawer) + main + optional SiteFooter. Routes matching FULLSCREEN_PATTERNS (currently the dependency-graph slug page) render full-screen with no footer and a scroll lock on body.

Nav structure: src/lib/site-config.ts (mainNav, footerNav, siteConfig). Items with url: '#' are dropdown-only triggers.

Component inventory (src/components/)

Component Purpose
SiteShell / SiteHeader / SiteFooter / OffCanvasNav Layout chrome
NavItem Header link with optional dropdown
SearchBar Fuse.js over /search-index.json, / keyboard shortcut
AuthorCard Author chip in 3 sizes (default / lead / advisor) linking to /authors/:slug
Breadcrumb Crumb list; Home auto-prepended
AreaIcons Animated inline SVGs for focus areas (shield/hexagon/neural/brain)
GeoIllustration Seeded deterministic animated SVG placeholder
FundingPipeline Interactive 4-stage grant pipeline card (FA2)

Server components in this layer: SiteFooter, AuthorCard, Breadcrumb, AreaIcons, GeoIllustration. Everything else is 'use client'.

Styling (Tailwind v4)

  • No tailwind.config.js. Theme tokens live in an @theme { ... } block inside src/app/globals.css. PostCSS uses only @tailwindcss/postcss.
  • Brand tokens: --color-blue (#1982F4), --color-pink (#E51A66), --color-teal, --color-black (#131316). text-blue / bg-blue/90 resolve to the brand color, not Tailwind's blue-500.
  • Custom font sizes override Tailwind defaults (text-xl = 48px, text-lg = 32px). Be deliberate with size classes.
  • Breakpoints: sm/md/lg default, xl = 1146px.
  • Common patterns: max-w-6xl mx-auto px-6 page container, rounded-full pill buttons, bg-white/95 backdrop-blur-sm sticky surfaces, @utility scrollbar-hide.
  • Prose rules for rendered Markdown live under .page-content and .page-top in globals.css.

Icons, images, avatars

  • Icons: public/icons/<name>.svg, referenced as <img src="/icons/<name>.svg">. Typos fail silently (broken image). Social icons include github, twitter, linkedin, orcid, google-scholar, arxiv, doi, acm, elsevier, researchgate, etc.; chrome includes chevron-*, menu, search.
  • Author avatars: authors.find(...).avatarPath is string | null; AuthorCard falls back to an initial badge.
  • next/image is not used here. Image optimization is disabled project-wide.

Utilities (src/lib/format.ts)

formatDate(str) → "Jan 5, 2026" via Intl.toLocaleDateString. stripFaPrefix(title) removes FA\d+:\s*. slugToName(slug) title-cases a dash-separated slug.


6. GitHub-only editing and public read integrations

Website content is reviewed in GitHub pull requests, then merged and deployed. Repository content is held in src/data/site-content/pages.json and opportunities.json behind the existing src/lib/indexer.ts read contracts. About remains src/data/about.json; research articles and profiles remain Markdown; AI/DHR/Neuro opportunities retain their existing authoritative JSON. See the exact route/source migration.

There is no runtime OAuth client, JWK, session encryption, admin DID allowlist, authenticated agent, edit audit writer, website CMS, or local community deletion. Legacy APIs return noncacheable 410 JSON; /api/status/ is always anonymous. Retired credentials are neither read nor needed. Do not restore the old writer scripts or mutate preserved external accounts/records as a website edit.

Keep @atproto/api: /api/users/[handle]/ uses the public profile reader. Hypercert claims, Constellation community records, public DID/PDS/profile reads, GainForest blob URLs, and the separate Simocracy/GainForest/FtC/other impact metric clients remain read-only integrations. Their source services are not retired by removal of website authentication. GraphQL POST queries used by public readers are not repository mutations.

Community entries can link to their record's explicit safe HTTPS sourceURL for management. If absent, explain that records are managed where created; never fabricate a source-service editor URL or offer local deletion.

Historical data/atproto/ snapshots stay immutable reference material, not a supported publishing or synchronization input. No source account, published record, discovery identity, or unrelated integration is deleted.


7. FA2 (Upgrade Economies & Governance)

FA2 is special-cased: hardcoded routes under /areas/economies-governance/ with hand-curated JSON in src/data/fa2/. areas/[slug]/page.tsx explicitly filters it out via HARDCODED_AREA_SLUGS = ['economies-governance'].

Route Component Data source
/areas/economies-governance/ page.tsx repository page area-economies-governance (fallback: hardcoded copy)
.../subareas/ subareas/page.tsx repository page area-eg-subareas + hardcoded 9-subarea list
.../opportunity-spaces/ opportunity-spaces/page.tsx src/data/fa2/opportunityspaces.json
.../opportunity-spaces/[slug]/ SSG via generateStaticParams opportunityspaces.json
.../impact/ impact/page.tsx repository page area-eg-impact
.../impact/report-2025/ report-2025/page.tsx src/data/fa2/impact.json + projects.json
.../impact/live-dashboard/ live-dashboard/page.tsx placeholder
.../projects/ projects/page.tsx → ProjectsExplorer.tsx (client) src/data/fa2/projects.json
.../dependency-graph/ dependency-graph/page.tsx lib/content dep-graph entries
.../dependency-graph/[slug]/ DependencyGraph.tsx (d3-force) dependency-graph/data/
.../edit/ edit/page.tsx noindex GitHub contribution guidance
.../sovereign-ai/[slug]/ SSG via generateStaticParams src/data/fa2/sovereign-ai/<slug>.json; PDF and shelf plate in public/sovereign-ai/

Sovereign AI program. FA2 runs one program, Sovereign AI, and the FA2 page presents it as its flagship: a #flagship-program box after the introduction and before Opportunity Spaces, in the shape of the Digital Human Rights one, with "Explore Sovereign AI" to the program site at /sov-ai (docs/sov-ai/README.md). The box's two paragraphs are flagshipCopy in src/lib/sovereign-ai.ts, the program site's own overview word for word; scripts/fa2-flagship.test.mjs holds them to public/sov-ai/index.html, so change the wording there first. The old #sovereign-ai anchor sits just above the box, since the sheets and redirects point at it. The box lists the program's one-page sheets: Why sovereign AI, Broad Listening & Simocracy, Hypercerts, the government pilot partnership and the summary for funders. Each sheet is one JSON file in src/data/fa2/sovereign-ai/ that names its layout (three-propositions, explainer, partnership or summary) and is registered in src/lib/sovereign-ai.ts, whose order is the order of the list; scripts/fa2-sovereign-ai.test.mjs fails if a JSON is not registered. Every sheet prints the kicker "Economies & Governance · Sovereign AI program". The JSON is published three ways:

  • the web edition at .../sovereign-ai/<slug>/ (src/components/sovereign-ai/, one component per layout, built from the shared blocks in parts.tsx), with a "Sovereign AI" crumb back to the flagship box;
  • npm run build-sheets [slug] prints it to public/sovereign-ai/<slug>.pdf with headless Chrome (scripts/build-sheets.mjs holds the print layouts and the blocks they share, scripts/sheets/sheet.css the shared look) and renders page one to public/sovereign-ai/<slug>.webp. It needs local Chrome, Python 3, pdftoppm and magick, reports the shrink-to-fit factor, and fails if a page still overflows A4. The PDFs are the one exception to the *.pdf ignore rule; rebuild and commit PDF and plate whenever the JSON changes. Slugs double as PDF file names, so keep them descriptive;
  • a link by its label in the flagship box on the FA2 page. Until 18 November 2026 the page stood the sheets on a shelf (SheetShelf.tsx, a client component after ai4cop.org's field sheets: a plain click takes a sheet down into a card offering the web edition and the PDF). The component and the shelf plates are kept, unused, so the shelf can come back: five sheets fit on one board from tablet width up; a sixth needs narrower gaps or sheets in globals.css and the row's gap classes.

Prose fields may carry [label](/site/path/) links; the web edition keeps them on the site and the PDF prints them as full plrd.org links (unstyled on paper, so a link never changes the printed layout). To print a sheet that should not be public yet, such as a country edition of the partnership sheet, keep its JSON outside the repo and pass the path: npm run build-sheets ~/somewhere/edition.json prints the PDF beside it and touches nothing in the site.

The sheets lived under /briefs/ until 22 October 2026 and under /programs/ for a day after, and PDFs went out with /briefs/ links. next.config.ts redirects every old address: .../briefs/<slug>/ and .../programs/<slug>/ to .../sovereign-ai/<slug>/, /briefs/<file> and /programs/<file> to /sovereign-ai/<file>, the drawings under /images/fa2/briefs/ and /images/fa2/programs/, and the bare index paths to the shelf. plrd.org/sovereign-ai/ is the program's short link. Keep those redirects.

The other areas (ai-robotics, digital-human-rights, neurotech) each have their own opportunity-spaces/ + [slug] pair powered by src/data/fa2/{ai,dhr,neuro}-opportunityspaces.json (yes, named under fa2/ for historical reasons).

Edits to authoritative JSON/Markdown are reviewed in GitHub and require merge/deployment. Former CMS-backed E&G opportunity fields use src/data/site-content/opportunities.json, not older FA2 fallback fields.


8. Environment variables

No website login, session, app-password, or JWK configuration is needed for a build or runtime. Remove retired auth values from deployment configuration through the normal authorized secret-management process; this code does not read them. See .env.example for retained public analytics/optional metrics.

src/data/site-content/publication.json supplies the recorded public discovery identity for /.well-known/site.standard.publication. No environment value is required and deployment settings cannot override it. Do not create a new publication/account or reintroduce a credential-based bootstrap script.


9. Gotchas (the "why isn't this working" list)

Build / types

  • Forgot to run build-content.mjs? tsc imports from generated JSON; it will compile stale types. Both dev and build auto-run the script; running tsc standalone does not.
  • .next/ caches types aggressively. After deleting pages, changing generateStaticParams, or switching branches, rm -rf .next.
  • params: Promise<{ slug: string }> in Next 15. Forgetting await produces a silent type error only caught by tsc --noEmit.

Content

  • unaffiliated: true on a publication silently hides it everywhere — there's no "draft" flag; unpublished content shouldn't live in content/.
  • Avatars come from public/images/authors/<slug>/avatar.*, not frontmatter.
  • Author references mix internal slugs and free-text external names. Always fall back to rendering the string.
  • Adding a frontmatter field requires edits in both the mapper (scripts/build-content.mjs) and the Type in src/lib/content.ts.
  • dev does not watch content/ — restart after markdown edits.
  • Hugo shortcodes (other than {{< youtube ID >}} in talks) are not expanded.

Routing

  • Missing trailing slashes 404 silently (skipTrailingSlashRedirect: true). Grep diffs for href="/foo" without the trailing /.
  • Don't add pages under src/app/research/ — /research/:path* redirects to /insights.
  • Adding a focus area? Not via areas/[slug]/ if it's economies-governance — that's the hardcoded tree.

UI / styling

  • This is Tailwind v4. No tailwind.config.js. Tokens live in @theme inside globals.css.
  • Custom text-xl/text-lg override defaults; use text-sm/text-base for body copy.
  • text-blue / bg-blue resolve to the brand --color-blue, not Tailwind's default blue.
  • Components using hooks or usePathname need 'use client' at the top.
  • Raw <img> throughout; next/image optimization is off project-wide.
  • Icon typos fail silently — confirm the file exists in public/icons/.
  • Adding a fullscreen route? Append a regex to FULLSCREEN_PATTERNS in SiteShell.tsx.

Retired CMS / public ATProto

  • Website editing happens only in GitHub. Never advise /admin login or a PDS sync command.
  • Source records and historical data remain intact; retirement is not deletion authorization.
  • Retain public profile/DID/Hypercert/community/metric readers when changing shared imports.
  • @atproto/common-web and @atproto/syntax remain transitive public-reader dependencies; they are not direct OAuth/runtime-write requirements.

10. Deployment

The repo lives at github.com/protocol/plrd.org (moved from daviddao/plrd.org; daviddao/plrd-v2 was an earlier name). main auto-deploys to Vercel. vercel.json sets only framework: nextjs + buildCommand: npm run build. *.pdf is gitignored, except the Sovereign AI sheets in public/sovereign-ai/.


11. Content ownership

GitHub is the editing/publishing workflow for this website. External public ATProto data is read-only context, not a website CMS. Do not add login, author publishing, credential-based maintenance writers, or shared-source mutations.